const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-yHxLdQqt.js","assets/useLeadSiteSearchSuggestions-CbbjIETE.js","assets/CityPagesModule-DBj8vywR.js","assets/imageOptimization-Csrlnz8M.js","assets/LeadSiteLuxuryHome-CDGnn4fH.js","assets/LeadSiteLandRanchHome-Da2uUjBN.js","assets/LeadSiteSearch-DHez-h-6.js","assets/LeadSiteListingCardImage-Cd6C-fbh.js","assets/LeadSiteMap-BHVnE4FF.js","assets/LeadSiteLuxurySearch-t_Pv0y9B.js","assets/LeadSiteListingDetail-CIY2k5DJ.js","assets/ListingVideoTour-NLh19LDN.js","assets/useListingVideos-B5VYYGK4.js","assets/LeadSiteLuxuryListingDetail-BVmc6ZiE.js","assets/LeadSiteCityPage-BCxz70Do.js","assets/LeadSiteSubdivisionPage-ypCe2AN1.js","assets/PublicLiveEvent-Cl-cTbHs.js","assets/useLiveEngagement-8Xx5CV5-.js","assets/LiveEventConsole-BdwUmyoE.js","assets/PostcardManager-Cpo3MBjd.js","assets/usePostcardZones-CsavTZo-.js","assets/DirectMail-CusnsmAW.js","assets/jspdf.es.min-CGrgL93d.js","assets/LeadSiteEditor-UQDSnS_3.js","assets/ImageUrlField-QyYcfGTr.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-DDItJFU-.js","assets/MLSListingDetail-B6i7zCGv.js","assets/EmailCampaignComposer-TZswcI3L.js","assets/EditorModeSelector-B57ZOzAG.js","assets/SharedCampaignTemplates-BxMNqChb.js","assets/TemplateEditorDialog-BSi9UJz5.js","assets/AgentTemplates-B2rwbK7h.js","assets/TheLocalMoveHome-C1xngcSl.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-C_7U_8Dp.js"])))=>i.map(i=>d[i]); var TTt=Object.defineProperty;var R7e=s=>{throw TypeError(s)};var ETt=(s,t,n)=>t in s?TTt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var Pa=(s,t,n)=>ETt(s,typeof t!="symbol"?t+"":t,n),uwe=(s,t,n)=>t.has(s)||R7e("Cannot "+n);var Xs=(s,t,n)=>(uwe(s,t,"read from private field"),n?n.call(s):t.get(s)),qi=(s,t,n)=>t.has(s)?R7e("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),Ha=(s,t,n,r)=>(uwe(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),Xo=(s,t,n)=>(uwe(s,t,"access private method"),n);var jV=(s,t,n,r)=>({set _(a){Ha(s,t,a,n)},get _(){return Xs(s,t,r)}});function ATt(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 MTt="modulepreload",ITt=function(s){return"/"+s},O7e={},vi=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=ITt(c),c in O7e)return;O7e[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":MTt,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((p,f)=>{h.addEventListener("load",p),h.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return a.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return t().catch(i)})};var Ih=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function jl(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function PTt(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 Gtt={exports:{}},m0e={},Wtt={exports:{}},gl={};/** * @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 R$=Symbol.for("react.element"),LTt=Symbol.for("react.portal"),DTt=Symbol.for("react.fragment"),RTt=Symbol.for("react.strict_mode"),OTt=Symbol.for("react.profiler"),FTt=Symbol.for("react.provider"),zTt=Symbol.for("react.context"),BTt=Symbol.for("react.forward_ref"),$Tt=Symbol.for("react.suspense"),UTt=Symbol.for("react.memo"),qTt=Symbol.for("react.lazy"),F7e=Symbol.iterator;function VTt(s){return s===null||typeof s!="object"?null:(s=F7e&&s[F7e]||s["@@iterator"],typeof s=="function"?s:null)}var Ktt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ytt=Object.assign,Ztt={};function TD(s,t,n){this.props=s,this.context=t,this.refs=Ztt,this.updater=n||Ktt}TD.prototype.isReactComponent={};TD.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")};TD.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function Qtt(){}Qtt.prototype=TD.prototype;function fEe(s,t,n){this.props=s,this.context=t,this.refs=Ztt,this.updater=n||Ktt}var xEe=fEe.prototype=new Qtt;xEe.constructor=fEe;Ytt(xEe,TD.prototype);xEe.isPureReactComponent=!0;var z7e=Array.isArray,Xtt=Object.prototype.hasOwnProperty,gEe={current:null},Jtt={key:!0,ref:!0,__self:!0,__source:!0};function est(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)Xtt.call(t,r)&&!Jtt.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,ye=pe[ie];if(0>>1;ie<_e;){var Me=2*(ie+1)-1,Te=pe[Me],Ce=Me+1,Ee=pe[Ce];if(0>a(Te,de))Cea(Ee,Te)?(pe[ie]=Ee,pe[Ce]=de,ie=Ce):(pe[ie]=Te,pe[Me]=de,ie=Me);else if(Cea(Ee,de))pe[ie]=Ee,pe[Ce]=de,ie=Ce;else break e}}return ce}function a(pe,ce){var de=pe.sortIndex-ce.sortIndex;return de!==0?de:pe.id-ce.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,p=3,f=!1,g=!1,b=!1,v=typeof setTimeout=="function"?setTimeout:null,j=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 S(pe){for(var ce=n(d);ce!==null;){if(ce.callback===null)r(d);else if(ce.startTime<=pe)r(d),ce.sortIndex=ce.expirationTime,t(c,ce);else break;ce=n(d)}}function A(pe){if(b=!1,S(pe),!g)if(n(c)!==null)g=!0,ne(T);else{var ce=n(d);ce!==null&&oe(A,ce.startTime-pe)}}function T(pe,ce){g=!1,b&&(b=!1,j(M),M=-1),f=!0;var de=p;try{for(S(ce),h=n(c);h!==null&&(!(h.expirationTime>ce)||pe&&!V());){var ie=h.callback;if(typeof ie=="function"){h.callback=null,p=h.priorityLevel;var ye=ie(h.expirationTime<=ce);ce=s.unstable_now(),typeof ye=="function"?h.callback=ye:h===n(c)&&r(c),S(ce)}else r(c);h=n(c)}if(h!==null)var _e=!0;else{var Me=n(d);Me!==null&&oe(A,Me.startTime-ce),_e=!1}return _e}finally{h=null,p=de,f=!1}}var D=!1,L=null,M=-1,F=5,z=-1;function V(){return!(s.unstable_now()-zpe||125ie?(pe.sortIndex=de,t(d,pe),n(c)===null&&pe===n(d)&&(b?(j(M),M=-1):b=!0,oe(A,de-ie))):(pe.sortIndex=ye,t(c,pe),g||f||(g=!0,ne(T))),pe},s.unstable_shouldYield=V,s.unstable_wrapCallback=function(pe){var ce=p;return function(){var de=p;p=ce;try{return pe.apply(this,arguments)}finally{p=de}}}})(ast);rst.exports=ast;var R7=rst.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 tEt=N,by=R7;function Zr(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"),Gke=Object.prototype.hasOwnProperty,sEt=/^[: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]*$/,$7e={},U7e={};function nEt(s){return Gke.call(U7e,s)?!0:Gke.call($7e,s)?!1:sEt.test(s)?U7e[s]=!0:($7e[s]=!0,!1)}function rEt(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 aEt(s,t,n,r){if(t===null||typeof t>"u"||rEt(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 cg(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 Nf={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){Nf[s]=new cg(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];Nf[t]=new cg(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){Nf[s]=new cg(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){Nf[s]=new cg(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){Nf[s]=new cg(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){Nf[s]=new cg(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){Nf[s]=new cg(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){Nf[s]=new cg(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){Nf[s]=new cg(s,5,!1,s.toLowerCase(),null,!1,!1)});var bEe=/[\-:]([a-z])/g;function _Ee(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(bEe,_Ee);Nf[t]=new cg(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(bEe,_Ee);Nf[t]=new cg(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(bEe,_Ee);Nf[t]=new cg(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){Nf[s]=new cg(s,1,!1,s.toLowerCase(),null,!1,!1)});Nf.xlinkHref=new cg("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){Nf[s]=new cg(s,1,!1,s.toLowerCase(),null,!0,!0)});function wEe(s,t,n,r){var a=Nf.hasOwnProperty(t)?Nf[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{pwe=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?o7(s):""}function iEt(s){switch(s.tag){case 5:return o7(s.type);case 16:return o7("Lazy");case 13:return o7("Suspense");case 19:return o7("SuspenseList");case 0:case 2:case 15:return s=fwe(s.type,!1),s;case 11:return s=fwe(s.type.render,!1),s;case 1:return s=fwe(s.type,!0),s;default:return""}}function Zke(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 xP:return"Fragment";case fP:return"Portal";case Wke:return"Profiler";case jEe:return"StrictMode";case Kke:return"Suspense";case Yke:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case lst:return(s.displayName||"Context")+".Consumer";case ost:return(s._context.displayName||"Context")+".Provider";case NEe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case kEe:return t=s.displayName||null,t!==null?t:Zke(s.type)||"Memo";case Wk:t=s._payload,s=s._init;try{return Zke(s(t))}catch{}}return null}function oEt(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 Zke(t);case 8:return t===jEe?"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 k4(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function dst(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function lEt(s){var t=dst(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 SV(s){s._valueTracker||(s._valueTracker=lEt(s))}function ust(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=dst(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function wpe(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 Qke(s,t){var n=t.checked;return Hu({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function V7e(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=k4(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 hst(s,t){t=t.checked,t!=null&&wEe(s,"checked",t,!1)}function Xke(s,t){hst(s,t);var n=k4(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")?Jke(s,t.type,n):t.hasOwnProperty("defaultValue")&&Jke(s,t.type,k4(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function H7e(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 Jke(s,t,n){(t!=="number"||wpe(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var l7=Array.isArray;function GP(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=CV.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function zz(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var O7={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},cEt=["Webkit","ms","Moz","O"];Object.keys(O7).forEach(function(s){cEt.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),O7[t]=O7[s]})});function xst(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||O7.hasOwnProperty(s)&&O7[s]?(""+t).trim():t+"px"}function gst(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=xst(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var dEt=Hu({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 sSe(s,t){if(t){if(dEt[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Zr(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Zr(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Zr(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Zr(62))}}function nSe(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 rSe=null;function SEe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var aSe=null,WP=null,KP=null;function K7e(s){if(s=z$(s)){if(typeof aSe!="function")throw Error(Zr(280));var t=s.stateNode;t&&(t=y0e(t),aSe(s.stateNode,s.type,t))}}function yst(s){WP?KP?KP.push(s):KP=[s]:WP=s}function vst(){if(WP){var s=WP,t=KP;if(KP=WP=null,K7e(s),t)for(s=0;s>>=0,s===0?32:31-(_Et(s)/wEt|0)|0}var TV=64,EV=4194304;function c7(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 Spe(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=c7(o):(i&=l,i!==0&&(r=c7(i)))}else l=n&~a,l!==0?r=c7(l):i!==0&&(r=c7(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 O$(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-ub(t),s[t]=n}function SEt(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=z7),n9e=" ",r9e=!1;function zst(s,t){switch(s){case"keyup":return eAt.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Bst(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var gP=!1;function sAt(s,t){switch(s){case"compositionend":return Bst(t);case"keypress":return t.which!==32?null:(r9e=!0,n9e);case"textInput":return s=t.data,s===n9e&&r9e?null:s;default:return null}}function nAt(s,t){if(gP)return s==="compositionend"||!LEe&&zst(s,t)?(s=Ost(),yW=MEe=ES=null,gP=!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=l9e(n)}}function Vst(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?Vst(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function Hst(){for(var s=window,t=wpe();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=wpe(s.document)}return t}function DEe(s){var t=s&&s.nodeName&&s.nodeName.toLowerCase();return t&&(t==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||t==="textarea"||s.contentEditable==="true")}function hAt(s){var t=Hst(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&Vst(n.ownerDocument.documentElement,n)){if(r!==null&&DEe(n)){if(t=r.start,s=r.end,s===void 0&&(s=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(s,n.value.length);else if(s=(t=n.ownerDocument||document)&&t.defaultView||window,s.getSelection){s=s.getSelection();var a=n.textContent.length,i=Math.min(r.start,a);r=r.end===void 0?i:Math.min(r.end,a),!s.extend&&i>r&&(a=r,r=i,i=a),a=c9e(n,i);var l=c9e(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,yP=null,uSe=null,$7=null,hSe=!1;function d9e(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;hSe||yP==null||yP!==wpe(r)||(r=yP,"selectionStart"in r&&DEe(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),$7&&Hz($7,r)||($7=r,r=Epe(uSe,"onSelect"),0_P||(s.current=ySe[_P],ySe[_P]=null,_P--)}function bd(s,t){_P++,ySe[_P]=s.current,s.current=t}var S4={},rx=V4(S4),Ug=V4(!1),lM=S4;function h8(s,t){var n=s.type.contextTypes;if(!n)return S4;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 qg(s){return s=s.childContextTypes,s!=null}function Mpe(){Ud(Ug),Ud(rx)}function g9e(s,t,n){if(rx.current!==S4)throw Error(Zr(168));bd(rx,t),bd(Ug,n)}function ent(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(Zr(108,oEt(s)||"Unknown",a));return Hu({},n,r)}function Ipe(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||S4,lM=rx.current,bd(rx,s),bd(Ug,Ug.current),!0}function y9e(s,t,n){var r=s.stateNode;if(!r)throw Error(Zr(169));n?(s=ent(s,t,lM),r.__reactInternalMemoizedMergedChildContext=s,Ud(Ug),Ud(rx),bd(rx,s)):Ud(Ug),bd(Ug,n)}var C2=null,v0e=!1,Ewe=!1;function tnt(s){C2===null?C2=[s]:C2.push(s)}function NAt(s){v0e=!0,tnt(s)}function H4(){if(!Ewe&&C2!==null){Ewe=!0;var s=0,t=Dc;try{var n=C2;for(Dc=1;s>=l,a-=l,D2=1<<32-ub(t)+a|n<M?(F=L,L=null):F=L.sibling;var z=p(j,L,S[M],A);if(z===null){L===null&&(L=F);break}s&&L&&z.alternate===null&&t(j,L),_=i(z,_,M),D===null?T=z:D.sibling=z,D=z,L=F}if(M===S.length)return n(j,L),du&&j3(j,M),T;if(L===null){for(;MM?(F=L,L=null):F=L.sibling;var V=p(j,L,z.value,A);if(V===null){L===null&&(L=F);break}s&&L&&V.alternate===null&&t(j,L),_=i(V,_,M),D===null?T=V:D.sibling=V,D=V,L=F}if(z.done)return n(j,L),du&&j3(j,M),T;if(L===null){for(;!z.done;M++,z=S.next())z=h(j,z.value,A),z!==null&&(_=i(z,_,M),D===null?T=z:D.sibling=z,D=z);return du&&j3(j,M),T}for(L=r(j,L);!z.done;M++,z=S.next())z=f(L,j,M,z.value,A),z!==null&&(s&&z.alternate!==null&&L.delete(z.key===null?M:z.key),_=i(z,_,M),D===null?T=z:D.sibling=z,D=z);return s&&L.forEach(function(W){return t(j,W)}),du&&j3(j,M),T}function v(j,_,S,A){if(typeof S=="object"&&S!==null&&S.type===xP&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case kV:e:{for(var T=S.key,D=_;D!==null;){if(D.key===T){if(T=S.type,T===xP){if(D.tag===7){n(j,D.sibling),_=a(D,S.props.children),_.return=j,j=_;break e}}else if(D.elementType===T||typeof T=="object"&&T!==null&&T.$$typeof===Wk&&_9e(T)===D.type){n(j,D.sibling),_=a(D,S.props),_.ref=XO(j,D,S),_.return=j,j=_;break e}n(j,D);break}else t(j,D);D=D.sibling}S.type===xP?(_=bA(S.props.children,j.mode,A,S.key),_.return=j,j=_):(A=SW(S.type,S.key,S.props,null,j.mode,A),A.ref=XO(j,_,S),A.return=j,j=A)}return l(j);case fP:e:{for(D=S.key;_!==null;){if(_.key===D)if(_.tag===4&&_.stateNode.containerInfo===S.containerInfo&&_.stateNode.implementation===S.implementation){n(j,_.sibling),_=a(_,S.children||[]),_.return=j,j=_;break e}else{n(j,_);break}else t(j,_);_=_.sibling}_=Owe(S,j.mode,A),_.return=j,j=_}return l(j);case Wk:return D=S._init,v(j,_,D(S._payload),A)}if(l7(S))return g(j,_,S,A);if(WO(S))return b(j,_,S,A);RV(j,S)}return typeof S=="string"&&S!==""||typeof S=="number"?(S=""+S,_!==null&&_.tag===6?(n(j,_.sibling),_=a(_,S),_.return=j,j=_):(n(j,_),_=Rwe(S,j.mode,A),_.return=j,j=_),l(j)):n(j,_)}return v}var p8=ant(!0),int=ant(!1),Dpe=V4(null),Rpe=null,NP=null,zEe=null;function BEe(){zEe=NP=Rpe=null}function $Ee(s){var t=Dpe.current;Ud(Dpe),s._currentValue=t}function _Se(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 ZP(s,t){Rpe=s,zEe=NP=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(Og=!0),s.firstContext=null)}function Wv(s){var t=s._currentValue;if(zEe!==s)if(s={context:s,memoizedValue:t,next:null},NP===null){if(Rpe===null)throw Error(Zr(308));NP=s,Rpe.dependencies={lanes:0,firstContext:s}}else NP=NP.next=s;return t}var HE=null;function UEe(s){HE===null?HE=[s]:HE.push(s)}function ont(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,UEe(t)):(n.next=a.next,a.next=n),t.interleaved=n,dN(s,r)}function dN(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 Kk=!1;function qEe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function lnt(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 H2(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function VS(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,ql&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,dN(s,n)}return a=r.interleaved,a===null?(t.next=t,UEe(r)):(t.next=a.next,a.next=t),r.interleaved=t,dN(s,n)}function bW(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,TEe(s,n)}}function w9e(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 Ope(s,t,n,r){var a=s.updateQueue;Kk=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var u=s.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var p=o.lane,f=o.eventTime;if((r&p)===p){u!==null&&(u=u.next={eventTime:f,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var g=s,b=o;switch(p=t,f=n,b.tag){case 1:if(g=b.payload,typeof g=="function"){h=g.call(f,h,p);break e}h=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=b.payload,p=typeof g=="function"?g.call(f,h,p):g,p==null)break e;h=Hu({},h,p);break e;case 2:Kk=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,p=a.effects,p===null?a.effects=[o]:p.push(o))}else f={eventTime:f,lane:p,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=f,c=h):u=u.next=f,l|=p;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;p=o,o=p.next,p.next=null,a.lastBaseUpdate=p,a.shared.pending=null}}while(!0);if(u===null&&(c=h),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=u,t=a.shared.interleaved,t!==null){a=t;do l|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);uM|=l,s.lanes=l,s.memoizedState=h}}function j9e(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=Mwe.transition;Mwe.transition={};try{s(!1),t()}finally{Dc=n,Mwe.transition=r}}function knt(){return Kv().memoizedState}function TAt(s,t,n){var r=GS(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Snt(s))Cnt(t,n);else if(n=ont(s,t,n,r),n!==null){var a=sg();hb(n,s,r,a),Tnt(n,t,r)}}function EAt(s,t,n){var r=GS(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Snt(s))Cnt(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,Cb(o,l)){var c=t.interleaved;c===null?(a.next=a,UEe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=ont(s,t,a,r),n!==null&&(a=sg(),hb(n,s,r,a),Tnt(n,t,r))}}function Snt(s){var t=s.alternate;return s===zu||t!==null&&t===zu}function Cnt(s,t){U7=zpe=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function Tnt(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,TEe(s,n)}}var Bpe={readContext:Wv,useCallback:Vf,useContext:Vf,useEffect:Vf,useImperativeHandle:Vf,useInsertionEffect:Vf,useLayoutEffect:Vf,useMemo:Vf,useReducer:Vf,useRef:Vf,useState:Vf,useDebugValue:Vf,useDeferredValue:Vf,useTransition:Vf,useMutableSource:Vf,useSyncExternalStore:Vf,useId:Vf,unstable_isNewReconciler:!1},AAt={readContext:Wv,useCallback:function(s,t){return z_().memoizedState=[s,t===void 0?null:t],s},useContext:Wv,useEffect:k9e,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,wW(4194308,4,bnt.bind(null,t,s),n)},useLayoutEffect:function(s,t){return wW(4194308,4,s,t)},useInsertionEffect:function(s,t){return wW(4,2,s,t)},useMemo:function(s,t){var n=z_();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=z_();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=TAt.bind(null,zu,s),[r.memoizedState,s]},useRef:function(s){var t=z_();return s={current:s},t.memoizedState=s},useState:N9e,useDebugValue:QEe,useDeferredValue:function(s){return z_().memoizedState=s},useTransition:function(){var s=N9e(!1),t=s[0];return s=CAt.bind(null,s[1]),z_().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=zu,a=z_();if(du){if(n===void 0)throw Error(Zr(407));n=n()}else{if(n=t(),Cp===null)throw Error(Zr(349));dM&30||hnt(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,k9e(pnt.bind(null,r,i,s),[s]),r.flags|=2048,Jz(9,mnt.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=z_(),t=Cp.identifierPrefix;if(du){var n=R2,r=D2;n=(r&~(1<<32-ub(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Qz++,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[J_]=t,s[Kz]=r,Fnt(s,t,!1,!1),t.stateNode=s;e:{switch(l=nSe(n,r),n){case"dialog":Dd("cancel",s),Dd("close",s),a=r;break;case"iframe":case"object":case"embed":Dd("load",s),a=r;break;case"video":case"audio":for(a=0;ag8&&(t.flags|=128,r=!0,JO(i,!1),t.lanes=4194304)}else{if(!r)if(s=Fpe(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),JO(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!du)return Hf(t),null}else 2*Ah()-i.renderingStartTime>g8&&n!==1073741824&&(t.flags|=128,r=!0,JO(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=Ah(),t.sibling=null,n=Mu.current,bd(Mu,r?n&1|2:n&1),t):(Hf(t),null);case 22:case 23:return nAe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?q0&1073741824&&(Hf(t),t.subtreeFlags&6&&(t.flags|=8192)):Hf(t),null;case 24:return null;case 25:return null}throw Error(Zr(156,t.tag))}function FAt(s,t){switch(OEe(t),t.tag){case 1:return qg(t.type)&&Mpe(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return f8(),Ud(Ug),Ud(rx),GEe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return HEe(t),null;case 13:if(Ud(Mu),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(Zr(340));m8()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Ud(Mu),null;case 4:return f8(),null;case 10:return $Ee(t.type._context),null;case 22:case 23:return nAe(),null;case 24:return null;default:return null}}var FV=!1,Qf=!1,zAt=typeof WeakSet=="function"?WeakSet:Set,si=null;function kP(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ah(s,t,r)}else n.current=null}function ASe(s,t,n){try{n()}catch(r){ah(s,t,r)}}var R9e=!1;function BAt(s,t){if(mSe=Cpe,s=Hst(),DEe(s)){if("selectionStart"in s)var n={start:s.selectionStart,end:s.selectionEnd};else e:{n=(n=s.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,d=0,u=0,h=s,p=null;t:for(;;){for(var f;h!==n||a!==0&&h.nodeType!==3||(o=l+a),h!==i||r!==0&&h.nodeType!==3||(c=l+r),h.nodeType===3&&(l+=h.nodeValue.length),(f=h.firstChild)!==null;)p=h,h=f;for(;;){if(h===s)break t;if(p===n&&++d===a&&(o=l),p===i&&++u===r&&(c=l),(f=h.nextSibling)!==null)break;h=p,p=h.parentNode}h=f}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(pSe={focusedElem:s,selectionRange:n},Cpe=!1,si=t;si!==null;)if(t=si,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,si=s;else for(;si!==null;){t=si;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 b=g.memoizedProps,v=g.memoizedState,j=t.stateNode,_=j.getSnapshotBeforeUpdate(t.elementType===t.type?b:G1(t.type,b),v);j.__reactInternalSnapshotBeforeUpdate=_}break;case 3:var S=t.stateNode.containerInfo;S.nodeType===1?S.textContent="":S.nodeType===9&&S.documentElement&&S.removeChild(S.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Zr(163))}}catch(A){ah(t,t.return,A)}if(s=t.sibling,s!==null){s.return=t.return,si=s;break}si=t.return}return g=R9e,R9e=!1,g}function q7(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&&ASe(t,n,i)}a=a.next}while(a!==r)}}function w0e(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 MSe(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 $nt(s){var t=s.alternate;t!==null&&(s.alternate=null,$nt(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[J_],delete t[Kz],delete t[gSe],delete t[wAt],delete t[jAt])),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 Unt(s){return s.tag===5||s.tag===3||s.tag===4}function O9e(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Unt(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 ISe(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=Ape));else if(r!==4&&(s=s.child,s!==null))for(ISe(s,t,n),s=s.sibling;s!==null;)ISe(s,t,n),s=s.sibling}function PSe(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(PSe(s,t,n),s=s.sibling;s!==null;)PSe(s,t,n),s=s.sibling}var ef=null,Y1=!1;function _k(s,t,n){for(n=n.child;n!==null;)qnt(s,t,n),n=n.sibling}function qnt(s,t,n){if(hw&&typeof hw.onCommitFiberUnmount=="function")try{hw.onCommitFiberUnmount(p0e,n)}catch{}switch(n.tag){case 5:Qf||kP(n,t);case 6:var r=ef,a=Y1;ef=null,_k(s,t,n),ef=r,Y1=a,ef!==null&&(Y1?(s=ef,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):ef.removeChild(n.stateNode));break;case 18:ef!==null&&(Y1?(s=ef,n=n.stateNode,s.nodeType===8?Twe(s.parentNode,n):s.nodeType===1&&Twe(s,n),qz(s)):Twe(ef,n.stateNode));break;case 4:r=ef,a=Y1,ef=n.stateNode.containerInfo,Y1=!0,_k(s,t,n),ef=r,Y1=a;break;case 0:case 11:case 14:case 15:if(!Qf&&(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)&&ASe(n,t,l),a=a.next}while(a!==r)}_k(s,t,n);break;case 1:if(!Qf&&(kP(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ah(n,t,o)}_k(s,t,n);break;case 21:_k(s,t,n);break;case 22:n.mode&1?(Qf=(r=Qf)||n.memoizedState!==null,_k(s,t,n),Qf=r):_k(s,t,n);break;default:_k(s,t,n)}}function F9e(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new zAt),t.forEach(function(r){var a=YAt.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function O1(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=Ah()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*UAt(r/1960))-r,10s?16:s,AS===null)var r=!1;else{if(s=AS,AS=null,qpe=0,ql&6)throw Error(Zr(331));var a=ql;for(ql|=4,si=s.current;si!==null;){var i=si,l=i.child;if(si.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cAh()-tAe?vA(s,0):eAe|=n),Vg(s,t)}function Qnt(s,t){t===0&&(s.mode&1?(t=EV,EV<<=1,!(EV&130023424)&&(EV=4194304)):t=1);var n=sg();s=dN(s,t),s!==null&&(O$(s,t,n),Vg(s,n))}function KAt(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),Qnt(s,n)}function YAt(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(Zr(314))}r!==null&&r.delete(t),Qnt(s,n)}var Xnt;Xnt=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||Ug.current)Og=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return Og=!1,RAt(s,t,n);Og=!!(s.flags&131072)}else Og=!1,du&&t.flags&1048576&&snt(t,Lpe,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;jW(s,t),s=t.pendingProps;var a=h8(t,rx.current);ZP(t,n),a=KEe(null,t,r,s,a,n);var i=YEe();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,qg(r)?(i=!0,Ipe(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,qEe(t),a.updater=_0e,t.stateNode=a,a._reactInternals=t,jSe(t,r,s,n),t=SSe(null,t,r,!0,i,n)):(t.tag=0,du&&i&&REe(t),qx(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(jW(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=QAt(r),s=G1(r,s),a){case 0:t=kSe(null,t,r,s,n);break e;case 1:t=P9e(null,t,r,s,n);break e;case 11:t=M9e(null,t,r,s,n);break e;case 14:t=I9e(null,t,r,G1(r.type,s),n);break e}throw Error(Zr(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:G1(r,a),kSe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:G1(r,a),P9e(s,t,r,a,n);case 3:e:{if(Dnt(t),s===null)throw Error(Zr(387));r=t.pendingProps,i=t.memoizedState,a=i.element,lnt(s,t),Ope(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=x8(Error(Zr(423)),t),t=L9e(s,t,r,n,a);break e}else if(r!==a){a=x8(Error(Zr(424)),t),t=L9e(s,t,r,n,a);break e}else for(ty=qS(t.stateNode.containerInfo.firstChild),sy=t,du=!0,tb=null,n=int(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(m8(),r===a){t=uN(s,t,n);break e}qx(s,t,r,n)}t=t.child}return t;case 5:return cnt(t),s===null&&bSe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,fSe(r,a)?l=null:i!==null&&fSe(r,i)&&(t.flags|=32),Lnt(s,t),qx(s,t,l,n),t.child;case 6:return s===null&&bSe(t),null;case 13:return Rnt(s,t,n);case 4:return VEe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=p8(t,null,r,n):qx(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:G1(r,a),M9e(s,t,r,a,n);case 7:return qx(s,t,t.pendingProps,n),t.child;case 8:return qx(s,t,t.pendingProps.children,n),t.child;case 12:return qx(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,bd(Dpe,r._currentValue),r._currentValue=l,i!==null)if(Cb(i.value,l)){if(i.children===a.children&&!Ug.current){t=uN(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=H2(-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),_Se(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(Zr(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),_Se(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}qx(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,ZP(t,n),a=Wv(a),r=r(a),t.flags|=1,qx(s,t,r,n),t.child;case 14:return r=t.type,a=G1(r,t.pendingProps),a=G1(r.type,a),I9e(s,t,r,a,n);case 15:return Int(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:G1(r,a),jW(s,t),t.tag=1,qg(r)?(s=!0,Ipe(t)):s=!1,ZP(t,n),Ent(t,r,a),jSe(t,r,a,n),SSe(null,t,r,!0,s,n);case 19:return Ont(s,t,n);case 22:return Pnt(s,t,n)}throw Error(Zr(156,t.tag))};function Jnt(s,t){return Sst(s,t)}function ZAt(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 Av(s,t,n,r){return new ZAt(s,t,n,r)}function aAe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function QAt(s){if(typeof s=="function")return aAe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===NEe)return 11;if(s===kEe)return 14}return 2}function WS(s,t){var n=s.alternate;return n===null?(n=Av(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 SW(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")aAe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case xP:return bA(n.children,a,i,t);case jEe:l=8,a|=8;break;case Wke:return s=Av(12,n,t,a|2),s.elementType=Wke,s.lanes=i,s;case Kke:return s=Av(13,n,t,a),s.elementType=Kke,s.lanes=i,s;case Yke:return s=Av(19,n,t,a),s.elementType=Yke,s.lanes=i,s;case cst:return N0e(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case ost:l=10;break e;case lst:l=9;break e;case NEe:l=11;break e;case kEe:l=14;break e;case Wk:l=16,r=null;break e}throw Error(Zr(130,s==null?s:typeof s,""))}return t=Av(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function bA(s,t,n,r){return s=Av(7,s,r,t),s.lanes=n,s}function N0e(s,t,n,r){return s=Av(22,s,r,t),s.elementType=cst,s.lanes=n,s.stateNode={isHidden:!1},s}function Rwe(s,t,n){return s=Av(6,s,null,t),s.lanes=n,s}function Owe(s,t,n){return t=Av(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function XAt(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=gwe(0),this.expirationTimes=gwe(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=gwe(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function iAe(s,t,n,r,a,i,l,o,c){return s=new XAt(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Av(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},qEe(i),s}function JAt(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(nrt)}catch(s){console.error(s)}}nrt(),nst.exports=ky;var Gx=nst.exports;const dAe=jl(Gx);var rrt,G9e=Gx;rrt=G9e.createRoot,G9e.hydrateRoot;const rMt=1,aMt=1e6;let Fwe=0;function iMt(){return Fwe=(Fwe+1)%Number.MAX_SAFE_INTEGER,Fwe.toString()}const zwe=new Map,W9e=s=>{if(zwe.has(s))return;const t=setTimeout(()=>{zwe.delete(s),G7({type:"REMOVE_TOAST",toastId:s})},aMt);zwe.set(s,t)},oMt=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,rMt)};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?W9e(n):s.toasts.forEach(r=>{W9e(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)}}},CW=[];let TW={toasts:[]};function G7(s){TW=oMt(TW,s),CW.forEach(t=>{t(TW)})}function Dr({...s}){const t=iMt(),n=a=>G7({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>G7({type:"DISMISS_TOAST",toastId:t});return G7({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function Ua(){const[s,t]=N.useState(TW);return N.useEffect(()=>(CW.push(t),()=>{const n=CW.indexOf(t);n>-1&&CW.splice(n,1)}),[s]),{...s,toast:Dr,dismiss:n=>G7({type:"DISMISS_TOAST",toastId:n})}}function wr(s,t,{checkForDefaultPrevented:n=!0}={}){return function(a){if(s==null||s(a),n===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}function K9e(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function hN(...s){return t=>{let n=!1;const r=s.map(a=>{const i=K9e(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{children:l,...o}=i,c=N.useMemo(()=>o,Object.values(o));return e.jsx(n.Provider,{value:c,children:l})};r.displayName=s+"Provider";function a(i){const l=N.useContext(n);if(l)return l;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${s}\``)}return[r,a]}function gu(s,t=[]){let n=[];function r(i,l){const o=N.createContext(l),c=n.length;n=[...n,l];const d=h=>{var j;const{scope:p,children:f,...g}=h,b=((j=p==null?void 0:p[s])==null?void 0:j[c])||o,v=N.useMemo(()=>g,Object.values(g));return e.jsx(b.Provider,{value:v,children:f})};d.displayName=i+"Provider";function u(h,p){var b;const f=((b=p==null?void 0:p[s])==null?void 0:b[c])||o,g=N.useContext(f);if(g)return g;if(l!==void 0)return l;throw new Error(`\`${h}\` must be used within \`${i}\``)}return[d,u]}const a=()=>{const i=n.map(l=>N.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return N.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[r,cMt(a,...t)]}function cMt(...s){const t=s[0];if(s.length===1)return t;const n=()=>{const r=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const l=r.reduce((o,{useScope:c,scopeName:d})=>{const h=c(i)[`__scope${d}`];return{...o,...h}},{});return N.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return n.scopeName=t.scopeName,n}function C4(s){const t=dMt(s),n=N.forwardRef((r,a)=>{const{children:i,...l}=r,o=N.Children.toArray(i),c=o.find(uMt);if(c){const d=c.props.children,u=o.map(h=>h===c?N.Children.count(d)>1?N.Children.only(null):N.isValidElement(d)?d.props.children:null:h);return e.jsx(t,{...l,ref:a,children:N.isValidElement(d)?N.cloneElement(d,void 0,u):null})}return e.jsx(t,{...l,ref:a,children:i})});return n.displayName=`${s}.Slot`,n}var uAe=C4("Slot");function dMt(s){const t=N.forwardRef((n,r)=>{const{children:a,...i}=n;if(N.isValidElement(a)){const l=mMt(a),o=hMt(i,a.props);return a.type!==N.Fragment&&(o.ref=r?hN(r,l):l),N.cloneElement(a,o)}return N.Children.count(a)>1?N.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var art=Symbol("radix.slottable");function irt(s){const t=({children:n})=>e.jsx(e.Fragment,{children:n});return t.displayName=`${s}.Slottable`,t.__radixId=art,t}function uMt(s){return N.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===art}function hMt(s,t){const n={...t};for(const r in t){const a=s[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?n[r]=(...o)=>{const c=i(...o);return a(...o),c}:a&&(n[r]=a):r==="style"?n[r]={...a,...i}:r==="className"&&(n[r]=[a,i].filter(Boolean).join(" "))}return{...s,...n}}function mMt(s){var r,a;let t=(r=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?s.props.ref:s.props.ref||s.ref)}function MD(s){const t=s+"CollectionProvider",[n,r]=gu(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=b=>{const{scope:v,children:j}=b,_=Nt.useRef(null),S=Nt.useRef(new Map).current;return e.jsx(a,{scope:v,itemMap:S,collectionRef:_,children:j})};l.displayName=t;const o=s+"CollectionSlot",c=C4(o),d=Nt.forwardRef((b,v)=>{const{scope:j,children:_}=b,S=i(o,j),A=Ti(v,S.collectionRef);return e.jsx(c,{ref:A,children:_})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",p=C4(u),f=Nt.forwardRef((b,v)=>{const{scope:j,children:_,...S}=b,A=Nt.useRef(null),T=Ti(v,A),D=i(u,j);return Nt.useEffect(()=>(D.itemMap.set(A,{ref:A,...S}),()=>void D.itemMap.delete(A))),e.jsx(p,{[h]:"",ref:T,children:_})});f.displayName=u;function g(b){const v=i(s+"CollectionConsumer",b);return Nt.useCallback(()=>{const _=v.collectionRef.current;if(!_)return[];const S=Array.from(_.querySelectorAll(`[${h}]`));return Array.from(v.itemMap.values()).sort((D,L)=>S.indexOf(D.ref.current)-S.indexOf(L.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:l,Slot:d,ItemSlot:f},g,r]}var pMt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],sa=pMt.reduce((s,t)=>{const n=C4(`Primitive.${t}`),r=N.forwardRef((a,i)=>{const{asChild:l,...o}=a,c=l?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(c,{...o,ref:i})});return r.displayName=`Primitive.${t}`,{...s,[t]:r}},{});function hAe(s,t){s&&Gx.flushSync(()=>s.dispatchEvent(t))}function dh(s){const t=N.useRef(s);return N.useEffect(()=>{t.current=s}),N.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function fMt(s,t=globalThis==null?void 0:globalThis.document){const n=dh(s);N.useEffect(()=>{const r=a=>{a.key==="Escape"&&n(a)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var xMt="DismissableLayer",FSe="dismissableLayer.update",gMt="dismissableLayer.pointerDownOutside",yMt="dismissableLayer.focusOutside",Y9e,ort=N.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),G4=N.forwardRef((s,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=N.useContext(ort),[u,h]=N.useState(null),p=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=N.useState({}),g=Ti(t,L=>h(L)),b=Array.from(d.layers),[v]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),j=b.indexOf(v),_=u?b.indexOf(u):-1,S=d.layersWithOutsidePointerEventsDisabled.size>0,A=_>=j,T=bMt(L=>{const M=L.target,F=[...d.branches].some(z=>z.contains(M));!A||F||(a==null||a(L),l==null||l(L),L.defaultPrevented||o==null||o())},p),D=_Mt(L=>{const M=L.target;[...d.branches].some(z=>z.contains(M))||(i==null||i(L),l==null||l(L),L.defaultPrevented||o==null||o())},p);return fMt(L=>{_===d.layers.size-1&&(r==null||r(L),!L.defaultPrevented&&o&&(L.preventDefault(),o()))},p),N.useEffect(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Y9e=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),Z9e(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=Y9e)}},[u,p,n,d]),N.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),Z9e())},[u,d]),N.useEffect(()=>{const L=()=>f({});return document.addEventListener(FSe,L),()=>document.removeEventListener(FSe,L)},[]),e.jsx(sa.div,{...c,ref:g,style:{pointerEvents:S?A?"auto":"none":void 0,...s.style},onFocusCapture:wr(s.onFocusCapture,D.onFocusCapture),onBlurCapture:wr(s.onBlurCapture,D.onBlurCapture),onPointerDownCapture:wr(s.onPointerDownCapture,T.onPointerDownCapture)})});G4.displayName=xMt;var vMt="DismissableLayerBranch",lrt=N.forwardRef((s,t)=>{const n=N.useContext(ort),r=N.useRef(null),a=Ti(t,r);return N.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),e.jsx(sa.div,{...s,ref:a})});lrt.displayName=vMt;function bMt(s,t=globalThis==null?void 0:globalThis.document){const n=dh(s),r=N.useRef(!1),a=N.useRef(()=>{});return N.useEffect(()=>{const i=o=>{if(o.target&&!r.current){let c=function(){crt(gMt,n,d,{discrete:!0})};const d={originalEvent:o};o.pointerType==="touch"?(t.removeEventListener("click",a.current),a.current=c,t.addEventListener("click",a.current,{once:!0})):c()}else t.removeEventListener("click",a.current);r.current=!1},l=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(l),t.removeEventListener("pointerdown",i),t.removeEventListener("click",a.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function _Mt(s,t=globalThis==null?void 0:globalThis.document){const n=dh(s),r=N.useRef(!1);return N.useEffect(()=>{const a=i=>{i.target&&!r.current&&crt(yMt,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Z9e(){const s=new CustomEvent(FSe);document.dispatchEvent(s)}function crt(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?hAe(a,i):a.dispatchEvent(i)}var wMt=G4,jMt=lrt,fh=globalThis!=null&&globalThis.document?N.useLayoutEffect:()=>{},NMt="Portal",ID=N.forwardRef((s,t)=>{var o;const{container:n,...r}=s,[a,i]=N.useState(!1);fh(()=>i(!0),[]);const l=n||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?dAe.createPortal(e.jsx(sa.div,{...r,ref:t}),l):null});ID.displayName=NMt;function kMt(s,t){return N.useReducer((n,r)=>t[n][r]??n,s)}var Bh=s=>{const{present:t,children:n}=s,r=SMt(t),a=typeof n=="function"?n({present:r.isPresent}):N.Children.only(n),i=Ti(r.ref,CMt(a));return typeof n=="function"||r.isPresent?N.cloneElement(a,{ref:i}):null};Bh.displayName="Presence";function SMt(s){const[t,n]=N.useState(),r=N.useRef(null),a=N.useRef(s),i=N.useRef("none"),l=s?"mounted":"unmounted",[o,c]=kMt(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return N.useEffect(()=>{const d=$V(r.current);i.current=o==="mounted"?d:"none"},[o]),fh(()=>{const d=r.current,u=a.current;if(u!==s){const p=i.current,f=$V(d);s?c("MOUNT"):f==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),fh(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,h=f=>{const b=$V(r.current).includes(f.animationName);if(f.target===t&&b&&(c("ANIMATION_END"),!a.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},p=f=>{f.target===t&&(i.current=$V(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:N.useCallback(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function $V(s){return(s==null?void 0:s.animationName)||"none"}function CMt(s){var r,a;let t=(r=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?s.props.ref:s.props.ref||s.ref)}var TMt=vEe[" useInsertionEffect ".trim().toString()]||fh;function mm({prop:s,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,i,l]=EMt({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a;{const u=N.useRef(s!==void 0);N.useEffect(()=>{const h=u.current;h!==o&&console.warn(`${r} is changing from ${h?"controlled":"uncontrolled"} to ${o?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=o},[o,r])}const d=N.useCallback(u=>{var h;if(o){const p=AMt(u)?u(s):u;p!==s&&((h=l.current)==null||h.call(l,p))}else i(u)},[o,s,i,l]);return[c,d]}function EMt({defaultProp:s,onChange:t}){const[n,r]=N.useState(s),a=N.useRef(n),i=N.useRef(t);return TMt(()=>{i.current=t},[t]),N.useEffect(()=>{var l;a.current!==n&&((l=i.current)==null||l.call(i,n),a.current=n)},[n,a]),[n,r,i]}function AMt(s){return typeof s=="function"}var drt=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"}),MMt="VisuallyHidden",E0e=N.forwardRef((s,t)=>e.jsx(sa.span,{...s,ref:t,style:{...drt,...s.style}}));E0e.displayName=MMt;var IMt=E0e,mAe="ToastProvider",[pAe,PMt,LMt]=MD("Toast"),[urt,wxn]=gu("Toast",[LMt]),[DMt,A0e]=urt(mAe),hrt=s=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=N.useState(null),[d,u]=N.useState(0),h=N.useRef(!1),p=N.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${mAe}\`. Expected non-empty \`string\`.`),e.jsx(pAe.Provider,{scope:t,children:e.jsx(DMt,{scope:t,label:n,duration:r,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:N.useCallback(()=>u(f=>f+1),[]),onToastRemove:N.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:p,children:l})})};hrt.displayName=mAe;var mrt="ToastViewport",RMt=["F8"],zSe="toast.viewportPause",BSe="toast.viewportResume",prt=N.forwardRef((s,t)=>{const{__scopeToast:n,hotkey:r=RMt,label:a="Notifications ({hotkey})",...i}=s,l=A0e(mrt,n),o=PMt(n),c=N.useRef(null),d=N.useRef(null),u=N.useRef(null),h=N.useRef(null),p=Ti(t,h,l.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=l.toastCount>0;N.useEffect(()=>{const v=j=>{var S;r.length!==0&&r.every(A=>j[A]||j.code===A)&&((S=h.current)==null||S.focus())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),N.useEffect(()=>{const v=c.current,j=h.current;if(g&&v&&j){const _=()=>{if(!l.isClosePausedRef.current){const D=new CustomEvent(zSe);j.dispatchEvent(D),l.isClosePausedRef.current=!0}},S=()=>{if(l.isClosePausedRef.current){const D=new CustomEvent(BSe);j.dispatchEvent(D),l.isClosePausedRef.current=!1}},A=D=>{!v.contains(D.relatedTarget)&&S()},T=()=>{v.contains(document.activeElement)||S()};return v.addEventListener("focusin",_),v.addEventListener("focusout",A),v.addEventListener("pointermove",_),v.addEventListener("pointerleave",T),window.addEventListener("blur",_),window.addEventListener("focus",S),()=>{v.removeEventListener("focusin",_),v.removeEventListener("focusout",A),v.removeEventListener("pointermove",_),v.removeEventListener("pointerleave",T),window.removeEventListener("blur",_),window.removeEventListener("focus",S)}}},[g,l.isClosePausedRef]);const b=N.useCallback(({tabbingDirection:v})=>{const _=o().map(S=>{const A=S.ref.current,T=[A,...YMt(A)];return v==="forwards"?T:T.reverse()});return(v==="forwards"?_.reverse():_).flat()},[o]);return N.useEffect(()=>{const v=h.current;if(v){const j=_=>{var T,D,L;const S=_.altKey||_.ctrlKey||_.metaKey;if(_.key==="Tab"&&!S){const M=document.activeElement,F=_.shiftKey;if(_.target===v&&F){(T=d.current)==null||T.focus();return}const W=b({tabbingDirection:F?"backwards":"forwards"}),K=W.findIndex(Y=>Y===M);Bwe(W.slice(K+1))?_.preventDefault():F?(D=d.current)==null||D.focus():(L=u.current)==null||L.focus()}};return v.addEventListener("keydown",j),()=>v.removeEventListener("keydown",j)}},[o,b]),e.jsxs(jMt,{ref:c,role:"region","aria-label":a.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&e.jsx($Se,{ref:d,onFocusFromOutsideViewport:()=>{const v=b({tabbingDirection:"forwards"});Bwe(v)}}),e.jsx(pAe.Slot,{scope:n,children:e.jsx(sa.ol,{tabIndex:-1,...i,ref:p})}),g&&e.jsx($Se,{ref:u,onFocusFromOutsideViewport:()=>{const v=b({tabbingDirection:"backwards"});Bwe(v)}})]})});prt.displayName=mrt;var frt="ToastFocusProxy",$Se=N.forwardRef((s,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...a}=s,i=A0e(frt,n);return e.jsx(E0e,{"aria-hidden":!0,tabIndex:0,...a,ref:t,style:{position:"fixed"},onFocus:l=>{var d;const o=l.relatedTarget;!((d=i.viewport)!=null&&d.contains(o))&&r()}})});$Se.displayName=frt;var $$="Toast",OMt="toast.swipeStart",FMt="toast.swipeMove",zMt="toast.swipeCancel",BMt="toast.swipeEnd",xrt=N.forwardRef((s,t)=>{const{forceMount:n,open:r,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=mm({prop:r,defaultProp:a??!0,onChange:i,caller:$$});return e.jsx(Bh,{present:n||o,children:e.jsx(qMt,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:dh(s.onPause),onResume:dh(s.onResume),onSwipeStart:wr(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:wr(s.onSwipeMove,d=>{const{x:u,y:h}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${h}px`)}),onSwipeCancel:wr(s.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:wr(s.onSwipeEnd,d=>{const{x:u,y:h}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${h}px`),c(!1)})})})});xrt.displayName=$$;var[$Mt,UMt]=urt($$,{onClose(){}}),qMt=N.forwardRef((s,t)=>{const{__scopeToast:n,type:r="foreground",duration:a,open:i,onClose:l,onEscapeKeyDown:o,onPause:c,onResume:d,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:p,onSwipeEnd:f,...g}=s,b=A0e($$,n),[v,j]=N.useState(null),_=Ti(t,Y=>j(Y)),S=N.useRef(null),A=N.useRef(null),T=a||b.duration,D=N.useRef(0),L=N.useRef(T),M=N.useRef(0),{onToastAdd:F,onToastRemove:z}=b,V=dh(()=>{var ee;(v==null?void 0:v.contains(document.activeElement))&&((ee=b.viewport)==null||ee.focus()),l()}),W=N.useCallback(Y=>{!Y||Y===1/0||(window.clearTimeout(M.current),D.current=new Date().getTime(),M.current=window.setTimeout(V,Y))},[V]);N.useEffect(()=>{const Y=b.viewport;if(Y){const ee=()=>{W(L.current),d==null||d()},ne=()=>{const oe=new Date().getTime()-D.current;L.current=L.current-oe,window.clearTimeout(M.current),c==null||c()};return Y.addEventListener(zSe,ne),Y.addEventListener(BSe,ee),()=>{Y.removeEventListener(zSe,ne),Y.removeEventListener(BSe,ee)}}},[b.viewport,T,c,d,W]),N.useEffect(()=>{i&&!b.isClosePausedRef.current&&W(T)},[i,T,b.isClosePausedRef,W]),N.useEffect(()=>(F(),()=>z()),[F,z]);const K=N.useMemo(()=>v?jrt(v):null,[v]);return b.viewport?e.jsxs(e.Fragment,{children:[K&&e.jsx(VMt,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:K}),e.jsx($Mt,{scope:n,onClose:V,children:Gx.createPortal(e.jsx(pAe.ItemSlot,{scope:n,children:e.jsx(wMt,{asChild:!0,onEscapeKeyDown:wr(o,()=>{b.isFocusedToastEscapeKeyDownRef.current||V(),b.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(sa.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":b.swipeDirection,...g,ref:_,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:wr(s.onKeyDown,Y=>{Y.key==="Escape"&&(o==null||o(Y.nativeEvent),Y.nativeEvent.defaultPrevented||(b.isFocusedToastEscapeKeyDownRef.current=!0,V()))}),onPointerDown:wr(s.onPointerDown,Y=>{Y.button===0&&(S.current={x:Y.clientX,y:Y.clientY})}),onPointerMove:wr(s.onPointerMove,Y=>{if(!S.current)return;const ee=Y.clientX-S.current.x,ne=Y.clientY-S.current.y,oe=!!A.current,pe=["left","right"].includes(b.swipeDirection),ce=["left","up"].includes(b.swipeDirection)?Math.min:Math.max,de=pe?ce(0,ee):0,ie=pe?0:ce(0,ne),ye=Y.pointerType==="touch"?10:2,_e={x:de,y:ie},Me={originalEvent:Y,delta:_e};oe?(A.current=_e,UV(FMt,h,Me,{discrete:!1})):Q9e(_e,b.swipeDirection,ye)?(A.current=_e,UV(OMt,u,Me,{discrete:!1}),Y.target.setPointerCapture(Y.pointerId)):(Math.abs(ee)>ye||Math.abs(ne)>ye)&&(S.current=null)}),onPointerUp:wr(s.onPointerUp,Y=>{const ee=A.current,ne=Y.target;if(ne.hasPointerCapture(Y.pointerId)&&ne.releasePointerCapture(Y.pointerId),A.current=null,S.current=null,ee){const oe=Y.currentTarget,pe={originalEvent:Y,delta:ee};Q9e(ee,b.swipeDirection,b.swipeThreshold)?UV(BMt,f,pe,{discrete:!0}):UV(zMt,p,pe,{discrete:!0}),oe.addEventListener("click",ce=>ce.preventDefault(),{once:!0})}})})})}),b.viewport)})]}):null}),VMt=s=>{const{__scopeToast:t,children:n,...r}=s,a=A0e($$,t),[i,l]=N.useState(!1),[o,c]=N.useState(!1);return WMt(()=>l(!0)),N.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(ID,{asChild:!0,children:e.jsx(E0e,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},HMt="ToastTitle",grt=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(sa.div,{...r,ref:t})});grt.displayName=HMt;var GMt="ToastDescription",yrt=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(sa.div,{...r,ref:t})});yrt.displayName=GMt;var vrt="ToastAction",brt=N.forwardRef((s,t)=>{const{altText:n,...r}=s;return n.trim()?e.jsx(wrt,{altText:n,asChild:!0,children:e.jsx(fAe,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${vrt}\`. Expected non-empty \`string\`.`),null)});brt.displayName=vrt;var _rt="ToastClose",fAe=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s,a=UMt(_rt,n);return e.jsx(wrt,{asChild:!0,children:e.jsx(sa.button,{type:"button",...r,ref:t,onClick:wr(s.onClick,a.onClose)})})});fAe.displayName=_rt;var wrt=N.forwardRef((s,t)=>{const{__scopeToast:n,altText:r,...a}=s;return e.jsx(sa.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...a,ref:t})});function jrt(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),KMt(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(...jrt(r))}}),t}function UV(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?hAe(a,i):a.dispatchEvent(i)}var Q9e=(s,t,n=0)=>{const r=Math.abs(s.x),a=Math.abs(s.y),i=r>a;return t==="left"||t==="right"?i&&r>n:!i&&a>n};function WMt(s=()=>{}){const t=dh(s);fh(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function KMt(s){return s.nodeType===s.ELEMENT_NODE}function YMt(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Bwe(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var ZMt=hrt,Nrt=prt,krt=xrt,Srt=grt,Crt=yrt,Trt=brt,Ert=fAe;function Art(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,J9e=So,qM=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return J9e(s,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:a,defaultVariants:i}=t,l=Object.keys(a).map(d=>{const u=n==null?void 0:n[d],h=i==null?void 0:i[d];if(u===null)return null;const p=X9e(u)||X9e(h);return a[d][p]}),o=n&&Object.entries(n).reduce((d,u)=>{let[h,p]=u;return p===void 0||(d[h]=p),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:h,className:p,...f}=u;return Object.entries(f).every(g=>{let[b,v]=g;return Array.isArray(v)?v.includes({...i,...o}[b]):{...i,...o}[b]===v})?[...d,h,p]:d},[]);return J9e(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 QMt=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Mrt=(...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 XMt={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 Irt=N.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>N.createElement("svg",{ref:c,...XMt,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:Mrt("lucide",a),...o},[...l.map(([d,u])=>N.createElement(d,u)),...Array.isArray(i)?i:[i]]));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const re=(s,t)=>{const n=N.forwardRef(({className:r,...a},i)=>N.createElement(Irt,{ref:i,iconNode:t,className:Mrt(`lucide-${QMt(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 EW=re("AArrowDown",[["path",{d:"M3.5 13h6",key:"p1my2r"}],["path",{d:"m2 16 4.5-9 4.5 9",key:"ndf0b3"}],["path",{d:"M18 7v9",key:"pknjwm"}],["path",{d:"m14 12 4 4 4-4",key:"buelq4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AW=re("AArrowUp",[["path",{d:"M3.5 13h6",key:"p1my2r"}],["path",{d:"m2 16 4.5-9 4.5 9",key:"ndf0b3"}],["path",{d:"M18 16V7",key:"ty0viw"}],["path",{d:"m14 11 4-4 4 4",key:"1pu57t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MW=re("ALargeSmall",[["path",{d:"M21 14h-5",key:"1vh23k"}],["path",{d:"M16 16v-3.5a2.5 2.5 0 0 1 5 0V16",key:"1wh10o"}],["path",{d:"M4.5 13h6",key:"dfilno"}],["path",{d:"m3 16 4.5-9 4.5 9",key:"2dxa0e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IW=re("Accessibility",[["circle",{cx:"16",cy:"4",r:"1",key:"1grugj"}],["path",{d:"m18 19 1-7-6 1",key:"r0i19z"}],["path",{d:"m5 8 3-3 5.5 3-2.36 3.5",key:"9ptxx2"}],["path",{d:"M4.24 14.5a5 5 0 0 0 6.88 6",key:"10kmtu"}],["path",{d:"M13.76 17.5a5 5 0 0 0-6.88-6",key:"2qq6rc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const am=re("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PW=re("AirVent",[["path",{d:"M6 12H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"larmp2"}],["path",{d:"M6 8h12",key:"6g4wlu"}],["path",{d:"M18.3 17.7a2.5 2.5 0 0 1-3.16 3.83 2.53 2.53 0 0 1-1.14-2V12",key:"1bo8pg"}],["path",{d:"M6.6 15.6A2 2 0 1 0 10 17v-5",key:"t9h90c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LW=re("Airplay",[["path",{d:"M5 17H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-1",key:"ns4c3b"}],["path",{d:"m12 15 5 6H7Z",key:"14qnn2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k3=re("AlarmClockCheck",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}],["path",{d:"m9 13 2 2 4-4",key:"6343dt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S3=re("AlarmClockMinus",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}],["path",{d:"M9 13h6",key:"1uhe8q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DW=re("AlarmClockOff",[["path",{d:"M6.87 6.87a8 8 0 1 0 11.26 11.26",key:"3on8tj"}],["path",{d:"M19.9 14.25a8 8 0 0 0-9.15-9.15",key:"15ghsc"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.26 18.67 4 21",key:"yzmioq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M4 4 2 6",key:"1ycko6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C3=re("AlarmClockPlus",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RW=re("AlarmClock",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M12 9v4l2 2",key:"1c63tq"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OW=re("AlarmSmoke",[["path",{d:"M11 21c0-2.5 2-2.5 2-5",key:"1sicvv"}],["path",{d:"M16 21c0-2.5 2-2.5 2-5",key:"1o3eny"}],["path",{d:"m19 8-.8 3a1.25 1.25 0 0 1-1.2 1H7a1.25 1.25 0 0 1-1.2-1L5 8",key:"1bvca4"}],["path",{d:"M21 3a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V4a1 1 0 0 1 1-1z",key:"x3qr1j"}],["path",{d:"M6 21c0-2.5 2-2.5 2-5",key:"i3w1gp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FW=re("Album",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["polyline",{points:"11 3 11 11 14 8 17 11 17 3",key:"1wcwz3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zW=re("AlignCenterHorizontal",[["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M10 16v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-4",key:"11f1s0"}],["path",{d:"M10 8V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v4",key:"t14dx9"}],["path",{d:"M20 16v1a2 2 0 0 1-2 2h-2a2 2 0 0 1-2-2v-1",key:"1w07xs"}],["path",{d:"M14 8V7c0-1.1.9-2 2-2h2a2 2 0 0 1 2 2v1",key:"1apec2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BW=re("AlignCenterVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"M8 10H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2h4",key:"14d6g8"}],["path",{d:"M16 10h4a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-4",key:"1e2lrw"}],["path",{d:"M8 20H7a2 2 0 0 1-2-2v-2c0-1.1.9-2 2-2h1",key:"1fkdwx"}],["path",{d:"M16 14h1a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-1",key:"1euafb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _A=re("AlignCenter",[["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 18H5",key:"18s9l3"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $W=re("AlignEndHorizontal",[["rect",{width:"6",height:"16",x:"4",y:"2",rx:"2",key:"z5wdxg"}],["rect",{width:"6",height:"9",x:"14",y:"9",rx:"2",key:"um7a8w"}],["path",{d:"M22 22H2",key:"19qnx5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UW=re("AlignEndVertical",[["rect",{width:"16",height:"6",x:"2",y:"4",rx:"2",key:"10wcwx"}],["rect",{width:"9",height:"6",x:"9",y:"14",rx:"2",key:"4p5bwg"}],["path",{d:"M22 22V2",key:"12ipfv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qW=re("AlignHorizontalDistributeCenter",[["rect",{width:"6",height:"14",x:"4",y:"5",rx:"2",key:"1wwnby"}],["rect",{width:"6",height:"10",x:"14",y:"7",rx:"2",key:"1fe6j6"}],["path",{d:"M17 22v-5",key:"4b6g73"}],["path",{d:"M17 7V2",key:"hnrr36"}],["path",{d:"M7 22v-3",key:"1r4jpn"}],["path",{d:"M7 5V2",key:"liy1u9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VW=re("AlignHorizontalDistributeEnd",[["rect",{width:"6",height:"14",x:"4",y:"5",rx:"2",key:"1wwnby"}],["rect",{width:"6",height:"10",x:"14",y:"7",rx:"2",key:"1fe6j6"}],["path",{d:"M10 2v20",key:"uyc634"}],["path",{d:"M20 2v20",key:"1tx262"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HW=re("AlignHorizontalDistributeStart",[["rect",{width:"6",height:"14",x:"4",y:"5",rx:"2",key:"1wwnby"}],["rect",{width:"6",height:"10",x:"14",y:"7",rx:"2",key:"1fe6j6"}],["path",{d:"M4 2v20",key:"gtpd5x"}],["path",{d:"M14 2v20",key:"tg6bpw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GW=re("AlignHorizontalJustifyCenter",[["rect",{width:"6",height:"14",x:"2",y:"5",rx:"2",key:"dy24zr"}],["rect",{width:"6",height:"10",x:"16",y:"7",rx:"2",key:"13zkjt"}],["path",{d:"M12 2v20",key:"t6zp3m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WW=re("AlignHorizontalJustifyEnd",[["rect",{width:"6",height:"14",x:"2",y:"5",rx:"2",key:"dy24zr"}],["rect",{width:"6",height:"10",x:"12",y:"7",rx:"2",key:"1ht384"}],["path",{d:"M22 2v20",key:"40qfg1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KW=re("AlignHorizontalJustifyStart",[["rect",{width:"6",height:"14",x:"6",y:"5",rx:"2",key:"hsirpf"}],["rect",{width:"6",height:"10",x:"16",y:"7",rx:"2",key:"13zkjt"}],["path",{d:"M2 2v20",key:"1ivd8o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YW=re("AlignHorizontalSpaceAround",[["rect",{width:"6",height:"10",x:"9",y:"7",rx:"2",key:"yn7j0q"}],["path",{d:"M4 22V2",key:"tsjzd3"}],["path",{d:"M20 22V2",key:"1bnhr8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZW=re("AlignHorizontalSpaceBetween",[["rect",{width:"6",height:"14",x:"3",y:"5",rx:"2",key:"j77dae"}],["rect",{width:"6",height:"10",x:"15",y:"7",rx:"2",key:"bq30hj"}],["path",{d:"M3 2v20",key:"1d2pfg"}],["path",{d:"M21 2v20",key:"p059bm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QW=re("AlignJustify",[["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 18h18",key:"1h113x"}],["path",{d:"M3 6h18",key:"d0wm0j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wA=re("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jA=re("AlignRight",[["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 18H7",key:"1ygte8"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XW=re("AlignStartHorizontal",[["rect",{width:"6",height:"16",x:"4",y:"6",rx:"2",key:"1n4dg1"}],["rect",{width:"6",height:"9",x:"14",y:"6",rx:"2",key:"17khns"}],["path",{d:"M22 2H2",key:"fhrpnj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JW=re("AlignStartVertical",[["rect",{width:"9",height:"6",x:"6",y:"14",rx:"2",key:"lpm2y7"}],["rect",{width:"16",height:"6",x:"6",y:"4",rx:"2",key:"rdj6ps"}],["path",{d:"M2 2v20",key:"1ivd8o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eK=re("AlignVerticalDistributeCenter",[["path",{d:"M22 17h-3",key:"1lwga1"}],["path",{d:"M22 7h-5",key:"o2endc"}],["path",{d:"M5 17H2",key:"1gx9xc"}],["path",{d:"M7 7H2",key:"6bq26l"}],["rect",{x:"5",y:"14",width:"14",height:"6",rx:"2",key:"1qrzuf"}],["rect",{x:"7",y:"4",width:"10",height:"6",rx:"2",key:"we8e9z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tK=re("AlignVerticalDistributeEnd",[["rect",{width:"14",height:"6",x:"5",y:"14",rx:"2",key:"jmoj9s"}],["rect",{width:"10",height:"6",x:"7",y:"4",rx:"2",key:"aza5on"}],["path",{d:"M2 20h20",key:"owomy5"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sK=re("AlignVerticalDistributeStart",[["rect",{width:"14",height:"6",x:"5",y:"14",rx:"2",key:"jmoj9s"}],["rect",{width:"10",height:"6",x:"7",y:"4",rx:"2",key:"aza5on"}],["path",{d:"M2 14h20",key:"myj16y"}],["path",{d:"M2 4h20",key:"mda7wb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nK=re("AlignVerticalJustifyCenter",[["rect",{width:"14",height:"6",x:"5",y:"16",rx:"2",key:"1i8z2d"}],["rect",{width:"10",height:"6",x:"7",y:"2",rx:"2",key:"ypihtt"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rK=re("AlignVerticalJustifyEnd",[["rect",{width:"14",height:"6",x:"5",y:"12",rx:"2",key:"4l4tp2"}],["rect",{width:"10",height:"6",x:"7",y:"2",rx:"2",key:"ypihtt"}],["path",{d:"M2 22h20",key:"272qi7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aK=re("AlignVerticalJustifyStart",[["rect",{width:"14",height:"6",x:"5",y:"16",rx:"2",key:"1i8z2d"}],["rect",{width:"10",height:"6",x:"7",y:"6",rx:"2",key:"13squh"}],["path",{d:"M2 2h20",key:"1ennik"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iK=re("AlignVerticalSpaceAround",[["rect",{width:"10",height:"6",x:"7",y:"9",rx:"2",key:"b1zbii"}],["path",{d:"M22 20H2",key:"1p1f7z"}],["path",{d:"M22 4H2",key:"1b7qnq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oK=re("AlignVerticalSpaceBetween",[["rect",{width:"14",height:"6",x:"5",y:"15",rx:"2",key:"1w91an"}],["rect",{width:"10",height:"6",x:"7",y:"3",rx:"2",key:"17wqzy"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M2 3h20",key:"91anmk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lK=re("Ambulance",[["path",{d:"M10 10H6",key:"1bsnug"}],["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.28a1 1 0 0 0-.684-.948l-1.923-.641a1 1 0 0 1-.578-.502l-1.539-3.076A1 1 0 0 0 16.382 8H14",key:"lrkjwd"}],["path",{d:"M8 8v4",key:"1fwk8c"}],["path",{d:"M9 18h6",key:"x1upvd"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cK=re("Ampersand",[["path",{d:"M17.5 12c0 4.4-3.6 8-8 8A4.5 4.5 0 0 1 5 15.5c0-6 8-4 8-8.5a3 3 0 1 0-6 0c0 3 2.5 8.5 12 13",key:"1o9ehi"}],["path",{d:"M16 12h3",key:"4uvgyw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dK=re("Ampersands",[["path",{d:"M10 17c-5-3-7-7-7-9a2 2 0 0 1 4 0c0 2.5-5 2.5-5 6 0 1.7 1.3 3 3 3 2.8 0 5-2.2 5-5",key:"12lh1k"}],["path",{d:"M22 17c-5-3-7-7-7-9a2 2 0 0 1 4 0c0 2.5-5 2.5-5 6 0 1.7 1.3 3 3 3 2.8 0 5-2.2 5-5",key:"173c68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uK=re("Amphora",[["path",{d:"M10 2v5.632c0 .424-.272.795-.653.982A6 6 0 0 0 6 14c.006 4 3 7 5 8",key:"1h8rid"}],["path",{d:"M10 5H8a2 2 0 0 0 0 4h.68",key:"3ezsi6"}],["path",{d:"M14 2v5.632c0 .424.272.795.652.982A6 6 0 0 1 18 14c0 4-3 7-5 8",key:"yt6q09"}],["path",{d:"M14 5h2a2 2 0 0 1 0 4h-.68",key:"8f95yk"}],["path",{d:"M18 22H6",key:"mg6kv4"}],["path",{d:"M9 2h6",key:"1jrp98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hK=re("Anchor",[["path",{d:"M12 22V8",key:"qkxhtm"}],["path",{d:"M5 12H2a10 10 0 0 0 20 0h-3",key:"1hv3nh"}],["circle",{cx:"12",cy:"5",r:"3",key:"rqqgnr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mK=re("Angry",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 16s-1.5-2-4-2-4 2-4 2",key:"epbg0q"}],["path",{d:"M7.5 8 10 9",key:"olxxln"}],["path",{d:"m14 9 2.5-1",key:"1j6cij"}],["path",{d:"M9 10h.01",key:"qbtxuw"}],["path",{d:"M15 10h.01",key:"1qmjsl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pK=re("Annoyed",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 15h8",key:"45n4r"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M14 9h2",key:"116p9w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fK=re("Antenna",[["path",{d:"M2 12 7 2",key:"117k30"}],["path",{d:"m7 12 5-10",key:"1tvx22"}],["path",{d:"m12 12 5-10",key:"ev1o1a"}],["path",{d:"m17 12 5-10",key:"1e4ti3"}],["path",{d:"M4.5 7h15",key:"vlsxkz"}],["path",{d:"M12 16v6",key:"c8a4gj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xK=re("Anvil",[["path",{d:"M7 10H6a4 4 0 0 1-4-4 1 1 0 0 1 1-1h4",key:"1hjpb6"}],["path",{d:"M7 5a1 1 0 0 1 1-1h13a1 1 0 0 1 1 1 7 7 0 0 1-7 7H8a1 1 0 0 1-1-1z",key:"1qn45f"}],["path",{d:"M9 12v5",key:"3anwtq"}],["path",{d:"M15 12v5",key:"5xh3zn"}],["path",{d:"M5 20a3 3 0 0 1 3-3h8a3 3 0 0 1 3 3 1 1 0 0 1-1 1H6a1 1 0 0 1-1-1",key:"1fi4x8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gK=re("Aperture",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m14.31 8 5.74 9.94",key:"1y6ab4"}],["path",{d:"M9.69 8h11.48",key:"1wxppr"}],["path",{d:"m7.38 12 5.74-9.94",key:"1grp0k"}],["path",{d:"M9.69 16 3.95 6.06",key:"libnyf"}],["path",{d:"M14.31 16H2.83",key:"x5fava"}],["path",{d:"m16.62 12-5.74 9.94",key:"1vwawt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yK=re("AppWindowMac",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M14 8h.01",key:"1primd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vK=re("AppWindow",[["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}],["path",{d:"M10 4v4",key:"pp8u80"}],["path",{d:"M2 8h20",key:"d11cs7"}],["path",{d:"M6 4v4",key:"1svtjw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bK=re("Apple",[["path",{d:"M12 20.94c1.5 0 2.75 1.06 4 1.06 3 0 6-8 6-12.22A4.91 4.91 0 0 0 17 5c-2.22 0-4 1.44-5 2-1-.56-2.78-2-5-2a4.9 4.9 0 0 0-5 4.78C2 14 5 22 8 22c1.25 0 2.5-1.06 4-1.06Z",key:"3s7exb"}],["path",{d:"M10 2c1 .5 2 2 2 5",key:"fcco2y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XP=re("ArchiveRestore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _K=re("ArchiveX",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"m9.5 17 5-5",key:"nakeu6"}],["path",{d:"m9.5 12 5 5",key:"1hccrj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const im=re("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wK=re("Armchair",[["path",{d:"M19 9V6a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v3",key:"irtipd"}],["path",{d:"M3 16a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-9a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",key:"1qyhux"}],["path",{d:"M5 18v2",key:"ppbyun"}],["path",{d:"M19 18v2",key:"gy7782"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jK=re("ArrowBigDownDash",[["path",{d:"M15 5H9",key:"1tp3ed"}],["path",{d:"M15 9v3h4l-7 7-7-7h4V9z",key:"ncdc4b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NK=re("ArrowBigDown",[["path",{d:"M15 6v6h4l-7 7-7-7h4V6h6z",key:"1thax2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kK=re("ArrowBigLeftDash",[["path",{d:"M19 15V9",key:"1hci5f"}],["path",{d:"M15 15h-3v4l-7-7 7-7v4h3v6z",key:"16tjna"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SK=re("ArrowBigLeft",[["path",{d:"M18 15h-6v4l-7-7 7-7v4h6v6z",key:"lbrdak"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CK=re("ArrowBigRightDash",[["path",{d:"M5 9v6",key:"158jrl"}],["path",{d:"M9 9h3V5l7 7-7 7v-4H9V9z",key:"1sg2xn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TK=re("ArrowBigRight",[["path",{d:"M6 9h6V5l7 7-7 7v-4H6V9z",key:"7fvt9c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EK=re("ArrowBigUpDash",[["path",{d:"M9 19h6",key:"456am0"}],["path",{d:"M9 15v-3H5l7-7 7 7h-4v3H9z",key:"1r2uve"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AK=re("ArrowBigUp",[["path",{d:"M9 18v-6H5l7-7 7 7h-4v6H9z",key:"1x06kx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MK=re("ArrowDown01",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["rect",{x:"15",y:"4",width:"4",height:"6",ry:"2",key:"1bwicg"}],["path",{d:"M17 20v-6h-2",key:"1qp1so"}],["path",{d:"M15 20h4",key:"1j968p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IK=re("ArrowDown10",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T3=re("ArrowDownAZ",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PK=re("ArrowDownFromLine",[["path",{d:"M19 3H5",key:"1236rx"}],["path",{d:"M12 21V7",key:"gj6g52"}],["path",{d:"m6 15 6 6 6-6",key:"h15q88"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LK=re("ArrowDownLeft",[["path",{d:"M17 7 7 17",key:"15tmo1"}],["path",{d:"M17 17H7V7",key:"1org7z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DK=re("ArrowDownNarrowWide",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h4",key:"6d7r33"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h10",key:"1438ji"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W7=re("ArrowDownRight",[["path",{d:"m7 7 10 10",key:"1fmybs"}],["path",{d:"M17 7v10H7",key:"6fjiku"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RK=re("ArrowDownToDot",[["path",{d:"M12 2v14",key:"jyx4ut"}],["path",{d:"m19 9-7 7-7-7",key:"1oe3oy"}],["circle",{cx:"12",cy:"21",r:"1",key:"o0uj5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OK=re("ArrowDownToLine",[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FK=re("ArrowDownUp",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"m21 8-4-4-4 4",key:"1c9v7m"}],["path",{d:"M17 4v16",key:"7dpous"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E3=re("ArrowDownWideNarrow",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A3=re("ArrowDownZA",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const om=re("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zK=re("ArrowLeftFromLine",[["path",{d:"m9 6-6 6 6 6",key:"7v63n9"}],["path",{d:"M3 12h14",key:"13k4hi"}],["path",{d:"M21 19V5",key:"b4bplr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BK=re("ArrowLeftRight",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $K=re("ArrowLeftToLine",[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wr=re("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UK=re("ArrowRightFromLine",[["path",{d:"M3 5v14",key:"1nt18q"}],["path",{d:"M21 12H7",key:"13ipq5"}],["path",{d:"m15 18 6-6-6-6",key:"6tx3qv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pw=re("ArrowRightLeft",[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qK=re("ArrowRightToLine",[["path",{d:"M17 12H3",key:"8awo09"}],["path",{d:"m11 18 6-6-6-6",key:"8c2y43"}],["path",{d:"M21 5v14",key:"nzette"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const za=re("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VK=re("ArrowUp01",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["rect",{x:"15",y:"4",width:"4",height:"6",ry:"2",key:"1bwicg"}],["path",{d:"M17 20v-6h-2",key:"1qp1so"}],["path",{d:"M15 20h4",key:"1j968p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HK=re("ArrowUp10",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M3=re("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sm=re("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GK=re("ArrowUpFromDot",[["path",{d:"m5 9 7-7 7 7",key:"1hw5ic"}],["path",{d:"M12 16V2",key:"ywoabb"}],["circle",{cx:"12",cy:"21",r:"1",key:"o0uj5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WK=re("ArrowUpFromLine",[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KK=re("ArrowUpLeft",[["path",{d:"M7 17V7h10",key:"11bw93"}],["path",{d:"M17 17 7 7",key:"2786uv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I3=re("ArrowUpNarrowWide",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M11 12h4",key:"q8tih4"}],["path",{d:"M11 16h7",key:"uosisv"}],["path",{d:"M11 20h10",key:"jvxblo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JP=re("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YK=re("ArrowUpToLine",[["path",{d:"M5 3h14",key:"7usisc"}],["path",{d:"m18 13-6-6-6 6",key:"1kf1n9"}],["path",{d:"M12 7v14",key:"1akyts"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZK=re("ArrowUpWideNarrow",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 16h7",key:"uosisv"}],["path",{d:"M11 20h4",key:"1krc32"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const P3=re("ArrowUpZA",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bu=re("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QK=re("ArrowsUpFromLine",[["path",{d:"m4 6 3-3 3 3",key:"9aidw8"}],["path",{d:"M7 17V3",key:"19qxw1"}],["path",{d:"m14 6 3-3 3 3",key:"6iy689"}],["path",{d:"M17 17V3",key:"o0fmgi"}],["path",{d:"M4 21h16",key:"1h09gz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XK=re("Asterisk",[["path",{d:"M12 6v12",key:"1vza4d"}],["path",{d:"M17.196 9 6.804 15",key:"1ah31z"}],["path",{d:"m6.804 9 10.392 6",key:"1b6pxd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JK=re("AtSign",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8",key:"7n84p3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eY=re("Atom",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M20.2 20.2c2.04-2.03.02-7.36-4.5-11.9-4.54-4.52-9.87-6.54-11.9-4.5-2.04 2.03-.02 7.36 4.5 11.9 4.54 4.52 9.87 6.54 11.9 4.5Z",key:"1l2ple"}],["path",{d:"M15.7 15.7c4.52-4.54 6.54-9.87 4.5-11.9-2.03-2.04-7.36-.02-11.9 4.5-4.52 4.54-6.54 9.87-4.5 11.9 2.03 2.04 7.36.02 11.9-4.5Z",key:"1wam0m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tY=re("AudioLines",[["path",{d:"M2 10v3",key:"1fnikh"}],["path",{d:"M6 6v11",key:"11sgs0"}],["path",{d:"M10 3v18",key:"yhl04a"}],["path",{d:"M14 8v7",key:"3a1oy3"}],["path",{d:"M18 5v13",key:"123xd1"}],["path",{d:"M22 10v3",key:"154ddg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sY=re("AudioWaveform",[["path",{d:"M2 13a2 2 0 0 0 2-2V7a2 2 0 0 1 4 0v13a2 2 0 0 0 4 0V4a2 2 0 0 1 4 0v13a2 2 0 0 0 4 0v-4a2 2 0 0 1 2-2",key:"57tc96"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vc=re("Award",[["path",{d:"m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526",key:"1yiouv"}],["circle",{cx:"12",cy:"8",r:"6",key:"1vp47v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nY=re("Axe",[["path",{d:"m14 12-8.5 8.5a2.12 2.12 0 1 1-3-3L11 9",key:"csbz4o"}],["path",{d:"M15 13 9 7l4-4 6 6h3a8 8 0 0 1-7 7z",key:"113wfo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const L3=re("Axis3d",[["path",{d:"M4 4v16h16",key:"1s015l"}],["path",{d:"m4 20 7-7",key:"17qe9y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rY=re("Baby",[["path",{d:"M9 12h.01",key:"157uk2"}],["path",{d:"M15 12h.01",key:"1k8ypt"}],["path",{d:"M10 16c.5.3 1.2.5 2 .5s1.5-.2 2-.5",key:"1u7htd"}],["path",{d:"M19 6.3a9 9 0 0 1 1.8 3.9 2 2 0 0 1 0 3.6 9 9 0 0 1-17.6 0 2 2 0 0 1 0-3.6A9 9 0 0 1 12 3c2 0 3.5 1.1 3.5 2.5s-.9 2.5-2 2.5c-.8 0-1.5-.4-1.5-1",key:"5yv0yz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aY=re("Backpack",[["path",{d:"M4 10a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z",key:"1ol0lm"}],["path",{d:"M8 10h8",key:"c7uz4u"}],["path",{d:"M8 18h8",key:"1no2b1"}],["path",{d:"M8 22v-6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v6",key:"1fr6do"}],["path",{d:"M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2",key:"donm21"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iY=re("BadgeAlert",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oY=re("BadgeCent",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M12 7v10",key:"jspqdw"}],["path",{d:"M15.4 10a4 4 0 1 0 0 4",key:"2eqtx8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D3=re("BadgeCheck",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lY=re("BadgeDollarSign",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 18V6",key:"zqpxq5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cY=re("BadgeEuro",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M7 12h5",key:"gblrwe"}],["path",{d:"M15 9.4a4 4 0 1 0 0 5.2",key:"1makmb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dY=re("BadgeHelp",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["line",{x1:"12",x2:"12.01",y1:"17",y2:"17",key:"io3f8k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uY=re("BadgeIndianRupee",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M8 8h8",key:"1bis0t"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m13 17-5-1h1a4 4 0 0 0 0-8",key:"nu2bwa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hY=re("BadgeInfo",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"12",x2:"12",y1:"16",y2:"12",key:"1y1yb1"}],["line",{x1:"12",x2:"12.01",y1:"8",y2:"8",key:"110wyk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mY=re("BadgeJapaneseYen",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 8 3 3v7",key:"17yadx"}],["path",{d:"m12 11 3-3",key:"p4cfq1"}],["path",{d:"M9 12h6",key:"1c52cq"}],["path",{d:"M9 16h6",key:"8wimt3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pY=re("BadgeMinus",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fY=re("BadgePercent",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xY=re("BadgePlus",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"12",x2:"12",y1:"8",y2:"16",key:"10p56q"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gY=re("BadgePoundSterling",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M8 12h4",key:"qz6y1c"}],["path",{d:"M10 16V9.5a2.5 2.5 0 0 1 5 0",key:"3mlbjk"}],["path",{d:"M8 16h7",key:"sbedsn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yY=re("BadgeRussianRuble",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M9 16h5",key:"1syiyw"}],["path",{d:"M9 12h5a2 2 0 1 0 0-4h-3v9",key:"1ge9c1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vY=re("BadgeSwissFranc",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M11 17V8h4",key:"1bfq6y"}],["path",{d:"M11 12h3",key:"2eqnfz"}],["path",{d:"M9 16h4",key:"1skf3a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bY=re("BadgeX",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"15",x2:"9",y1:"9",y2:"15",key:"f7djnv"}],["line",{x1:"9",x2:"15",y1:"9",y2:"15",key:"1shsy8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _Y=re("Badge",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wY=re("BaggageClaim",[["path",{d:"M22 18H6a2 2 0 0 1-2-2V7a2 2 0 0 0-2-2",key:"4irg2o"}],["path",{d:"M17 14V4a2 2 0 0 0-2-2h-1a2 2 0 0 0-2 2v10",key:"14fcyx"}],["rect",{width:"13",height:"8",x:"8",y:"6",rx:"1",key:"o6oiis"}],["circle",{cx:"18",cy:"20",r:"2",key:"t9985n"}],["circle",{cx:"9",cy:"20",r:"2",key:"e5v82j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eL=re("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jY=re("Banana",[["path",{d:"M4 13c3.5-2 8-2 10 2a5.5 5.5 0 0 1 8 5",key:"1cscit"}],["path",{d:"M5.15 17.89c5.52-1.52 8.65-6.89 7-12C11.55 4 11.5 2 13 2c3.22 0 5 5.5 5 8 0 6.5-4.2 12-10.49 12C5.11 22 2 22 2 20c0-1.5 1.14-1.55 3.15-2.11Z",key:"1y1nbv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NY=re("Bandage",[["path",{d:"M10 10.01h.01",key:"1e9xi7"}],["path",{d:"M10 14.01h.01",key:"ac23bv"}],["path",{d:"M14 10.01h.01",key:"2wfrvf"}],["path",{d:"M14 14.01h.01",key:"8tw8yn"}],["path",{d:"M18 6v11.5",key:"dkbidh"}],["path",{d:"M6 6v12",key:"vkc79e"}],["rect",{x:"2",y:"6",width:"20",height:"12",rx:"2",key:"1wpnh2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kY=re("Banknote",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M6 12h.01M18 12h.01",key:"113zkx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SY=re("Barcode",[["path",{d:"M3 5v14",key:"1nt18q"}],["path",{d:"M8 5v14",key:"1ybrkv"}],["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"M17 5v14",key:"ycjyhj"}],["path",{d:"M21 5v14",key:"nzette"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CY=re("Baseline",[["path",{d:"M4 20h16",key:"14thso"}],["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tp=re("Bath",[["path",{d:"M10 4 8 6",key:"1rru8s"}],["path",{d:"M17 19v2",key:"ts1sot"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M7 19v2",key:"12npes"}],["path",{d:"M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5",key:"14ym8i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TY=re("BatteryCharging",[["path",{d:"M15 7h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-2",key:"1sdynx"}],["path",{d:"M6 7H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h1",key:"1gkd3k"}],["path",{d:"m11 7-3 5h4l-3 5",key:"b4a64w"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EY=re("BatteryFull",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}],["line",{x1:"6",x2:"6",y1:"11",y2:"13",key:"1wd6dw"}],["line",{x1:"10",x2:"10",y1:"11",y2:"13",key:"haxvl5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"13",key:"c6fn6x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AY=re("BatteryLow",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}],["line",{x1:"6",x2:"6",y1:"11",y2:"13",key:"1wd6dw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MY=re("BatteryMedium",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}],["line",{x1:"6",x2:"6",y1:"11",y2:"13",key:"1wd6dw"}],["line",{x1:"10",x2:"10",y1:"11",y2:"13",key:"haxvl5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IY=re("BatteryWarning",[["path",{d:"M10 17h.01",key:"nbq80n"}],["path",{d:"M10 7v6",key:"nne03l"}],["path",{d:"M14 7h2a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-2",key:"1x5o8m"}],["path",{d:"M22 11v2",key:"1wo06k"}],["path",{d:"M6 7H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"1mdjgh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PY=re("Battery",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K7=re("Beaker",[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LY=re("BeanOff",[["path",{d:"M9 9c-.64.64-1.521.954-2.402 1.165A6 6 0 0 0 8 22a13.96 13.96 0 0 0 9.9-4.1",key:"bq3udt"}],["path",{d:"M10.75 5.093A6 6 0 0 1 22 8c0 2.411-.61 4.68-1.683 6.66",key:"17ccse"}],["path",{d:"M5.341 10.62a4 4 0 0 0 6.487 1.208M10.62 5.341a4.015 4.015 0 0 1 2.039 2.04",key:"18zqgq"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DY=re("Bean",[["path",{d:"M10.165 6.598C9.954 7.478 9.64 8.36 9 9c-.64.64-1.521.954-2.402 1.165A6 6 0 0 0 8 22c7.732 0 14-6.268 14-14a6 6 0 0 0-11.835-1.402Z",key:"1tvzk7"}],["path",{d:"M5.341 10.62a4 4 0 1 0 5.279-5.28",key:"2cyri2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G2=re("BedDouble",[["path",{d:"M2 20v-8a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v8",key:"1k78r4"}],["path",{d:"M4 10V6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4",key:"fb3tl2"}],["path",{d:"M12 4v6",key:"1dcgq2"}],["path",{d:"M2 18h20",key:"ajqnye"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RY=re("BedSingle",[["path",{d:"M3 20v-8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v8",key:"1wm6mi"}],["path",{d:"M5 10V6a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v4",key:"4k93s5"}],["path",{d:"M3 18h18",key:"1h113x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ny=re("Bed",[["path",{d:"M2 4v16",key:"vw9hq8"}],["path",{d:"M2 8h18a2 2 0 0 1 2 2v10",key:"1dgv2r"}],["path",{d:"M2 17h20",key:"18nfp3"}],["path",{d:"M6 8v9",key:"1yriud"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OY=re("Beef",[["circle",{cx:"12.5",cy:"8.5",r:"2.5",key:"9738u8"}],["path",{d:"M12.5 2a6.5 6.5 0 0 0-6.22 4.6c-1.1 3.13-.78 3.9-3.18 6.08A3 3 0 0 0 5 18c4 0 8.4-1.8 11.4-4.3A6.5 6.5 0 0 0 12.5 2Z",key:"o0f6za"}],["path",{d:"m18.5 6 2.19 4.5a6.48 6.48 0 0 1 .31 2 6.49 6.49 0 0 1-2.6 5.2C15.4 20.2 11 22 7 22a3 3 0 0 1-2.68-1.66L2.4 16.5",key:"k7p6i0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FY=re("BeerOff",[["path",{d:"M13 13v5",key:"igwfh0"}],["path",{d:"M17 11.47V8",key:"16yw0g"}],["path",{d:"M17 11h1a3 3 0 0 1 2.745 4.211",key:"1xbt65"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 8v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2v-3",key:"c55o3e"}],["path",{d:"M7.536 7.535C6.766 7.649 6.154 8 5.5 8a2.5 2.5 0 0 1-1.768-4.268",key:"1ydug7"}],["path",{d:"M8.727 3.204C9.306 2.767 9.885 2 11 2c1.56 0 2 1.5 3 1.5s1.72-.5 2.5-.5a1 1 0 1 1 0 5c-.78 0-1.5-.5-2.5-.5a3.149 3.149 0 0 0-.842.12",key:"q81o7q"}],["path",{d:"M9 14.6V18",key:"20ek98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zY=re("Beer",[["path",{d:"M17 11h1a3 3 0 0 1 0 6h-1",key:"1yp76v"}],["path",{d:"M9 12v6",key:"1u1cab"}],["path",{d:"M13 12v6",key:"1sugkk"}],["path",{d:"M14 7.5c-1 0-1.44.5-3 .5s-2-.5-3-.5-1.72.5-2.5.5a2.5 2.5 0 0 1 0-5c.78 0 1.57.5 2.5.5S9.44 2 11 2s2 1.5 3 1.5 1.72-.5 2.5-.5a2.5 2.5 0 0 1 0 5c-.78 0-1.5-.5-2.5-.5Z",key:"1510fo"}],["path",{d:"M5 8v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8",key:"19jb7n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BY=re("BellDot",[["path",{d:"M19.4 14.9C20.2 16.4 21 17 21 17H3s3-2 3-9c0-3.3 2.7-6 6-6 .7 0 1.3.1 1.9.3",key:"xcehk"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["circle",{cx:"18",cy:"8",r:"3",key:"1g0gzu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $Y=re("BellElectric",[["path",{d:"M18.8 4A6.3 8.7 0 0 1 20 9",key:"xve1fh"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["circle",{cx:"9",cy:"9",r:"7",key:"p2h5vp"}],["rect",{width:"10",height:"6",x:"4",y:"16",rx:"2",key:"17f3te"}],["path",{d:"M14 19c3 0 4.6-1.6 4.6-1.6",key:"n7odp6"}],["circle",{cx:"20",cy:"16",r:"2",key:"1v9bxh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UY=re("BellMinus",[["path",{d:"M18.4 12c.8 3.8 2.6 5 2.6 5H3s3-2 3-9c0-3.3 2.7-6 6-6 1.8 0 3.4.8 4.5 2",key:"eck70s"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"M15 8h6",key:"8ybuxh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fw=re("BellOff",[["path",{d:"M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5",key:"o7mx20"}],["path",{d:"M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7",key:"16f1lm"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qY=re("BellPlus",[["path",{d:"M19.3 14.8C20.1 16.4 21 17 21 17H3s3-2 3-9c0-3.3 2.7-6 6-6 1 0 1.9.2 2.8.7",key:"guizqy"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"M15 8h6",key:"8ybuxh"}],["path",{d:"M18 5v6",key:"g5ayrv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KS=re("BellRing",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"M4 2C2.8 3.7 2 5.7 2 8",key:"tap9e0"}],["path",{d:"M22 8c0-2.3-.8-4.3-2-6",key:"5bb3ad"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lm=re("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const R3=re("BetweenHorizontalEnd",[["rect",{width:"13",height:"7",x:"3",y:"3",rx:"1",key:"11xb64"}],["path",{d:"m22 15-3-3 3-3",key:"26chmm"}],["rect",{width:"13",height:"7",x:"3",y:"14",rx:"1",key:"k6ky7n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const O3=re("BetweenHorizontalStart",[["rect",{width:"13",height:"7",x:"8",y:"3",rx:"1",key:"pkso9a"}],["path",{d:"m2 9 3 3-3 3",key:"1agib5"}],["rect",{width:"13",height:"7",x:"8",y:"14",rx:"1",key:"1q5fc1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VY=re("BetweenVerticalEnd",[["rect",{width:"7",height:"13",x:"3",y:"3",rx:"1",key:"1fdu0f"}],["path",{d:"m9 22 3-3 3 3",key:"17z65a"}],["rect",{width:"7",height:"13",x:"14",y:"3",rx:"1",key:"1squn4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HY=re("BetweenVerticalStart",[["rect",{width:"7",height:"13",x:"3",y:"8",rx:"1",key:"1fjrkv"}],["path",{d:"m15 2-3 3-3-3",key:"1uh6eb"}],["rect",{width:"7",height:"13",x:"14",y:"8",rx:"1",key:"w3fjg8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GY=re("BicepsFlexed",[["path",{d:"M12.409 13.017A5 5 0 0 1 22 15c0 3.866-4 7-9 7-4.077 0-8.153-.82-10.371-2.462-.426-.316-.631-.832-.62-1.362C2.118 12.723 2.627 2 10 2a3 3 0 0 1 3 3 2 2 0 0 1-2 2c-1.105 0-1.64-.444-2-1",key:"1pmlyh"}],["path",{d:"M15 14a5 5 0 0 0-7.584 2",key:"5rb254"}],["path",{d:"M9.964 6.825C8.019 7.977 9.5 13 8 15",key:"kbvsx9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WY=re("Bike",[["circle",{cx:"18.5",cy:"17.5",r:"3.5",key:"15x4ox"}],["circle",{cx:"5.5",cy:"17.5",r:"3.5",key:"1noe27"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["path",{d:"M12 17.5V14l-3-3 4-3 2 3h2",key:"1npguv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KY=re("Binary",[["rect",{x:"14",y:"14",width:"4",height:"6",rx:"2",key:"p02svl"}],["rect",{x:"6",y:"4",width:"4",height:"6",rx:"2",key:"xm4xkj"}],["path",{d:"M6 20h4",key:"1i6q5t"}],["path",{d:"M14 10h4",key:"ru81e7"}],["path",{d:"M6 14h2v6",key:"16z9wg"}],["path",{d:"M14 4h2v6",key:"1idq9u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YY=re("Binoculars",[["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M19 7V4a1 1 0 0 0-1-1h-2a1 1 0 0 0-1 1v3",key:"3apit1"}],["path",{d:"M20 21a2 2 0 0 0 2-2v-3.851c0-1.39-2-2.962-2-4.829V8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v11a2 2 0 0 0 2 2z",key:"rhpgnw"}],["path",{d:"M 22 16 L 2 16",key:"14lkq7"}],["path",{d:"M4 21a2 2 0 0 1-2-2v-3.851c0-1.39 2-2.962 2-4.829V8a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v11a2 2 0 0 1-2 2z",key:"104b3k"}],["path",{d:"M9 7V4a1 1 0 0 0-1-1H6a1 1 0 0 0-1 1v3",key:"14fczp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZY=re("Biohazard",[["circle",{cx:"12",cy:"11.9",r:"2",key:"e8h31w"}],["path",{d:"M6.7 3.4c-.9 2.5 0 5.2 2.2 6.7C6.5 9 3.7 9.6 2 11.6",key:"17bolr"}],["path",{d:"m8.9 10.1 1.4.8",key:"15ezny"}],["path",{d:"M17.3 3.4c.9 2.5 0 5.2-2.2 6.7 2.4-1.2 5.2-.6 6.9 1.5",key:"wtwa5u"}],["path",{d:"m15.1 10.1-1.4.8",key:"1r0b28"}],["path",{d:"M16.7 20.8c-2.6-.4-4.6-2.6-4.7-5.3-.2 2.6-2.1 4.8-4.7 5.2",key:"m7qszh"}],["path",{d:"M12 13.9v1.6",key:"zfyyim"}],["path",{d:"M13.5 5.4c-1-.2-2-.2-3 0",key:"1bi9q0"}],["path",{d:"M17 16.4c.7-.7 1.2-1.6 1.5-2.5",key:"1rhjqw"}],["path",{d:"M5.5 13.9c.3.9.8 1.8 1.5 2.5",key:"8gsud3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QY=re("Bird",[["path",{d:"M16 7h.01",key:"1kdx03"}],["path",{d:"M3.4 18H12a8 8 0 0 0 8-8V7a4 4 0 0 0-7.28-2.3L2 20",key:"oj1oa8"}],["path",{d:"m20 7 2 .5-2 .5",key:"12nv4d"}],["path",{d:"M10 18v3",key:"1yea0a"}],["path",{d:"M14 17.75V21",key:"1pymcb"}],["path",{d:"M7 18a6 6 0 0 0 3.84-10.61",key:"1npnn0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XY=re("Bitcoin",[["path",{d:"M11.767 19.089c4.924.868 6.14-6.025 1.216-6.894m-1.216 6.894L5.86 18.047m5.908 1.042-.347 1.97m1.563-8.864c4.924.869 6.14-6.025 1.215-6.893m-1.215 6.893-3.94-.694m5.155-6.2L8.29 4.26m5.908 1.042.348-1.97M7.48 20.364l3.126-17.727",key:"yr8idg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JY=re("Blend",[["circle",{cx:"9",cy:"9",r:"7",key:"p2h5vp"}],["circle",{cx:"15",cy:"15",r:"7",key:"19ennj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eZ=re("Blinds",[["path",{d:"M3 3h18",key:"o7r712"}],["path",{d:"M20 7H8",key:"gd2fo2"}],["path",{d:"M20 11H8",key:"1ynp89"}],["path",{d:"M10 19h10",key:"19hjk5"}],["path",{d:"M8 15h12",key:"1yqzne"}],["path",{d:"M4 3v14",key:"fggqzn"}],["circle",{cx:"4",cy:"19",r:"2",key:"p3m9r0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tZ=re("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sZ=re("BluetoothConnected",[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}],["line",{x1:"18",x2:"21",y1:"12",y2:"12",key:"1rsjjs"}],["line",{x1:"3",x2:"6",y1:"12",y2:"12",key:"11yl8c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nZ=re("BluetoothOff",[["path",{d:"m17 17-5 5V12l-5 5",key:"v5aci6"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M14.5 9.5 17 7l-5-5v4.5",key:"1kddfz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rZ=re("BluetoothSearching",[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}],["path",{d:"M20.83 14.83a4 4 0 0 0 0-5.66",key:"k8tn1j"}],["path",{d:"M18 12h.01",key:"yjnet6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aZ=re("Bluetooth",[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YS=re("Bold",[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iZ=re("Bolt",[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oZ=re("Bomb",[["circle",{cx:"11",cy:"13",r:"9",key:"hd149"}],["path",{d:"M14.35 4.65 16.3 2.7a2.41 2.41 0 0 1 3.4 0l1.6 1.6a2.4 2.4 0 0 1 0 3.4l-1.95 1.95",key:"jp4j1b"}],["path",{d:"m22 2-1.5 1.5",key:"ay92ug"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lZ=re("Bone",[["path",{d:"M17 10c.7-.7 1.69 0 2.5 0a2.5 2.5 0 1 0 0-5 .5.5 0 0 1-.5-.5 2.5 2.5 0 1 0-5 0c0 .81.7 1.8 0 2.5l-7 7c-.7.7-1.69 0-2.5 0a2.5 2.5 0 0 0 0 5c.28 0 .5.22.5.5a2.5 2.5 0 1 0 5 0c0-.81-.7-1.8 0-2.5Z",key:"w610uw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cZ=re("BookA",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m8 13 4-7 4 7",key:"4rari8"}],["path",{d:"M9.1 11h5.7",key:"1gkovt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dZ=re("BookAudio",[["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8v3",key:"gejaml"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M8 8v3",key:"1qzp49"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uZ=re("BookCheck",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9 9.5 2 2 4-4",key:"1dth82"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hZ=re("BookCopy",[["path",{d:"M2 16V4a2 2 0 0 1 2-2h11",key:"spzkk5"}],["path",{d:"M22 18H11a2 2 0 1 0 0 4h10.5a.5.5 0 0 0 .5-.5v-15a.5.5 0 0 0-.5-.5H11a2 2 0 0 0-2 2v12",key:"1wz07i"}],["path",{d:"M5 14H4a2 2 0 1 0 0 4h1",key:"16gqf9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const F3=re("BookDashed",[["path",{d:"M12 17h2",key:"13u4lk"}],["path",{d:"M12 22h2",key:"kn7ki6"}],["path",{d:"M12 2h2",key:"cvn524"}],["path",{d:"M18 22h1a1 1 0 0 0 1-1",key:"w6gbqz"}],["path",{d:"M18 2h1a1 1 0 0 1 1 1v1",key:"1vpra5"}],["path",{d:"M20 15v2h-2",key:"fph276"}],["path",{d:"M20 8v3",key:"deu0bs"}],["path",{d:"M4 11V9",key:"v3xsx8"}],["path",{d:"M4 19.5V15",key:"6gr39e"}],["path",{d:"M4 5v-.5A2.5 2.5 0 0 1 6.5 2H8",key:"wywhs9"}],["path",{d:"M8 22H6.5a1 1 0 0 1 0-5H8",key:"1cu73q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mZ=re("BookDown",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9 10 3 3 3-3",key:"zt5b4y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pZ=re("BookHeadphones",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M8 12v-2a4 4 0 0 1 8 0v2",key:"1vsqkj"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fZ=re("BookHeart",[["path",{d:"M16 8.2A2.22 2.22 0 0 0 13.8 6c-.8 0-1.4.3-1.8.9-.4-.6-1-.9-1.8-.9A2.22 2.22 0 0 0 8 8.2c0 .6.3 1.2.7 1.6A226.652 226.652 0 0 0 12 13a404 404 0 0 0 3.3-3.1 2.413 2.413 0 0 0 .7-1.7",key:"1t75a8"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xZ=re("BookImage",[["path",{d:"m20 13.7-2.1-2.1a2 2 0 0 0-2.8 0L9.7 17",key:"q6ojf0"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["circle",{cx:"10",cy:"8",r:"2",key:"2qkj4p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gZ=re("BookKey",[["path",{d:"m19 3 1 1",key:"ze14oc"}],["path",{d:"m20 2-4.5 4.5",key:"1sppr8"}],["path",{d:"M20 8v13a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"1ocbpn"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H14",key:"1gfsgw"}],["circle",{cx:"14",cy:"8",r:"2",key:"u49eql"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yZ=re("BookLock",[["path",{d:"M18 6V4a2 2 0 1 0-4 0v2",key:"1aquzs"}],["path",{d:"M20 15v6a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"1rkj32"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H10",key:"18wgow"}],["rect",{x:"12",y:"6",width:"8",height:"5",rx:"1",key:"73l30o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vZ=re("BookMarked",[["path",{d:"M10 2v8l3-3 3 3V2",key:"sqw3rj"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bZ=re("BookMinus",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _Z=re("BookOpenCheck",[["path",{d:"M12 21V7",key:"gj6g52"}],["path",{d:"m16 12 2 2 4-4",key:"mdajum"}],["path",{d:"M22 6V4a1 1 0 0 0-1-1h-5a4 4 0 0 0-4 4 4 4 0 0 0-4-4H3a1 1 0 0 0-1 1v13a1 1 0 0 0 1 1h6a3 3 0 0 1 3 3 3 3 0 0 1 3-3h6a1 1 0 0 0 1-1v-1.3",key:"8arnkb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wZ=re("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $u=re("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jZ=re("BookPlus",[["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NZ=re("BookText",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M8 11h8",key:"vwpz6n"}],["path",{d:"M8 7h6",key:"1f0q6e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kZ=re("BookType",[["path",{d:"M10 13h4",key:"ytezjc"}],["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8V6H8v2",key:"x8j6u4"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SZ=re("BookUp2",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M18 2h1a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"161d7n"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2",key:"1lorq7"}],["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CZ=re("BookUp",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TZ=re("BookUser",[["path",{d:"M15 13a3 3 0 1 0-6 0",key:"10j68g"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EZ=re("BookX",[["path",{d:"m14.5 7-5 5",key:"dy991v"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9.5 7 5 5",key:"s45iea"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AZ=re("Book",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MZ=re("BookmarkCheck",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IZ=re("BookmarkMinus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tL=re("BookmarkPlus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"12",x2:"12",y1:"7",y2:"13",key:"1cppfj"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PZ=re("BookmarkX",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rv=re("Bookmark",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LZ=re("BoomBox",[["path",{d:"M4 9V5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4",key:"vvzvr1"}],["path",{d:"M8 8v1",key:"xcqmfk"}],["path",{d:"M12 8v1",key:"1rj8u4"}],["path",{d:"M16 8v1",key:"1q12zr"}],["rect",{width:"20",height:"12",x:"2",y:"9",rx:"2",key:"igpb89"}],["circle",{cx:"8",cy:"15",r:"2",key:"fa4a8s"}],["circle",{cx:"16",cy:"15",r:"2",key:"14c3ya"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DZ=re("BotMessageSquare",[["path",{d:"M12 6V2H8",key:"1155em"}],["path",{d:"m8 18-4 4V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2Z",key:"w2lp3e"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M9 11v2",key:"1ueba0"}],["path",{d:"M15 11v2",key:"i11awn"}],["path",{d:"M20 12h2",key:"1q8mjw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RZ=re("BotOff",[["path",{d:"M13.67 8H18a2 2 0 0 1 2 2v4.33",key:"7az073"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M22 22 2 2",key:"1r8tn9"}],["path",{d:"M8 8H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h12a2 2 0 0 0 1.414-.586",key:"s09a7a"}],["path",{d:"M9 13v2",key:"rq6x2g"}],["path",{d:"M9.67 4H12v2.33",key:"110xot"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZS=re("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y7=re("Box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OZ=re("Boxes",[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const z3=re("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FZ=re("Brackets",[["path",{d:"M16 3h3v18h-3",key:"1yor1f"}],["path",{d:"M8 21H5V3h3",key:"1qrfwo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zZ=re("BrainCircuit",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M9 13a4.5 4.5 0 0 0 3-4",key:"10igwf"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M12 13h4",key:"1ku699"}],["path",{d:"M12 18h6a2 2 0 0 1 2 2v1",key:"105ag5"}],["path",{d:"M12 8h8",key:"1lhi5i"}],["path",{d:"M16 8V5a2 2 0 0 1 2-2",key:"u6izg6"}],["circle",{cx:"16",cy:"13",r:".5",key:"ry7gng"}],["circle",{cx:"18",cy:"3",r:".5",key:"1aiba7"}],["circle",{cx:"20",cy:"21",r:".5",key:"yhc1fs"}],["circle",{cx:"20",cy:"8",r:".5",key:"1e43v0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BZ=re("BrainCog",[["path",{d:"M12 5a3 3 0 1 0-5.997.142 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588 4 4 0 0 0 7.636 2.106 3.2 3.2 0 0 0 .164-.546c.028-.13.306-.13.335 0a3.2 3.2 0 0 0 .163.546 4 4 0 0 0 7.636-2.106 4 4 0 0 0 .556-6.588 4 4 0 0 0-2.526-5.77A3 3 0 1 0 12 5",key:"1kgmhc"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m15.7 10.4-.9.4",key:"ayzo6p"}],["path",{d:"m9.2 13.2-.9.4",key:"1uzb3g"}],["path",{d:"m13.6 15.7-.4-.9",key:"11ifqf"}],["path",{d:"m10.8 9.2-.4-.9",key:"1pmk2v"}],["path",{d:"m15.7 13.5-.9-.4",key:"7ng02m"}],["path",{d:"m9.2 10.9-.9-.4",key:"1x66zd"}],["path",{d:"m10.5 15.7.4-.9",key:"3js94g"}],["path",{d:"m13.1 9.2.4-.9",key:"18n7mc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z7=re("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $Z=re("BrickWall",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 9v6",key:"199k2o"}],["path",{d:"M16 15v6",key:"8rj2es"}],["path",{d:"M16 3v6",key:"1j6rpj"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M8 15v6",key:"1stoo3"}],["path",{d:"M8 3v6",key:"vlvjmk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UZ=re("BriefcaseBusiness",[["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 6V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2",key:"1ksdt3"}],["path",{d:"M22 13a18.15 18.15 0 0 1-20 0",key:"12hx5q"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qZ=re("BriefcaseConveyorBelt",[["path",{d:"M10 20v2",key:"1n8e1g"}],["path",{d:"M14 20v2",key:"1lq872"}],["path",{d:"M18 20v2",key:"10uadw"}],["path",{d:"M21 20H3",key:"kdqkdp"}],["path",{d:"M6 20v2",key:"a9bc87"}],["path",{d:"M8 16V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v12",key:"17n9tx"}],["rect",{x:"4",y:"6",width:"16",height:"10",rx:"2",key:"1097i5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VZ=re("BriefcaseMedical",[["path",{d:"M12 11v4",key:"a6ujw6"}],["path",{d:"M14 13h-4",key:"1pl8zg"}],["path",{d:"M16 6V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2",key:"1ksdt3"}],["path",{d:"M18 6v14",key:"1mu4gy"}],["path",{d:"M6 6v14",key:"1s15cj"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vm=re("Briefcase",[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HZ=re("BringToFront",[["rect",{x:"8",y:"8",width:"8",height:"8",rx:"2",key:"yj20xf"}],["path",{d:"M4 10a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2",key:"1ltk23"}],["path",{d:"M14 20a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2",key:"1q24h9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GZ=re("Brush",[["path",{d:"m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08",key:"1styjt"}],["path",{d:"M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z",key:"z0l1mu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WZ=re("BugOff",[["path",{d:"M15 7.13V6a3 3 0 0 0-5.14-2.1L8 2",key:"vl8zik"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M22 13h-4v-2a4 4 0 0 0-4-4h-1.3",key:"1ou0bd"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M7.7 7.7A4 4 0 0 0 6 11v3a6 6 0 0 0 11.13 3.13",key:"1njkjs"}],["path",{d:"M12 20v-8",key:"i3yub9"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KZ=re("BugPlay",[["path",{d:"M12.765 21.522a.5.5 0 0 1-.765-.424v-8.196a.5.5 0 0 1 .765-.424l5.878 3.674a1 1 0 0 1 0 1.696z",key:"17shqo"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M18 11a4 4 0 0 0-4-4h-4a4 4 0 0 0-4 4v3a6.1 6.1 0 0 0 2 4.5",key:"1tjixy"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YZ=re("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ga=re("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NA=re("Building",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["path",{d:"M9 22v-4h6v4",key:"r93iot"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZZ=re("BusFront",[["path",{d:"M4 6 2 7",key:"1mqr15"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"m22 7-2-1",key:"1umjhc"}],["rect",{width:"16",height:"16",x:"4",y:"3",rx:"2",key:"1wxw4b"}],["path",{d:"M4 11h16",key:"mpoxn0"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M16 15h.01",key:"rnfrdf"}],["path",{d:"M6 19v2",key:"1loha6"}],["path",{d:"M18 21v-2",key:"sqyl04"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QZ=re("Bus",[["path",{d:"M8 6v6",key:"18i7km"}],["path",{d:"M15 6v6",key:"1sg6z9"}],["path",{d:"M2 12h19.6",key:"de5uta"}],["path",{d:"M18 18h3s.5-1.7.8-2.8c.1-.4.2-.8.2-1.2 0-.4-.1-.8-.2-1.2l-1.4-5C20.1 6.8 19.1 6 18 6H4a2 2 0 0 0-2 2v10h3",key:"1wwztk"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}],["path",{d:"M9 18h5",key:"lrx6i"}],["circle",{cx:"16",cy:"18",r:"2",key:"1v4tcr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XZ=re("CableCar",[["path",{d:"M10 3h.01",key:"lbucoy"}],["path",{d:"M14 2h.01",key:"1k8aa1"}],["path",{d:"m2 9 20-5",key:"1kz0j5"}],["path",{d:"M12 12V6.5",key:"1vbrij"}],["rect",{width:"16",height:"10",x:"4",y:"12",rx:"3",key:"if91er"}],["path",{d:"M9 12v5",key:"3anwtq"}],["path",{d:"M15 12v5",key:"5xh3zn"}],["path",{d:"M4 17h16",key:"g4d7ey"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JZ=re("Cable",[["path",{d:"M17 21v-2a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1",key:"10bnsj"}],["path",{d:"M19 15V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V9",key:"1eqmu1"}],["path",{d:"M21 21v-2h-4",key:"14zm7j"}],["path",{d:"M3 5h4V3",key:"z442eg"}],["path",{d:"M7 5a1 1 0 0 1 1 1v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1V3",key:"ebdjd7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eQ=re("CakeSlice",[["circle",{cx:"9",cy:"7",r:"2",key:"1305pl"}],["path",{d:"M7.2 7.9 3 11v9c0 .6.4 1 1 1h16c.6 0 1-.4 1-1v-9c0-2-3-6-7-8l-3.6 2.6",key:"xle13f"}],["path",{d:"M16 13H3",key:"1wpj08"}],["path",{d:"M16 17H3",key:"3lvfcd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hu=re("Cake",[["path",{d:"M20 21v-8a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8",key:"1w3rig"}],["path",{d:"M4 16s.5-1 2-1 2.5 2 4 2 2.5-2 4-2 2.5 2 4 2 2-1 2-1",key:"n2jgmb"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M7 8v3",key:"1qtyvj"}],["path",{d:"M12 8v3",key:"hwp4zt"}],["path",{d:"M17 8v3",key:"1i6e5u"}],["path",{d:"M7 4h.01",key:"1bh4kh"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M17 4h.01",key:"1upcoc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xw=re("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tQ=re("Calendar1",[["path",{d:"M11 14h1v4",key:"fy54vd"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sQ=re("CalendarArrowDown",[["path",{d:"m14 18 4 4 4-4",key:"1waygx"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M18 14v8",key:"irew45"}],["path",{d:"M21 11.354V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h7.343",key:"bse4f3"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nQ=re("CalendarArrowUp",[["path",{d:"m14 18 4-4 4 4",key:"ftkppy"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M18 22v-8",key:"su0gjh"}],["path",{d:"M21 11.343V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h9",key:"1exg90"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rQ=re("CalendarCheck2",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 14V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"bce9hv"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m16 20 2 2 4-4",key:"13tcca"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QS=re("CalendarCheck",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m9 16 2 2 4-4",key:"19s6y9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cm=re("CalendarClock",[["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M17.5 17.5 16 16.3V14",key:"akvzfd"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aQ=re("CalendarCog",[["path",{d:"m15.2 16.9-.9-.4",key:"1r0w5f"}],["path",{d:"m15.2 19.1-.9.4",key:"j188fs"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"m16.9 15.2-.4-.9",key:"699xu"}],["path",{d:"m16.9 20.8-.4.9",key:"dfjc4z"}],["path",{d:"m19.5 14.3-.4.9",key:"1eb35c"}],["path",{d:"m19.5 21.7-.4-.9",key:"1tonu5"}],["path",{d:"M21 10.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6",key:"11kmuh"}],["path",{d:"m21.7 16.5-.9.4",key:"1knoei"}],["path",{d:"m21.7 19.5-.9-.4",key:"q4dx6b"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tl=re("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iQ=re("CalendarFold",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 17V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h11Z",key:"kg77oy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M15 22v-4a2 2 0 0 1 2-2h4",key:"1gnbqr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mb=re("CalendarHeart",[["path",{d:"M3 10h18V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h7",key:"136lmk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21.29 14.7a2.43 2.43 0 0 0-2.65-.52c-.3.12-.57.3-.8.53l-.34.34-.35-.34a2.43 2.43 0 0 0-2.65-.53c-.3.12-.56.3-.79.53-.95.94-1 2.53.2 3.74L17.5 22l3.6-3.55c1.2-1.21 1.14-2.8.19-3.74Z",key:"1t7hil"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oQ=re("CalendarMinus2",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M10 16h4",key:"17e571"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lQ=re("CalendarMinus",[["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 15V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8.5",key:"1scpom"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q7=re("CalendarOff",[["path",{d:"M4.2 4.2A2 2 0 0 0 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 1.82-1.18",key:"16swn3"}],["path",{d:"M21 15.5V6a2 2 0 0 0-2-2H9.5",key:"yhw86o"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h7",key:"1wap6i"}],["path",{d:"M21 10h-5.5",key:"quycpq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cQ=re("CalendarPlus2",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M10 16h4",key:"17e571"}],["path",{d:"M12 14v4",key:"1thi36"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fg=re("CalendarPlus",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 13V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"3spt84"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M19 16v6",key:"tddt3s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dQ=re("CalendarRange",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M17 14h-6",key:"bkmgh3"}],["path",{d:"M13 18H7",key:"bb0bb7"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 18h.01",key:"1bdyru"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uQ=re("CalendarSearch",[["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 11.75V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h7.25",key:"1jrsq6"}],["path",{d:"m22 22-1.875-1.875",key:"13zax7"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hQ=re("CalendarSync",[["path",{d:"M11 10v4h4",key:"172dkj"}],["path",{d:"m11 14 1.535-1.605a5 5 0 0 1 8 1.5",key:"vu0qm5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"m21 18-1.535 1.605a5 5 0 0 1-8-1.5",key:"1qgeyt"}],["path",{d:"M21 22v-4h-4",key:"hrummi"}],["path",{d:"M21 8.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h4.3",key:"mctw84"}],["path",{d:"M3 10h4",key:"1el30a"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mQ=re("CalendarX2",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 13V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"3spt84"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m17 22 5-5",key:"1k6ppv"}],["path",{d:"m17 17 5 5",key:"p7ous7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X7=re("CalendarX",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m14 14-4 4",key:"rymu2i"}],["path",{d:"m10 14 4 4",key:"3sz06r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yr=re("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pQ=re("CameraOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16",key:"qmtpty"}],["path",{d:"M9.5 4h5L17 7h3a2 2 0 0 1 2 2v7.5",key:"1ufyfc"}],["path",{d:"M14.121 15.121A3 3 0 1 1 9.88 10.88",key:"11zox6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pf=re("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fQ=re("CandyCane",[["path",{d:"M5.7 21a2 2 0 0 1-3.5-2l8.6-14a6 6 0 0 1 10.4 6 2 2 0 1 1-3.464-2 2 2 0 1 0-3.464-2Z",key:"isaq8g"}],["path",{d:"M17.75 7 15 2.1",key:"12x7e8"}],["path",{d:"M10.9 4.8 13 9",key:"100a87"}],["path",{d:"m7.9 9.7 2 4.4",key:"ntfhaj"}],["path",{d:"M4.9 14.7 7 18.9",key:"1x43jy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xQ=re("CandyOff",[["path",{d:"m8.5 8.5-1 1a4.95 4.95 0 0 0 7 7l1-1",key:"1ff4ui"}],["path",{d:"M11.843 6.187A4.947 4.947 0 0 1 16.5 7.5a4.947 4.947 0 0 1 1.313 4.657",key:"1sbrv4"}],["path",{d:"M14 16.5V14",key:"1maf8j"}],["path",{d:"M14 6.5v1.843",key:"1a6u6t"}],["path",{d:"M10 10v7.5",key:"80pj65"}],["path",{d:"m16 7 1-5 1.367.683A3 3 0 0 0 19.708 3H21v1.292a3 3 0 0 0 .317 1.341L22 7l-5 1",key:"11a9mt"}],["path",{d:"m8 17-1 5-1.367-.683A3 3 0 0 0 4.292 21H3v-1.292a3 3 0 0 0-.317-1.341L2 17l5-1",key:"3mjmon"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gQ=re("Candy",[["path",{d:"m9.5 7.5-2 2a4.95 4.95 0 1 0 7 7l2-2a4.95 4.95 0 1 0-7-7Z",key:"ue6khb"}],["path",{d:"M14 6.5v10",key:"5xnk7c"}],["path",{d:"M10 7.5v10",key:"1uew51"}],["path",{d:"m16 7 1-5 1.37.68A3 3 0 0 0 19.7 3H21v1.3c0 .46.1.92.32 1.33L22 7l-5 1",key:"b9cp6k"}],["path",{d:"m8 17-1 5-1.37-.68A3 3 0 0 0 4.3 21H3v-1.3a3 3 0 0 0-.32-1.33L2 17l5-1",key:"5lney8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yQ=re("Cannabis",[["path",{d:"M12 22v-4",key:"1utk9m"}],["path",{d:"M7 12c-1.5 0-4.5 1.5-5 3 3.5 1.5 6 1 6 1-1.5 1.5-2 3.5-2 5 2.5 0 4.5-1.5 6-3 1.5 1.5 3.5 3 6 3 0-1.5-.5-3.5-2-5 0 0 2.5.5 6-1-.5-1.5-3.5-3-5-3 1.5-1 4-4 4-6-2.5 0-5.5 1.5-7 3 0-2.5-.5-5-2-7-1.5 2-2 4.5-2 7-1.5-1.5-4.5-3-7-3 0 2 2.5 5 4 6",key:"1mezod"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vQ=re("CaptionsOff",[["path",{d:"M10.5 5H19a2 2 0 0 1 2 2v8.5",key:"jqtk4d"}],["path",{d:"M17 11h-.5",key:"1961ue"}],["path",{d:"M19 19H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2",key:"1keqsi"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M7 11h4",key:"1o1z6v"}],["path",{d:"M7 15h2.5",key:"1ina1g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const B3=re("Captions",[["rect",{width:"18",height:"14",x:"3",y:"5",rx:"2",ry:"2",key:"12ruh7"}],["path",{d:"M7 15h4M15 15h2M7 11h2M13 11h4",key:"1ueiar"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bQ=re("CarFront",[["path",{d:"m21 8-2 2-1.5-3.7A2 2 0 0 0 15.646 5H8.4a2 2 0 0 0-1.903 1.257L5 10 3 8",key:"1imjwt"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 14h.01",key:"7oqj8z"}],["rect",{width:"18",height:"8",x:"3",y:"10",rx:"2",key:"a7itu8"}],["path",{d:"M5 18v2",key:"ppbyun"}],["path",{d:"M19 18v2",key:"gy7782"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _Q=re("CarTaxiFront",[["path",{d:"M10 2h4",key:"n1abiw"}],["path",{d:"m21 8-2 2-1.5-3.7A2 2 0 0 0 15.646 5H8.4a2 2 0 0 0-1.903 1.257L5 10 3 8",key:"1imjwt"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 14h.01",key:"7oqj8z"}],["rect",{width:"18",height:"8",x:"3",y:"10",rx:"2",key:"a7itu8"}],["path",{d:"M5 18v2",key:"ppbyun"}],["path",{d:"M19 18v2",key:"gy7782"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wQ=re("Car",[["path",{d:"M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2",key:"5owen"}],["circle",{cx:"7",cy:"17",r:"2",key:"u2ysq9"}],["path",{d:"M9 17h6",key:"r8uit2"}],["circle",{cx:"17",cy:"17",r:"2",key:"axvx0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jQ=re("Caravan",[["path",{d:"M18 19V9a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v8a2 2 0 0 0 2 2h2",key:"19jm3t"}],["path",{d:"M2 9h3a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H2",key:"13hakp"}],["path",{d:"M22 17v1a1 1 0 0 1-1 1H10v-9a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v9",key:"1crci8"}],["circle",{cx:"8",cy:"19",r:"2",key:"t8fc5s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NQ=re("Carrot",[["path",{d:"M2.27 21.7s9.87-3.5 12.73-6.36a4.5 4.5 0 0 0-6.36-6.37C5.77 11.84 2.27 21.7 2.27 21.7zM8.64 14l-2.05-2.04M15.34 15l-2.46-2.46",key:"rfqxbe"}],["path",{d:"M22 9s-1.33-2-3.5-2C16.86 7 15 9 15 9s1.33 2 3.5 2S22 9 22 9z",key:"6b25w4"}],["path",{d:"M15 2s-2 1.33-2 3.5S15 9 15 9s2-1.84 2-3.5C17 3.33 15 2 15 2z",key:"fn65lo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kQ=re("CaseLower",[["circle",{cx:"7",cy:"12",r:"3",key:"12clwm"}],["path",{d:"M10 9v6",key:"17i7lo"}],["circle",{cx:"17",cy:"12",r:"3",key:"gl7c2s"}],["path",{d:"M14 7v8",key:"dl84cr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SQ=re("CaseSensitive",[["path",{d:"m3 15 4-8 4 8",key:"1vwr6u"}],["path",{d:"M4 13h6",key:"1r9ots"}],["circle",{cx:"18",cy:"12",r:"3",key:"1kchzo"}],["path",{d:"M21 9v6",key:"anns31"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CQ=re("CaseUpper",[["path",{d:"m3 15 4-8 4 8",key:"1vwr6u"}],["path",{d:"M4 13h6",key:"1r9ots"}],["path",{d:"M15 11h4.5a2 2 0 0 1 0 4H15V7h4a2 2 0 0 1 0 4",key:"1sqfas"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TQ=re("CassetteTape",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["circle",{cx:"8",cy:"10",r:"2",key:"1xl4ub"}],["path",{d:"M8 12h8",key:"1wcyev"}],["circle",{cx:"16",cy:"10",r:"2",key:"r14t7q"}],["path",{d:"m6 20 .7-2.9A1.4 1.4 0 0 1 8.1 16h7.8a1.4 1.4 0 0 1 1.4 1l.7 3",key:"l01ucn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EQ=re("Cast",[["path",{d:"M2 8V6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6",key:"3zrzxg"}],["path",{d:"M2 12a9 9 0 0 1 8 8",key:"g6cvee"}],["path",{d:"M2 16a5 5 0 0 1 4 4",key:"1y1dii"}],["line",{x1:"2",x2:"2.01",y1:"20",y2:"20",key:"xu2jvo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AQ=re("Castle",[["path",{d:"M22 20v-9H2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2Z",key:"109fe4"}],["path",{d:"M18 11V4H6v7",key:"mon5oj"}],["path",{d:"M15 22v-4a3 3 0 0 0-3-3a3 3 0 0 0-3 3v4",key:"1k4jtn"}],["path",{d:"M22 11V9",key:"3zbp94"}],["path",{d:"M2 11V9",key:"1x5rnq"}],["path",{d:"M6 4V2",key:"1rsq15"}],["path",{d:"M18 4V2",key:"1jsdo1"}],["path",{d:"M10 4V2",key:"75d9ly"}],["path",{d:"M14 4V2",key:"8nj3z6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MQ=re("Cat",[["path",{d:"M12 5c.67 0 1.35.09 2 .26 1.78-2 5.03-2.84 6.42-2.26 1.4.58-.42 7-.42 7 .57 1.07 1 2.24 1 3.44C21 17.9 16.97 21 12 21s-9-3-9-7.56c0-1.25.5-2.4 1-3.44 0 0-1.89-6.42-.5-7 1.39-.58 4.72.23 6.5 2.23A9.04 9.04 0 0 1 12 5Z",key:"x6xyqk"}],["path",{d:"M8 14v.5",key:"1nzgdb"}],["path",{d:"M16 14v.5",key:"1lajdz"}],["path",{d:"M11.25 16.25h1.5L12 17l-.75-.75Z",key:"12kq1m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IQ=re("Cctv",[["path",{d:"M16.75 12h3.632a1 1 0 0 1 .894 1.447l-2.034 4.069a1 1 0 0 1-1.708.134l-2.124-2.97",key:"ir91b5"}],["path",{d:"M17.106 9.053a1 1 0 0 1 .447 1.341l-3.106 6.211a1 1 0 0 1-1.342.447L3.61 12.3a2.92 2.92 0 0 1-1.3-3.91L3.69 5.6a2.92 2.92 0 0 1 3.92-1.3z",key:"jlp8i1"}],["path",{d:"M2 19h3.76a2 2 0 0 0 1.8-1.1L9 15",key:"19bib8"}],["path",{d:"M2 21v-4",key:"l40lih"}],["path",{d:"M7 9h.01",key:"19b3jx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $3=re("ChartArea",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z",key:"q0gr47"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U3=re("ChartBarBig",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"7",y:"13",width:"9",height:"4",rx:"1",key:"1iip1u"}],["rect",{x:"7",y:"5",width:"12",height:"4",rx:"1",key:"1anskk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PQ=re("ChartBarDecreasing",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11h8",key:"1feolt"}],["path",{d:"M7 16h3",key:"ur6vzw"}],["path",{d:"M7 6h12",key:"sz5b0d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LQ=re("ChartBarIncreasing",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11h8",key:"1feolt"}],["path",{d:"M7 16h12",key:"wsnu98"}],["path",{d:"M7 6h3",key:"w9rmul"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DQ=re("ChartBarStacked",[["path",{d:"M11 13v4",key:"vyy2rb"}],["path",{d:"M15 5v4",key:"1gx88a"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"7",y:"13",width:"9",height:"4",rx:"1",key:"1iip1u"}],["rect",{x:"7",y:"5",width:"12",height:"4",rx:"1",key:"1anskk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q3=re("ChartBar",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 16h8",key:"srdodz"}],["path",{d:"M7 11h12",key:"127s9w"}],["path",{d:"M7 6h3",key:"w9rmul"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V3=re("ChartCandlestick",[["path",{d:"M9 5v4",key:"14uxtq"}],["rect",{width:"4",height:"6",x:"7",y:"9",rx:"1",key:"f4fvz0"}],["path",{d:"M9 15v2",key:"r5rk32"}],["path",{d:"M17 3v2",key:"1l2re6"}],["rect",{width:"4",height:"8",x:"15",y:"5",rx:"1",key:"z38je5"}],["path",{d:"M17 13v3",key:"5l0wba"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H3=re("ChartColumnBig",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RQ=re("ChartColumnDecreasing",[["path",{d:"M13 17V9",key:"1fwyjl"}],["path",{d:"M18 17v-3",key:"1sqioe"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 17V5",key:"1wzmnc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G3=re("ChartColumnIncreasing",[["path",{d:"M13 17V9",key:"1fwyjl"}],["path",{d:"M18 17V5",key:"sfb6ij"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OQ=re("ChartColumnStacked",[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yo=re("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FQ=re("ChartGantt",[["path",{d:"M10 6h8",key:"zvc2xc"}],["path",{d:"M12 16h6",key:"yi5mkt"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 11h7",key:"wz2hg0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W3=re("ChartLine",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zQ=re("ChartNetwork",[["path",{d:"m13.11 7.664 1.78 2.672",key:"go2gg9"}],["path",{d:"m14.162 12.788-3.324 1.424",key:"11x848"}],["path",{d:"m20 4-6.06 1.515",key:"1wxxh7"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["circle",{cx:"12",cy:"6",r:"2",key:"1jj5th"}],["circle",{cx:"16",cy:"12",r:"2",key:"4ma0v8"}],["circle",{cx:"9",cy:"15",r:"2",key:"lf2ghp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BQ=re("ChartNoAxesColumnDecreasing",[["path",{d:"M12 20V10",key:"g8npz5"}],["path",{d:"M18 20v-4",key:"8uic4z"}],["path",{d:"M6 20V4",key:"1w1bmo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K3=re("ChartNoAxesColumnIncreasing",[["line",{x1:"12",x2:"12",y1:"20",y2:"10",key:"1vz5eb"}],["line",{x1:"18",x2:"18",y1:"20",y2:"4",key:"cun8e5"}],["line",{x1:"6",x2:"6",y1:"20",y2:"16",key:"hq0ia6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y3=re("ChartNoAxesColumn",[["line",{x1:"18",x2:"18",y1:"20",y2:"10",key:"1xfpm4"}],["line",{x1:"12",x2:"12",y1:"20",y2:"4",key:"be30l9"}],["line",{x1:"6",x2:"6",y1:"20",y2:"14",key:"1r4le6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $Q=re("ChartNoAxesCombined",[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14v7",key:"1g90b9"}],["path",{d:"M20 10v11",key:"1iqoj0"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18v3",key:"1yp0dc"}],["path",{d:"M8 14v7",key:"n3cwzv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z3=re("ChartNoAxesGantt",[["path",{d:"M8 6h10",key:"9lnwnk"}],["path",{d:"M6 12h9",key:"1g9pqf"}],["path",{d:"M11 18h7",key:"c8dzvl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q3=re("ChartPie",[["path",{d:"M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z",key:"pzmjnu"}],["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X3=re("ChartScatter",[["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}],["circle",{cx:"18.5",cy:"5.5",r:".5",fill:"currentColor",key:"lysivs"}],["circle",{cx:"11.5",cy:"11.5",r:".5",fill:"currentColor",key:"byv1b8"}],["circle",{cx:"7.5",cy:"16.5",r:".5",fill:"currentColor",key:"nkw3mc"}],["circle",{cx:"17.5",cy:"14.5",r:".5",fill:"currentColor",key:"1gjh6j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UQ=re("ChartSpline",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 16c.5-2 1.5-7 4-7 2 0 2 3 4 3 2.5 0 4.5-5 5-7",key:"lw07rv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J7=re("CheckCheck",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lr=re("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qQ=re("ChefHat",[["path",{d:"M17 21a1 1 0 0 0 1-1v-5.35c0-.457.316-.844.727-1.041a4 4 0 0 0-2.134-7.589 5 5 0 0 0-9.186 0 4 4 0 0 0-2.134 7.588c.411.198.727.585.727 1.041V20a1 1 0 0 0 1 1Z",key:"1qvrer"}],["path",{d:"M6 17h12",key:"1jwigz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VQ=re("Cherry",[["path",{d:"M2 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z",key:"cvxqlc"}],["path",{d:"M12 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z",key:"1ostrc"}],["path",{d:"M7 14c3.22-2.91 4.29-8.75 5-12 1.66 2.38 4.94 9 5 12",key:"hqx58h"}],["path",{d:"M22 9c-4.29 0-7.14-2.33-10-7 5.71 0 10 4.67 10 7Z",key:"eykp1o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const io=re("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HQ=re("ChevronFirst",[["path",{d:"m17 18-6-6 6-6",key:"1yerx2"}],["path",{d:"M7 6v12",key:"1p53r6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GQ=re("ChevronLast",[["path",{d:"m7 18 6-6-6-6",key:"lwmzdw"}],["path",{d:"M17 6v12",key:"1o0aio"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fl=re("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ga=re("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sx=re("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WQ=re("ChevronsDownUp",[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KQ=re("ChevronsDown",[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YQ=re("ChevronsLeftRightEllipsis",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZQ=re("ChevronsLeftRight",[["path",{d:"m9 7-5 5 5 5",key:"j5w590"}],["path",{d:"m15 7 5 5-5 5",key:"1bl6da"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QQ=re("ChevronsLeft",[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XQ=re("ChevronsRightLeft",[["path",{d:"m20 17-5-5 5-5",key:"30x0n2"}],["path",{d:"m4 17 5-5-5-5",key:"16spf4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JQ=re("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hg=re("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eX=re("ChevronsUp",[["path",{d:"m17 11-5-5-5 5",key:"e8nh98"}],["path",{d:"m17 18-5-5-5 5",key:"2avn1x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kA=re("Chrome",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["line",{x1:"21.17",x2:"12",y1:"8",y2:"8",key:"a0cw5f"}],["line",{x1:"3.95",x2:"8.54",y1:"6.06",y2:"14",key:"1kftof"}],["line",{x1:"10.88",x2:"15.46",y1:"21.94",y2:"14",key:"1ymyh8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tX=re("Church",[["path",{d:"M10 9h4",key:"u4k05v"}],["path",{d:"M12 7v5",key:"ma6bk"}],["path",{d:"M14 22v-4a2 2 0 0 0-4 0v4",key:"1pdhuj"}],["path",{d:"M18 22V5.618a1 1 0 0 0-.553-.894l-4.553-2.277a2 2 0 0 0-1.788 0L6.553 4.724A1 1 0 0 0 6 5.618V22",key:"1rkokr"}],["path",{d:"m18 7 3.447 1.724a1 1 0 0 1 .553.894V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9.618a1 1 0 0 1 .553-.894L6 7",key:"1w6esw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sX=re("CigaretteOff",[["path",{d:"M12 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h13",key:"1gdiyg"}],["path",{d:"M18 8c0-2.5-2-2.5-2-5",key:"1il607"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M21 12a1 1 0 0 1 1 1v2a1 1 0 0 1-.5.866",key:"166zjj"}],["path",{d:"M22 8c0-2.5-2-2.5-2-5",key:"1gah44"}],["path",{d:"M7 12v4",key:"jqww69"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nX=re("Cigarette",[["path",{d:"M17 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h14",key:"1mb5g1"}],["path",{d:"M18 8c0-2.5-2-2.5-2-5",key:"1il607"}],["path",{d:"M21 16a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"1yl5r7"}],["path",{d:"M22 8c0-2.5-2-2.5-2-5",key:"1gah44"}],["path",{d:"M7 12v4",key:"jqww69"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gi=re("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J3=re("CircleArrowDown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8 12 4 4 4-4",key:"k98ssh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e5=re("CircleArrowLeft",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 12H8",key:"1fr5h0"}],["path",{d:"m12 8-4 4 4 4",key:"15vm53"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t5=re("CircleArrowOutDownLeft",[["path",{d:"M2 12a10 10 0 1 1 10 10",key:"1yn6ov"}],["path",{d:"m2 22 10-10",key:"28ilpk"}],["path",{d:"M8 22H2v-6",key:"sulq54"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const s5=re("CircleArrowOutDownRight",[["path",{d:"M12 22a10 10 0 1 1 10-10",key:"130bv5"}],["path",{d:"M22 22 12 12",key:"131aw7"}],["path",{d:"M22 16v6h-6",key:"1gvm70"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n5=re("CircleArrowOutUpLeft",[["path",{d:"M2 8V2h6",key:"hiwtdz"}],["path",{d:"m2 2 10 10",key:"1oh8rs"}],["path",{d:"M12 2A10 10 0 1 1 2 12",key:"rrk4fa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const r5=re("CircleArrowOutUpRight",[["path",{d:"M22 12A10 10 0 1 1 12 2",key:"1fm58d"}],["path",{d:"M22 2 12 12",key:"yg2myt"}],["path",{d:"M16 2h6v6",key:"zan5cs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a5=re("CircleArrowRight",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const i5=re("CircleArrowUp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zi=re("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xr=re("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const o5=re("CircleChevronDown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 10-4 4-4-4",key:"894hmk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const l5=re("CircleChevronLeft",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m14 16-4-4 4-4",key:"ojs7w8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const c5=re("CircleChevronRight",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m10 8 4 4-4 4",key:"1wy4r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const d5=re("CircleChevronUp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m8 14 4-4 4 4",key:"fy2ptz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rX=re("CircleDashed",[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const u5=re("CircleDivide",[["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}],["line",{x1:"12",x2:"12",y1:"16",y2:"16",key:"aqc6ln"}],["line",{x1:"12",x2:"12",y1:"8",y2:"8",key:"1mkcni"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aX=re("CircleDollarSign",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 18V6",key:"zqpxq5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iX=re("CircleDotDashed",[["path",{d:"M10.1 2.18a9.93 9.93 0 0 1 3.8 0",key:"1qdqn0"}],["path",{d:"M17.6 3.71a9.95 9.95 0 0 1 2.69 2.7",key:"1bq7p6"}],["path",{d:"M21.82 10.1a9.93 9.93 0 0 1 0 3.8",key:"1rlaqf"}],["path",{d:"M20.29 17.6a9.95 9.95 0 0 1-2.7 2.69",key:"1xk03u"}],["path",{d:"M13.9 21.82a9.94 9.94 0 0 1-3.8 0",key:"l7re25"}],["path",{d:"M6.4 20.29a9.95 9.95 0 0 1-2.69-2.7",key:"1v18p6"}],["path",{d:"M2.18 13.9a9.93 9.93 0 0 1 0-3.8",key:"xdo6bj"}],["path",{d:"M3.71 6.4a9.95 9.95 0 0 1 2.7-2.69",key:"1jjmaz"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oX=re("CircleDot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lX=re("CircleEllipsis",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M17 12h.01",key:"1m0b6t"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M7 12h.01",key:"eqddd0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cX=re("CircleEqual",[["path",{d:"M7 10h10",key:"1101jm"}],["path",{d:"M7 14h10",key:"1mhdw3"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dX=re("CircleFadingArrowUp",[["path",{d:"M12 2a10 10 0 0 1 7.38 16.75",key:"175t95"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}],["path",{d:"M2.5 8.875a10 10 0 0 0-.5 3",key:"1vce0s"}],["path",{d:"M2.83 16a10 10 0 0 0 2.43 3.4",key:"o3fkw4"}],["path",{d:"M4.636 5.235a10 10 0 0 1 .891-.857",key:"1szpfk"}],["path",{d:"M8.644 21.42a10 10 0 0 0 7.631-.38",key:"9yhvd4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uX=re("CircleFadingPlus",[["path",{d:"M12 2a10 10 0 0 1 7.38 16.75",key:"175t95"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"M16 12H8",key:"1fr5h0"}],["path",{d:"M2.5 8.875a10 10 0 0 0-.5 3",key:"1vce0s"}],["path",{d:"M2.83 16a10 10 0 0 0 2.43 3.4",key:"o3fkw4"}],["path",{d:"M4.636 5.235a10 10 0 0 1 .891-.857",key:"1szpfk"}],["path",{d:"M8.644 21.42a10 10 0 0 0 7.631-.38",key:"9yhvd4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const h5=re("CircleGauge",[["path",{d:"M15.6 2.7a10 10 0 1 0 5.7 5.7",key:"1e0p6d"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M13.4 10.6 19 5",key:"1kr7tw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y_=re("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const m5=re("CircleMinus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hX=re("CircleOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.35 2.69A10 10 0 0 1 21.3 15.65",key:"1pfsoa"}],["path",{d:"M19.08 19.08A10 10 0 1 1 4.92 4.92",key:"1ablyi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const p5=re("CircleParkingOff",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m5 5 14 14",key:"11anup"}],["path",{d:"M13 13a3 3 0 1 0 0-6H9v2",key:"uoagbd"}],["path",{d:"M9 17v-2.34",key:"a9qo08"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const f5=re("CircleParking",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9 17V7h4a3 3 0 0 1 0 6H9",key:"1dfk2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const x5=re("CirclePause",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const g5=re("CirclePercent",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pu=re("CirclePlay",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polygon",{points:"10 8 16 12 10 16 10 8",key:"1cimsy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const y5=re("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const v5=re("CirclePower",[["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M7.998 9.003a5 5 0 1 0 8-.005",key:"1pek45"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const b5=re("CircleSlash2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mX=re("CircleSlash",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _5=re("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w5=re("CircleUserRound",[["path",{d:"M18 20a6 6 0 0 0-12 0",key:"1qehca"}],["circle",{cx:"12",cy:"10",r:"4",key:"1h16sb"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const j5=re("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gc=re("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dm=re("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pX=re("CircuitBoard",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M11 9h4a2 2 0 0 0 2-2V3",key:"1ve2rv"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"M7 21v-4a2 2 0 0 1 2-2h4",key:"1fwkro"}],["circle",{cx:"15",cy:"15",r:"2",key:"3i40o0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fX=re("Citrus",[["path",{d:"M21.66 17.67a1.08 1.08 0 0 1-.04 1.6A12 12 0 0 1 4.73 2.38a1.1 1.1 0 0 1 1.61-.04z",key:"4ite01"}],["path",{d:"M19.65 15.66A8 8 0 0 1 8.35 4.34",key:"1gxipu"}],["path",{d:"m14 10-5.5 5.5",key:"92pfem"}],["path",{d:"M14 17.85V10H6.15",key:"xqmtsk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xX=re("Clapperboard",[["path",{d:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z",key:"1tn4o7"}],["path",{d:"m6.2 5.3 3.1 3.9",key:"iuk76l"}],["path",{d:"m12.4 3.4 3.1 4",key:"6hsd6n"}],["path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z",key:"ltgou9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W2=re("ClipboardCheck",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"m9 14 2 2 4-4",key:"df797q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gX=re("ClipboardCopy",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ov=re("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yX=re("ClipboardMinus",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M9 14h6",key:"159ibu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vX=re("ClipboardPaste",[["path",{d:"M15 2H9a1 1 0 0 0-1 1v2c0 .6.4 1 1 1h6c.6 0 1-.4 1-1V3c0-.6-.4-1-1-1Z",key:"1pp7kr"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2M16 4h2a2 2 0 0 1 2 2v2M11 14h10",key:"2ik1ml"}],["path",{d:"m17 10 4 4-4 4",key:"vp2hj1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const N5=re("ClipboardPenLine",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",key:"1oijnt"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-.5",key:"1but9f"}],["path",{d:"M16 4h2a2 2 0 0 1 1.73 1",key:"1p8n7l"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k5=re("ClipboardPen",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",key:"1oijnt"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-5.5",key:"cereej"}],["path",{d:"M4 13.5V6a2 2 0 0 1 2-2h2",key:"5ua5vh"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bX=re("ClipboardPlus",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M9 14h6",key:"159ibu"}],["path",{d:"M12 17v-6",key:"1y8rbf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _X=re("ClipboardType",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M9 12v-1h6v1",key:"iehl6m"}],["path",{d:"M11 17h2",key:"12w5me"}],["path",{d:"M12 11v6",key:"1bwqyc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wX=re("ClipboardX",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"m15 11-6 6",key:"1toa9n"}],["path",{d:"m9 11 6 6",key:"wlibny"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jX=re("Clipboard",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NX=re("Clock1",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 14.5 8",key:"12zbmj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kX=re("Clock10",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 8 10",key:"atfzqc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SX=re("Clock11",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 9.5 8",key:"l5bg6f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CX=re("Clock12",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12",key:"1fub01"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TX=re("Clock2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 10",key:"1g230d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e9=re("Clock3",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16.5 12",key:"1aq6pp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EX=re("Clock4",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AX=re("Clock5",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 14.5 16",key:"1pcbox"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MX=re("Clock6",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 12 16.5",key:"hb2qv6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IX=re("Clock7",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 9.5 16",key:"ka3394"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PX=re("Clock8",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 8 14",key:"tmc9b4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LX=re("Clock9",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 7.5 12",key:"1k60p0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DX=re("ClockAlert",[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["path",{d:"M16 21.16a10 10 0 1 1 5-13.516",key:"cxo92l"}],["path",{d:"M20 11.5v6",key:"2ei3xq"}],["path",{d:"M20 21.5h.01",key:"1r2dzp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RX=re("ClockArrowDown",[["path",{d:"M12.338 21.994A10 10 0 1 1 21.925 13.227",key:"1i7shu"}],["path",{d:"M12 6v6l2 1",key:"19cm8n"}],["path",{d:"m14 18 4 4 4-4",key:"1waygx"}],["path",{d:"M18 14v8",key:"irew45"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OX=re("ClockArrowUp",[["path",{d:"M13.228 21.925A10 10 0 1 1 21.994 12.338",key:"1fzlyi"}],["path",{d:"M12 6v6l1.562.781",key:"1ujuk9"}],["path",{d:"m14 18 4-4 4 4",key:"ftkppy"}],["path",{d:"M18 22v-8",key:"su0gjh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gr=re("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FX=re("CloudAlert",[["path",{d:"M12 12v4",key:"tww15h"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M17 18h.5a1 1 0 0 0 0-9h-1.79A7 7 0 1 0 7 17.708",key:"xsb5ju"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zX=re("CloudCog",[["circle",{cx:"12",cy:"17",r:"3",key:"1spfwm"}],["path",{d:"M4.2 15.1A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.2",key:"zaobp"}],["path",{d:"m15.7 18.4-.9-.3",key:"4qxpbn"}],["path",{d:"m9.2 15.9-.9-.3",key:"17q7o2"}],["path",{d:"m10.6 20.7.3-.9",key:"1pf4s2"}],["path",{d:"m13.1 14.2.3-.9",key:"1mnuqm"}],["path",{d:"m13.6 20.7-.4-1",key:"1jpd1m"}],["path",{d:"m10.8 14.3-.4-1",key:"17ugyy"}],["path",{d:"m8.3 18.6 1-.4",key:"s42vdx"}],["path",{d:"m14.7 15.8 1-.4",key:"2wizun"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S5=re("CloudDownload",[["path",{d:"M12 13v8l-4-4",key:"1f5nwf"}],["path",{d:"m12 21 4-4",key:"1lfcce"}],["path",{d:"M4.393 15.269A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.436 8.284",key:"ui1hmy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BX=re("CloudDrizzle",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M8 19v1",key:"1dk2by"}],["path",{d:"M8 14v1",key:"84yxot"}],["path",{d:"M16 19v1",key:"v220m7"}],["path",{d:"M16 14v1",key:"g12gj6"}],["path",{d:"M12 21v1",key:"q8vafk"}],["path",{d:"M12 16v1",key:"1mx6rx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $X=re("CloudFog",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 17H7",key:"pygtm1"}],["path",{d:"M17 21H9",key:"1u2q02"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UX=re("CloudHail",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 14v2",key:"a1is7l"}],["path",{d:"M8 14v2",key:"1e9m6t"}],["path",{d:"M16 20h.01",key:"xwek51"}],["path",{d:"M8 20h.01",key:"1vjney"}],["path",{d:"M12 16v2",key:"z66u1j"}],["path",{d:"M12 22h.01",key:"1urd7a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qX=re("CloudLightning",[["path",{d:"M6 16.326A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 .5 8.973",key:"1cez44"}],["path",{d:"m13 12-3 5h4l-3 5",key:"1t22er"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VX=re("CloudMoonRain",[["path",{d:"M10.188 8.5A6 6 0 0 1 16 4a1 1 0 0 0 6 6 6 6 0 0 1-3 5.197",key:"erj67n"}],["path",{d:"M11 20v2",key:"174qtz"}],["path",{d:"M3 20a5 5 0 1 1 8.9-4H13a3 3 0 0 1 2 5.24",key:"1qmrp3"}],["path",{d:"M7 19v2",key:"12npes"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HX=re("CloudMoon",[["path",{d:"M10.188 8.5A6 6 0 0 1 16 4a1 1 0 0 0 6 6 6 6 0 0 1-3 5.197",key:"erj67n"}],["path",{d:"M13 16a3 3 0 1 1 0 6H7a5 5 0 1 1 4.9-6Z",key:"p44pc9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GX=re("CloudOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5.782 5.782A7 7 0 0 0 9 19h8.5a4.5 4.5 0 0 0 1.307-.193",key:"yfwify"}],["path",{d:"M21.532 16.5A4.5 4.5 0 0 0 17.5 10h-1.79A7.008 7.008 0 0 0 10 5.07",key:"jlfiyv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WX=re("CloudRainWind",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m9.2 22 3-7",key:"sb5f6j"}],["path",{d:"m9 13-3 7",key:"500co5"}],["path",{d:"m17 13-3 7",key:"8t2fiy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KX=re("CloudRain",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 14v6",key:"1j4efv"}],["path",{d:"M8 14v6",key:"17c4r9"}],["path",{d:"M12 16v6",key:"c8a4gj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YX=re("CloudSnow",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M8 19h.01",key:"puxtts"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M12 21h.01",key:"h35vbk"}],["path",{d:"M16 15h.01",key:"rnfrdf"}],["path",{d:"M16 19h.01",key:"1vcnzz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZX=re("CloudSunRain",[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M3 20a5 5 0 1 1 8.9-4H13a3 3 0 0 1 2 5.24",key:"1qmrp3"}],["path",{d:"M11 20v2",key:"174qtz"}],["path",{d:"M7 19v2",key:"12npes"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QX=re("CloudSun",[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z",key:"s09mg5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C5=re("CloudUpload",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XX=re("Cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JX=re("Cloudy",[["path",{d:"M17.5 21H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"gqqjvc"}],["path",{d:"M22 10a3 3 0 0 0-3-3h-2.207a5.502 5.502 0 0 0-10.702.5",key:"1p2s76"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const O2=re("Clover",[["path",{d:"M16.17 7.83 2 22",key:"t58vo8"}],["path",{d:"M4.02 12a2.827 2.827 0 1 1 3.81-4.17A2.827 2.827 0 1 1 12 4.02a2.827 2.827 0 1 1 4.17 3.81A2.827 2.827 0 1 1 19.98 12a2.827 2.827 0 1 1-3.81 4.17A2.827 2.827 0 1 1 12 19.98a2.827 2.827 0 1 1-4.17-3.81A1 1 0 1 1 4 12",key:"17k36q"}],["path",{d:"m7.83 7.83 8.34 8.34",key:"1d7sxk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eJ=re("Club",[["path",{d:"M17.28 9.05a5.5 5.5 0 1 0-10.56 0A5.5 5.5 0 1 0 12 17.66a5.5 5.5 0 1 0 5.28-8.6Z",key:"27yuqz"}],["path",{d:"M12 17.66L12 22",key:"ogfahf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T2=re("CodeXml",[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SA=re("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tJ=re("Codepen",[["polygon",{points:"12 2 22 8.5 22 15.5 12 22 2 15.5 2 8.5 12 2",key:"srzb37"}],["line",{x1:"12",x2:"12",y1:"22",y2:"15.5",key:"1t73f2"}],["polyline",{points:"22 8.5 12 15.5 2 8.5",key:"ajlxae"}],["polyline",{points:"2 15.5 12 8.5 22 15.5",key:"susrui"}],["line",{x1:"12",x2:"12",y1:"2",y2:"8.5",key:"2cldga"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sJ=re("Codesandbox",[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}],["polyline",{points:"7.5 4.21 12 6.81 16.5 4.21",key:"fabo96"}],["polyline",{points:"7.5 19.79 7.5 14.6 3 12",key:"z377f1"}],["polyline",{points:"21 12 16.5 14.6 16.5 19.79",key:"9nrev1"}],["polyline",{points:"3.27 6.96 12 12.01 20.73 6.96",key:"1180pa"}],["line",{x1:"12",x2:"12",y1:"22.08",y2:"12",key:"3z3uq6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ry=re("Coffee",[["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M14 2v2",key:"6buw04"}],["path",{d:"M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1",key:"pwadti"}],["path",{d:"M6 2v2",key:"colzsn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nJ=re("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t9=re("Coins",[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T5=re("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yk=re("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rJ=re("Columns4",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7.5 3v18",key:"w0wo6v"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M16.5 3v18",key:"10tjh1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aJ=re("Combine",[["path",{d:"M10 18H5a3 3 0 0 1-3-3v-1",key:"ru65g8"}],["path",{d:"M14 2a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"e30een"}],["path",{d:"M20 2a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"2ahx8o"}],["path",{d:"m7 21 3-3-3-3",key:"127cv2"}],["rect",{x:"14",y:"14",width:"8",height:"8",rx:"2",key:"1b0bso"}],["rect",{x:"2",y:"2",width:"8",height:"8",rx:"2",key:"1x09vl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iJ=re("Command",[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sL=re("Compass",[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oJ=re("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lJ=re("Computer",[["rect",{width:"14",height:"8",x:"5",y:"2",rx:"2",key:"wc9tft"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6 18h2",key:"rwmk9e"}],["path",{d:"M12 18h6",key:"aqd8w3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cJ=re("ConciergeBell",[["path",{d:"M3 20a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1Z",key:"1pvr1r"}],["path",{d:"M20 16a8 8 0 1 0-16 0",key:"1pa543"}],["path",{d:"M12 4v4",key:"1bq03y"}],["path",{d:"M10 4h4",key:"1xpv9s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dJ=re("Cone",[["path",{d:"m20.9 18.55-8-15.98a1 1 0 0 0-1.8 0l-8 15.98",key:"53pte7"}],["ellipse",{cx:"12",cy:"19",rx:"9",ry:"3",key:"1ji25f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uJ=re("Construction",[["rect",{x:"2",y:"6",width:"20",height:"8",rx:"1",key:"1estib"}],["path",{d:"M17 14v7",key:"7m2elx"}],["path",{d:"M7 14v7",key:"1cm7wv"}],["path",{d:"M17 3v3",key:"1v4jwn"}],["path",{d:"M7 3v3",key:"7o6guu"}],["path",{d:"M10 14 2.3 6.3",key:"1023jk"}],["path",{d:"m14 6 7.7 7.7",key:"1s8pl2"}],["path",{d:"m8 6 8 8",key:"hl96qh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E5=re("ContactRound",[["path",{d:"M16 2v2",key:"scm5qe"}],["path",{d:"M17.915 22a6 6 0 0 0-12 0",key:"suqz9p"}],["path",{d:"M8 2v2",key:"pbkmx"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CA=re("Contact",[["path",{d:"M16 2v2",key:"scm5qe"}],["path",{d:"M7 22v-2a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2",key:"1waht3"}],["path",{d:"M8 2v2",key:"pbkmx"}],["circle",{cx:"12",cy:"11",r:"3",key:"itu57m"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hJ=re("Container",[["path",{d:"M22 7.7c0-.6-.4-1.2-.8-1.5l-6.3-3.9a1.72 1.72 0 0 0-1.7 0l-10.3 6c-.5.2-.9.8-.9 1.4v6.6c0 .5.4 1.2.8 1.5l6.3 3.9a1.72 1.72 0 0 0 1.7 0l10.3-6c.5-.3.9-1 .9-1.5Z",key:"1t2lqe"}],["path",{d:"M10 21.9V14L2.1 9.1",key:"o7czzq"}],["path",{d:"m10 14 11.9-6.9",key:"zm5e20"}],["path",{d:"M14 19.8v-8.1",key:"159ecu"}],["path",{d:"M18 17.5V9.4",key:"11uown"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mJ=re("Contrast",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 18a6 6 0 0 0 0-12v12z",key:"j4l70d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pJ=re("Cookie",[["path",{d:"M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5",key:"laymnq"}],["path",{d:"M8.5 8.5v.01",key:"ue8clq"}],["path",{d:"M16 15.5v.01",key:"14dtrp"}],["path",{d:"M12 12v.01",key:"u5ubse"}],["path",{d:"M11 17v.01",key:"1hyl5a"}],["path",{d:"M7 14v.01",key:"uct60s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fJ=re("CookingPot",[["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M20 12v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8",key:"u0tga0"}],["path",{d:"m4 8 16-4",key:"16g0ng"}],["path",{d:"m8.86 6.78-.45-1.81a2 2 0 0 1 1.45-2.43l1.94-.48a2 2 0 0 1 2.43 1.46l.45 1.8",key:"12cejc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xJ=re("CopyCheck",[["path",{d:"m12 15 2 2 4-4",key:"2c609p"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gJ=re("CopyMinus",[["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yJ=re("CopyPlus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vJ=re("CopySlash",[["line",{x1:"12",x2:"18",y1:"18",y2:"12",key:"ebkxgr"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bJ=re("CopyX",[["line",{x1:"12",x2:"18",y1:"12",y2:"18",key:"1rg63v"}],["line",{x1:"12",x2:"18",y1:"18",y2:"12",key:"ebkxgr"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ta=re("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _J=re("Copyleft",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.17 14.83a4 4 0 1 0 0-5.66",key:"1sveal"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wJ=re("Copyright",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M14.83 14.83a4 4 0 1 1 0-5.66",key:"1i56pz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jJ=re("CornerDownLeft",[["polyline",{points:"9 10 4 15 9 20",key:"r3jprv"}],["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NJ=re("CornerDownRight",[["polyline",{points:"15 10 20 15 15 20",key:"1q7qjw"}],["path",{d:"M4 4v7a4 4 0 0 0 4 4h12",key:"z08zvw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kJ=re("CornerLeftDown",[["polyline",{points:"14 15 9 20 4 15",key:"nkc4i"}],["path",{d:"M20 4h-7a4 4 0 0 0-4 4v12",key:"nbpdq2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SJ=re("CornerLeftUp",[["polyline",{points:"14 9 9 4 4 9",key:"m9oyvo"}],["path",{d:"M20 20h-7a4 4 0 0 1-4-4V4",key:"1blwi3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CJ=re("CornerRightDown",[["polyline",{points:"10 15 15 20 20 15",key:"axus6l"}],["path",{d:"M4 4h7a4 4 0 0 1 4 4v12",key:"wcbgct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TJ=re("CornerRightUp",[["polyline",{points:"10 9 15 4 20 9",key:"1lr6px"}],["path",{d:"M4 20h7a4 4 0 0 0 4-4V4",key:"1plgdj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EJ=re("CornerUpLeft",[["polyline",{points:"9 14 4 9 9 4",key:"881910"}],["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AJ=re("CornerUpRight",[["polyline",{points:"15 14 20 9 15 4",key:"1tbx3s"}],["path",{d:"M4 20v-7a4 4 0 0 1 4-4h12",key:"1lu4f8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MJ=re("Cpu",[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IJ=re("CreativeCommons",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M10 9.3a2.8 2.8 0 0 0-3.5 1 3.1 3.1 0 0 0 0 3.4 2.7 2.7 0 0 0 3.5 1",key:"1ss3eq"}],["path",{d:"M17 9.3a2.8 2.8 0 0 0-3.5 1 3.1 3.1 0 0 0 0 3.4 2.7 2.7 0 0 0 3.5 1",key:"1od56t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ff=re("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PJ=re("Croissant",[["path",{d:"m4.6 13.11 5.79-3.21c1.89-1.05 4.79 1.78 3.71 3.71l-3.22 5.81C8.8 23.16.79 15.23 4.6 13.11Z",key:"1ozxlb"}],["path",{d:"m10.5 9.5-1-2.29C9.2 6.48 8.8 6 8 6H4.5C2.79 6 2 6.5 2 8.5a7.71 7.71 0 0 0 2 4.83",key:"ffuyb5"}],["path",{d:"M8 6c0-1.55.24-4-2-4-2 0-2.5 2.17-2.5 4",key:"osnpzi"}],["path",{d:"m14.5 13.5 2.29 1c.73.3 1.21.7 1.21 1.5v3.5c0 1.71-.5 2.5-2.5 2.5a7.71 7.71 0 0 1-4.83-2",key:"1vubaw"}],["path",{d:"M18 16c1.55 0 4-.24 4 2 0 2-2.17 2.5-4 2.5",key:"wxr772"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LJ=re("Crop",[["path",{d:"M6 2v14a2 2 0 0 0 2 2h14",key:"ron5a4"}],["path",{d:"M18 22V8a2 2 0 0 0-2-2H2",key:"7s9ehn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DJ=re("Cross",[["path",{d:"M4 9a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h4a1 1 0 0 1 1 1v4a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-4a1 1 0 0 1 1-1h4a2 2 0 0 0 2-2v-2a2 2 0 0 0-2-2h-4a1 1 0 0 1-1-1V4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4a1 1 0 0 1-1 1z",key:"1xbrqy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RJ=re("Crosshair",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"22",x2:"18",y1:"12",y2:"12",key:"l9bcsi"}],["line",{x1:"6",x2:"2",y1:"12",y2:"12",key:"13hhkx"}],["line",{x1:"12",x2:"12",y1:"6",y2:"2",key:"10w3f3"}],["line",{x1:"12",x2:"12",y1:"22",y2:"18",key:"15g9kq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xf=re("Crown",[["path",{d:"M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z",key:"1vdc57"}],["path",{d:"M5 21h14",key:"11awu3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OJ=re("Cuboid",[["path",{d:"m21.12 6.4-6.05-4.06a2 2 0 0 0-2.17-.05L2.95 8.41a2 2 0 0 0-.95 1.7v5.82a2 2 0 0 0 .88 1.66l6.05 4.07a2 2 0 0 0 2.17.05l9.95-6.12a2 2 0 0 0 .95-1.7V8.06a2 2 0 0 0-.88-1.66Z",key:"1u2ovd"}],["path",{d:"M10 22v-8L2.25 9.15",key:"11pn4q"}],["path",{d:"m10 14 11.77-6.87",key:"1kt1wh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FJ=re("CupSoda",[["path",{d:"m6 8 1.75 12.28a2 2 0 0 0 2 1.72h4.54a2 2 0 0 0 2-1.72L18 8",key:"8166m8"}],["path",{d:"M5 8h14",key:"pcz4l3"}],["path",{d:"M7 15a6.47 6.47 0 0 1 5 0 6.47 6.47 0 0 0 5 0",key:"yjz344"}],["path",{d:"m12 8 1-6h2",key:"3ybfa4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zJ=re("Currency",[["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}],["line",{x1:"3",x2:"6",y1:"3",y2:"6",key:"1jkytn"}],["line",{x1:"21",x2:"18",y1:"3",y2:"6",key:"14zfjt"}],["line",{x1:"3",x2:"6",y1:"21",y2:"18",key:"iusuec"}],["line",{x1:"21",x2:"18",y1:"21",y2:"18",key:"yj2dd7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BJ=re("Cylinder",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5v14a9 3 0 0 0 18 0V5",key:"aqi0yr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $J=re("Dam",[["path",{d:"M11 11.31c1.17.56 1.54 1.69 3.5 1.69 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"157kva"}],["path",{d:"M11.75 18c.35.5 1.45 1 2.75 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"d7q6m6"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M7 3a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1L10 4a1 1 0 0 0-1-1z",key:"pr6s65"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UJ=re("DatabaseBackup",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 12a9 3 0 0 0 5 2.69",key:"1ui2ym"}],["path",{d:"M21 9.3V5",key:"6k6cib"}],["path",{d:"M3 5v14a9 3 0 0 0 6.47 2.88",key:"i62tjy"}],["path",{d:"M12 12v4h4",key:"1bxaet"}],["path",{d:"M13 20a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L12 16",key:"1f4ei9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qJ=re("DatabaseZap",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const s9=re("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VJ=re("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HJ=re("Dessert",[["circle",{cx:"12",cy:"4",r:"2",key:"muu5ef"}],["path",{d:"M10.2 3.2C5.5 4 2 8.1 2 13a2 2 0 0 0 4 0v-1a2 2 0 0 1 4 0v4a2 2 0 0 0 4 0v-4a2 2 0 0 1 4 0v1a2 2 0 0 0 4 0c0-4.9-3.5-9-8.2-9.8",key:"lfo06j"}],["path",{d:"M3.2 14.8a9 9 0 0 0 17.6 0",key:"12xarc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GJ=re("Diameter",[["circle",{cx:"19",cy:"19",r:"2",key:"17f5cg"}],["circle",{cx:"5",cy:"5",r:"2",key:"1gwv83"}],["path",{d:"M6.48 3.66a10 10 0 0 1 13.86 13.86",key:"xr8kdq"}],["path",{d:"m6.41 6.41 11.18 11.18",key:"uhpjw7"}],["path",{d:"M3.66 6.48a10 10 0 0 0 13.86 13.86",key:"cldpwv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WJ=re("DiamondMinus",[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41L13.7 2.71a2.41 2.41 0 0 0-3.41 0z",key:"1ey20j"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A5=re("DiamondPercent",[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41L13.7 2.71a2.41 2.41 0 0 0-3.41 0Z",key:"1tpxz2"}],["path",{d:"M9.2 9.2h.01",key:"1b7bvt"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"M14.7 14.8h.01",key:"17nsh4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KJ=re("DiamondPlus",[["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41L13.7 2.71a2.41 2.41 0 0 0-3.41 0z",key:"1ey20j"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YJ=re("Diamond",[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z",key:"1f1r0c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZJ=re("Dice1",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QJ=re("Dice2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M9 15h.01",key:"fzyn71"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XJ=re("Dice3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JJ=re("Dice4",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M8 8h.01",key:"1e4136"}],["path",{d:"M8 16h.01",key:"18s6g9"}],["path",{d:"M16 16h.01",key:"1f9h7w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eee=re("Dice5",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M8 8h.01",key:"1e4136"}],["path",{d:"M8 16h.01",key:"18s6g9"}],["path",{d:"M16 16h.01",key:"1f9h7w"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tee=re("Dice6",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M16 16h.01",key:"1f9h7w"}],["path",{d:"M8 8h.01",key:"1e4136"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const see=re("Dices",[["rect",{width:"12",height:"12",x:"2",y:"10",rx:"2",ry:"2",key:"6agr2n"}],["path",{d:"m17.92 14 3.5-3.5a2.24 2.24 0 0 0 0-3l-5-4.92a2.24 2.24 0 0 0-3 0L10 6",key:"1o487t"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 14h.01",key:"ssrbsk"}],["path",{d:"M15 6h.01",key:"cblpky"}],["path",{d:"M18 9h.01",key:"2061c0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nee=re("Diff",[["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 10h14",key:"elsbfy"}],["path",{d:"M5 21h14",key:"11awu3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ree=re("Disc2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aee=re("Disc3",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M6 12c0-1.7.7-3.2 1.8-4.2",key:"oqkarx"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M18 12c0 1.7-.7 3.2-1.8 4.2",key:"1eah9h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iee=re("DiscAlbum",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"12",cy:"12",r:"5",key:"nd82uf"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oee=re("Disc",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lee=re("Divide",[["circle",{cx:"12",cy:"6",r:"1",key:"1bh7o1"}],["line",{x1:"5",x2:"19",y1:"12",y2:"12",key:"13b5wn"}],["circle",{cx:"12",cy:"18",r:"1",key:"lqb9t5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cee=re("DnaOff",[["path",{d:"M15 2c-1.35 1.5-2.092 3-2.5 4.5L14 8",key:"1bivrr"}],["path",{d:"m17 6-2.891-2.891",key:"xu6p2f"}],["path",{d:"M2 15c3.333-3 6.667-3 10-3",key:"nxix30"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"m20 9 .891.891",key:"3xwk7g"}],["path",{d:"M22 9c-1.5 1.35-3 2.092-4.5 2.5l-1-1",key:"18cutr"}],["path",{d:"M3.109 14.109 4 15",key:"q76aoh"}],["path",{d:"m6.5 12.5 1 1",key:"cs35ky"}],["path",{d:"m7 18 2.891 2.891",key:"1sisit"}],["path",{d:"M9 22c1.35-1.5 2.092-3 2.5-4.5L10 16",key:"rlvei3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dee=re("Dna",[["path",{d:"m10 16 1.5 1.5",key:"11lckj"}],["path",{d:"m14 8-1.5-1.5",key:"1ohn8i"}],["path",{d:"M15 2c-1.798 1.998-2.518 3.995-2.807 5.993",key:"80uv8i"}],["path",{d:"m16.5 10.5 1 1",key:"696xn5"}],["path",{d:"m17 6-2.891-2.891",key:"xu6p2f"}],["path",{d:"M2 15c6.667-6 13.333 0 20-6",key:"1pyr53"}],["path",{d:"m20 9 .891.891",key:"3xwk7g"}],["path",{d:"M3.109 14.109 4 15",key:"q76aoh"}],["path",{d:"m6.5 12.5 1 1",key:"cs35ky"}],["path",{d:"m7 18 2.891 2.891",key:"1sisit"}],["path",{d:"M9 22c1.798-1.998 2.518-3.995 2.807-5.993",key:"q3hbxp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uee=re("Dock",[["path",{d:"M2 8h20",key:"d11cs7"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M6 16h12",key:"u522kt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hee=re("Dog",[["path",{d:"M11.25 16.25h1.5L12 17z",key:"w7jh35"}],["path",{d:"M16 14v.5",key:"1lajdz"}],["path",{d:"M4.42 11.247A13.152 13.152 0 0 0 4 14.556C4 18.728 7.582 21 12 21s8-2.272 8-6.444a11.702 11.702 0 0 0-.493-3.309",key:"u7s9ue"}],["path",{d:"M8 14v.5",key:"1nzgdb"}],["path",{d:"M8.5 8.5c-.384 1.05-1.083 2.028-2.344 2.5-1.931.722-3.576-.297-3.656-1-.113-.994 1.177-6.53 4-7 1.923-.321 3.651.845 3.651 2.235A7.497 7.497 0 0 1 14 5.277c0-1.39 1.844-2.598 3.767-2.277 2.823.47 4.113 6.006 4 7-.08.703-1.725 1.722-3.656 1-1.261-.472-1.855-1.45-2.239-2.5",key:"v8hric"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zl=re("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mee=re("Donut",[["path",{d:"M20.5 10a2.5 2.5 0 0 1-2.4-3H18a2.95 2.95 0 0 1-2.6-4.4 10 10 0 1 0 6.3 7.1c-.3.2-.8.3-1.2.3",key:"19sr3x"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pee=re("DoorClosed",[["path",{d:"M18 20V6a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v14",key:"36qu9e"}],["path",{d:"M2 20h20",key:"owomy5"}],["path",{d:"M14 12v.01",key:"xfcn54"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gw=re("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fee=re("Dot",[["circle",{cx:"12.1",cy:"12.1",r:"1",key:"18d7e5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Da=re("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xee=re("DraftingCompass",[["path",{d:"m12.99 6.74 1.93 3.44",key:"iwagvd"}],["path",{d:"M19.136 12a10 10 0 0 1-14.271 0",key:"ppmlo4"}],["path",{d:"m21 21-2.16-3.84",key:"vylbct"}],["path",{d:"m3 21 8.02-14.26",key:"1ssaw4"}],["circle",{cx:"12",cy:"5",r:"2",key:"f1ur92"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gee=re("Drama",[["path",{d:"M10 11h.01",key:"d2at3l"}],["path",{d:"M14 6h.01",key:"k028ub"}],["path",{d:"M18 6h.01",key:"1v4wsw"}],["path",{d:"M6.5 13.1h.01",key:"1748ia"}],["path",{d:"M22 5c0 9-4 12-6 12s-6-3-6-12c0-2 2-3 6-3s6 1 6 3",key:"172yzv"}],["path",{d:"M17.4 9.9c-.8.8-2 .8-2.8 0",key:"1obv0w"}],["path",{d:"M10.1 7.1C9 7.2 7.7 7.7 6 8.6c-3.5 2-4.7 3.9-3.7 5.6 4.5 7.8 9.5 8.4 11.2 7.4.9-.5 1.9-2.1 1.9-4.7",key:"rqjl8i"}],["path",{d:"M9.1 16.5c.3-1.1 1.4-1.7 2.4-1.4",key:"1mr6wy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yee=re("Dribbble",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M19.13 5.09C15.22 9.14 10 10.44 2.25 10.94",key:"hpej1"}],["path",{d:"M21.75 12.84c-6.62-1.41-12.14 1-16.38 6.32",key:"1tr44o"}],["path",{d:"M8.56 2.75c4.37 6 6 9.42 8 17.72",key:"kbh691"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vee=re("Drill",[["path",{d:"M10 18a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H5a3 3 0 0 1-3-3 1 1 0 0 1 1-1z",key:"ioqxb1"}],["path",{d:"M13 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1l-.81 3.242a1 1 0 0 1-.97.758H8",key:"1rs59n"}],["path",{d:"M14 4h3a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-3",key:"105ega"}],["path",{d:"M18 6h4",key:"66u95g"}],["path",{d:"m5 10-2 8",key:"xt2lic"}],["path",{d:"m7 18 2-8",key:"1bzku2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bee=re("Droplet",[["path",{d:"M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z",key:"c7niix"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pb=re("Droplets",[["path",{d:"M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z",key:"1ptgy4"}],["path",{d:"M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97",key:"1sl1rz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ee=re("Drum",[["path",{d:"m2 2 8 8",key:"1v6059"}],["path",{d:"m22 2-8 8",key:"173r8a"}],["ellipse",{cx:"12",cy:"9",rx:"10",ry:"5",key:"liohsx"}],["path",{d:"M7 13.4v7.9",key:"1yi6u9"}],["path",{d:"M12 14v8",key:"1tn2tj"}],["path",{d:"M17 13.4v7.9",key:"eqz2v3"}],["path",{d:"M2 9v8a10 5 0 0 0 20 0V9",key:"1750ul"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wee=re("Drumstick",[["path",{d:"M15.4 15.63a7.875 6 135 1 1 6.23-6.23 4.5 3.43 135 0 0-6.23 6.23",key:"1dtqwm"}],["path",{d:"m8.29 12.71-2.6 2.6a2.5 2.5 0 1 0-1.65 4.65A2.5 2.5 0 1 0 8.7 18.3l2.59-2.59",key:"1oq1fw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jee=re("Dumbbell",[["path",{d:"M14.4 14.4 9.6 9.6",key:"ic80wn"}],["path",{d:"M18.657 21.485a2 2 0 1 1-2.829-2.828l-1.767 1.768a2 2 0 1 1-2.829-2.829l6.364-6.364a2 2 0 1 1 2.829 2.829l-1.768 1.767a2 2 0 1 1 2.828 2.829z",key:"nnl7wr"}],["path",{d:"m21.5 21.5-1.4-1.4",key:"1f1ice"}],["path",{d:"M3.9 3.9 2.5 2.5",key:"1evmna"}],["path",{d:"M6.404 12.768a2 2 0 1 1-2.829-2.829l1.768-1.767a2 2 0 1 1-2.828-2.829l2.828-2.828a2 2 0 1 1 2.829 2.828l1.767-1.768a2 2 0 1 1 2.829 2.829z",key:"yhosts"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nee=re("EarOff",[["path",{d:"M6 18.5a3.5 3.5 0 1 0 7 0c0-1.57.92-2.52 2.04-3.46",key:"1qngmn"}],["path",{d:"M6 8.5c0-.75.13-1.47.36-2.14",key:"b06bma"}],["path",{d:"M8.8 3.15A6.5 6.5 0 0 1 19 8.5c0 1.63-.44 2.81-1.09 3.76",key:"g10hsz"}],["path",{d:"M12.5 6A2.5 2.5 0 0 1 15 8.5M10 13a2 2 0 0 0 1.82-1.18",key:"ygzou7"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kee=re("Ear",[["path",{d:"M6 8.5a6.5 6.5 0 1 1 13 0c0 6-6 6-6 10a3.5 3.5 0 1 1-7 0",key:"1dfaln"}],["path",{d:"M15 8.5a2.5 2.5 0 0 0-5 0v1a2 2 0 1 1 0 4",key:"1qnva7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const See=re("EarthLock",[["path",{d:"M7 3.34V5a3 3 0 0 0 3 3",key:"w732o8"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2 2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"f02343"}],["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M12 2a10 10 0 1 0 9.54 13",key:"zjsr6q"}],["path",{d:"M20 6V4a2 2 0 1 0-4 0v2",key:"1of5e8"}],["rect",{width:"8",height:"5",x:"14",y:"6",rx:"1",key:"1fmf51"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M5=re("Earth",[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cee=re("Eclipse",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a7 7 0 1 0 10 10",key:"1yuj32"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tee=re("EggFried",[["circle",{cx:"11.5",cy:"12.5",r:"3.5",key:"1cl1mi"}],["path",{d:"M3 8c0-3.5 2.5-6 6.5-6 5 0 4.83 3 7.5 5s5 2 5 6c0 4.5-2.5 6.5-7 6.5-2.5 0-2.5 2.5-6 2.5s-7-2-7-5.5c0-3 1.5-3 1.5-5C3.5 10 3 9 3 8Z",key:"165ef9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eee=re("EggOff",[["path",{d:"M6.399 6.399C5.362 8.157 4.65 10.189 4.5 12c-.37 4.43 1.27 9.95 7.5 10 3.256-.026 5.259-1.547 6.375-3.625",key:"6et380"}],["path",{d:"M19.532 13.875A14.07 14.07 0 0 0 19.5 12c-.36-4.34-3.95-9.96-7.5-10-1.04.012-2.082.502-3.046 1.297",key:"gcdc3f"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nL=re("Egg",[["path",{d:"M12 22c6.23-.05 7.87-5.57 7.5-10-.36-4.34-3.95-9.96-7.5-10-3.55.04-7.14 5.66-7.5 10-.37 4.43 1.27 9.95 7.5 10z",key:"1c39pg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lg=re("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xf=re("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Aee=re("EqualApproximately",[["path",{d:"M5 15a6.5 6.5 0 0 1 7 0 6.5 6.5 0 0 0 7 0",key:"yrdkhy"}],["path",{d:"M5 9a6.5 6.5 0 0 1 7 0 6.5 6.5 0 0 0 7 0",key:"gzkvyz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mee=re("EqualNot",[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}],["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Iee=re("Equal",[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pee=re("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lee=re("EthernetPort",[["path",{d:"m15 20 3-3h2a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h2l3 3z",key:"rbahqx"}],["path",{d:"M6 8v1",key:"1636ez"}],["path",{d:"M10 8v1",key:"1talb4"}],["path",{d:"M14 8v1",key:"1rsfgr"}],["path",{d:"M18 8v1",key:"gnkwox"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dee=re("Euro",[["path",{d:"M4 10h12",key:"1y6xl8"}],["path",{d:"M4 14h9",key:"1loblj"}],["path",{d:"M19 6a7.7 7.7 0 0 0-5.2-2A7.9 7.9 0 0 0 6 12c0 4.4 3.5 8 7.8 8 2 0 3.8-.8 5.2-2",key:"1j6lzo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ree=re("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tr=re("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oee=re("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gf=re("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ir=re("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oh=re("Facebook",[["path",{d:"M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z",key:"1jg4f8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fee=re("Factory",[["path",{d:"M2 20a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8l-7 5V8l-7 5V4a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"159hny"}],["path",{d:"M17 18h1",key:"uldtlt"}],["path",{d:"M12 18h1",key:"s9uhes"}],["path",{d:"M7 18h1",key:"1neino"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zee=re("Fan",[["path",{d:"M10.827 16.379a6.082 6.082 0 0 1-8.618-7.002l5.412 1.45a6.082 6.082 0 0 1 7.002-8.618l-1.45 5.412a6.082 6.082 0 0 1 8.618 7.002l-5.412-1.45a6.082 6.082 0 0 1-7.002 8.618l1.45-5.412Z",key:"484a7f"}],["path",{d:"M12 12v.01",key:"u5ubse"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bee=re("FastForward",[["polygon",{points:"13 19 22 12 13 5 13 19",key:"587y9g"}],["polygon",{points:"2 19 11 12 2 5 2 19",key:"3pweh0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ee=re("Feather",[["path",{d:"M12.67 19a2 2 0 0 0 1.416-.588l6.154-6.172a6 6 0 0 0-8.49-8.49L5.586 9.914A2 2 0 0 0 5 11.328V18a1 1 0 0 0 1 1z",key:"18jl4k"}],["path",{d:"M16 8 2 22",key:"vp34q"}],["path",{d:"M17.5 15H9",key:"1oz8nu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uee=re("Fence",[["path",{d:"M4 3 2 5v15c0 .6.4 1 1 1h2c.6 0 1-.4 1-1V5Z",key:"1n2rgs"}],["path",{d:"M6 8h4",key:"utf9t1"}],["path",{d:"M6 18h4",key:"12yh4b"}],["path",{d:"m12 3-2 2v15c0 .6.4 1 1 1h2c.6 0 1-.4 1-1V5Z",key:"3ha7mj"}],["path",{d:"M14 8h4",key:"1r8wg2"}],["path",{d:"M14 18h4",key:"1t3kbu"}],["path",{d:"m20 3-2 2v15c0 .6.4 1 1 1h2c.6 0 1-.4 1-1V5Z",key:"dfd4e2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qee=re("FerrisWheel",[["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m6.8 15-3.5 2",key:"hjy98k"}],["path",{d:"m20.7 7-3.5 2",key:"f08gto"}],["path",{d:"M6.8 9 3.3 7",key:"1aevh4"}],["path",{d:"m20.7 17-3.5-2",key:"1liqo3"}],["path",{d:"m9 22 3-8 3 8",key:"wees03"}],["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M18 18.7a9 9 0 1 0-12 0",key:"dhzg4g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vee=re("Figma",[["path",{d:"M5 5.5A3.5 3.5 0 0 1 8.5 2H12v7H8.5A3.5 3.5 0 0 1 5 5.5z",key:"1340ok"}],["path",{d:"M12 2h3.5a3.5 3.5 0 1 1 0 7H12V2z",key:"1hz3m3"}],["path",{d:"M12 12.5a3.5 3.5 0 1 1 7 0 3.5 3.5 0 1 1-7 0z",key:"1oz8n2"}],["path",{d:"M5 19.5A3.5 3.5 0 0 1 8.5 16H12v3.5a3.5 3.5 0 1 1-7 0z",key:"1ff65i"}],["path",{d:"M5 12.5A3.5 3.5 0 0 1 8.5 9H12v7H8.5A3.5 3.5 0 0 1 5 12.5z",key:"pdip6e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hee=re("FileArchive",[["path",{d:"M10 12v-1",key:"v7bkov"}],["path",{d:"M10 18v-2",key:"1cjy8d"}],["path",{d:"M10 7V6",key:"dljcrl"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 .274 1.01",key:"gkbcor"}],["circle",{cx:"10",cy:"20",r:"2",key:"1xzdoj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gee=re("FileAudio2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2",key:"17k7jt"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"3",cy:"17",r:"1",key:"vo6nti"}],["path",{d:"M2 17v-3a4 4 0 0 1 8 0v3",key:"1ggdre"}],["circle",{cx:"9",cy:"17",r:"1",key:"bc1fq4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wee=re("FileAudio",[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I5=re("FileAxis3d",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m8 18 4-4",key:"12zab0"}],["path",{d:"M8 10v8h8",key:"tlaukw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kee=re("FileBadge2",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m14 12.5 1 5.5-3-1-3 1 1-5.5",key:"14xlky"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yee=re("FileBadge",[["path",{d:"M12 22h6a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"12ixgl"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M5 17a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z",key:"u0c8gj"}],["path",{d:"M7 16.5 8 22l-3-1-3 1 1-5.5",key:"5gm2nr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zee=re("FileBox",[["path",{d:"M14.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"16lz6z"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 13.1a2 2 0 0 0-1 1.76v3.24a2 2 0 0 0 .97 1.78L6 21.7a2 2 0 0 0 2.03.01L11 19.9a2 2 0 0 0 1-1.76V14.9a2 2 0 0 0-.97-1.78L8 11.3a2 2 0 0 0-2.03-.01Z",key:"99pj1s"}],["path",{d:"M7 17v5",key:"1yj1jh"}],["path",{d:"M11.7 14.2 7 17l-4.7-2.8",key:"1yk8tc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const P5=re("FileChartColumnIncreasing",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 18v-2",key:"qcmpov"}],["path",{d:"M12 18v-4",key:"q1q25u"}],["path",{d:"M16 18v-6",key:"15y0np"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const L5=re("FileChartColumn",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 18v-1",key:"zg0ygc"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"M16 18v-3",key:"j5jt4h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D5=re("FileChartLine",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m16 13-3.5 3.5-2-2L8 17",key:"zz7yod"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const R5=re("FileChartPie",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3.5",key:"13ddob"}],["path",{d:"M4.017 11.512a6 6 0 1 0 8.466 8.475",key:"s6vs5t"}],["path",{d:"M9 16a1 1 0 0 1-1-1v-4c0-.552.45-1.008.995-.917a6 6 0 0 1 4.922 4.922c.091.544-.365.995-.917.995z",key:"1dl6s6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qee=re("FileCheck2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m3 15 2 2 4-4",key:"1lhrkk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n9=re("FileCheck",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m9 15 2 2 4-4",key:"1grp1n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xee=re("FileClock",[["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"37hlfg"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"8",cy:"16",r:"6",key:"10v15b"}],["path",{d:"M9.5 17.5 8 16.25V14",key:"1o80t2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jee=re("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ete=re("FileCode",[["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const O5=re("FileCog",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m3.2 12.9-.9-.4",key:"1i3dj5"}],["path",{d:"m3.2 15.1-.9.4",key:"1fvgj0"}],["path",{d:"M4.677 21.5a2 2 0 0 0 1.313.5H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2.5",key:"1yo3oz"}],["path",{d:"m4.9 11.2-.4-.9",key:"otmhb9"}],["path",{d:"m4.9 16.8-.4.9",key:"1b8z07"}],["path",{d:"m7.5 10.3-.4.9",key:"11k65u"}],["path",{d:"m7.5 17.7-.4-.9",key:"431x55"}],["path",{d:"m9.7 12.5-.9.4",key:"87sjan"}],["path",{d:"m9.7 15.5-.9-.4",key:"khqm91"}],["circle",{cx:"6",cy:"14",r:"3",key:"a1xfv6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tte=re("FileDiff",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ste=re("FileDigit",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["rect",{width:"4",height:"6",x:"2",y:"12",rx:"2",key:"jm304g"}],["path",{d:"M10 12h2v6",key:"12zw74"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TA=re("FileDown",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nte=re("FileHeart",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2",key:"17k7jt"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10.29 10.7a2.43 2.43 0 0 0-2.66-.52c-.29.12-.56.3-.78.53l-.35.34-.35-.34a2.43 2.43 0 0 0-2.65-.53c-.3.12-.56.3-.79.53-.95.94-1 2.53.2 3.74L6.5 18l3.6-3.55c1.2-1.21 1.14-2.8.19-3.74Z",key:"1c1fso"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K2=re("FileImage",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rte=re("FileInput",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ate=re("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ite=re("FileJson",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"1oajmo"}],["path",{d:"M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"mpwhp6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ote=re("FileKey2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v6",key:"rc0qvx"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"4",cy:"16",r:"2",key:"1ehqvc"}],["path",{d:"m10 10-4.5 4.5",key:"7fwrp6"}],["path",{d:"m9 11 1 1",key:"wa6s5q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lte=re("FileKey",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["circle",{cx:"10",cy:"16",r:"2",key:"4ckbqe"}],["path",{d:"m16 10-4.5 4.5",key:"7p3ebg"}],["path",{d:"m15 11 1 1",key:"1bsyx3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cte=re("FileLock2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v1",key:"jmtmu2"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["rect",{width:"8",height:"5",x:"2",y:"13",rx:"1",key:"10y5wo"}],["path",{d:"M8 13v-2a2 2 0 1 0-4 0v2",key:"1pdxzg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dte=re("FileLock",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["rect",{width:"8",height:"6",x:"8",y:"12",rx:"1",key:"3yr8at"}],["path",{d:"M10 12v-2a2 2 0 1 1 4 0v2",key:"j4i8d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ute=re("FileMinus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hte=re("FileMinus",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 15h6",key:"cctwl0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mte=re("FileMusic",[["path",{d:"M10.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v8.4",key:"1d3kfm"}],["path",{d:"M8 18v-7.7L16 9v7",key:"1oie6o"}],["circle",{cx:"14",cy:"16",r:"2",key:"1bzzi3"}],["circle",{cx:"6",cy:"18",r:"2",key:"1fncim"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pte=re("FileOutput",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 7V4a2 2 0 0 1 2-2 2 2 0 0 0-2 2",key:"1vk7w2"}],["path",{d:"M4.063 20.999a2 2 0 0 0 2 1L18 22a2 2 0 0 0 2-2V7l-5-5H6",key:"1jink5"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zk=re("FilePenLine",[["path",{d:"m18 5-2.414-2.414A2 2 0 0 0 14.172 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2",key:"142zxg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const F5=re("FilePen",[["path",{d:"M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5",key:"1couwa"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fte=re("FilePlus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}],["path",{d:"M6 12v6",key:"1u72j0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xte=re("FilePlus",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gte=re("FileQuestion",[["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yte=re("FileScan",[["path",{d:"M20 10V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h4",key:"1rdf37"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M16 14a2 2 0 0 0-2 2",key:"ceaadl"}],["path",{d:"M20 14a2 2 0 0 1 2 2",key:"1ny6zw"}],["path",{d:"M20 22a2 2 0 0 0 2-2",key:"1l9q4k"}],["path",{d:"M16 22a2 2 0 0 1-2-2",key:"1wqh5n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vte=re("FileSearch2",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"11.5",cy:"14.5",r:"2.5",key:"1bq0ko"}],["path",{d:"M13.3 16.3 15 18",key:"2quom7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bte=re("FileSearch",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"ms7g94"}],["path",{d:"m9 18-1.5-1.5",key:"1j6qii"}],["circle",{cx:"5",cy:"14",r:"3",key:"ufru5t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _te=re("FileSliders",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M10 11v2",key:"1s651w"}],["path",{d:"M8 17h8",key:"wh5c61"}],["path",{d:"M14 16v2",key:"12fp5e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yw=re("FileSpreadsheet",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const r9=re("FileStack",[["path",{d:"M21 7h-3a2 2 0 0 1-2-2V2",key:"9rb54x"}],["path",{d:"M21 6v6.5c0 .8-.7 1.5-1.5 1.5h-7c-.8 0-1.5-.7-1.5-1.5v-9c0-.8.7-1.5 1.5-1.5H17Z",key:"1059l0"}],["path",{d:"M7 8v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H15",key:"16874u"}],["path",{d:"M3 12v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H11",key:"k2ox98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wte=re("FileSymlink",[["path",{d:"m10 18 3-3-3-3",key:"18f6ys"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 11V4a2 2 0 0 1 2-2h9l5 5v13a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h7",key:"50q2rw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jte=re("FileTerminal",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m8 16 2-2-2-2",key:"10vzyd"}],["path",{d:"M12 18h4",key:"1wd2n7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nr=re("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nte=re("FileType2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 13v-1h6v1",key:"1dh9dg"}],["path",{d:"M5 12v6",key:"150t9c"}],["path",{d:"M4 18h2",key:"1xrofg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kte=re("FileType",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 13v-1h6v1",key:"1bb014"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M11 18h2",key:"12mj7e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ste=re("FileUp",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"m15 15-3-3-3 3",key:"15xj92"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cte=re("FileUser",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 18a3 3 0 1 0-6 0",key:"16awa0"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tte=re("FileVideo2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["rect",{width:"8",height:"6",x:"2",y:"12",rx:"1",key:"1a6c1e"}],["path",{d:"m10 15.5 4 2.5v-6l-4 2.5",key:"t7cp39"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a9=re("FileVideo",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m10 11 5 3-5 3v-6Z",key:"7ntvm4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ete=re("FileVolume2",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M11.5 13.5a2.5 2.5 0 0 1 0 3",key:"1fccat"}],["path",{d:"M15 12a5 5 0 0 1 0 6",key:"ps46cm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ate=re("FileVolume",[["path",{d:"M11 11a5 5 0 0 1 0 6",key:"193qb2"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 6.765V4a2 2 0 0 1 2-2h9l5 5v13a2 2 0 0 1-2 2H6a2 2 0 0 1-.93-.23",key:"ifyjnl"}],["path",{d:"M7 10.51a.5.5 0 0 0-.826-.38l-1.893 1.628A1 1 0 0 1 3.63 12H2.5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h1.129a1 1 0 0 1 .652.242l1.893 1.63a.5.5 0 0 0 .826-.38z",key:"mk8rxu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mte=re("FileWarning",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ite=re("FileX2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m8 12.5-5 5",key:"b853mi"}],["path",{d:"m3 12.5 5 5",key:"1qls4r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pte=re("FileX",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m14.5 12.5-5 5",key:"b62r18"}],["path",{d:"m9.5 12.5 5 5",key:"1rk7el"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rL=re("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lte=re("Files",[["path",{d:"M20 7h-3a2 2 0 0 1-2-2V2",key:"x099mo"}],["path",{d:"M9 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7l4 4v10a2 2 0 0 1-2 2Z",key:"18t6ie"}],["path",{d:"M3 7.6v12.8A1.6 1.6 0 0 0 4.6 22h9.8",key:"1nja0z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ph=re("Film",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dte=re("FilterX",[["path",{d:"M13.013 3H2l8 9.46V19l4 2v-8.54l.9-1.055",key:"1fi1da"}],["path",{d:"m22 3-5 5",key:"12jva0"}],["path",{d:"m17 3 5 5",key:"k36vhe"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fv=re("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rte=re("Fingerprint",[["path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4",key:"1nerag"}],["path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88",key:"o46ks0"}],["path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02",key:"ptglia"}],["path",{d:"M2 12a10 10 0 0 1 18-6",key:"ydlgp0"}],["path",{d:"M2 16h.01",key:"1gqxmh"}],["path",{d:"M21.8 16c.2-2 .131-5.354 0-6",key:"drycrb"}],["path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2",key:"1tidbn"}],["path",{d:"M8.65 22c.21-.66.45-1.32.57-2",key:"13wd9y"}],["path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2",key:"1fr1j5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ote=re("FireExtinguisher",[["path",{d:"M15 6.5V3a1 1 0 0 0-1-1h-2a1 1 0 0 0-1 1v3.5",key:"sqyvz"}],["path",{d:"M9 18h8",key:"i7pszb"}],["path",{d:"M18 3h-3",key:"7idoqj"}],["path",{d:"M11 3a6 6 0 0 0-6 6v11",key:"1v5je3"}],["path",{d:"M5 13h4",key:"svpcxo"}],["path",{d:"M17 10a4 4 0 0 0-8 0v10a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2Z",key:"vsjego"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fte=re("FishOff",[["path",{d:"M18 12.47v.03m0-.5v.47m-.475 5.056A6.744 6.744 0 0 1 15 18c-3.56 0-7.56-2.53-8.5-6 .348-1.28 1.114-2.433 2.121-3.38m3.444-2.088A8.802 8.802 0 0 1 15 6c3.56 0 6.06 2.54 7 6-.309 1.14-.786 2.177-1.413 3.058",key:"1j1hse"}],["path",{d:"M7 10.67C7 8 5.58 5.97 2.73 5.5c-1 1.5-1 5 .23 6.5-1.24 1.5-1.24 5-.23 6.5C5.58 18.03 7 16 7 13.33m7.48-4.372A9.77 9.77 0 0 1 16 6.07m0 11.86a9.77 9.77 0 0 1-1.728-3.618",key:"1q46z8"}],["path",{d:"m16.01 17.93-.23 1.4A2 2 0 0 1 13.8 21H9.5a5.96 5.96 0 0 0 1.49-3.98M8.53 3h5.27a2 2 0 0 1 1.98 1.67l.23 1.4M2 2l20 20",key:"1407gh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zte=re("FishSymbol",[["path",{d:"M2 16s9-15 20-4C11 23 2 8 2 8",key:"h4oh4o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bte=re("Fish",[["path",{d:"M6.5 12c.94-3.46 4.94-6 8.5-6 3.56 0 6.06 2.54 7 6-.94 3.47-3.44 6-7 6s-7.56-2.53-8.5-6Z",key:"15baut"}],["path",{d:"M18 12v.5",key:"18hhni"}],["path",{d:"M16 17.93a9.77 9.77 0 0 1 0-11.86",key:"16dt7o"}],["path",{d:"M7 10.67C7 8 5.58 5.97 2.73 5.5c-1 1.5-1 5 .23 6.5-1.24 1.5-1.24 5-.23 6.5C5.58 18.03 7 16 7 13.33",key:"l9di03"}],["path",{d:"M10.46 7.26C10.2 5.88 9.17 4.24 8 3h5.8a2 2 0 0 1 1.98 1.67l.23 1.4",key:"1kjonw"}],["path",{d:"m16.01 17.93-.23 1.4A2 2 0 0 1 13.8 21H9.5a5.96 5.96 0 0 0 1.49-3.98",key:"1zlm23"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $te=re("FlagOff",[["path",{d:"M8 2c3 0 5 2 8 2s4-1 4-1v11",key:"9rwyz9"}],["path",{d:"M4 22V4",key:"1plyxx"}],["path",{d:"M4 15s1-1 4-1 5 2 8 2",key:"1myooe"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ute=re("FlagTriangleLeft",[["path",{d:"M17 22V2L7 7l10 5",key:"1rmf0r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qte=re("FlagTriangleRight",[["path",{d:"M7 22V2l10 5-10 5",key:"17n18y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y2=re("Flag",[["path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z",key:"i9b6wo"}],["line",{x1:"4",x2:"4",y1:"22",y2:"15",key:"1cm3nv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vte=re("FlameKindling",[["path",{d:"M12 2c1 3 2.5 3.5 3.5 4.5A5 5 0 0 1 17 10a5 5 0 1 1-10 0c0-.3 0-.6.1-.9a2 2 0 1 0 3.3-2C8 4.5 11 2 12 2Z",key:"1ir223"}],["path",{d:"m5 22 14-4",key:"1brv4h"}],["path",{d:"m5 18 14 4",key:"lgyyje"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _c=re("Flame",[["path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z",key:"96xj49"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hte=re("FlashlightOff",[["path",{d:"M16 16v4a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2V10c0-2-2-2-2-4",key:"1r120k"}],["path",{d:"M7 2h11v4c0 2-2 2-2 4v1",key:"dz1920"}],["line",{x1:"11",x2:"18",y1:"6",y2:"6",key:"bi1vpe"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gte=re("Flashlight",[["path",{d:"M18 6c0 2-2 2-2 4v10a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2V10c0-2-2-2-2-4V2h12z",key:"1orkel"}],["line",{x1:"6",x2:"18",y1:"6",y2:"6",key:"1z11jq"}],["line",{x1:"12",x2:"12",y1:"12",y2:"12",key:"1f4yc1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wte=re("FlaskConicalOff",[["path",{d:"M10 10 4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-1.272-2.542",key:"59ek9y"}],["path",{d:"M10 2v2.343",key:"15t272"}],["path",{d:"M14 2v6.343",key:"sxr80q"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M7 16h9",key:"t5njau"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XS=re("FlaskConical",[["path",{d:"M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2",key:"pzvekw"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M7 16h10",key:"wp8him"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kte=re("FlaskRound",[["path",{d:"M10 2v7.31",key:"5d1hyh"}],["path",{d:"M14 9.3V1.99",key:"14k4l0"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14 9.3a6.5 6.5 0 1 1-4 0",key:"1r8fvy"}],["path",{d:"M5.52 16h12.96",key:"46hh1i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yte=re("FlipHorizontal2",[["path",{d:"m3 7 5 5-5 5V7",key:"couhi7"}],["path",{d:"m21 7-5 5 5 5V7",key:"6ouia7"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 2v2",key:"tus03m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const i9=re("FlipHorizontal",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h3",key:"1i73f7"}],["path",{d:"M16 3h3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-3",key:"saxlbk"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 2v2",key:"tus03m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zte=re("FlipVertical2",[["path",{d:"m17 3-5 5-5-5h10",key:"1ftt6x"}],["path",{d:"m17 21-5-5-5 5h10",key:"1m0wmu"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qte=re("FlipVertical",[["path",{d:"M21 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v3",key:"14bfxa"}],["path",{d:"M21 16v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3",key:"14rx03"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lb=re("Flower2",[["path",{d:"M12 5a3 3 0 1 1 3 3m-3-3a3 3 0 1 0-3 3m3-3v1M9 8a3 3 0 1 0 3 3M9 8h1m5 0a3 3 0 1 1-3 3m3-3h-1m-2 3v-1",key:"3pnvol"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["path",{d:"M12 10v12",key:"6ubwww"}],["path",{d:"M12 22c4.2 0 7-1.667 7-5-4.2 0-7 1.667-7 5Z",key:"9hd38g"}],["path",{d:"M12 22c-4.2 0-7-1.667-7-5 4.2 0 7 1.667 7 5Z",key:"ufn41s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xte=re("Flower",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M12 16.5A4.5 4.5 0 1 1 7.5 12 4.5 4.5 0 1 1 12 7.5a4.5 4.5 0 1 1 4.5 4.5 4.5 4.5 0 1 1-4.5 4.5",key:"14wa3c"}],["path",{d:"M12 7.5V9",key:"1oy5b0"}],["path",{d:"M7.5 12H9",key:"eltsq1"}],["path",{d:"M16.5 12H15",key:"vk5kw4"}],["path",{d:"M12 16.5V15",key:"k7eayi"}],["path",{d:"m8 8 1.88 1.88",key:"nxy4qf"}],["path",{d:"M14.12 9.88 16 8",key:"1lst6k"}],["path",{d:"m8 16 1.88-1.88",key:"h2eex1"}],["path",{d:"M14.12 14.12 16 16",key:"uqkrx3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jte=re("Focus",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ese=re("FoldHorizontal",[["path",{d:"M2 12h6",key:"1wqiqv"}],["path",{d:"M22 12h-6",key:"1eg9hc"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m19 9-3 3 3 3",key:"12ol22"}],["path",{d:"m5 15 3-3-3-3",key:"1kdhjc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tse=re("FoldVertical",[["path",{d:"M12 22v-6",key:"6o8u61"}],["path",{d:"M12 8V2",key:"1wkif3"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}],["path",{d:"m15 19-3-3-3 3",key:"e37ymu"}],["path",{d:"m15 5-3 3-3-3",key:"19d6lf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sse=re("FolderArchive",[["circle",{cx:"15",cy:"19",r:"2",key:"u2pros"}],["path",{d:"M20.9 19.8A2 2 0 0 0 22 18V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h5.1",key:"1jj40k"}],["path",{d:"M15 11v-1",key:"cntcp"}],["path",{d:"M15 17v-2",key:"1279jj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nse=re("FolderCheck",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"m9 13 2 2 4-4",key:"6343dt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rse=re("FolderClock",[["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}],["path",{d:"M7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2",key:"1urifu"}],["path",{d:"M16 14v2l1 1",key:"xth2jh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ase=re("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ise=re("FolderCode",[["path",{d:"M10 10.5 8 13l2 2.5",key:"m4t9c1"}],["path",{d:"m14 10.5 2 2.5-2 2.5",key:"14w2eb"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2z",key:"1u1bxd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const z5=re("FolderCog",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v3.3",key:"1k8050"}],["path",{d:"m21.7 19.4-.9-.3",key:"1qgwi9"}],["path",{d:"m15.2 16.9-.9-.3",key:"1t7mvx"}],["path",{d:"m16.6 21.7.3-.9",key:"1j67ps"}],["path",{d:"m19.1 15.2.3-.9",key:"18r7jp"}],["path",{d:"m19.6 21.7-.4-1",key:"z2vh2"}],["path",{d:"m16.8 15.3-.4-1",key:"1ei7r6"}],["path",{d:"m14.3 19.6 1-.4",key:"11sv9r"}],["path",{d:"m20.7 16.8 1-.4",key:"19m87a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ose=re("FolderDot",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["circle",{cx:"12",cy:"13",r:"1",key:"49l61u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lse=re("FolderDown",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"m15 13-3 3-3-3",key:"6j2sf0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cse=re("FolderGit2",[["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["path",{d:"M18 19c-2.8 0-5-2.2-5-5v8",key:"pkpw2h"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dse=re("FolderGit",[["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M14 13h3",key:"1dgedf"}],["path",{d:"M7 13h3",key:"1pygq7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const use=re("FolderHeart",[["path",{d:"M11 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v1.5",key:"6hud8k"}],["path",{d:"M13.9 17.45c-1.2-1.2-1.14-2.8-.2-3.73a2.43 2.43 0 0 1 3.44 0l.36.34.34-.34a2.43 2.43 0 0 1 3.45-.01c.95.95 1 2.53-.2 3.74L17.5 21Z",key:"wpff58"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hse=re("FolderInput",[["path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1",key:"fm4g5t"}],["path",{d:"M2 13h10",key:"pgb2dq"}],["path",{d:"m9 16 3-3-3-3",key:"6m91ic"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mse=re("FolderKanban",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M12 10v2",key:"hh53o1"}],["path",{d:"M16 10v6",key:"1d6xys"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pse=re("FolderKey",[["circle",{cx:"16",cy:"20",r:"2",key:"1vifvg"}],["path",{d:"M10 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v2",key:"3hgo9p"}],["path",{d:"m22 14-4.5 4.5",key:"1ef6z8"}],["path",{d:"m21 15 1 1",key:"1ejcpy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fse=re("FolderLock",[["rect",{width:"8",height:"5",x:"14",y:"17",rx:"1",key:"19aais"}],["path",{d:"M10 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v2.5",key:"1w6v7t"}],["path",{d:"M20 17v-2a2 2 0 1 0-4 0v2",key:"pwaxnr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xse=re("FolderMinus",[["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gse=re("FolderOpenDot",[["path",{d:"m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5c0-1.1.9-2 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2",key:"1nmvlm"}],["circle",{cx:"14",cy:"15",r:"1",key:"1gm4qj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yf=re("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yse=re("FolderOutput",[["path",{d:"M2 7.5V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-1.5",key:"1yk7aj"}],["path",{d:"M2 13h10",key:"pgb2dq"}],["path",{d:"m5 10-3 3 3 3",key:"1r8ie0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const B5=re("FolderPen",[["path",{d:"M2 11.5V5a2 2 0 0 1 2-2h3.9c.7 0 1.3.3 1.7.9l.8 1.2c.4.6 1 .9 1.7.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-9.5",key:"a8xqs0"}],["path",{d:"M11.378 13.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1saktj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vse=re("FolderPlus",[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bse=re("FolderRoot",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}],["path",{d:"M12 15v5",key:"11xva1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _se=re("FolderSearch2",[["circle",{cx:"11.5",cy:"12.5",r:"2.5",key:"1ea5ju"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M13.3 14.3 15 16",key:"1y4v1n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wse=re("FolderSearch",[["path",{d:"M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jse=re("FolderSymlink",[["path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h7",key:"x1c07l"}],["path",{d:"m8 16 3-3-3-3",key:"rlqrt1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nse=re("FolderSync",[["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v.5",key:"1dkoa9"}],["path",{d:"M12 10v4h4",key:"1czhmt"}],["path",{d:"m12 14 1.535-1.605a5 5 0 0 1 8 1.5",key:"lvuxfi"}],["path",{d:"M22 22v-4h-4",key:"1ewp4q"}],["path",{d:"m22 18-1.535 1.605a5 5 0 0 1-8-1.5",key:"14ync0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kse=re("FolderTree",[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sse=re("FolderUp",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"m9 13 3-3 3 3",key:"1pxg3c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cse=re("FolderX",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"m9.5 10.5 5 5",key:"ra9qjz"}],["path",{d:"m14.5 10.5-5 5",key:"l2rkpq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tse=re("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ese=re("Folders",[["path",{d:"M20 17a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3.9a2 2 0 0 1-1.69-.9l-.81-1.2a2 2 0 0 0-1.67-.9H8a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2Z",key:"4u7rpt"}],["path",{d:"M2 8v11a2 2 0 0 0 2 2h14",key:"1eicx1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ase=re("Footprints",[["path",{d:"M4 16v-2.38C4 11.5 2.97 10.5 3 8c.03-2.72 1.49-6 4.5-6C9.37 2 10 3.8 10 5.5c0 3.11-2 5.66-2 8.68V16a2 2 0 1 1-4 0Z",key:"1dudjm"}],["path",{d:"M20 20v-2.38c0-2.12 1.03-3.12 1-5.62-.03-2.72-1.49-6-4.5-6C14.63 6 14 7.8 14 9.5c0 3.11 2 5.66 2 8.68V20a2 2 0 1 0 4 0Z",key:"l2t8xc"}],["path",{d:"M16 17h4",key:"1dejxt"}],["path",{d:"M4 13h4",key:"1bwh8b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mse=re("Forklift",[["path",{d:"M12 12H5a2 2 0 0 0-2 2v5",key:"7zsz91"}],["circle",{cx:"13",cy:"19",r:"2",key:"wjnkru"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M8 19h3m5-17v17h6M6 12V7c0-1.1.9-2 2-2h3l5 5",key:"13bk1p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ise=re("Forward",[["polyline",{points:"15 17 20 12 15 7",key:"1w3sku"}],["path",{d:"M4 18v-2a4 4 0 0 1 4-4h12",key:"jmiej9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pse=re("Frame",[["line",{x1:"22",x2:"2",y1:"6",y2:"6",key:"15w7dq"}],["line",{x1:"22",x2:"2",y1:"18",y2:"18",key:"1ip48p"}],["line",{x1:"6",x2:"6",y1:"2",y2:"22",key:"a2lnyx"}],["line",{x1:"18",x2:"18",y1:"2",y2:"22",key:"8vb6jd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lse=re("Framer",[["path",{d:"M5 16V9h14V2H5l14 14h-7m-7 0 7 7v-7m-7 0h7",key:"1a2nng"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dse=re("Frown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 16s-1.5-2-4-2-4 2-4 2",key:"epbg0q"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rse=re("Fuel",[["line",{x1:"3",x2:"15",y1:"22",y2:"22",key:"xegly4"}],["line",{x1:"4",x2:"14",y1:"9",y2:"9",key:"xcnuvu"}],["path",{d:"M14 22V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v18",key:"16j0yd"}],["path",{d:"M14 13h2a2 2 0 0 1 2 2v2a2 2 0 0 0 2 2a2 2 0 0 0 2-2V9.83a2 2 0 0 0-.59-1.42L18 5",key:"7cu91f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ose=re("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fse=re("GalleryHorizontalEnd",[["path",{d:"M2 7v10",key:"a2pl2d"}],["path",{d:"M6 5v14",key:"1kq3d7"}],["rect",{width:"12",height:"18",x:"10",y:"3",rx:"2",key:"13i7bc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zse=re("GalleryHorizontal",[["path",{d:"M2 3v18",key:"pzttux"}],["rect",{width:"12",height:"18",x:"6",y:"3",rx:"2",key:"btr8bg"}],["path",{d:"M22 3v18",key:"6jf3v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bse=re("GalleryThumbnails",[["rect",{width:"18",height:"14",x:"3",y:"3",rx:"2",key:"74y24f"}],["path",{d:"M4 21h1",key:"16zlid"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M19 21h1",key:"edywat"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $se=re("GalleryVerticalEnd",[["path",{d:"M7 2h10",key:"nczekb"}],["path",{d:"M5 6h14",key:"u2x4p"}],["rect",{width:"18",height:"12",x:"3",y:"10",rx:"2",key:"l0tzu3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Use=re("GalleryVertical",[["path",{d:"M3 2h18",key:"15qxfx"}],["rect",{width:"18",height:"12",x:"3",y:"6",rx:"2",key:"1439r6"}],["path",{d:"M3 22h18",key:"8prr45"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qse=re("Gamepad2",[["line",{x1:"6",x2:"10",y1:"11",y2:"11",key:"1gktln"}],["line",{x1:"8",x2:"8",y1:"9",y2:"13",key:"qnk9ow"}],["line",{x1:"15",x2:"15.01",y1:"12",y2:"12",key:"krot7o"}],["line",{x1:"18",x2:"18.01",y1:"10",y2:"10",key:"1lcuu1"}],["path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z",key:"mfqc10"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vse=re("Gamepad",[["line",{x1:"6",x2:"10",y1:"12",y2:"12",key:"161bw2"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"15",x2:"15.01",y1:"13",y2:"13",key:"dqpgro"}],["line",{x1:"18",x2:"18.01",y1:"11",y2:"11",key:"meh2c"}],["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hse=re("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gse=re("Gavel",[["path",{d:"m14.5 12.5-8 8a2.119 2.119 0 1 1-3-3l8-8",key:"15492f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m9 7 8 8",key:"5jnvq1"}],["path",{d:"m21 11-8-8",key:"z4y7zo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wse=re("Gem",[["path",{d:"M6 3h12l4 6-10 13L2 9Z",key:"1pcd5k"}],["path",{d:"M11 3 8 9l4 13 4-13-3-6",key:"1fcu3u"}],["path",{d:"M2 9h20",key:"16fsjt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EA=re("Ghost",[["path",{d:"M9 10h.01",key:"qbtxuw"}],["path",{d:"M15 10h.01",key:"1qmjsl"}],["path",{d:"M12 2a8 8 0 0 0-8 8v12l3-3 2.5 2.5L12 19l2.5 2.5L17 19l3 3V10a8 8 0 0 0-8-8z",key:"uwwb07"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bi=re("Gift",[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kse=re("GitBranchPlus",[["path",{d:"M6 3v12",key:"qpgusn"}],["path",{d:"M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"1d02ji"}],["path",{d:"M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"chk6ph"}],["path",{d:"M15 6a9 9 0 0 0-9 9",key:"or332x"}],["path",{d:"M18 15v6",key:"9wciyi"}],["path",{d:"M21 18h-6",key:"139f0c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yse=re("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $5=re("GitCommitHorizontal",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zse=re("GitCommitVertical",[["path",{d:"M12 3v6",key:"1holv5"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M12 15v6",key:"a9ows0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qse=re("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xse=re("GitCompare",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jse=re("GitFork",[["circle",{cx:"12",cy:"18",r:"3",key:"1mpf1b"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["path",{d:"M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9",key:"1uq4wg"}],["path",{d:"M12 12v3",key:"158kv8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ene=re("GitGraph",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M5 9v6",key:"158jrl"}],["circle",{cx:"5",cy:"18",r:"3",key:"104gr9"}],["path",{d:"M12 3v18",key:"108xh3"}],["circle",{cx:"19",cy:"6",r:"3",key:"108a5v"}],["path",{d:"M16 15.7A9 9 0 0 0 19 9",key:"1e3vqb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tne=re("GitMerge",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sne=re("GitPullRequestArrow",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M5 9v12",key:"ih889a"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nne=re("GitPullRequestClosed",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 9v12",key:"1sc30k"}],["path",{d:"m21 3-6 6",key:"16nqsk"}],["path",{d:"m21 9-6-6",key:"9j17rh"}],["path",{d:"M18 11.5V15",key:"65xf6f"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rne=re("GitPullRequestCreateArrow",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M5 9v12",key:"ih889a"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v3",key:"1rbwk6"}],["path",{d:"M19 15v6",key:"10aioa"}],["path",{d:"M22 18h-6",key:"1d5gi5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ane=re("GitPullRequestCreate",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 9v12",key:"1sc30k"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v3",key:"1jb6z3"}],["path",{d:"M18 15v6",key:"9wciyi"}],["path",{d:"M21 18h-6",key:"139f0c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ine=re("GitPullRequestDraft",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M18 6V5",key:"1oao2s"}],["path",{d:"M18 11v-1",key:"11c8tz"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const one=re("GitPullRequest",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lne=re("Github",[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cne=re("Gitlab",[["path",{d:"m22 13.29-3.33-10a.42.42 0 0 0-.14-.18.38.38 0 0 0-.22-.11.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18l-2.26 6.67H8.32L6.1 3.26a.42.42 0 0 0-.1-.18.38.38 0 0 0-.26-.08.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18L2 13.29a.74.74 0 0 0 .27.83L12 21l9.69-6.88a.71.71 0 0 0 .31-.83Z",key:"148pdi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dne=re("GlassWater",[["path",{d:"M5.116 4.104A1 1 0 0 1 6.11 3h11.78a1 1 0 0 1 .994 1.105L17.19 20.21A2 2 0 0 1 15.2 22H8.8a2 2 0 0 1-2-1.79z",key:"p55z4y"}],["path",{d:"M6 12a5 5 0 0 1 6 0 5 5 0 0 0 6 0",key:"mjntcy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const une=re("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hne=re("GlobeLock",[["path",{d:"M15.686 15A14.5 14.5 0 0 1 12 22a14.5 14.5 0 0 1 0-20 10 10 0 1 0 9.542 13",key:"qkt0x6"}],["path",{d:"M2 12h8.5",key:"ovaggd"}],["path",{d:"M20 6V4a2 2 0 1 0-4 0v2",key:"1of5e8"}],["rect",{width:"8",height:"5",x:"14",y:"6",rx:"1",key:"1fmf51"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lc=re("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mne=re("Goal",[["path",{d:"M12 13V2l8 4-8 4",key:"5wlwwj"}],["path",{d:"M20.561 10.222a9 9 0 1 1-12.55-5.29",key:"1c0wjv"}],["path",{d:"M8.002 9.997a5 5 0 1 0 8.9 2.02",key:"gb1g7m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pne=re("Grab",[["path",{d:"M18 11.5V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1.4",key:"edstyy"}],["path",{d:"M14 10V8a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"19wdwo"}],["path",{d:"M10 9.9V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v5",key:"1lugqo"}],["path",{d:"M6 14a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1hbeus"}],["path",{d:"M18 11a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-4a8 8 0 0 1-8-8 2 2 0 1 1 4 0",key:"1etffm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _d=re("GraduationCap",[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fne=re("Grape",[["path",{d:"M22 5V2l-5.89 5.89",key:"1eenpo"}],["circle",{cx:"16.6",cy:"15.89",r:"3",key:"xjtalx"}],["circle",{cx:"8.11",cy:"7.4",r:"3",key:"u2fv6i"}],["circle",{cx:"12.35",cy:"11.65",r:"3",key:"i6i8g7"}],["circle",{cx:"13.91",cy:"5.85",r:"3",key:"6ye0dv"}],["circle",{cx:"18.15",cy:"10.09",r:"3",key:"snx9no"}],["circle",{cx:"6.56",cy:"13.2",r:"3",key:"17x4xg"}],["circle",{cx:"10.8",cy:"17.44",r:"3",key:"1hogw9"}],["circle",{cx:"5",cy:"19",r:"3",key:"1sn6vo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xne=re("Grid2x2Check",[["path",{d:"M12 3v17a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6a1 1 0 0 1-1 1H3",key:"11za1p"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U5=re("Grid2x2Plus",[["path",{d:"M12 3v17a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6a1 1 0 0 1-1 1H3",key:"11za1p"}],["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M19 22v-6",key:"qhmiwi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gne=re("Grid2x2X",[["path",{d:"M12 3v17a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6a1 1 0 0 1-1 1H3",key:"11za1p"}],["path",{d:"m16 16 5 5",key:"8tpb07"}],["path",{d:"m16 21 5-5",key:"193jll"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q5=re("Grid2x2",[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xv=re("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yne=re("GripHorizontal",[["circle",{cx:"12",cy:"9",r:"1",key:"124mty"}],["circle",{cx:"19",cy:"9",r:"1",key:"1ruzo2"}],["circle",{cx:"5",cy:"9",r:"1",key:"1a8b28"}],["circle",{cx:"12",cy:"15",r:"1",key:"1e56xg"}],["circle",{cx:"19",cy:"15",r:"1",key:"1a92ep"}],["circle",{cx:"5",cy:"15",r:"1",key:"5r1jwy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uu=re("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vne=re("Grip",[["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"19",cy:"5",r:"1",key:"w8mnmm"}],["circle",{cx:"5",cy:"5",r:"1",key:"lttvr7"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}],["circle",{cx:"19",cy:"19",r:"1",key:"shf9b7"}],["circle",{cx:"5",cy:"19",r:"1",key:"bfqh0e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bne=re("Group",[["path",{d:"M3 7V5c0-1.1.9-2 2-2h2",key:"adw53z"}],["path",{d:"M17 3h2c1.1 0 2 .9 2 2v2",key:"an4l38"}],["path",{d:"M21 17v2c0 1.1-.9 2-2 2h-2",key:"144t0e"}],["path",{d:"M7 21H5c-1.1 0-2-.9-2-2v-2",key:"rtnfgi"}],["rect",{width:"7",height:"5",x:"7",y:"7",rx:"1",key:"1eyiv7"}],["rect",{width:"7",height:"5",x:"10",y:"12",rx:"1",key:"1qlmkx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ne=re("Guitar",[["path",{d:"m11.9 12.1 4.514-4.514",key:"109xqo"}],["path",{d:"M20.1 2.3a1 1 0 0 0-1.4 0l-1.114 1.114A2 2 0 0 0 17 4.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 17.828 7h1.344a2 2 0 0 0 1.414-.586L21.7 5.3a1 1 0 0 0 0-1.4z",key:"txyc8t"}],["path",{d:"m6 16 2 2",key:"16qmzd"}],["path",{d:"M8.2 9.9C8.7 8.8 9.8 8 11 8c2.8 0 5 2.2 5 5 0 1.2-.8 2.3-1.9 2.8l-.9.4A2 2 0 0 0 12 18a4 4 0 0 1-4 4c-3.3 0-6-2.7-6-6a4 4 0 0 1 4-4 2 2 0 0 0 1.8-1.2z",key:"1u8q3z"}],["circle",{cx:"11.5",cy:"12.5",r:".5",fill:"currentColor",key:"16onso"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wne=re("Ham",[["path",{d:"M13.144 21.144A7.274 10.445 45 1 0 2.856 10.856",key:"1k1t7q"}],["path",{d:"M13.144 21.144A7.274 4.365 45 0 0 2.856 10.856a7.274 4.365 45 0 0 10.288 10.288",key:"153t1g"}],["path",{d:"M16.565 10.435 18.6 8.4a2.501 2.501 0 1 0 1.65-4.65 2.5 2.5 0 1 0-4.66 1.66l-2.024 2.025",key:"gzrt0n"}],["path",{d:"m8.5 16.5-1-1",key:"otr954"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const o9=re("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jne=re("HandCoins",[["path",{d:"M11 15h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 17",key:"geh8rc"}],["path",{d:"m7 21 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"1fto5m"}],["path",{d:"m2 16 6 6",key:"1pfhp9"}],["circle",{cx:"16",cy:"9",r:"2.9",key:"1n0dlu"}],["circle",{cx:"6",cy:"5",r:"3",key:"151irh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AA=re("HandHeart",[["path",{d:"M11 14h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 16",key:"1ifwr1"}],["path",{d:"m7 20 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"17abbs"}],["path",{d:"m2 15 6 6",key:"10dquu"}],["path",{d:"M19.5 8.5c.7-.7 1.5-1.6 1.5-2.7A2.73 2.73 0 0 0 16 4a2.78 2.78 0 0 0-5 1.8c0 1.2.8 2 1.5 2.8L16 12Z",key:"1h3036"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sb=re("HandHelping",[["path",{d:"M11 12h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 14",key:"1j4xps"}],["path",{d:"m7 18 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"uospg8"}],["path",{d:"m2 13 6 6",key:"16e5sb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nne=re("HandMetal",[["path",{d:"M18 12.5V10a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1.4",key:"wc6myp"}],["path",{d:"M14 11V9a2 2 0 1 0-4 0v2",key:"94qvcw"}],["path",{d:"M10 10.5V5a2 2 0 1 0-4 0v9",key:"m1ah89"}],["path",{d:"m7 15-1.76-1.76a2 2 0 0 0-2.83 2.82l3.6 3.6C7.5 21.14 9.2 22 12 22h2a8 8 0 0 0 8-8V7a2 2 0 1 0-4 0v5",key:"t1skq1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kne=re("HandPlatter",[["path",{d:"M12 3V2",key:"ar7q03"}],["path",{d:"m15.4 17.4 3.2-2.8a2 2 0 1 1 2.8 2.9l-3.6 3.3c-.7.8-1.7 1.2-2.8 1.2h-4c-1.1 0-2.1-.4-2.8-1.2l-1.302-1.464A1 1 0 0 0 6.151 19H5",key:"n2g93r"}],["path",{d:"M2 14h12a2 2 0 0 1 0 4h-2",key:"1o2jem"}],["path",{d:"M4 10h16",key:"img6z1"}],["path",{d:"M5 10a7 7 0 0 1 14 0",key:"1ega1o"}],["path",{d:"M5 14v6a1 1 0 0 1-1 1H2",key:"1hescx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const l9=re("Hand",[["path",{d:"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1fvzgz"}],["path",{d:"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"1kc0my"}],["path",{d:"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8",key:"10h0bg"}],["path",{d:"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"1s1gnw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fb=re("Handshake",[["path",{d:"m11 17 2 2a1 1 0 1 0 3-3",key:"efffak"}],["path",{d:"m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4",key:"9pr0kb"}],["path",{d:"m21 3 1 11h-2",key:"1tisrp"}],["path",{d:"M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3",key:"1uvwmv"}],["path",{d:"M3 4h8",key:"1ep09j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sne=re("HardDriveDownload",[["path",{d:"M12 2v8",key:"1q4o3n"}],["path",{d:"m16 6-4 4-4-4",key:"6wukr"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 18h.01",key:"h775k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cne=re("HardDriveUpload",[["path",{d:"m16 6-4-4-4 4",key:"13yo43"}],["path",{d:"M12 2v8",key:"1q4o3n"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 18h.01",key:"h775k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const c9=re("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tne=re("HardHat",[["path",{d:"M10 10V5a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v5",key:"1p9q5i"}],["path",{d:"M14 6a6 6 0 0 1 6 6v3",key:"1hnv84"}],["path",{d:"M4 15v-3a6 6 0 0 1 6-6",key:"9ciidu"}],["rect",{x:"2",y:"15",width:"20",height:"4",rx:"1",key:"g3x8cw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JS=re("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ene=re("Haze",[["path",{d:"m5.2 6.2 1.4 1.4",key:"17imol"}],["path",{d:"M2 13h2",key:"13gyu8"}],["path",{d:"M20 13h2",key:"16rner"}],["path",{d:"m17.4 7.6 1.4-1.4",key:"t4xlah"}],["path",{d:"M22 17H2",key:"1gtaj3"}],["path",{d:"M22 21H2",key:"1gy6en"}],["path",{d:"M16 13a4 4 0 0 0-8 0",key:"1dyczq"}],["path",{d:"M12 5V2.5",key:"1vytko"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ane=re("HdmiPort",[["path",{d:"M22 9a1 1 0 0 0-1-1H3a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h1l2 2h12l2-2h1a1 1 0 0 0 1-1Z",key:"2128wb"}],["path",{d:"M7.5 12h9",key:"1t0ckc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aL=re("Heading1",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"m17 12 3-2v8",key:"1hhhft"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iL=re("Heading2",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1",key:"9jr5yi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const d9=re("Heading3",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2",key:"68ncm8"}],["path",{d:"M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2",key:"1ejuhz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mne=re("Heading4",[["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17 10v3a1 1 0 0 0 1 1h3",key:"tj5zdr"}],["path",{d:"M21 10v8",key:"1kdml4"}],["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ine=re("Heading5",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17 13v-3h4",key:"1nvgqp"}],["path",{d:"M17 17.7c.4.2.8.3 1.3.3 1.5 0 2.7-1.1 2.7-2.5S19.8 13 18.3 13H17",key:"2nebdn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pne=re("Heading6",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["circle",{cx:"19",cy:"16",r:"2",key:"15mx69"}],["path",{d:"M20 10c-2 2-3 3.5-3 6",key:"f35dl0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lne=re("Heading",[["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M6 20V4",key:"1w1bmo"}],["path",{d:"M18 20V4",key:"o2hl4u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dne=re("HeadphoneOff",[["path",{d:"M21 14h-1.343",key:"1jdnxi"}],["path",{d:"M9.128 3.47A9 9 0 0 1 21 12v3.343",key:"6kipu2"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20.414 20.414A2 2 0 0 1 19 21h-1a2 2 0 0 1-2-2v-3",key:"9x50f4"}],["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 2.636-6.364",key:"1bkxnm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rne=re("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const One=re("Headset",[["path",{d:"M3 11h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5Zm0 0a9 9 0 1 1 18 0m0 0v5a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3Z",key:"12oyoe"}],["path",{d:"M21 16v2a4 4 0 0 1-4 4h-5",key:"1x7m43"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fne=re("HeartCrack",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"m12 13-1-1 2-2-3-3 2-2",key:"xjdxli"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MA=re("HeartHandshake",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"M12 5 9.04 7.96a2.17 2.17 0 0 0 0 3.08c.82.82 2.13.85 3 .07l2.07-1.9a2.82 2.82 0 0 1 3.79 0l2.96 2.66",key:"4oyue0"}],["path",{d:"m18 15-2-2",key:"60u0ii"}],["path",{d:"m15 18-2-2",key:"6p76be"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zne=re("HeartOff",[["line",{x1:"2",y1:"2",x2:"22",y2:"22",key:"1w4vcy"}],["path",{d:"M16.5 16.5 12 21l-7-7c-1.5-1.45-3-3.2-3-5.5a5.5 5.5 0 0 1 2.14-4.35",key:"3mpagl"}],["path",{d:"M8.76 3.1c1.15.22 2.13.78 3.24 1.9 1.5-1.5 2.74-2 4.5-2A5.5 5.5 0 0 1 22 8.5c0 2.12-1.3 3.78-2.67 5.17",key:"1gh3v3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bne=re("HeartPulse",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"M3.22 12H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27",key:"1uw2ng"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yi=re("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ne=re("Heater",[["path",{d:"M11 8c2-3-2-3 0-6",key:"1ldv5m"}],["path",{d:"M15.5 8c2-3-2-3 0-6",key:"1otqoz"}],["path",{d:"M6 10h.01",key:"1lbq93"}],["path",{d:"M6 14h.01",key:"zudwn7"}],["path",{d:"M10 16v-4",key:"1c25yv"}],["path",{d:"M14 16v-4",key:"1dkbt8"}],["path",{d:"M18 16v-4",key:"1yg9me"}],["path",{d:"M20 6a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h3",key:"1ubg90"}],["path",{d:"M5 20v2",key:"1abpe8"}],["path",{d:"M19 20v2",key:"kqn6ft"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Une=re("Hexagon",[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qne=re("Highlighter",[["path",{d:"m9 11-6 6v3h9l3-3",key:"1a3l36"}],["path",{d:"m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4",key:"14a9rk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IA=re("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vne=re("HopOff",[["path",{d:"M10.82 16.12c1.69.6 3.91.79 5.18.85.28.01.53-.09.7-.27",key:"qyzcap"}],["path",{d:"M11.14 20.57c.52.24 2.44 1.12 4.08 1.37.46.06.86-.25.9-.71.12-1.52-.3-3.43-.5-4.28",key:"y078lb"}],["path",{d:"M16.13 21.05c1.65.63 3.68.84 4.87.91a.9.9 0 0 0 .7-.26",key:"1utre3"}],["path",{d:"M17.99 5.52a20.83 20.83 0 0 1 3.15 4.5.8.8 0 0 1-.68 1.13c-1.17.1-2.5.02-3.9-.25",key:"17o9hm"}],["path",{d:"M20.57 11.14c.24.52 1.12 2.44 1.37 4.08.04.3-.08.59-.31.75",key:"1d1n4p"}],["path",{d:"M4.93 4.93a10 10 0 0 0-.67 13.4c.35.43.96.4 1.17-.12.69-1.71 1.07-5.07 1.07-6.71 1.34.45 3.1.9 4.88.62a.85.85 0 0 0 .48-.24",key:"9uv3tt"}],["path",{d:"M5.52 17.99c1.05.95 2.91 2.42 4.5 3.15a.8.8 0 0 0 1.13-.68c.2-2.34-.33-5.3-1.57-8.28",key:"1292wz"}],["path",{d:"M8.35 2.68a10 10 0 0 1 9.98 1.58c.43.35.4.96-.12 1.17-1.5.6-4.3.98-6.07 1.05",key:"7ozu9p"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hne=re("Hop",[["path",{d:"M10.82 16.12c1.69.6 3.91.79 5.18.85.55.03 1-.42.97-.97-.06-1.27-.26-3.5-.85-5.18",key:"18lxf1"}],["path",{d:"M11.5 6.5c1.64 0 5-.38 6.71-1.07.52-.2.55-.82.12-1.17A10 10 0 0 0 4.26 18.33c.35.43.96.4 1.17-.12.69-1.71 1.07-5.07 1.07-6.71 1.34.45 3.1.9 4.88.62a.88.88 0 0 0 .73-.74c.3-2.14-.15-3.5-.61-4.88",key:"vtfxrw"}],["path",{d:"M15.62 16.95c.2.85.62 2.76.5 4.28a.77.77 0 0 1-.9.7 16.64 16.64 0 0 1-4.08-1.36",key:"13hl71"}],["path",{d:"M16.13 21.05c1.65.63 3.68.84 4.87.91a.9.9 0 0 0 .96-.96 17.68 17.68 0 0 0-.9-4.87",key:"1sl8oj"}],["path",{d:"M16.94 15.62c.86.2 2.77.62 4.29.5a.77.77 0 0 0 .7-.9 16.64 16.64 0 0 0-1.36-4.08",key:"19c6kt"}],["path",{d:"M17.99 5.52a20.82 20.82 0 0 1 3.15 4.5.8.8 0 0 1-.68 1.13c-2.33.2-5.3-.32-8.27-1.57",key:"85ghs3"}],["path",{d:"M4.93 4.93 3 3a.7.7 0 0 1 0-1",key:"x087yj"}],["path",{d:"M9.58 12.18c1.24 2.98 1.77 5.95 1.57 8.28a.8.8 0 0 1-1.13.68 20.82 20.82 0 0 1-4.5-3.15",key:"11xdqo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gne=re("Hospital",[["path",{d:"M12 6v4",key:"16clxf"}],["path",{d:"M14 14h-4",key:"esezmu"}],["path",{d:"M14 18h-4",key:"16mqa2"}],["path",{d:"M14 8h-4",key:"z8ypaz"}],["path",{d:"M18 12h2a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2h2",key:"b1k337"}],["path",{d:"M18 22V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v18",key:"16g51d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wne=re("Hotel",[["path",{d:"M10 22v-6.57",key:"1wmca3"}],["path",{d:"M12 11h.01",key:"z322tv"}],["path",{d:"M12 7h.01",key:"1ivr5q"}],["path",{d:"M14 15.43V22",key:"1q2vjd"}],["path",{d:"M15 16a5 5 0 0 0-6 0",key:"o9wqvi"}],["path",{d:"M16 11h.01",key:"xkw8gn"}],["path",{d:"M16 7h.01",key:"1kdx03"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 7h.01",key:"1vti4s"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",key:"1uxh74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kne=re("Hourglass",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M5 2h14",key:"pdyrp9"}],["path",{d:"M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22",key:"1d314k"}],["path",{d:"M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2",key:"1vvvr6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yne=re("HousePlug",[["path",{d:"M10 12V8.964",key:"1vll13"}],["path",{d:"M14 12V8.964",key:"1x3qvg"}],["path",{d:"M15 12a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-2a1 1 0 0 1 1-1z",key:"ppykja"}],["path",{d:"M8.5 21H5a2 2 0 0 1-2-2v-9a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2v-2",key:"1gvg2z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zne=re("HousePlus",[["path",{d:"M13.22 2.416a2 2 0 0 0-2.511.057l-7 5.999A2 2 0 0 0 3 10v9a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7.354",key:"5phn05"}],["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M15 6h6",key:"1jlkvy"}],["path",{d:"M18 3v6",key:"x1uolp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zr=re("House",[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V5=re("IceCreamBowl",[["path",{d:"M12 17c5 0 8-2.69 8-6H4c0 3.31 3 6 8 6m-4 4h8m-4-3v3M5.14 11a3.5 3.5 0 1 1 6.71 0",key:"1uxfcu"}],["path",{d:"M12.14 11a3.5 3.5 0 1 1 6.71 0",key:"4k3m1s"}],["path",{d:"M15.5 6.5a3.5 3.5 0 1 0-7 0",key:"zmuahr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H5=re("IceCreamCone",[["path",{d:"m7 11 4.08 10.35a1 1 0 0 0 1.84 0L17 11",key:"1v6356"}],["path",{d:"M17 7A5 5 0 0 0 7 7",key:"151p3v"}],["path",{d:"M17 7a2 2 0 0 1 0 4H7a2 2 0 0 1 0-4",key:"1sdaij"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qne=re("IdCard",[["path",{d:"M16 10h2",key:"8sgtl7"}],["path",{d:"M16 14h2",key:"epxaof"}],["path",{d:"M6.17 15a3 3 0 0 1 5.66 0",key:"n6f512"}],["circle",{cx:"9",cy:"11",r:"2",key:"yxgjnd"}],["rect",{x:"2",y:"5",width:"20",height:"14",rx:"2",key:"qneu4z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xne=re("ImageDown",[["path",{d:"M10.3 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10l-3.1-3.1a2 2 0 0 0-2.814.014L6 21",key:"9csbqa"}],["path",{d:"m14 19 3 3v-5.5",key:"9ldu5r"}],["path",{d:"m17 22 3-3",key:"1nkfve"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jne=re("ImageMinus",[["path",{d:"M21 9v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7",key:"m87ecr"}],["line",{x1:"16",x2:"22",y1:"5",y2:"5",key:"ez7e4s"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ere=re("ImageOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tre=re("ImagePlay",[["path",{d:"m11 16-5 5",key:"j5f7ct"}],["path",{d:"M11 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6.5",key:"7s81lt"}],["path",{d:"M15.765 22a.5.5 0 0 1-.765-.424V13.38a.5.5 0 0 1 .765-.424l5.878 3.674a1 1 0 0 1 0 1.696z",key:"1omb6s"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ay=re("ImagePlus",[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sre=re("ImageUp",[["path",{d:"M10.3 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10l-3.1-3.1a2 2 0 0 0-2.814.014L6 21",key:"9csbqa"}],["path",{d:"m14 19.5 3-3 3 3",key:"9vmjn0"}],["path",{d:"M17 22v-5.5",key:"1aa6fl"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nre=re("ImageUpscale",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M17 21h2a2 2 0 0 0 2-2",key:"130fy9"}],["path",{d:"M21 12v3",key:"1wzk3p"}],["path",{d:"m21 3-5 5",key:"1g5oa7"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2",key:"kk3yz1"}],["path",{d:"m5 21 4.144-4.144a1.21 1.21 0 0 1 1.712 0L13 19",key:"fyekpt"}],["path",{d:"M9 3h3",key:"d52fa"}],["rect",{x:"3",y:"11",width:"10",height:"10",rx:"1",key:"1wpmix"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nl=re("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rre=re("Images",[["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"m22 13-1.296-1.296a2.41 2.41 0 0 0-3.408 0L11 18",key:"nf6bnh"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["rect",{width:"16",height:"16",x:"6",y:"2",rx:"2",key:"12espp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const are=re("Import",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m8 11 4 4 4-4",key:"1dohi6"}],["path",{d:"M8 5H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-4",key:"1ywtjm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z2=re("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G5=re("IndentDecrease",[["path",{d:"M21 12H11",key:"wd7e0v"}],["path",{d:"M21 18H11",key:"4wu86t"}],["path",{d:"M21 6H11",key:"6dy1d6"}],["path",{d:"m7 8-4 4 4 4",key:"o5hrat"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W5=re("IndentIncrease",[["path",{d:"M21 12H11",key:"wd7e0v"}],["path",{d:"M21 18H11",key:"4wu86t"}],["path",{d:"M21 6H11",key:"6dy1d6"}],["path",{d:"m3 8 4 4-4 4",key:"1a3j6y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ire=re("IndianRupee",[["path",{d:"M6 3h12",key:"ggurg9"}],["path",{d:"M6 8h12",key:"6g4wlu"}],["path",{d:"m6 13 8.5 8",key:"u1kupk"}],["path",{d:"M6 13h3",key:"wdp6ag"}],["path",{d:"M9 13c6.667 0 6.667-10 0-10",key:"1nkvk2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ore=re("Infinity",[["path",{d:"M12 12c-2-2.67-4-4-6-4a4 4 0 1 0 0 8c2 0 4-1.33 6-4Zm0 0c2 2.67 4 4 6 4a4 4 0 0 0 0-8c-2 0-4 1.33-6 4Z",key:"1z0uae"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vw=re("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lre=re("InspectionPanel",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 7h.01",key:"7u93v4"}],["path",{d:"M17 7h.01",key:"14a9sn"}],["path",{d:"M7 17h.01",key:"19xn7k"}],["path",{d:"M17 17h.01",key:"1sd3ek"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mu=re("Instagram",[["rect",{width:"20",height:"20",x:"2",y:"2",rx:"5",ry:"5",key:"2e1cvw"}],["path",{d:"M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z",key:"9exkf1"}],["line",{x1:"17.5",x2:"17.51",y1:"6.5",y2:"6.5",key:"r4j83e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e4=re("Italic",[["line",{x1:"19",x2:"10",y1:"4",y2:"4",key:"15jd3p"}],["line",{x1:"14",x2:"5",y1:"20",y2:"20",key:"bu0au3"}],["line",{x1:"15",x2:"9",y1:"4",y2:"20",key:"uljnxc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cre=re("IterationCcw",[["path",{d:"M20 10c0-4.4-3.6-8-8-8s-8 3.6-8 8 3.6 8 8 8h8",key:"4znkd0"}],["polyline",{points:"16 14 20 18 16 22",key:"11njsm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dre=re("IterationCw",[["path",{d:"M4 10c0-4.4 3.6-8 8-8s8 3.6 8 8-3.6 8-8 8H4",key:"tuf4su"}],["polyline",{points:"8 22 4 18 8 14",key:"evkj9s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ure=re("JapaneseYen",[["path",{d:"M12 9.5V21m0-11.5L6 3m6 6.5L18 3",key:"2ej80x"}],["path",{d:"M6 15h12",key:"1hwgt5"}],["path",{d:"M6 11h12",key:"wf4gp6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hre=re("Joystick",[["path",{d:"M21 17a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-2Z",key:"jg2n2t"}],["path",{d:"M6 15v-2",key:"gd6mvg"}],["path",{d:"M12 15V9",key:"8c7uyn"}],["circle",{cx:"12",cy:"6",r:"3",key:"1gm2ql"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q2=re("Kanban",[["path",{d:"M6 5v11",key:"mdvv1e"}],["path",{d:"M12 5v6",key:"14ar3b"}],["path",{d:"M18 5v14",key:"7ji314"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PA=re("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mre=re("KeySquare",[["path",{d:"M12.4 2.7a2.5 2.5 0 0 1 3.4 0l5.5 5.5a2.5 2.5 0 0 1 0 3.4l-3.7 3.7a2.5 2.5 0 0 1-3.4 0L8.7 9.8a2.5 2.5 0 0 1 0-3.4z",key:"165ttr"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"m9.4 10.6-6.814 6.814A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814",key:"1ubxi2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gg=re("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pre=re("KeyboardMusic",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M6 8h4",key:"utf9t1"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M6 12v4",key:"dy92yo"}],["path",{d:"M10 12v4",key:"1fxnav"}],["path",{d:"M14 12v4",key:"1hft58"}],["path",{d:"M18 12v4",key:"tjjnbz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fre=re("KeyboardOff",[["path",{d:"M 20 4 A2 2 0 0 1 22 6",key:"1g1fkt"}],["path",{d:"M 22 6 L 22 16.41",key:"1qjg3w"}],["path",{d:"M 7 16 L 16 16",key:"n0yqwb"}],["path",{d:"M 9.69 4 L 20 4",key:"kbpcgx"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20 20H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2",key:"s23sx2"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M8 12h.01",key:"czm47f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xre=re("Keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gre=re("LampCeiling",[["path",{d:"M12 2v5",key:"nd4vlx"}],["path",{d:"M6 7h12l4 9H2l4-9Z",key:"123d64"}],["path",{d:"M9.17 16a3 3 0 1 0 5.66 0",key:"1061mw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yre=re("LampDesk",[["path",{d:"m14 5-3 3 2 7 8-8-7-2Z",key:"1b0msb"}],["path",{d:"m14 5-3 3-3-3 3-3 3 3Z",key:"1uemms"}],["path",{d:"M9.5 6.5 4 12l3 6",key:"1bx08v"}],["path",{d:"M3 22v-2c0-1.1.9-2 2-2h4a2 2 0 0 1 2 2v2H3Z",key:"wap775"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vre=re("LampFloor",[["path",{d:"M9 2h6l3 7H6l3-7Z",key:"wcx6mj"}],["path",{d:"M12 9v13",key:"3n1su1"}],["path",{d:"M9 22h6",key:"1rlq3v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bre=re("LampWallDown",[["path",{d:"M11 13h6l3 7H8l3-7Z",key:"9n3qlo"}],["path",{d:"M14 13V8a2 2 0 0 0-2-2H8",key:"1hu4hb"}],["path",{d:"M4 9h2a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H4v6Z",key:"s053bc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _re=re("LampWallUp",[["path",{d:"M11 4h6l3 7H8l3-7Z",key:"11x1ee"}],["path",{d:"M14 11v5a2 2 0 0 1-2 2H8",key:"eutp5o"}],["path",{d:"M4 15h2a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2H4v-6Z",key:"1iuthr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wre=re("Lamp",[["path",{d:"M8 2h8l4 10H4L8 2Z",key:"9dma5w"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M8 22v-2c0-1.1.9-2 2-2h4a2 2 0 0 1 2 2v2H8Z",key:"mwf4oh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jre=re("LandPlot",[["path",{d:"m12 8 6-3-6-3v10",key:"mvpnpy"}],["path",{d:"m8 11.99-5.5 3.14a1 1 0 0 0 0 1.74l8.5 4.86a2 2 0 0 0 2 0l8.5-4.86a1 1 0 0 0 0-1.74L16 12",key:"ek95tt"}],["path",{d:"m6.49 12.85 11.02 6.3",key:"1kt42w"}],["path",{d:"M17.51 12.85 6.5 19.15",key:"v55bdg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nre=re("Landmark",[["line",{x1:"3",x2:"21",y1:"22",y2:"22",key:"j8o0r"}],["line",{x1:"6",x2:"6",y1:"18",y2:"11",key:"10tf0k"}],["line",{x1:"10",x2:"10",y1:"18",y2:"11",key:"54lgf6"}],["line",{x1:"14",x2:"14",y1:"18",y2:"11",key:"380y"}],["line",{x1:"18",x2:"18",y1:"18",y2:"11",key:"1kevvc"}],["polygon",{points:"12 2 20 7 4 7",key:"jkujk7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kre=re("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sre=re("LaptopMinimalCheck",[["path",{d:"M2 20h20",key:"owomy5"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}],["rect",{x:"3",y:"4",width:"18",height:"12",rx:"2",key:"8ur36m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K5=re("LaptopMinimal",[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cre=re("Laptop",[["path",{d:"M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16",key:"tarvll"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tre=re("LassoSelect",[["path",{d:"M7 22a5 5 0 0 1-2-4",key:"umushi"}],["path",{d:"M7 16.93c.96.43 1.96.74 2.99.91",key:"ybbtv3"}],["path",{d:"M3.34 14A6.8 6.8 0 0 1 2 10c0-4.42 4.48-8 10-8s10 3.58 10 8a7.19 7.19 0 0 1-.33 2",key:"gt5e1w"}],["path",{d:"M5 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",key:"bq3ynw"}],["path",{d:"M14.33 22h-.09a.35.35 0 0 1-.24-.32v-10a.34.34 0 0 1 .33-.34c.08 0 .15.03.21.08l7.34 6a.33.33 0 0 1-.21.59h-4.49l-2.57 3.85a.35.35 0 0 1-.28.14z",key:"72q637"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ere=re("Lasso",[["path",{d:"M7 22a5 5 0 0 1-2-4",key:"umushi"}],["path",{d:"M3.3 14A6.8 6.8 0 0 1 2 10c0-4.4 4.5-8 10-8s10 3.6 10 8-4.5 8-10 8a12 12 0 0 1-5-1",key:"146dds"}],["path",{d:"M5 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",key:"bq3ynw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Are=re("Laugh",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M18 13a6 6 0 0 1-6 5 6 6 0 0 1-6-5h12Z",key:"b2q4dd"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mre=re("Layers2",[["path",{d:"m16.02 12 5.48 3.13a1 1 0 0 1 0 1.74L13 21.74a2 2 0 0 1-2 0l-8.5-4.87a1 1 0 0 1 0-1.74L7.98 12",key:"1cuww1"}],["path",{d:"M13 13.74a2 2 0 0 1-2 0L2.5 8.87a1 1 0 0 1 0-1.74L11 2.26a2 2 0 0 1 2 0l8.5 4.87a1 1 0 0 1 0 1.74Z",key:"pdlvxu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ire=re("Layers3",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m6.08 9.5-3.5 1.6a1 1 0 0 0 0 1.81l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9a1 1 0 0 0 0-1.83l-3.5-1.59",key:"1e5n1m"}],["path",{d:"m6.08 14.5-3.5 1.6a1 1 0 0 0 0 1.81l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9a1 1 0 0 0 0-1.83l-3.5-1.59",key:"1iwflc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const u9=re("Layers",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65",key:"dd6zsq"}],["path",{d:"m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65",key:"ep9fru"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t4=re("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vf=re("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pre=re("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lre=re("LayoutPanelLeft",[["rect",{width:"7",height:"18",x:"3",y:"3",rx:"1",key:"2obqm"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dre=re("LayoutPanelTop",[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const s4=re("LayoutTemplate",[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"9",height:"7",x:"3",y:"14",rx:"1",key:"jqznyg"}],["rect",{width:"5",height:"7",x:"16",y:"14",rx:"1",key:"q5h2i8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rre=re("Leaf",[["path",{d:"M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10Z",key:"nnexq3"}],["path",{d:"M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12",key:"mt58a7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ore=re("LeafyGreen",[["path",{d:"M2 22c1.25-.987 2.27-1.975 3.9-2.2a5.56 5.56 0 0 1 3.8 1.5 4 4 0 0 0 6.187-2.353 3.5 3.5 0 0 0 3.69-5.116A3.5 3.5 0 0 0 20.95 8 3.5 3.5 0 1 0 16 3.05a3.5 3.5 0 0 0-5.831 1.373 3.5 3.5 0 0 0-5.116 3.69 4 4 0 0 0-2.348 6.155C3.499 15.42 4.409 16.712 4.2 18.1 3.926 19.743 3.014 20.732 2 22",key:"1134nt"}],["path",{d:"M2 22 17 7",key:"1q7jp2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fre=re("Lectern",[["path",{d:"M16 12h3a2 2 0 0 0 1.902-1.38l1.056-3.333A1 1 0 0 0 21 6H3a1 1 0 0 0-.958 1.287l1.056 3.334A2 2 0 0 0 5 12h3",key:"13jjxg"}],["path",{d:"M18 6V3a1 1 0 0 0-1-1h-3",key:"1550fe"}],["rect",{width:"8",height:"12",x:"8",y:"10",rx:"1",key:"qmu8b6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zre=re("LetterText",[["path",{d:"M15 12h6",key:"upa0zy"}],["path",{d:"M15 6h6",key:"1jlkvy"}],["path",{d:"m3 13 3.553-7.724a.5.5 0 0 1 .894 0L11 13",key:"blevx4"}],["path",{d:"M3 18h18",key:"1h113x"}],["path",{d:"M4 11h6",key:"olkgv1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bre=re("LibraryBig",[["rect",{width:"8",height:"18",x:"3",y:"3",rx:"1",key:"oynpb5"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M20.4 18.9c.2.5-.1 1.1-.6 1.3l-1.9.7c-.5.2-1.1-.1-1.3-.6L11.1 5.1c-.2-.5.1-1.1.6-1.3l1.9-.7c.5-.2 1.1.1 1.3.6Z",key:"1qboyk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wg=re("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oL=re("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $re=re("Ligature",[["path",{d:"M8 20V8c0-2.2 1.8-4 4-4 1.5 0 2.8.8 3.5 2",key:"1rtphz"}],["path",{d:"M6 12h4",key:"a4o3ry"}],["path",{d:"M14 12h2v8",key:"c1fccl"}],["path",{d:"M6 20h4",key:"1i6q5t"}],["path",{d:"M14 20h4",key:"lzx1xo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ure=re("LightbulbOff",[["path",{d:"M16.8 11.2c.8-.9 1.2-2 1.2-3.2a6 6 0 0 0-9.3-5",key:"1fkcox"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M6.3 6.3a4.67 4.67 0 0 0 1.2 5.2c.7.7 1.3 1.5 1.5 2.5",key:"10m8kw"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bw=re("Lightbulb",[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qre=re("Link2Off",[["path",{d:"M9 17H7A5 5 0 0 1 7 7",key:"10o201"}],["path",{d:"M15 7h2a5 5 0 0 1 4 8",key:"1d3206"}],["line",{x1:"8",x2:"12",y1:"12",y2:"12",key:"rvw6j4"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const El=re("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tl=re("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bf=re("Linkedin",[["path",{d:"M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z",key:"c2jq9f"}],["rect",{width:"4",height:"12",x:"2",y:"9",key:"mk3on5"}],["circle",{cx:"4",cy:"4",r:"2",key:"bt5ra8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vre=re("ListCheck",[["path",{d:"M11 18H3",key:"n3j2dh"}],["path",{d:"m15 18 2 2 4-4",key:"1szwhi"}],["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pu=re("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hre=re("ListCollapse",[["path",{d:"m3 10 2.5-2.5L3 5",key:"i6eama"}],["path",{d:"m3 19 2.5-2.5L3 14",key:"w2gmor"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gre=re("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const h9=re("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wre=re("ListMinus",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M21 12h-6",key:"bt1uis"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kre=re("ListMusic",[["path",{d:"M21 15V6",key:"h1cx4g"}],["path",{d:"M18.5 18a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z",key:"8saifv"}],["path",{d:"M12 12H3",key:"18klou"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M12 18H3",key:"11ftsu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zv=re("ListOrdered",[["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M4 10h2",key:"16xx2s"}],["path",{d:"M4 6h1v4",key:"cnovpq"}],["path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1",key:"m9a95d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yre=re("ListPlus",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zre=re("ListRestart",[["path",{d:"M21 6H3",key:"1jwq7v"}],["path",{d:"M7 12H3",key:"13ou7f"}],["path",{d:"M7 18H3",key:"1sijw9"}],["path",{d:"M12 18a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L11 14",key:"qth677"}],["path",{d:"M11 10v4h4",key:"172dkj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qre=re("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xre=re("ListTodo",[["rect",{x:"3",y:"5",width:"6",height:"6",rx:"1",key:"1defrl"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jre=re("ListTree",[["path",{d:"M21 12h-8",key:"1bmf0i"}],["path",{d:"M21 6H8",key:"1pqkrb"}],["path",{d:"M21 18h-8",key:"1tm79t"}],["path",{d:"M3 6v4c0 1.1.9 2 2 2h3",key:"1ywdgy"}],["path",{d:"M3 10v6c0 1.1.9 2 2 2h3",key:"2wc746"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eae=re("ListVideo",[["path",{d:"M12 12H3",key:"18klou"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M12 18H3",key:"11ftsu"}],["path",{d:"m16 12 5 3-5 3v-6Z",key:"zpskkp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tae=re("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ep=re("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ss=re("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sae=re("LoaderPinwheel",[["path",{d:"M22 12a1 1 0 0 1-10 0 1 1 0 0 0-10 0",key:"1lzz15"}],["path",{d:"M7 20.7a1 1 0 1 1 5-8.7 1 1 0 1 0 5-8.6",key:"1gnrpi"}],["path",{d:"M7 3.3a1 1 0 1 1 5 8.6 1 1 0 1 0 5 8.6",key:"u9yy5q"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nae=re("Loader",[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rae=re("LocateFixed",[["line",{x1:"2",x2:"5",y1:"12",y2:"12",key:"bvdh0s"}],["line",{x1:"19",x2:"22",y1:"12",y2:"12",key:"1tbv5k"}],["line",{x1:"12",x2:"12",y1:"2",y2:"5",key:"11lu5j"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}],["circle",{cx:"12",cy:"12",r:"7",key:"fim9np"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aae=re("LocateOff",[["line",{x1:"2",x2:"5",y1:"12",y2:"12",key:"bvdh0s"}],["line",{x1:"19",x2:"22",y1:"12",y2:"12",key:"1tbv5k"}],["line",{x1:"12",x2:"12",y1:"2",y2:"5",key:"11lu5j"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}],["path",{d:"M7.11 7.11C5.83 8.39 5 10.1 5 12c0 3.87 3.13 7 7 7 1.9 0 3.61-.83 4.89-2.11",key:"1oh7ia"}],["path",{d:"M18.71 13.96c.19-.63.29-1.29.29-1.96 0-3.87-3.13-7-7-7-.67 0-1.33.1-1.96.29",key:"3qdecy"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lL=re("Locate",[["line",{x1:"2",x2:"5",y1:"12",y2:"12",key:"bvdh0s"}],["line",{x1:"19",x2:"22",y1:"12",y2:"12",key:"1tbv5k"}],["line",{x1:"12",x2:"12",y1:"2",y2:"5",key:"11lu5j"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}],["circle",{cx:"12",cy:"12",r:"7",key:"fim9np"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y5=re("LockKeyholeOpen",[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{width:"18",height:"12",x:"3",y:"10",rx:"2",key:"l0tzu3"}],["path",{d:"M7 10V7a5 5 0 0 1 9.33-2.5",key:"car5b7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iae=re("LockKeyhole",[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z5=re("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rc=re("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LA=re("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DA=re("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oae=re("Logs",[["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M3 18h1",key:"1eiwyy"}],["path",{d:"M3 6h1",key:"rgxa97"}],["path",{d:"M8 12h1",key:"1con00"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M8 6h1",key:"tn6mkg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lae=re("Lollipop",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}],["path",{d:"M11 11a2 2 0 0 0 4 0 4 4 0 0 0-8 0 6 6 0 0 0 12 0",key:"107gwy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cae=re("Luggage",[["path",{d:"M6 20a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2",key:"1m57jg"}],["path",{d:"M8 18V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v14",key:"1l99gc"}],["path",{d:"M10 20h4",key:"ni2waw"}],["circle",{cx:"16",cy:"20",r:"2",key:"1vifvg"}],["circle",{cx:"8",cy:"20",r:"2",key:"ckkr5m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dae=re("Magnet",[["path",{d:"m6 15-4-4 6.75-6.77a7.79 7.79 0 0 1 11 11L13 22l-4-4 6.39-6.36a2.14 2.14 0 0 0-3-3L6 15",key:"1i3lhw"}],["path",{d:"m5 8 4 4",key:"j6kj7e"}],["path",{d:"m12 15 4 4",key:"lnac28"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cL=re("MailCheck",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uae=re("MailMinus",[["path",{d:"M22 15V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"fuxbkv"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M16 19h6",key:"xwg31i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dL=re("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const m9=re("MailPlus",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M16 19h6",key:"xwg31i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hae=re("MailQuestion",[["path",{d:"M22 10.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h12.5",key:"e61zoh"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M18 15.28c.2-.4.5-.8.9-1a2.1 2.1 0 0 1 2.6.4c.3.4.5.8.5 1.3 0 1.3-2 2-2 2",key:"7z9rxb"}],["path",{d:"M20 22v.01",key:"12bgn6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mae=re("MailSearch",[["path",{d:"M22 12.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h7.5",key:"w80f2v"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M18 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z",key:"8lzu5m"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m22 22-1.5-1.5",key:"1x83k4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pae=re("MailWarning",[["path",{d:"M22 10.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h12.5",key:"e61zoh"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M20 14v4",key:"1hm744"}],["path",{d:"M20 22v.01",key:"12bgn6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uL=re("MailX",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h9",key:"1j9vog"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m17 17 4 4",key:"1b3523"}],["path",{d:"m21 17-4 4",key:"uinynz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hs=re("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fae=re("Mailbox",[["path",{d:"M22 17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9.5C2 7 4 5 6.5 5H18c2.2 0 4 1.8 4 4v8Z",key:"1lbycx"}],["polyline",{points:"15,9 18,9 18,11",key:"1pm9c0"}],["path",{d:"M6.5 5C9 5 11 7 11 9.5V17a2 2 0 0 1-2 2",key:"15i455"}],["line",{x1:"6",x2:"7",y1:"10",y2:"10",key:"1e2scm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xae=re("Mails",[["rect",{width:"16",height:"13",x:"6",y:"4",rx:"2",key:"1drq3f"}],["path",{d:"m22 7-7.1 3.78c-.57.3-1.23.3-1.8 0L6 7",key:"xn252p"}],["path",{d:"M2 8v11c0 1.1.9 2 2 2h14",key:"n13cji"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gae=re("MapPinCheckInside",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yae=re("MapPinCheck",[["path",{d:"M19.43 12.935c.357-.967.57-1.955.57-2.935a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32.197 32.197 0 0 0 .813-.728",key:"1dq61d"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"m16 18 2 2 4-4",key:"1mkfmb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vae=re("MapPinHouse",[["path",{d:"M15 22a1 1 0 0 1-1-1v-4a1 1 0 0 1 .445-.832l3-2a1 1 0 0 1 1.11 0l3 2A1 1 0 0 1 22 17v4a1 1 0 0 1-1 1z",key:"1p1rcz"}],["path",{d:"M18 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 .601.2",key:"mcbcs9"}],["path",{d:"M18 22v-3",key:"1t1ugv"}],["circle",{cx:"10",cy:"10",r:"3",key:"1ns7v1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bae=re("MapPinMinusInside",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ae=re("MapPinMinus",[["path",{d:"M18.977 14C19.6 12.701 20 11.343 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32 32 0 0 0 .824-.738",key:"11uxia"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M16 18h6",key:"987eiv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wae=re("MapPinOff",[["path",{d:"M12.75 7.09a3 3 0 0 1 2.16 2.16",key:"1d4wjd"}],["path",{d:"M17.072 17.072c-1.634 2.17-3.527 3.912-4.471 4.727a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 1.432-4.568",key:"12yil7"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.475 2.818A8 8 0 0 1 20 10c0 1.183-.31 2.377-.81 3.533",key:"lhrkcz"}],["path",{d:"M9.13 9.13a3 3 0 0 0 3.74 3.74",key:"13wojd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jae=re("MapPinPlusInside",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nae=re("MapPinPlus",[["path",{d:"M19.914 11.105A7.298 7.298 0 0 0 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32 32 0 0 0 .824-.738",key:"fcdtly"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M16 18h6",key:"987eiv"}],["path",{d:"M19 15v6",key:"10aioa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kae=re("MapPinXInside",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sae=re("MapPinX",[["path",{d:"M19.752 11.901A7.78 7.78 0 0 0 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 19 19 0 0 0 .09-.077",key:"y0ewhp"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"m21.5 15.5-5 5",key:"11iqnx"}],["path",{d:"m21.5 20.5-5-5",key:"1bylgx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ca=re("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cae=re("MapPinned",[["path",{d:"M18 8c0 3.613-3.869 7.429-5.393 8.795a1 1 0 0 1-1.214 0C9.87 15.429 6 11.613 6 8a6 6 0 0 1 12 0",key:"11u0oz"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["path",{d:"M8.714 14h-3.71a1 1 0 0 0-.948.683l-2.004 6A1 1 0 0 0 3 22h18a1 1 0 0 0 .948-1.316l-2-6a1 1 0 0 0-.949-.684h-3.712",key:"q8zwxj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RA=re("Map",[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tae=re("Martini",[["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M12 11v11",key:"ur9y6a"}],["path",{d:"m19 3-7 8-7-8Z",key:"1sgpiw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const p9=re("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OA=re("Maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X2=re("Medal",[["path",{d:"M7.21 15 2.66 7.14a2 2 0 0 1 .13-2.2L4.4 2.8A2 2 0 0 1 6 2h12a2 2 0 0 1 1.6.8l1.6 2.14a2 2 0 0 1 .14 2.2L16.79 15",key:"143lza"}],["path",{d:"M11 12 5.12 2.2",key:"qhuxz6"}],["path",{d:"m13 12 5.88-9.8",key:"hbye0f"}],["path",{d:"M8 7h8",key:"i86dvs"}],["circle",{cx:"12",cy:"17",r:"5",key:"qbz8iq"}],["path",{d:"M12 18v-2h-.5",key:"fawc4q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eae=re("MegaphoneOff",[["path",{d:"M9.26 9.26 3 11v3l14.14 3.14",key:"3429n"}],["path",{d:"M21 15.34V6l-7.31 2.03",key:"4o1dh8"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qd=re("Megaphone",[["path",{d:"m3 11 18-5v12L3 14v-3z",key:"n962bs"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Aae=re("Meh",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"8",x2:"16",y1:"15",y2:"15",key:"1xb1d9"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mae=re("MemoryStick",[["path",{d:"M6 19v-3",key:"1nvgqn"}],["path",{d:"M10 19v-3",key:"iu8nkm"}],["path",{d:"M14 19v-3",key:"kcehxu"}],["path",{d:"M18 19v-3",key:"1vh91z"}],["path",{d:"M8 11V9",key:"63erz4"}],["path",{d:"M16 11V9",key:"fru6f3"}],["path",{d:"M12 11V9",key:"ha00sb"}],["path",{d:"M2 15h20",key:"16ne18"}],["path",{d:"M2 7a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v1.1a2 2 0 0 0 0 3.837V17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5.1a2 2 0 0 0 0-3.837Z",key:"lhddv3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n4=re("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Iae=re("Merge",[["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}],["path",{d:"M12 2v10.3a4 4 0 0 1-1.172 2.872L4 22",key:"1hyw0i"}],["path",{d:"m20 22-5-5",key:"1m27yz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pae=re("MessageCircleCode",[["path",{d:"M10 9.5 8 12l2 2.5",key:"3mjy60"}],["path",{d:"m14 9.5 2 2.5-2 2.5",key:"1bir2l"}],["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22z",key:"k85zhp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lae=re("MessageCircleDashed",[["path",{d:"M13.5 3.1c-.5 0-1-.1-1.5-.1s-1 .1-1.5.1",key:"16ll65"}],["path",{d:"M19.3 6.8a10.45 10.45 0 0 0-2.1-2.1",key:"1nq77a"}],["path",{d:"M20.9 13.5c.1-.5.1-1 .1-1.5s-.1-1-.1-1.5",key:"1sf7wn"}],["path",{d:"M17.2 19.3a10.45 10.45 0 0 0 2.1-2.1",key:"x1hs5g"}],["path",{d:"M10.5 20.9c.5.1 1 .1 1.5.1s1-.1 1.5-.1",key:"19m18z"}],["path",{d:"M3.5 17.5 2 22l4.5-1.5",key:"1f36qi"}],["path",{d:"M3.1 10.5c0 .5-.1 1-.1 1.5s.1 1 .1 1.5",key:"1vz3ju"}],["path",{d:"M6.8 4.7a10.45 10.45 0 0 0-2.1 2.1",key:"19f9do"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hL=re("MessageCircleHeart",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M15.8 9.2a2.5 2.5 0 0 0-3.5 0l-.3.4-.35-.3a2.42 2.42 0 1 0-3.2 3.6l3.6 3.5 3.6-3.5c1.2-1.2 1.1-2.7.2-3.7",key:"43lnbm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dae=re("MessageCircleMore",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rae=re("MessageCircleOff",[["path",{d:"M20.5 14.9A9 9 0 0 0 9.1 3.5",key:"1iebmn"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5.6 5.6C3 8.3 2.2 12.5 4 16l-2 6 6-2c3.4 1.8 7.6 1.1 10.3-1.7",key:"1ov8ce"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oae=re("MessageCirclePlus",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const f9=re("MessageCircleQuestion",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fae=re("MessageCircleReply",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}],["path",{d:"M7 12h7a2 2 0 0 1 2 2v1",key:"1gheu4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zae=re("MessageCircleWarning",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bae=re("MessageCircleX",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ql=re("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ae=re("MessageSquareCode",[["path",{d:"M10 7.5 8 10l2 2.5",key:"xb17xw"}],["path",{d:"m14 7.5 2 2.5-2 2.5",key:"5rap1v"}],["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uae=re("MessageSquareDashed",[["path",{d:"M10 17H7l-4 4v-7",key:"1r71xu"}],["path",{d:"M14 17h1",key:"nufu4t"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 14v1a2 2 0 0 1-2 2",key:"29akq3"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M9 3h1",key:"1yesri"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qae=re("MessageSquareDiff",[["path",{d:"m5 19-2 2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2",key:"1xuzuj"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 17h6",key:"r8uit2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vae=re("MessageSquareDot",[["path",{d:"M11.7 3H5a2 2 0 0 0-2 2v16l4-4h12a2 2 0 0 0 2-2v-2.7",key:"uodpkb"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mL=re("MessageSquareHeart",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M14.8 7.5a1.84 1.84 0 0 0-2.6 0l-.2.3-.3-.3a1.84 1.84 0 1 0-2.4 2.8L12 13l2.7-2.7c.9-.9.8-2.1.1-2.8",key:"1blaws"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hae=re("MessageSquareLock",[["path",{d:"M19 15v-2a2 2 0 1 0-4 0v2",key:"h3d1vz"}],["path",{d:"M9 17H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3.5",key:"xsnnhn"}],["rect",{x:"13",y:"15",width:"8",height:"5",rx:"1",key:"1ccwuk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const x9=re("MessageSquareMore",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M16 10h.01",key:"1m94wz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gae=re("MessageSquareOff",[["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M3.6 3.6c-.4.3-.6.8-.6 1.4v16l4-4h10",key:"pwpm4a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rw=re("MessageSquarePlus",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _w=re("MessageSquareQuote",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M8 12a2 2 0 0 0 2-2V8H8",key:"1jfesj"}],["path",{d:"M14 12a2 2 0 0 0 2-2V8h-2",key:"1dq9mh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wae=re("MessageSquareReply",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"m10 7-3 3 3 3",key:"1eugdv"}],["path",{d:"M17 13v-1a2 2 0 0 0-2-2H7",key:"ernfh3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kae=re("MessageSquareShare",[["path",{d:"M21 12v3a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h7",key:"tqtdkg"}],["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"m16 8 5-5",key:"15mbrl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yae=re("MessageSquareText",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M13 8H7",key:"14i4kc"}],["path",{d:"M17 12H7",key:"16if0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zae=re("MessageSquareWarning",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v2",key:"stiyo7"}],["path",{d:"M12 13h.01",key:"y0uutt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qae=re("MessageSquareX",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ci=re("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pL=re("MessagesSquare",[["path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z",key:"p1xzt8"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1",key:"1cx29u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xae=re("MicOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q5=re("MicVocal",[["path",{d:"m11 7.601-5.994 8.19a1 1 0 0 0 .1 1.298l.817.818a1 1 0 0 0 1.314.087L15.09 12",key:"80a601"}],["path",{d:"M16.5 21.174C15.5 20.5 14.372 20 13 20c-2.058 0-3.928 2.356-6 2-2.072-.356-2.775-3.369-1.5-4.5",key:"j0ngtp"}],["circle",{cx:"16",cy:"7",r:"5",key:"d08jfb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bv=re("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jae=re("Microchip",[["path",{d:"M18 12h2",key:"quuxs7"}],["path",{d:"M18 16h2",key:"zsn3lv"}],["path",{d:"M18 20h2",key:"9x5y9y"}],["path",{d:"M18 4h2",key:"1luxfb"}],["path",{d:"M18 8h2",key:"nxqzg"}],["path",{d:"M4 12h2",key:"1ltxp0"}],["path",{d:"M4 16h2",key:"8a5zha"}],["path",{d:"M4 20h2",key:"27dk57"}],["path",{d:"M4 4h2",key:"10groj"}],["path",{d:"M4 8h2",key:"18vq6w"}],["path",{d:"M8 2a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2h-1.5c-.276 0-.494.227-.562.495a2 2 0 0 1-3.876 0C9.994 2.227 9.776 2 9.5 2z",key:"1681fp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eie=re("Microscope",[["path",{d:"M6 18h8",key:"1borvv"}],["path",{d:"M3 22h18",key:"8prr45"}],["path",{d:"M14 22a7 7 0 1 0 0-14h-1",key:"1jwaiy"}],["path",{d:"M9 14h2",key:"197e7h"}],["path",{d:"M9 12a2 2 0 0 1-2-2V6h6v4a2 2 0 0 1-2 2Z",key:"1bmzmy"}],["path",{d:"M12 6V3a1 1 0 0 0-1-1H9a1 1 0 0 0-1 1v3",key:"1drr47"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tie=re("Microwave",[["rect",{width:"20",height:"15",x:"2",y:"4",rx:"2",key:"2no95f"}],["rect",{width:"8",height:"7",x:"6",y:"8",rx:"1",key:"zh9wx"}],["path",{d:"M18 8v7",key:"o5zi4n"}],["path",{d:"M6 19v2",key:"1loha6"}],["path",{d:"M18 19v2",key:"1dawf0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sie=re("Milestone",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M4 6a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h13a2 2 0 0 0 1.152-.365l3.424-2.317a1 1 0 0 0 0-1.635l-3.424-2.318A2 2 0 0 0 17 6z",key:"1btarq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nie=re("MilkOff",[["path",{d:"M8 2h8",key:"1ssgc1"}],["path",{d:"M9 2v1.343M15 2v2.789a4 4 0 0 0 .672 2.219l.656.984a4 4 0 0 1 .672 2.22v1.131M7.8 7.8l-.128.192A4 4 0 0 0 7 10.212V20a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-3",key:"y0ejgx"}],["path",{d:"M7 15a6.47 6.47 0 0 1 5 0 6.472 6.472 0 0 0 3.435.435",key:"iaxqsy"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rie=re("Milk",[["path",{d:"M8 2h8",key:"1ssgc1"}],["path",{d:"M9 2v2.789a4 4 0 0 1-.672 2.219l-.656.984A4 4 0 0 0 7 10.212V20a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-9.789a4 4 0 0 0-.672-2.219l-.656-.984A4 4 0 0 1 15 4.788V2",key:"qtp12x"}],["path",{d:"M7 15a6.472 6.472 0 0 1 5 0 6.47 6.47 0 0 0 5 0",key:"ygeh44"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aie=re("Minimize2",[["polyline",{points:"4 14 10 14 10 20",key:"11kfnr"}],["polyline",{points:"20 10 14 10 14 4",key:"rlmsce"}],["line",{x1:"14",x2:"21",y1:"10",y2:"3",key:"o5lafz"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iie=re("Minimize",[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xb=re("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oie=re("MonitorCheck",[["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lie=re("MonitorCog",[["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m15.2 4.9-.9-.4",key:"12wd2u"}],["path",{d:"m15.2 7.1-.9.4",key:"1r2vl7"}],["path",{d:"m16.9 3.2-.4-.9",key:"3zbo91"}],["path",{d:"m16.9 8.8-.4.9",key:"1qr2dn"}],["path",{d:"m19.5 2.3-.4.9",key:"1rjrkq"}],["path",{d:"m19.5 9.7-.4-.9",key:"heryx5"}],["path",{d:"m21.7 4.5-.9.4",key:"17fqt1"}],["path",{d:"m21.7 7.5-.9-.4",key:"14zyni"}],["path",{d:"M22 13v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7",key:"1tnzv8"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cie=re("MonitorDot",[["circle",{cx:"19",cy:"6",r:"3",key:"108a5v"}],["path",{d:"M22 12v3a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9",key:"1fet9y"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const die=re("MonitorDown",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"m15 10-3 3-3-3",key:"lzhmyn"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uie=re("MonitorOff",[["path",{d:"M17 17H4a2 2 0 0 1-2-2V5c0-1.5 1-2 1-2",key:"k0q8oc"}],["path",{d:"M22 15V5a2 2 0 0 0-2-2H9",key:"cp1ac0"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hie=re("MonitorPause",[["path",{d:"M10 13V7",key:"1u13u9"}],["path",{d:"M14 13V7",key:"1vj9om"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fL=re("MonitorPlay",[["path",{d:"M10 7.75a.75.75 0 0 1 1.142-.638l3.664 2.249a.75.75 0 0 1 0 1.278l-3.664 2.25a.75.75 0 0 1-1.142-.64z",key:"1pctta"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",key:"x3v2xh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mie=re("MonitorSmartphone",[["path",{d:"M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8",key:"10dyio"}],["path",{d:"M10 19v-3.96 3.15",key:"1irgej"}],["path",{d:"M7 19h5",key:"qswx4l"}],["rect",{width:"6",height:"10",x:"16",y:"12",rx:"2",key:"1egngj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pie=re("MonitorSpeaker",[["path",{d:"M5.5 20H8",key:"1k40s5"}],["path",{d:"M17 9h.01",key:"1j24nn"}],["rect",{width:"10",height:"16",x:"12",y:"4",rx:"2",key:"ixliua"}],["path",{d:"M8 6H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h4",key:"1mp6e1"}],["circle",{cx:"17",cy:"15",r:"1",key:"tqvash"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fie=re("MonitorStop",[["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",key:"x3v2xh"}],["rect",{x:"9",y:"7",width:"6",height:"6",rx:"1",key:"5m2oou"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FA=re("MonitorUp",[["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}],["path",{d:"M12 13V7",key:"h0r20n"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xie=re("MonitorX",[["path",{d:"m14.5 12.5-5-5",key:"1jahn5"}],["path",{d:"m9.5 12.5 5-5",key:"1k2t7b"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gb=re("Monitor",[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gie=re("MoonStar",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9",key:"4ay0iu"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yie=re("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vie=re("MountainSnow",[["path",{d:"m8 3 4 8 5-5 5 15H2L8 3z",key:"otkl63"}],["path",{d:"M4.14 15.08c2.62-1.57 5.24-1.43 7.86.42 2.74 1.94 5.49 2 8.23.19",key:"1pvmmp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bie=re("Mountain",[["path",{d:"m8 3 4 8 5-5 5 15H2L8 3z",key:"otkl63"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ie=re("MouseOff",[["path",{d:"M12 6v.343",key:"1gyhex"}],["path",{d:"M18.218 18.218A7 7 0 0 1 5 15V9a7 7 0 0 1 .782-3.218",key:"ukzz01"}],["path",{d:"M19 13.343V9A7 7 0 0 0 8.56 2.902",key:"104jy9"}],["path",{d:"M22 22 2 2",key:"1r8tn9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wie=re("MousePointer2",[["path",{d:"M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z",key:"edeuup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jie=re("MousePointerBan",[["path",{d:"M2.034 2.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.944L8.204 7.545a1 1 0 0 0-.66.66l-1.066 3.443a.5.5 0 0 1-.944.033z",key:"11pp1i"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}],["path",{d:"m11.8 11.8 8.4 8.4",key:"oogvdj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oc=re("MousePointerClick",[["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z",key:"s0h3yz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fm=re("MousePointer",[["path",{d:"M12.586 12.586 19 19",key:"ea5xo7"}],["path",{d:"M3.688 3.037a.497.497 0 0 0-.651.651l6.5 15.999a.501.501 0 0 0 .947-.062l1.569-6.083a2 2 0 0 1 1.448-1.479l6.124-1.579a.5.5 0 0 0 .063-.947z",key:"277e5u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nie=re("Mouse",[["rect",{x:"5",y:"2",width:"14",height:"20",rx:"7",key:"11ol66"}],["path",{d:"M12 6v4",key:"16clxf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X5=re("Move3d",[["path",{d:"M5 3v16h16",key:"1mqmf9"}],["path",{d:"m5 19 6-6",key:"jh6hbb"}],["path",{d:"m2 6 3-3 3 3",key:"tkyvxa"}],["path",{d:"m18 16 3 3-3 3",key:"1d4glt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kie=re("MoveDiagonal2",[["path",{d:"M19 13v6h-6",key:"1hxl6d"}],["path",{d:"M5 11V5h6",key:"12e2xe"}],["path",{d:"m5 5 14 14",key:"11anup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sie=re("MoveDiagonal",[["path",{d:"M11 19H5v-6",key:"8awifj"}],["path",{d:"M13 5h6v6",key:"7voy1q"}],["path",{d:"M19 5 5 19",key:"wwaj1z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cie=re("MoveDownLeft",[["path",{d:"M11 19H5V13",key:"1akmht"}],["path",{d:"M19 5L5 19",key:"72u4yj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tie=re("MoveDownRight",[["path",{d:"M19 13V19H13",key:"10vkzq"}],["path",{d:"M5 5L19 19",key:"5zm2fv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eie=re("MoveDown",[["path",{d:"M8 18L12 22L16 18",key:"cskvfv"}],["path",{d:"M12 2V22",key:"r89rzk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Aie=re("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mie=re("MoveLeft",[["path",{d:"M6 8L2 12L6 16",key:"kyvwex"}],["path",{d:"M2 12H22",key:"1m8cig"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Iie=re("MoveRight",[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pie=re("MoveUpLeft",[["path",{d:"M5 11V5H11",key:"3q78g9"}],["path",{d:"M5 5L19 19",key:"5zm2fv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lie=re("MoveUpRight",[["path",{d:"M13 5H19V11",key:"1n1gyv"}],["path",{d:"M19 5L5 19",key:"72u4yj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Die=re("MoveUp",[["path",{d:"M8 6L12 2L16 6",key:"1yvkyx"}],["path",{d:"M12 2V22",key:"r89rzk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rie=re("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oie=re("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fie=re("Music2",[["circle",{cx:"8",cy:"18",r:"4",key:"1fc0mg"}],["path",{d:"M12 18V2l7 4",key:"g04rme"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zie=re("Music3",[["circle",{cx:"12",cy:"18",r:"4",key:"m3r9ws"}],["path",{d:"M16 18V2",key:"40x2m5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bie=re("Music4",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["path",{d:"m9 9 12-2",key:"1e64n2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xL=re("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ie=re("Navigation2Off",[["path",{d:"M9.31 9.31 5 21l7-4 7 4-1.17-3.17",key:"qoq2o2"}],["path",{d:"M14.53 8.88 12 2l-1.17 3.17",key:"k3sjzy"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uie=re("Navigation2",[["polygon",{points:"12 2 19 21 12 17 5 21 12 2",key:"x8c0qg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qie=re("NavigationOff",[["path",{d:"M8.43 8.43 3 11l8 2 2 8 2.57-5.43",key:"1vdtb7"}],["path",{d:"M17.39 11.73 22 2l-9.73 4.61",key:"tya3r6"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const g9=re("Navigation",[["polygon",{points:"3 11 22 2 13 21 11 13 3 11",key:"1ltx0t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vie=re("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iy=re("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hie=re("Nfc",[["path",{d:"M6 8.32a7.43 7.43 0 0 1 0 7.36",key:"9iaqei"}],["path",{d:"M9.46 6.21a11.76 11.76 0 0 1 0 11.58",key:"1yha7l"}],["path",{d:"M12.91 4.1a15.91 15.91 0 0 1 .01 15.8",key:"4iu2gk"}],["path",{d:"M16.37 2a20.16 20.16 0 0 1 0 20",key:"sap9u2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gie=re("NotebookPen",[["path",{d:"M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4",key:"re6nr2"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"pqwjuv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wie=re("NotebookTabs",[["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M15 2v20",key:"dcj49h"}],["path",{d:"M15 7h5",key:"1xj5lc"}],["path",{d:"M15 12h5",key:"w5shd9"}],["path",{d:"M15 17h5",key:"1qaofu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kie=re("NotebookText",[["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M9.5 8h5",key:"11mslq"}],["path",{d:"M9.5 12H16",key:"ktog6x"}],["path",{d:"M9.5 16H14",key:"p1seyn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yie=re("Notebook",[["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M16 2v20",key:"rotuqe"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zie=re("NotepadTextDashed",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v2",key:"j91f56"}],["path",{d:"M20 12v2",key:"w8o0tu"}],["path",{d:"M20 18v2a2 2 0 0 1-2 2h-1",key:"1c9ggx"}],["path",{d:"M13 22h-2",key:"191ugt"}],["path",{d:"M7 22H6a2 2 0 0 1-2-2v-2",key:"1rt9px"}],["path",{d:"M4 14v-2",key:"1v0sqh"}],["path",{d:"M4 8V6a2 2 0 0 1 2-2h2",key:"1mwabg"}],["path",{d:"M8 10h6",key:"3oa6kw"}],["path",{d:"M8 14h8",key:"1fgep2"}],["path",{d:"M8 18h5",key:"17enja"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qie=re("NotepadText",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"16",height:"18",x:"4",y:"4",rx:"2",key:"1u9h20"}],["path",{d:"M8 10h6",key:"3oa6kw"}],["path",{d:"M8 14h8",key:"1fgep2"}],["path",{d:"M8 18h5",key:"17enja"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xie=re("NutOff",[["path",{d:"M12 4V2",key:"1k5q1u"}],["path",{d:"M5 10v4a7.004 7.004 0 0 0 5.277 6.787c.412.104.802.292 1.102.592L12 22l.621-.621c.3-.3.69-.488 1.102-.592a7.01 7.01 0 0 0 4.125-2.939",key:"1xcvy9"}],["path",{d:"M19 10v3.343",key:"163tfc"}],["path",{d:"M12 12c-1.349-.573-1.905-1.005-2.5-2-.546.902-1.048 1.353-2.5 2-1.018-.644-1.46-1.08-2-2-1.028.71-1.69.918-3 1 1.081-1.048 1.757-2.03 2-3 .194-.776.84-1.551 1.79-2.21m11.654 5.997c.887-.457 1.28-.891 1.556-1.787 1.032.916 1.683 1.157 3 1-1.297-1.036-1.758-2.03-2-3-.5-2-4-4-8-4-.74 0-1.461.068-2.15.192",key:"17914v"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jie=re("Nut",[["path",{d:"M12 4V2",key:"1k5q1u"}],["path",{d:"M5 10v4a7.004 7.004 0 0 0 5.277 6.787c.412.104.802.292 1.102.592L12 22l.621-.621c.3-.3.69-.488 1.102-.592A7.003 7.003 0 0 0 19 14v-4",key:"1tgyif"}],["path",{d:"M12 4C8 4 4.5 6 4 8c-.243.97-.919 1.952-2 3 1.31-.082 1.972-.29 3-1 .54.92.982 1.356 2 2 1.452-.647 1.954-1.098 2.5-2 .595.995 1.151 1.427 2.5 2 1.31-.621 1.862-1.058 2.5-2 .629.977 1.162 1.423 2.5 2 1.209-.548 1.68-.967 2-2 1.032.916 1.683 1.157 3 1-1.297-1.036-1.758-2.03-2-3-.5-2-4-4-8-4Z",key:"tnsqj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z_=re("OctagonAlert",[["path",{d:"M12 16h.01",key:"1drbdi"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M15.312 2a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586l-4.688-4.688A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2z",key:"1fd625"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eoe=re("OctagonMinus",[["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J5=re("OctagonPause",[["path",{d:"M10 15V9",key:"1lckn7"}],["path",{d:"M14 15V9",key:"1muqhk"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eT=re("OctagonX",[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const toe=re("Octagon",[["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const soe=re("Omega",[["path",{d:"M3 20h4.5a.5.5 0 0 0 .5-.5v-.282a.52.52 0 0 0-.247-.437 8 8 0 1 1 8.494-.001.52.52 0 0 0-.247.438v.282a.5.5 0 0 0 .5.5H21",key:"1x94xo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const noe=re("Option",[["path",{d:"M3 3h6l6 18h6",key:"ph9rgk"}],["path",{d:"M14 3h7",key:"16f0ms"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const roe=re("Orbit",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M10.4 21.9a10 10 0 0 0 9.941-15.416",key:"eohfx2"}],["path",{d:"M13.5 2.1a10 10 0 0 0-9.841 15.416",key:"19pvbm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aoe=re("Origami",[["path",{d:"M12 12V4a1 1 0 0 1 1-1h6.297a1 1 0 0 1 .651 1.759l-4.696 4.025",key:"1bx4vc"}],["path",{d:"m12 21-7.414-7.414A2 2 0 0 1 4 12.172V6.415a1.002 1.002 0 0 1 1.707-.707L20 20.009",key:"1h3km6"}],["path",{d:"m12.214 3.381 8.414 14.966a1 1 0 0 1-.167 1.199l-1.168 1.163a1 1 0 0 1-.706.291H6.351a1 1 0 0 1-.625-.219L3.25 18.8a1 1 0 0 1 .631-1.781l4.165.027",key:"1hj4wg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ioe=re("Package2",[["path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z",key:"1ront0"}],["path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9",key:"19h2x1"}],["path",{d:"M12 3v6",key:"1holv5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ooe=re("PackageCheck",[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const loe=re("PackageMinus",[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const coe=re("PackageOpen",[["path",{d:"M12 22v-9",key:"x3hkom"}],["path",{d:"M15.17 2.21a1.67 1.67 0 0 1 1.63 0L21 4.57a1.93 1.93 0 0 1 0 3.36L8.82 14.79a1.655 1.655 0 0 1-1.64 0L3 12.43a1.93 1.93 0 0 1 0-3.36z",key:"2ntwy6"}],["path",{d:"M20 13v3.87a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13",key:"1pmm1c"}],["path",{d:"M21 12.43a1.93 1.93 0 0 0 0-3.36L8.83 2.2a1.64 1.64 0 0 0-1.63 0L3 4.57a1.93 1.93 0 0 0 0 3.36l12.18 6.86a1.636 1.636 0 0 0 1.63 0z",key:"12ttoo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const y9=re("PackagePlus",[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const doe=re("PackageSearch",[["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}],["circle",{cx:"18.5",cy:"15.5",r:"2.5",key:"b5zd12"}],["path",{d:"M20.27 17.27 22 19",key:"1l4muz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uoe=re("PackageX",[["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}],["path",{d:"m17 13 5 5m-5 0 5-5",key:"im3w4b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oc=re("Package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7",key:"yx3hmr"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hoe=re("PaintBucket",[["path",{d:"m19 11-8-8-8.6 8.6a2 2 0 0 0 0 2.8l5.2 5.2c.8.8 2 .8 2.8 0L19 11Z",key:"irua1i"}],["path",{d:"m5 2 5 5",key:"1lls2c"}],["path",{d:"M2 13h15",key:"1hkzvu"}],["path",{d:"M22 20a2 2 0 1 1-4 0c0-1.6 1.7-2.4 2-4 .3 1.6 2 2.4 2 4Z",key:"xk76lq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const moe=re("PaintRoller",[["rect",{width:"16",height:"6",x:"2",y:"2",rx:"2",key:"jcyz7m"}],["path",{d:"M10 16v-2a2 2 0 0 1 2-2h8a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2",key:"1b9h7c"}],["rect",{width:"4",height:"6",x:"8",y:"16",rx:"1",key:"d6e7yl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tT=re("PaintbrushVertical",[["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M14 2v4",key:"qmzblu"}],["path",{d:"M17 2a1 1 0 0 1 1 1v9H6V3a1 1 0 0 1 1-1z",key:"ycvu00"}],["path",{d:"M6 12a1 1 0 0 0-1 1v1a2 2 0 0 0 2 2h2a1 1 0 0 1 1 1v2.9a2 2 0 1 0 4 0V17a1 1 0 0 1 1-1h2a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1",key:"iw4wnp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const poe=re("Paintbrush",[["path",{d:"m14.622 17.897-10.68-2.913",key:"vj2p1u"}],["path",{d:"M18.376 2.622a1 1 0 1 1 3.002 3.002L17.36 9.643a.5.5 0 0 0 0 .707l.944.944a2.41 2.41 0 0 1 0 3.408l-.944.944a.5.5 0 0 1-.707 0L8.354 7.348a.5.5 0 0 1 0-.707l.944-.944a2.41 2.41 0 0 1 3.408 0l.944.944a.5.5 0 0 0 .707 0z",key:"18tc5c"}],["path",{d:"M9 8c-1.804 2.71-3.97 3.46-6.583 3.948a.507.507 0 0 0-.302.819l7.32 8.883a1 1 0 0 0 1.185.204C12.735 20.405 16 16.792 16 15",key:"ytzfxy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xl=re("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const foe=re("PanelBottomClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"m15 8-3 3-3-3",key:"1oxy1z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sT=re("PanelBottomDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M14 15h1",key:"171nev"}],["path",{d:"M19 15h2",key:"1vnucp"}],["path",{d:"M3 15h2",key:"8bym0q"}],["path",{d:"M9 15h1",key:"1tg3ks"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xoe=re("PanelBottomOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const goe=re("PanelBottom",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nT=re("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rT=re("PanelLeftDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 14v1",key:"askpd8"}],["path",{d:"M9 19v2",key:"16tejx"}],["path",{d:"M9 3v2",key:"1noubl"}],["path",{d:"M9 9v1",key:"19ebxg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aT=re("PanelLeftOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iT=re("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yoe=re("PanelRightClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oT=re("PanelRightDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 14v1",key:"ilsfch"}],["path",{d:"M15 19v2",key:"1fst2f"}],["path",{d:"M15 3v2",key:"z204g4"}],["path",{d:"M15 9v1",key:"z2a8b1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const voe=re("PanelRightOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const boe=re("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _oe=re("PanelTopClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"m9 16 3-3 3 3",key:"1idcnm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lT=re("PanelTopDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M14 9h1",key:"l0svgy"}],["path",{d:"M19 9h2",key:"te2zfg"}],["path",{d:"M3 9h2",key:"1h4ldw"}],["path",{d:"M9 9h1",key:"15jzuz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const woe=re("PanelTopOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"m15 14-3 3-3-3",key:"g215vf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const joe=re("PanelTop",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Noe=re("PanelsLeftBottom",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M9 15h12",key:"5ijen5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const koe=re("PanelsRightBottom",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h12",key:"1wkqb3"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E2=re("PanelsTopLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const r4=re("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Soe=re("Parentheses",[["path",{d:"M8 21s-4-3-4-9 4-9 4-9",key:"uto9ud"}],["path",{d:"M16 3s4 3 4 9-4 9-4 9",key:"4w2vsq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Coe=re("ParkingMeter",[["path",{d:"M11 15h2",key:"199qp6"}],["path",{d:"M12 12v3",key:"158kv8"}],["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M15.282 19a1 1 0 0 0 .948-.68l2.37-6.988a7 7 0 1 0-13.2 0l2.37 6.988a1 1 0 0 0 .948.68z",key:"1jofit"}],["path",{d:"M9 9a3 3 0 1 1 6 0",key:"jdoeu8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uh=re("PartyPopper",[["path",{d:"M5.8 11.3 2 22l10.7-3.79",key:"gwxi1d"}],["path",{d:"M4 3h.01",key:"1vcuye"}],["path",{d:"M22 8h.01",key:"1mrtc2"}],["path",{d:"M15 2h.01",key:"1cjtqr"}],["path",{d:"M22 20h.01",key:"1mrys2"}],["path",{d:"m22 2-2.24.75a2.9 2.9 0 0 0-1.96 3.12c.1.86-.57 1.63-1.45 1.63h-.38c-.86 0-1.6.6-1.76 1.44L14 10",key:"hbicv8"}],["path",{d:"m22 13-.82-.33c-.86-.34-1.82.2-1.98 1.11c-.11.7-.72 1.22-1.43 1.22H17",key:"1i94pl"}],["path",{d:"m11 2 .33.82c.34.86-.2 1.82-1.11 1.98C9.52 4.9 9 5.52 9 6.23V7",key:"1cofks"}],["path",{d:"M11 13c1.93 1.93 2.83 4.17 2 5-.83.83-3.07-.07-5-2-1.93-1.93-2.83-4.17-2-5 .83-.83 3.07.07 5 2Z",key:"4kbmks"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _f=re("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Toe=re("PawPrint",[["circle",{cx:"11",cy:"4",r:"2",key:"vol9p0"}],["circle",{cx:"18",cy:"8",r:"2",key:"17gozi"}],["circle",{cx:"20",cy:"16",r:"2",key:"1v9bxh"}],["path",{d:"M9 10a5 5 0 0 1 5 5v3.5a3.5 3.5 0 0 1-6.84 1.045Q6.52 17.48 4.46 16.84A3.5 3.5 0 0 1 5.5 10Z",key:"1ydw1z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eoe=re("PcCase",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",key:"1uq1d7"}],["path",{d:"M15 14h.01",key:"1kp3bh"}],["path",{d:"M9 6h6",key:"dgm16u"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nb=re("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Aoe=re("PenOff",[["path",{d:"m10 10-6.157 6.162a2 2 0 0 0-.5.833l-1.322 4.36a.5.5 0 0 0 .622.624l4.358-1.323a2 2 0 0 0 .83-.5L14 13.982",key:"bjo8r8"}],["path",{d:"m12.829 7.172 4.359-4.346a1 1 0 1 1 3.986 3.986l-4.353 4.353",key:"16h5ne"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a4=re("PenTool",[["path",{d:"M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z",key:"nt11vn"}],["path",{d:"m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18",key:"15qc1e"}],["path",{d:"m2.3 2.3 7.286 7.286",key:"1wuzzi"}],["circle",{cx:"11",cy:"11",r:"2",key:"xmgehs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nv=re("Pen",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gL=re("PencilLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}],["path",{d:"m15 5 3 3",key:"1w25hb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Moe=re("PencilOff",[["path",{d:"m10 10-6.157 6.162a2 2 0 0 0-.5.833l-1.322 4.36a.5.5 0 0 0 .622.624l4.358-1.323a2 2 0 0 0 .83-.5L14 13.982",key:"bjo8r8"}],["path",{d:"m12.829 7.172 4.359-4.346a1 1 0 1 1 3.986 3.986l-4.353 4.353",key:"16h5ne"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ioe=re("PencilRuler",[["path",{d:"M13 7 8.7 2.7a2.41 2.41 0 0 0-3.4 0L2.7 5.3a2.41 2.41 0 0 0 0 3.4L7 13",key:"orapub"}],["path",{d:"m8 6 2-2",key:"115y1s"}],["path",{d:"m18 16 2-2",key:"ee94s4"}],["path",{d:"m17 11 4.3 4.3c.94.94.94 2.46 0 3.4l-2.6 2.6c-.94.94-2.46.94-3.4 0L11 17",key:"cfq27r"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ja=re("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Poe=re("Pentagon",[["path",{d:"M10.83 2.38a2 2 0 0 1 2.34 0l8 5.74a2 2 0 0 1 .73 2.25l-3.04 9.26a2 2 0 0 1-1.9 1.37H7.04a2 2 0 0 1-1.9-1.37L2.1 10.37a2 2 0 0 1 .73-2.25z",key:"2hea0t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const i4=re("Percent",[["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5",key:"4mh3h7"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5",key:"1mdrzq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Loe=re("PersonStanding",[["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["path",{d:"m9 20 3-6 3 6",key:"se2kox"}],["path",{d:"m6 8 6 2 6-2",key:"4o3us4"}],["path",{d:"M12 10v4",key:"1kjpxc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Doe=re("PhilippinePeso",[["path",{d:"M20 11H4",key:"6ut86h"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"M7 21V4a1 1 0 0 1 1-1h4a1 1 0 0 1 0 12H7",key:"1ana5r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const v9=re("PhoneCall",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}],["path",{d:"M14.05 2a9 9 0 0 1 8 7.94",key:"vmijpz"}],["path",{d:"M14.05 6A5 5 0 0 1 18 10",key:"13nbpp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Roe=re("PhoneForwarded",[["polyline",{points:"18 2 22 6 18 10",key:"6vjanh"}],["line",{x1:"14",x2:"22",y1:"6",y2:"6",key:"1jsywh"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ooe=re("PhoneIncoming",[["polyline",{points:"16 2 16 8 22 8",key:"1ygljm"}],["line",{x1:"22",x2:"16",y1:"2",y2:"8",key:"1xzwqn"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Foe=re("PhoneMissed",[["line",{x1:"22",x2:"16",y1:"2",y2:"8",key:"1xzwqn"}],["line",{x1:"16",x2:"22",y1:"2",y2:"8",key:"13zxdn"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zoe=re("PhoneOff",[["path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34a19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91",key:"z86iuo"}],["line",{x1:"22",x2:"2",y1:"2",y2:"22",key:"11kh81"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Boe=re("PhoneOutgoing",[["polyline",{points:"22 8 22 2 16 2",key:"1g204g"}],["line",{x1:"16",x2:"22",y1:"8",y2:"2",key:"1ggias"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pr=re("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $oe=re("Pi",[["line",{x1:"9",x2:"9",y1:"4",y2:"20",key:"ovs5a5"}],["path",{d:"M4 7c0-1.7 1.3-3 3-3h13",key:"10pag4"}],["path",{d:"M18 20c-1.7 0-3-1.3-3-3V4",key:"1gaosr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uoe=re("Piano",[["path",{d:"M18.5 8c-1.4 0-2.6-.8-3.2-2A6.87 6.87 0 0 0 2 9v11a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-8.5C22 9.6 20.4 8 18.5 8",key:"lag0yf"}],["path",{d:"M2 14h20",key:"myj16y"}],["path",{d:"M6 14v4",key:"9ng0ue"}],["path",{d:"M10 14v4",key:"1v8uk5"}],["path",{d:"M14 14v4",key:"1tqops"}],["path",{d:"M18 14v4",key:"18uqwm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qoe=re("Pickaxe",[["path",{d:"M14.531 12.469 6.619 20.38a1 1 0 1 1-3-3l7.912-7.912",key:"we99rg"}],["path",{d:"M15.686 4.314A12.5 12.5 0 0 0 5.461 2.958 1 1 0 0 0 5.58 4.71a22 22 0 0 1 6.318 3.393",key:"1w6hck"}],["path",{d:"M17.7 3.7a1 1 0 0 0-1.4 0l-4.6 4.6a1 1 0 0 0 0 1.4l2.6 2.6a1 1 0 0 0 1.4 0l4.6-4.6a1 1 0 0 0 0-1.4z",key:"15hgfx"}],["path",{d:"M19.686 8.314a12.501 12.501 0 0 1 1.356 10.225 1 1 0 0 1-1.751-.119 22 22 0 0 0-3.393-6.319",key:"452b4h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Voe=re("PictureInPicture2",[["path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4",key:"daa4of"}],["rect",{width:"10",height:"7",x:"12",y:"13",rx:"2",key:"1nb8gs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hoe=re("PictureInPicture",[["path",{d:"M8 4.5v5H3m-1-6 6 6m13 0v-3c0-1.16-.84-2-2-2h-7m-9 9v2c0 1.05.95 2 2 2h3",key:"bcd8fb"}],["rect",{width:"10",height:"7",x:"12",y:"13.5",ry:"2",key:"136fx3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Goe=re("PiggyBank",[["path",{d:"M19 5c-1.5 0-2.8 1.4-3 2-3.5-1.5-11-.3-11 5 0 1.8 0 3 2 4.5V20h4v-2h3v2h4v-4c1-.5 1.7-1 2-2h2v-4h-2c0-1-.5-1.5-1-2V5z",key:"1ivx2i"}],["path",{d:"M2 9v1c0 1.1.9 2 2 2h1",key:"nm575m"}],["path",{d:"M16 11h.01",key:"xkw8gn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Woe=re("PilcrowLeft",[["path",{d:"M14 3v11",key:"mlfb7b"}],["path",{d:"M14 9h-3a3 3 0 0 1 0-6h9",key:"1ulc19"}],["path",{d:"M18 3v11",key:"1phi0r"}],["path",{d:"M22 18H2l4-4",key:"yt65j9"}],["path",{d:"m6 22-4-4",key:"6jgyf5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Koe=re("PilcrowRight",[["path",{d:"M10 3v11",key:"o3l5kj"}],["path",{d:"M10 9H7a1 1 0 0 1 0-6h8",key:"1wb1nc"}],["path",{d:"M14 3v11",key:"mlfb7b"}],["path",{d:"m18 14 4 4H2",key:"4r8io1"}],["path",{d:"m22 18-4 4",key:"1hjjrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yoe=re("Pilcrow",[["path",{d:"M13 4v16",key:"8vvj80"}],["path",{d:"M17 4v16",key:"7dpous"}],["path",{d:"M19 4H9.5a4.5 4.5 0 0 0 0 9H13",key:"sh4n9v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zoe=re("PillBottle",[["path",{d:"M18 11h-4a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h4",key:"17ldeb"}],["path",{d:"M6 7v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V7",key:"nc37y6"}],["rect",{width:"16",height:"5",x:"4",y:"2",rx:"1",key:"3jeezo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qoe=re("Pill",[["path",{d:"m10.5 20.5 10-10a4.95 4.95 0 1 0-7-7l-10 10a4.95 4.95 0 1 0 7 7Z",key:"wa1lgi"}],["path",{d:"m8.5 8.5 7 7",key:"rvfmvr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const b9=re("PinOff",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const o4=re("Pin",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xoe=re("Pipette",[["path",{d:"m2 22 1-1h3l9-9",key:"1sre89"}],["path",{d:"M3 21v-3l9-9",key:"hpe2y6"}],["path",{d:"m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z",key:"196du1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Joe=re("Pizza",[["path",{d:"m12 14-1 1",key:"11onhr"}],["path",{d:"m13.75 18.25-1.25 1.42",key:"1yisr3"}],["path",{d:"M17.775 5.654a15.68 15.68 0 0 0-12.121 12.12",key:"1qtqk6"}],["path",{d:"M18.8 9.3a1 1 0 0 0 2.1 7.7",key:"fbbbr2"}],["path",{d:"M21.964 20.732a1 1 0 0 1-1.232 1.232l-18-5a1 1 0 0 1-.695-1.232A19.68 19.68 0 0 1 15.732 2.037a1 1 0 0 1 1.232.695z",key:"1hyfdd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ele=re("PlaneLanding",[["path",{d:"M2 22h20",key:"272qi7"}],["path",{d:"M3.77 10.77 2 9l2-4.5 1.1.55c.55.28.9.84.9 1.45s.35 1.17.9 1.45L8 8.5l3-6 1.05.53a2 2 0 0 1 1.09 1.52l.72 5.4a2 2 0 0 0 1.09 1.52l4.4 2.2c.42.22.78.55 1.01.96l.6 1.03c.49.88-.06 1.98-1.06 2.1l-1.18.15c-.47.06-.95-.02-1.37-.24L4.29 11.15a2 2 0 0 1-.52-.38Z",key:"1ma21e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tle=re("PlaneTakeoff",[["path",{d:"M2 22h20",key:"272qi7"}],["path",{d:"M6.36 17.4 4 17l-2-4 1.1-.55a2 2 0 0 1 1.8 0l.17.1a2 2 0 0 0 1.8 0L8 12 5 6l.9-.45a2 2 0 0 1 2.09.2l4.02 3a2 2 0 0 0 2.1.2l4.19-2.06a2.41 2.41 0 0 1 1.73-.17L21 7a1.4 1.4 0 0 1 .87 1.99l-.38.76c-.23.46-.6.84-1.07 1.08L7.58 17.2a2 2 0 0 1-1.22.18Z",key:"fkigj9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _9=re("Plane",[["path",{d:"M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z",key:"1v9wt8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Al=re("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sle=re("Plug2",[["path",{d:"M9 2v6",key:"17ngun"}],["path",{d:"M15 2v6",key:"s7yy2p"}],["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M5 8h14",key:"pcz4l3"}],["path",{d:"M6 11V8h12v3a6 6 0 1 1-12 0Z",key:"wtfw2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cT=re("PlugZap",[["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m18 3-4 4h6l-4 4",key:"16psg9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J2=re("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const As=re("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nle=re("PocketKnife",[["path",{d:"M3 2v1c0 1 2 1 2 2S3 6 3 7s2 1 2 2-2 1-2 2 2 1 2 2",key:"19w3oe"}],["path",{d:"M18 6h.01",key:"1v4wsw"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M20.83 8.83a4 4 0 0 0-5.66-5.66l-12 12a4 4 0 1 0 5.66 5.66Z",key:"6fykxj"}],["path",{d:"M18 11.66V22a4 4 0 0 0 4-4V6",key:"1utzek"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rle=re("Pocket",[["path",{d:"M4 3h16a2 2 0 0 1 2 2v6a10 10 0 0 1-10 10A10 10 0 0 1 2 11V5a2 2 0 0 1 2-2z",key:"1mz881"}],["polyline",{points:"8 10 12 14 16 10",key:"w4mbv5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ale=re("Podcast",[["path",{d:"M16.85 18.58a9 9 0 1 0-9.7 0",key:"d71mpg"}],["path",{d:"M8 14a5 5 0 1 1 8 0",key:"fc81rn"}],["circle",{cx:"12",cy:"11",r:"1",key:"1gvufo"}],["path",{d:"M13 17a1 1 0 1 0-2 0l.5 4.5a.5.5 0 1 0 1 0Z",key:"za5kbj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ile=re("PointerOff",[["path",{d:"M10 4.5V4a2 2 0 0 0-2.41-1.957",key:"jsi14n"}],["path",{d:"M13.9 8.4a2 2 0 0 0-1.26-1.295",key:"hirc7f"}],["path",{d:"M21.7 16.2A8 8 0 0 0 22 14v-3a2 2 0 1 0-4 0v-1a2 2 0 0 0-3.63-1.158",key:"1jxb2e"}],["path",{d:"m7 15-1.8-1.8a2 2 0 0 0-2.79 2.86L6 19.7a7.74 7.74 0 0 0 6 2.3h2a8 8 0 0 0 5.657-2.343",key:"10r7hm"}],["path",{d:"M6 6v8",key:"tv5xkp"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ole=re("Pointer",[["path",{d:"M22 14a8 8 0 0 1-8 8",key:"56vcr3"}],["path",{d:"M18 11v-1a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1agjmk"}],["path",{d:"M14 10V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1",key:"wdbh2u"}],["path",{d:"M10 9.5V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v10",key:"1ibuk9"}],["path",{d:"M18 11a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"g6ys72"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lle=re("Popcorn",[["path",{d:"M18 8a2 2 0 0 0 0-4 2 2 0 0 0-4 0 2 2 0 0 0-4 0 2 2 0 0 0-4 0 2 2 0 0 0 0 4",key:"10td1f"}],["path",{d:"M10 22 9 8",key:"yjptiv"}],["path",{d:"m14 22 1-14",key:"8jwc8b"}],["path",{d:"M20 8c.5 0 .9.4.8 1l-2.6 12c-.1.5-.7 1-1.2 1H7c-.6 0-1.1-.4-1.2-1L3.2 9c-.1-.6.3-1 .8-1Z",key:"1qo33t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cle=re("Popsicle",[["path",{d:"M18.6 14.4c.8-.8.8-2 0-2.8l-8.1-8.1a4.95 4.95 0 1 0-7.1 7.1l8.1 8.1c.9.7 2.1.7 2.9-.1Z",key:"1o68ps"}],["path",{d:"m22 22-5.5-5.5",key:"17o70y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dle=re("PoundSterling",[["path",{d:"M18 7c0-5.333-8-5.333-8 0",key:"1prm2n"}],["path",{d:"M10 7v14",key:"18tmcs"}],["path",{d:"M6 21h12",key:"4dkmi1"}],["path",{d:"M6 13h10",key:"ybwr4a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ule=re("PowerOff",[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w9=re("Power",[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oy=re("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hle=re("PrinterCheck",[["path",{d:"M13.5 22H7a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v.5",key:"qeb09x"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}],["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v2",key:"1md90i"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const j9=re("Printer",[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mle=re("Projector",[["path",{d:"M5 7 3 5",key:"1yys58"}],["path",{d:"M9 6V3",key:"1ptz9u"}],["path",{d:"m13 7 2-2",key:"1w3vmq"}],["circle",{cx:"9",cy:"13",r:"3",key:"1mma13"}],["path",{d:"M11.83 12H20a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h2.17",key:"2frwzc"}],["path",{d:"M16 16h2",key:"dnq2od"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ple=re("Proportions",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M12 9v11",key:"1fnkrn"}],["path",{d:"M2 9h13a2 2 0 0 1 2 2v9",key:"11z3ex"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fle=re("Puzzle",[["path",{d:"M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z",key:"w46dr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xle=re("Pyramid",[["path",{d:"M2.5 16.88a1 1 0 0 1-.32-1.43l9-13.02a1 1 0 0 1 1.64 0l9 13.01a1 1 0 0 1-.32 1.44l-8.51 4.86a2 2 0 0 1-1.98 0Z",key:"aenxs0"}],["path",{d:"M12 2v20",key:"t6zp3m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ly=re("QrCode",[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yb=re("Quote",[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gle=re("Rabbit",[["path",{d:"M13 16a3 3 0 0 1 2.24 5",key:"1epib5"}],["path",{d:"M18 12h.01",key:"yjnet6"}],["path",{d:"M18 21h-8a4 4 0 0 1-4-4 7 7 0 0 1 7-7h.2L9.6 6.4a1 1 0 1 1 2.8-2.8L15.8 7h.2c3.3 0 6 2.7 6 6v1a2 2 0 0 1-2 2h-1a3 3 0 0 0-3 3",key:"ue9ozu"}],["path",{d:"M20 8.54V4a2 2 0 1 0-4 0v3",key:"49iql8"}],["path",{d:"M7.612 12.524a3 3 0 1 0-1.6 4.3",key:"1e33i0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zA=re("Radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yle=re("Radiation",[["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M7.5 4.2c-.3-.5-.9-.7-1.3-.4C3.9 5.5 2.3 8.1 2 11c-.1.5.4 1 1 1h5c0-1.5.8-2.8 2-3.4-1.1-1.9-2-3.5-2.5-4.4z",key:"wy49g3"}],["path",{d:"M21 12c.6 0 1-.4 1-1-.3-2.9-1.8-5.5-4.1-7.1-.4-.3-1.1-.2-1.3.3-.6.9-1.5 2.5-2.6 4.3 1.2.7 2 2 2 3.5h5z",key:"vklnvr"}],["path",{d:"M7.5 19.8c-.3.5-.1 1.1.4 1.3 2.6 1.2 5.6 1.2 8.2 0 .5-.2.7-.8.4-1.3-.5-.9-1.4-2.5-2.5-4.3-1.2.7-2.8.7-4 0-1.1 1.8-2 3.4-2.5 4.3z",key:"wkdf1o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vle=re("Radical",[["path",{d:"M3 12h3.28a1 1 0 0 1 .948.684l2.298 7.934a.5.5 0 0 0 .96-.044L13.82 4.771A1 1 0 0 1 14.792 4H21",key:"1mqj8i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ble=re("RadioReceiver",[["path",{d:"M5 16v2",key:"g5qcv5"}],["path",{d:"M19 16v2",key:"1gbaio"}],["rect",{width:"20",height:"8",x:"2",y:"8",rx:"2",key:"vjsjur"}],["path",{d:"M18 12h.01",key:"yjnet6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _le=re("RadioTower",[["path",{d:"M4.9 16.1C1 12.2 1 5.8 4.9 1.9",key:"s0qx1y"}],["path",{d:"M7.8 4.7a6.14 6.14 0 0 0-.8 7.5",key:"1idnkw"}],["circle",{cx:"12",cy:"9",r:"2",key:"1092wv"}],["path",{d:"M16.2 4.8c2 2 2.26 5.11.8 7.47",key:"ojru2q"}],["path",{d:"M19.1 1.9a9.96 9.96 0 0 1 0 14.1",key:"rhi7fg"}],["path",{d:"M9.5 18h5",key:"mfy3pd"}],["path",{d:"m8 22 4-11 4 11",key:"25yftu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wf=re("Radio",[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wle=re("Radius",[["path",{d:"M20.34 17.52a10 10 0 1 0-2.82 2.82",key:"fydyku"}],["circle",{cx:"19",cy:"19",r:"2",key:"17f5cg"}],["path",{d:"m13.41 13.41 4.18 4.18",key:"1gqbwc"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jle=re("RailSymbol",[["path",{d:"M5 15h14",key:"m0yey3"}],["path",{d:"M5 9h14",key:"7tsvo6"}],["path",{d:"m14 20-5-5 6-6-5-5",key:"1jo42i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nle=re("Rainbow",[["path",{d:"M22 17a10 10 0 0 0-20 0",key:"ozegv"}],["path",{d:"M6 17a6 6 0 0 1 12 0",key:"5giftw"}],["path",{d:"M10 17a2 2 0 0 1 4 0",key:"gnsikk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kle=re("Rat",[["path",{d:"M17 5c0-1.7-1.3-3-3-3s-3 1.3-3 3c0 .8.3 1.5.8 2H11c-3.9 0-7 3.1-7 7c0 2.2 1.8 4 4 4",key:"1wq71c"}],["path",{d:"M16.8 3.9c.3-.3.6-.5 1-.7 1.5-.6 3.3.1 3.9 1.6.6 1.5-.1 3.3-1.6 3.9l1.6 2.8c.2.3.2.7.2 1-.2.8-.9 1.2-1.7 1.1 0 0-1.6-.3-2.7-.6H17c-1.7 0-3 1.3-3 3",key:"1crdmb"}],["path",{d:"M13.2 18a3 3 0 0 0-2.2-5",key:"1ol3lk"}],["path",{d:"M13 22H4a2 2 0 0 1 0-4h12",key:"bt3f23"}],["path",{d:"M16 9h.01",key:"1bdo4e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sle=re("Ratio",[["rect",{width:"12",height:"20",x:"6",y:"2",rx:"2",key:"1oxtiu"}],["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cle=re("ReceiptCent",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M12 6.5v11",key:"ecfhkf"}],["path",{d:"M15 9.4a4 4 0 1 0 0 5.2",key:"1makmb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tle=re("ReceiptEuro",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 12h5",key:"1g6qi8"}],["path",{d:"M16 9.5a4 4 0 1 0 0 5.2",key:"b2px4r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ele=re("ReceiptIndianRupee",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 7h8",key:"i86dvs"}],["path",{d:"M12 17.5 8 15h1a4 4 0 0 0 0-8",key:"grpkl4"}],["path",{d:"M8 11h8",key:"vwpz6n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ale=re("ReceiptJapaneseYen",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"m12 10 3-3",key:"1mc12w"}],["path",{d:"m9 7 3 3v7.5",key:"39i0xv"}],["path",{d:"M9 11h6",key:"1fldmi"}],["path",{d:"M9 15h6",key:"cctwl0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mle=re("ReceiptPoundSterling",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 13h5",key:"1k9z8w"}],["path",{d:"M10 17V9.5a2.5 2.5 0 0 1 5 0",key:"1dzgp0"}],["path",{d:"M8 17h7",key:"8mjdqu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ile=re("ReceiptRussianRuble",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 15h5",key:"vxg57a"}],["path",{d:"M8 11h5a2 2 0 1 0 0-4h-3v10",key:"1usi5u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ple=re("ReceiptSwissFranc",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M10 17V7h5",key:"k7jq18"}],["path",{d:"M10 11h4",key:"1i0mka"}],["path",{d:"M8 15h5",key:"vxg57a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lle=re("ReceiptText",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M14 8H8",key:"1l3xfs"}],["path",{d:"M16 12H8",key:"1fr5h0"}],["path",{d:"M13 16H8",key:"wsln4y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dle=re("Receipt",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 17.5v-11",key:"1jc1ny"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dT=re("RectangleEllipsis",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M17 12h.01",key:"1m0b6t"}],["path",{d:"M7 12h.01",key:"eqddd0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rle=re("RectangleHorizontal",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ole=re("RectangleVertical",[["rect",{width:"12",height:"20",x:"6",y:"2",rx:"2",key:"1oxtiu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fle=re("Recycle",[["path",{d:"M7 19H4.815a1.83 1.83 0 0 1-1.57-.881 1.785 1.785 0 0 1-.004-1.784L7.196 9.5",key:"x6z5xu"}],["path",{d:"M11 19h8.203a1.83 1.83 0 0 0 1.556-.89 1.784 1.784 0 0 0 0-1.775l-1.226-2.12",key:"1x4zh5"}],["path",{d:"m14 16-3 3 3 3",key:"f6jyew"}],["path",{d:"M8.293 13.596 7.196 9.5 3.1 10.598",key:"wf1obh"}],["path",{d:"m9.344 5.811 1.093-1.892A1.83 1.83 0 0 1 11.985 3a1.784 1.784 0 0 1 1.546.888l3.943 6.843",key:"9tzpgr"}],["path",{d:"m13.378 9.633 4.096 1.098 1.097-4.096",key:"1oe83g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zle=re("Redo2",[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ble=re("RedoDot",[["circle",{cx:"12",cy:"17",r:"1",key:"1ixnty"}],["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const l4=re("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $le=re("RefreshCcwDot",[["path",{d:"M3 2v6h6",key:"18ldww"}],["path",{d:"M21 12A9 9 0 0 0 6 5.3L3 8",key:"1pbrqz"}],["path",{d:"M21 22v-6h-6",key:"usdfbe"}],["path",{d:"M3 12a9 9 0 0 0 15 6.7l3-2.7",key:"1hosoe"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yL=re("RefreshCcw",[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ule=re("RefreshCwOff",[["path",{d:"M21 8L18.74 5.74A9.75 9.75 0 0 0 12 3C11 3 10.03 3.16 9.13 3.47",key:"1krf6h"}],["path",{d:"M8 16H3v5",key:"1cv678"}],["path",{d:"M3 12C3 9.51 4 7.26 5.64 5.64",key:"ruvoct"}],["path",{d:"m3 16 2.26 2.26A9.75 9.75 0 0 0 12 21c2.49 0 4.74-1 6.36-2.64",key:"19q130"}],["path",{d:"M21 12c0 1-.16 1.97-.47 2.87",key:"4w8emr"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M22 22 2 2",key:"1r8tn9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ai=re("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qle=re("Refrigerator",[["path",{d:"M5 6a4 4 0 0 1 4-4h6a4 4 0 0 1 4 4v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6Z",key:"fpq118"}],["path",{d:"M5 10h14",key:"elsbfy"}],["path",{d:"M15 7v6",key:"1nx30x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vle=re("Regex",[["path",{d:"M17 3v10",key:"15fgeh"}],["path",{d:"m12.67 5.5 8.66 5",key:"1gpheq"}],["path",{d:"m12.67 10.5 8.66-5",key:"1dkfa6"}],["path",{d:"M9 17a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2z",key:"swwfx4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hle=re("RemoveFormatting",[["path",{d:"M4 7V4h16v3",key:"9msm58"}],["path",{d:"M5 20h6",key:"1h6pxn"}],["path",{d:"M13 4 8 20",key:"kqq6aj"}],["path",{d:"m15 15 5 5",key:"me55sn"}],["path",{d:"m20 15-5 5",key:"11p7ol"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gle=re("Repeat1",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}],["path",{d:"M11 10h1v4",key:"70cz1p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wle=re("Repeat2",[["path",{d:"m2 9 3-3 3 3",key:"1ltn5i"}],["path",{d:"M13 18H7a2 2 0 0 1-2-2V6",key:"1r6tfw"}],["path",{d:"m22 15-3 3-3-3",key:"4rnwn2"}],["path",{d:"M11 6h6a2 2 0 0 1 2 2v10",key:"2f72bc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vL=re("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kle=re("ReplaceAll",[["path",{d:"M14 14a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"1yyzbs"}],["path",{d:"M14 4a2 2 0 0 1 2-2",key:"1w2hp7"}],["path",{d:"M16 10a2 2 0 0 1-2-2",key:"shjach"}],["path",{d:"M20 14a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"zfj4xr"}],["path",{d:"M20 2a2 2 0 0 1 2 2",key:"188mtx"}],["path",{d:"M22 8a2 2 0 0 1-2 2",key:"ddf4tu"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a 3 3 0 0 1 3-3h1",key:"1ageje"}],["rect",{x:"2",y:"14",width:"8",height:"8",rx:"2",key:"4rksxw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yle=re("Replace",[["path",{d:"M14 4a2 2 0 0 1 2-2",key:"1w2hp7"}],["path",{d:"M16 10a2 2 0 0 1-2-2",key:"shjach"}],["path",{d:"M20 2a2 2 0 0 1 2 2",key:"188mtx"}],["path",{d:"M22 8a2 2 0 0 1-2 2",key:"ddf4tu"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a3 3 0 0 1 3-3h1",key:"3y3t5z"}],["rect",{x:"2",y:"14",width:"8",height:"8",rx:"2",key:"4rksxw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zle=re("ReplyAll",[["polyline",{points:"7 17 2 12 7 7",key:"t83bqg"}],["polyline",{points:"12 17 7 12 12 7",key:"1g4ajm"}],["path",{d:"M22 18v-2a4 4 0 0 0-4-4H7",key:"1fcyog"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const N9=re("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qle=re("Rewind",[["polygon",{points:"11 19 2 12 11 5 11 19",key:"14yba5"}],["polygon",{points:"22 19 13 12 22 5 22 19",key:"1pi1cj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xle=re("Ribbon",[["path",{d:"M12 11.22C11 9.997 10 9 10 8a2 2 0 0 1 4 0c0 1-.998 2.002-2.01 3.22",key:"1rnhq3"}],["path",{d:"m12 18 2.57-3.5",key:"116vt7"}],["path",{d:"M6.243 9.016a7 7 0 0 1 11.507-.009",key:"10dq0b"}],["path",{d:"M9.35 14.53 12 11.22",key:"tdsyp2"}],["path",{d:"M9.35 14.53C7.728 12.246 6 10.221 6 7a6 5 0 0 1 12 0c-.005 3.22-1.778 5.235-3.43 7.5l3.557 4.527a1 1 0 0 1-.203 1.43l-1.894 1.36a1 1 0 0 1-1.384-.215L12 18l-2.679 3.593a1 1 0 0 1-1.39.213l-1.865-1.353a1 1 0 0 1-.203-1.422z",key:"nmifey"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nx=re("Rocket",[["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z",key:"m3kijz"}],["path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z",key:"1fmvmk"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0",key:"1f8sc4"}],["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jle=re("RockingChair",[["polyline",{points:"3.5 2 6.5 12.5 18 12.5",key:"y3iy52"}],["line",{x1:"9.5",x2:"5.5",y1:"12.5",y2:"20",key:"19vg5i"}],["line",{x1:"15",x2:"18.5",y1:"12.5",y2:"20",key:"1inpmv"}],["path",{d:"M2.75 18a13 13 0 0 0 18.5 0",key:"1nquas"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ece=re("RollerCoaster",[["path",{d:"M6 19V5",key:"1r845m"}],["path",{d:"M10 19V6.8",key:"9j2tfs"}],["path",{d:"M14 19v-7.8",key:"10s8qv"}],["path",{d:"M18 5v4",key:"1tajlv"}],["path",{d:"M18 19v-6",key:"ielfq3"}],["path",{d:"M22 19V9",key:"158nzp"}],["path",{d:"M2 19V9a4 4 0 0 1 4-4c2 0 4 1.33 6 4s4 4 6 4a4 4 0 1 0-3-6.65",key:"1930oh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uT=re("Rotate3d",[["path",{d:"M16.466 7.5C15.643 4.237 13.952 2 12 2 9.239 2 7 6.477 7 12s2.239 10 5 10c.342 0 .677-.069 1-.2",key:"10n0gc"}],["path",{d:"m15.194 13.707 3.814 1.86-1.86 3.814",key:"16shm9"}],["path",{d:"M19 15.57c-1.804.885-4.274 1.43-7 1.43-5.523 0-10-2.239-10-5s4.477-5 10-5c4.838 0 8.873 1.718 9.8 4",key:"1lxi77"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tce=re("RotateCcwSquare",[["path",{d:"M20 9V7a2 2 0 0 0-2-2h-6",key:"19z8uc"}],["path",{d:"m15 2-3 3 3 3",key:"177bxs"}],["path",{d:"M20 13v5a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2",key:"d36hnl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fh=re("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sce=re("RotateCwSquare",[["path",{d:"M12 5H6a2 2 0 0 0-2 2v3",key:"l96uqu"}],["path",{d:"m9 8 3-3-3-3",key:"1gzgc3"}],["path",{d:"M4 14v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2",key:"1w2k5h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BA=re("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nce=re("RouteOff",[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5c.4 0 .9-.1 1.3-.2",key:"1effex"}],["path",{d:"M5.2 5.2A3.5 3.53 0 0 0 6.5 12H12",key:"k9y2ds"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M21 15.3a3.5 3.5 0 0 0-3.3-3.3",key:"11nlu2"}],["path",{d:"M15 5h-4.3",key:"6537je"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k9=re("Route",[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15",key:"1d8sl"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rce=re("Router",[["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6.01 18H6",key:"19vcac"}],["path",{d:"M10.01 18H10",key:"uamcmx"}],["path",{d:"M15 10v4",key:"qjz1xs"}],["path",{d:"M17.84 7.17a4 4 0 0 0-5.66 0",key:"1rif40"}],["path",{d:"M20.66 4.34a8 8 0 0 0-11.31 0",key:"6a5xfq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hT=re("Rows2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mT=re("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ace=re("Rows4",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 7.5H3",key:"1hm9pq"}],["path",{d:"M21 12H3",key:"2avoz0"}],["path",{d:"M21 16.5H3",key:"n7jzkj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ice=re("Rss",[["path",{d:"M4 11a9 9 0 0 1 9 9",key:"pv89mb"}],["path",{d:"M4 4a16 16 0 0 1 16 16",key:"k0647b"}],["circle",{cx:"5",cy:"19",r:"1",key:"bfqh0e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eN=re("Ruler",[["path",{d:"M21.3 15.3a2.4 2.4 0 0 1 0 3.4l-2.6 2.6a2.4 2.4 0 0 1-3.4 0L2.7 8.7a2.41 2.41 0 0 1 0-3.4l2.6-2.6a2.41 2.41 0 0 1 3.4 0Z",key:"icamh8"}],["path",{d:"m14.5 12.5 2-2",key:"inckbg"}],["path",{d:"m11.5 9.5 2-2",key:"fmmyf7"}],["path",{d:"m8.5 6.5 2-2",key:"vc6u1g"}],["path",{d:"m17.5 15.5 2-2",key:"wo5hmg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oce=re("RussianRuble",[["path",{d:"M6 11h8a4 4 0 0 0 0-8H9v18",key:"18ai8t"}],["path",{d:"M6 15h8",key:"1y8f6l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lce=re("Sailboat",[["path",{d:"M22 18H2a4 4 0 0 0 4 4h12a4 4 0 0 0 4-4Z",key:"1404fh"}],["path",{d:"M21 14 10 2 3 14h18Z",key:"1nzg7v"}],["path",{d:"M10 2v16",key:"1labyt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cce=re("Salad",[["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 21a9 9 0 0 0 9-9H3a9 9 0 0 0 9 9Z",key:"4rw317"}],["path",{d:"M11.38 12a2.4 2.4 0 0 1-.4-4.77 2.4 2.4 0 0 1 3.2-2.77 2.4 2.4 0 0 1 3.47-.63 2.4 2.4 0 0 1 3.37 3.37 2.4 2.4 0 0 1-1.1 3.7 2.51 2.51 0 0 1 .03 1.1",key:"10xrj0"}],["path",{d:"m13 12 4-4",key:"1hckqy"}],["path",{d:"M10.9 7.25A3.99 3.99 0 0 0 4 10c0 .73.2 1.41.54 2",key:"1p4srx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dce=re("Sandwich",[["path",{d:"m2.37 11.223 8.372-6.777a2 2 0 0 1 2.516 0l8.371 6.777",key:"f1wd0e"}],["path",{d:"M21 15a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-5.25",key:"1pfu07"}],["path",{d:"M3 15a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h9",key:"1oq9qw"}],["path",{d:"m6.67 15 6.13 4.6a2 2 0 0 0 2.8-.4l3.15-4.2",key:"1fnwu5"}],["rect",{width:"20",height:"4",x:"2",y:"11",rx:"1",key:"itshg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uce=re("SatelliteDish",[["path",{d:"M4 10a7.31 7.31 0 0 0 10 10Z",key:"1fzpp3"}],["path",{d:"m9 15 3-3",key:"88sc13"}],["path",{d:"M17 13a6 6 0 0 0-6-6",key:"15cc6u"}],["path",{d:"M21 13A10 10 0 0 0 11 3",key:"11nf8s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hce=re("Satellite",[["path",{d:"M13 7 9 3 5 7l4 4",key:"vyckw6"}],["path",{d:"m17 11 4 4-4 4-4-4",key:"rchckc"}],["path",{d:"m8 12 4 4 6-6-4-4Z",key:"1sshf7"}],["path",{d:"m16 8 3-3",key:"x428zp"}],["path",{d:"M9 21a6 6 0 0 0-6-6",key:"1iajcf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mce=re("SaveAll",[["path",{d:"M10 2v3a1 1 0 0 0 1 1h5",key:"1xspal"}],["path",{d:"M18 18v-6a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6",key:"1ra60u"}],["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"M8 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9.172a2 2 0 0 1 1.414.586l2.828 2.828A2 2 0 0 1 22 6.828V16a2 2 0 0 1-2.01 2z",key:"1yve0x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pce=re("SaveOff",[["path",{d:"M13 13H8a1 1 0 0 0-1 1v7",key:"h8g396"}],["path",{d:"M14 8h1",key:"1lfen6"}],["path",{d:"M17 21v-4",key:"1yknxs"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20.41 20.41A2 2 0 0 1 19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 .59-1.41",key:"1t4vdl"}],["path",{d:"M29.5 11.5s5 5 4 5",key:"zzn4i6"}],["path",{d:"M9 3h6.2a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V15",key:"24cby9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ho=re("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pT=re("Scale3d",[["path",{d:"M5 7v11a1 1 0 0 0 1 1h11",key:"13dt1j"}],["path",{d:"M5.293 18.707 11 13",key:"ezgbsx"}],["circle",{cx:"19",cy:"19",r:"2",key:"17f5cg"}],["circle",{cx:"5",cy:"5",r:"2",key:"1gwv83"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S9=re("Scale",[["path",{d:"m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"7g6ntu"}],["path",{d:"m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"ijws7r"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2",key:"3gwbw2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fce=re("Scaling",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M14 15H9v-5",key:"pi4jk9"}],["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M21 3 9 15",key:"15kdhq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xce=re("ScanBarcode",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M8 7v10",key:"23sfjj"}],["path",{d:"M12 7v10",key:"jspqdw"}],["path",{d:"M17 7v10",key:"578dap"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gce=re("ScanEye",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yce=re("ScanFace",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 9h.01",key:"x1ddxp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vce=re("ScanLine",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 12h10",key:"b7w52i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bce=re("ScanQrCode",[["path",{d:"M17 12v4a1 1 0 0 1-1 1h-4",key:"uk4fdo"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M17 8V7",key:"q2g9wo"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M7 17h.01",key:"19xn7k"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{x:"7",y:"7",width:"5",height:"5",rx:"1",key:"m9kyts"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ce=re("ScanSearch",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wce=re("ScanText",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 8h8",key:"1jbsf9"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M7 16h6",key:"1vyc9m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jce=re("Scan",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nce=re("School",[["path",{d:"M14 22v-4a2 2 0 1 0-4 0v4",key:"hhkicm"}],["path",{d:"m18 10 3.447 1.724a1 1 0 0 1 .553.894V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-7.382a1 1 0 0 1 .553-.894L6 10",key:"1xqip1"}],["path",{d:"M18 5v17",key:"1sw6gf"}],["path",{d:"m4 6 7.106-3.553a2 2 0 0 1 1.788 0L20 6",key:"9d2mlk"}],["path",{d:"M6 5v17",key:"1xfsm0"}],["circle",{cx:"12",cy:"9",r:"2",key:"1092wv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kce=re("ScissorsLineDashed",[["path",{d:"M5.42 9.42 8 12",key:"12pkuq"}],["circle",{cx:"4",cy:"8",r:"2",key:"107mxr"}],["path",{d:"m14 6-8.58 8.58",key:"gvzu5l"}],["circle",{cx:"4",cy:"16",r:"2",key:"1ehqvc"}],["path",{d:"M10.8 14.8 14 18",key:"ax7m9r"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sce=re("Scissors",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M8.12 8.12 12 12",key:"1alkpv"}],["path",{d:"M20 4 8.12 15.88",key:"xgtan2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M14.8 14.8 20 20",key:"ptml3r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cce=re("ScreenShareOff",[["path",{d:"M13 3H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-3",key:"i8wdob"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m22 3-5 5",key:"12jva0"}],["path",{d:"m17 3 5 5",key:"k36vhe"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tce=re("ScreenShare",[["path",{d:"M13 3H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-3",key:"i8wdob"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m17 8 5-5",key:"fqif7o"}],["path",{d:"M17 3h5v5",key:"1o3tu8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C9=re("ScrollText",[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ece=re("Scroll",[["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ace=re("SearchCheck",[["path",{d:"m8 11 2 2 4-4",key:"1sed1v"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mce=re("SearchCode",[["path",{d:"m13 13.5 2-2.5-2-2.5",key:"1rvxrh"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}],["path",{d:"M9 8.5 7 11l2 2.5",key:"6ffwbx"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ice=re("SearchSlash",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T9=re("SearchX",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["path",{d:"m8.5 8.5 5 5",key:"a8mexj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _r=re("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pce=re("Section",[["path",{d:"M16 5a4 3 0 0 0-8 0c0 4 8 3 8 7a4 3 0 0 1-8 0",key:"vqan6v"}],["path",{d:"M8 19a4 3 0 0 0 8 0c0-4-8-3-8-7a4 3 0 0 1 8 0",key:"wdjd8o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fT=re("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lce=re("SendToBack",[["rect",{x:"14",y:"14",width:"8",height:"8",rx:"2",key:"1b0bso"}],["rect",{x:"2",y:"2",width:"8",height:"8",rx:"2",key:"1x09vl"}],["path",{d:"M7 14v1a2 2 0 0 0 2 2h1",key:"pao6x6"}],["path",{d:"M14 7h1a2 2 0 0 1 2 2v1",key:"19tdru"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cr=re("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dce=re("SeparatorHorizontal",[["line",{x1:"3",x2:"21",y1:"12",y2:"12",key:"10d38w"}],["polyline",{points:"8 8 12 4 16 8",key:"zo8t4w"}],["polyline",{points:"16 16 12 20 8 16",key:"1oyrid"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rce=re("SeparatorVertical",[["line",{x1:"12",x2:"12",y1:"3",y2:"21",key:"1efggb"}],["polyline",{points:"8 8 4 12 8 16",key:"bnfmv4"}],["polyline",{points:"16 16 20 12 16 8",key:"u90052"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oce=re("ServerCog",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5",key:"tn8das"}],["path",{d:"M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5",key:"1g2pve"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m15.7 13.4-.9-.3",key:"1jwmzr"}],["path",{d:"m9.2 10.9-.9-.3",key:"qapnim"}],["path",{d:"m10.6 15.7.3-.9",key:"quwk0k"}],["path",{d:"m13.6 15.7-.4-1",key:"cb9xp7"}],["path",{d:"m10.8 9.3-.4-1",key:"1uaiz5"}],["path",{d:"m8.3 13.6 1-.4",key:"s6srou"}],["path",{d:"m14.7 10.8 1-.4",key:"4d31cq"}],["path",{d:"m13.4 8.3-.3.9",key:"1bm987"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fce=re("ServerCrash",[["path",{d:"M6 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-2",key:"4b9dqc"}],["path",{d:"M6 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-2",key:"22nnkd"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m13 6-4 6h6l-4 6",key:"14hqih"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zce=re("ServerOff",[["path",{d:"M7 2h13a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-5",key:"bt2siv"}],["path",{d:"M10 10 2.5 2.5C2 2 2 2.5 2 5v3a2 2 0 0 0 2 2h6z",key:"1hjrv1"}],["path",{d:"M22 17v-1a2 2 0 0 0-2-2h-1",key:"1iynyr"}],["path",{d:"M4 14a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16.5l1-.5.5.5-8-8H4z",key:"161ggg"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bce=re("Server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E9=re("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vo=re("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ce=re("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hl=re("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A9=re("Share",[["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["polyline",{points:"16 6 12 2 8 6",key:"m901s6"}],["line",{x1:"12",x2:"12",y1:"2",y2:"15",key:"1p0rca"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uce=re("Sheet",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["line",{x1:"3",x2:"21",y1:"9",y2:"9",key:"1vqk6q"}],["line",{x1:"3",x2:"21",y1:"15",y2:"15",key:"o2sbyz"}],["line",{x1:"9",x2:"9",y1:"9",y2:"21",key:"1ib60c"}],["line",{x1:"15",x2:"15",y1:"9",y2:"21",key:"1n26ft"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qce=re("Shell",[["path",{d:"M14 11a2 2 0 1 1-4 0 4 4 0 0 1 8 0 6 6 0 0 1-12 0 8 8 0 0 1 16 0 10 10 0 1 1-20 0 11.93 11.93 0 0 1 2.42-7.22 2 2 0 1 1 3.16 2.44",key:"1cn552"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bL=re("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vce=re("ShieldBan",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m4.243 5.21 14.39 12.472",key:"1c9a7c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ng=re("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hce=re("ShieldEllipsis",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gce=re("ShieldHalf",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 22V2",key:"zs6s6o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wce=re("ShieldMinus",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9 12h6",key:"1c52cq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $A=re("ShieldOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kce=re("ShieldPlus",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9 12h6",key:"1c52cq"}],["path",{d:"M12 9v6",key:"199k2o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yce=re("ShieldQuestion",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xT=re("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hh=re("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zce=re("ShipWheel",[["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}],["path",{d:"M12 2v7.5",key:"1e5rl5"}],["path",{d:"m19 5-5.23 5.23",key:"1ezxxf"}],["path",{d:"M22 12h-7.5",key:"le1719"}],["path",{d:"m19 19-5.23-5.23",key:"p3fmgn"}],["path",{d:"M12 14.5V22",key:"dgcmos"}],["path",{d:"M10.23 13.77 5 19",key:"qwopd4"}],["path",{d:"M9.5 12H2",key:"r7bup8"}],["path",{d:"M10.23 10.23 5 5",key:"k2y7lj"}],["circle",{cx:"12",cy:"12",r:"2.5",key:"ix0uyj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qce=re("Ship",[["path",{d:"M12 10.189V14",key:"1p8cqu"}],["path",{d:"M12 2v3",key:"qbqxhf"}],["path",{d:"M19 13V7a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v6",key:"qpkstq"}],["path",{d:"M19.38 20A11.6 11.6 0 0 0 21 14l-8.188-3.639a2 2 0 0 0-1.624 0L3 14a11.6 11.6 0 0 0 2.81 7.76",key:"7tigtc"}],["path",{d:"M2 21c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1s1.2 1 2.5 1c2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"1924j5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xce=re("Shirt",[["path",{d:"M20.38 3.46 16 2a4 4 0 0 1-8 0L3.62 3.46a2 2 0 0 0-1.34 2.23l.58 3.47a1 1 0 0 0 .99.84H6v10c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V10h2.15a1 1 0 0 0 .99-.84l.58-3.47a2 2 0 0 0-1.34-2.23z",key:"1wgbhj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ww=re("ShoppingBag",[["path",{d:"M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z",key:"hou9p0"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jce=re("ShoppingBasket",[["path",{d:"m15 11-1 9",key:"5wnq3a"}],["path",{d:"m19 11-4-7",key:"cnml18"}],["path",{d:"M2 11h20",key:"3eubbj"}],["path",{d:"m3.5 11 1.6 7.4a2 2 0 0 0 2 1.6h9.8a2 2 0 0 0 2-1.6l1.7-7.4",key:"yiazzp"}],["path",{d:"M4.5 15.5h15",key:"13mye1"}],["path",{d:"m5 11 4-7",key:"116ra9"}],["path",{d:"m9 11 1 9",key:"1ojof7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zg=re("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ede=re("Shovel",[["path",{d:"M2 22v-5l5-5 5 5-5 5z",key:"1fh25c"}],["path",{d:"M9.5 14.5 16 8",key:"1smz5x"}],["path",{d:"m17 2 5 5-.5.5a3.53 3.53 0 0 1-5 0s0 0 0 0a3.53 3.53 0 0 1 0-5L17 2",key:"1q8uv5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tde=re("ShowerHead",[["path",{d:"m4 4 2.5 2.5",key:"uv2vmf"}],["path",{d:"M13.5 6.5a4.95 4.95 0 0 0-7 7",key:"frdkwv"}],["path",{d:"M15 5 5 15",key:"1ag8rq"}],["path",{d:"M14 17v.01",key:"eokfpp"}],["path",{d:"M10 16v.01",key:"14uyyl"}],["path",{d:"M13 13v.01",key:"1v1k97"}],["path",{d:"M16 10v.01",key:"5169yg"}],["path",{d:"M11 20v.01",key:"cj92p8"}],["path",{d:"M17 14v.01",key:"11cswd"}],["path",{d:"M20 11v.01",key:"19e0od"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sde=re("Shrink",[["path",{d:"m15 15 6 6m-6-6v4.8m0-4.8h4.8",key:"17vawe"}],["path",{d:"M9 19.8V15m0 0H4.2M9 15l-6 6",key:"chjx8e"}],["path",{d:"M15 4.2V9m0 0h4.8M15 9l6-6",key:"lav6yq"}],["path",{d:"M9 4.2V9m0 0H4.2M9 9 3 3",key:"1pxi2q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nde=re("Shrub",[["path",{d:"M12 22v-7l-2-2",key:"eqv9mc"}],["path",{d:"M17 8v.8A6 6 0 0 1 13.8 20H10A6.5 6.5 0 0 1 7 8a5 5 0 0 1 10 0Z",key:"ubcgy"}],["path",{d:"m14 14-2 2",key:"847xa2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UA=re("Shuffle",[["path",{d:"m18 14 4 4-4 4",key:"10pe0f"}],["path",{d:"m18 2 4 4-4 4",key:"pucp1d"}],["path",{d:"M2 18h1.973a4 4 0 0 0 3.3-1.7l5.454-8.6a4 4 0 0 1 3.3-1.7H22",key:"1ailkh"}],["path",{d:"M2 6h1.972a4 4 0 0 1 3.6 2.2",key:"km57vx"}],["path",{d:"M22 18h-6.041a4 4 0 0 1-3.3-1.8l-.359-.45",key:"os18l9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rde=re("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ade=re("SignalHigh",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}],["path",{d:"M12 20v-8",key:"i3yub9"}],["path",{d:"M17 20V8",key:"1tkaf5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ide=re("SignalLow",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ode=re("SignalMedium",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}],["path",{d:"M12 20v-8",key:"i3yub9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lde=re("SignalZero",[["path",{d:"M2 20h.01",key:"4haj6o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cde=re("Signal",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}],["path",{d:"M12 20v-8",key:"i3yub9"}],["path",{d:"M17 20V8",key:"1tkaf5"}],["path",{d:"M22 4v16",key:"sih9yq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dde=re("Signature",[["path",{d:"m21 17-2.156-1.868A.5.5 0 0 0 18 15.5v.5a1 1 0 0 1-1 1h-2a1 1 0 0 1-1-1c0-2.545-3.991-3.97-8.5-4a1 1 0 0 0 0 5c4.153 0 4.745-11.295 5.708-13.5a2.5 2.5 0 1 1 3.31 3.284",key:"y32ogt"}],["path",{d:"M3 21h18",key:"itz85i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ude=re("SignpostBig",[["path",{d:"M10 9H4L2 7l2-2h6",key:"1hq7x2"}],["path",{d:"M14 5h6l2 2-2 2h-6",key:"bv62ej"}],["path",{d:"M10 22V4a2 2 0 1 1 4 0v18",key:"eqpcf2"}],["path",{d:"M8 22h8",key:"rmew8v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hde=re("Signpost",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M18 6a2 2 0 0 1 1.387.56l2.307 2.22a1 1 0 0 1 0 1.44l-2.307 2.22A2 2 0 0 1 18 13H6a2 2 0 0 1-1.387-.56l-2.306-2.22a1 1 0 0 1 0-1.44l2.306-2.22A2 2 0 0 1 6 6z",key:"gqqp9m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mde=re("Siren",[["path",{d:"M7 18v-6a5 5 0 1 1 10 0v6",key:"pcx96s"}],["path",{d:"M5 21a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2z",key:"1b4s83"}],["path",{d:"M21 12h1",key:"jtio3y"}],["path",{d:"M18.5 4.5 18 5",key:"g5sp9y"}],["path",{d:"M2 12h1",key:"1uaihz"}],["path",{d:"M12 2v1",key:"11qlp1"}],["path",{d:"m4.929 4.929.707.707",key:"1i51kw"}],["path",{d:"M12 12v6",key:"3ahymv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pde=re("SkipBack",[["polygon",{points:"19 20 9 12 19 4 19 20",key:"o2sva"}],["line",{x1:"5",x2:"5",y1:"19",y2:"5",key:"1ocqjk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fde=re("SkipForward",[["polygon",{points:"5 4 15 12 5 20 5 4",key:"16p6eg"}],["line",{x1:"19",x2:"19",y1:"5",y2:"19",key:"futhcm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xde=re("Skull",[["path",{d:"m12.5 17-.5-1-.5 1h1z",key:"3me087"}],["path",{d:"M15 22a1 1 0 0 0 1-1v-1a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20v1a1 1 0 0 0 1 1z",key:"1o5pge"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gde=re("Slack",[["rect",{width:"3",height:"8",x:"13",y:"2",rx:"1.5",key:"diqz80"}],["path",{d:"M19 8.5V10h1.5A1.5 1.5 0 1 0 19 8.5",key:"183iwg"}],["rect",{width:"3",height:"8",x:"8",y:"14",rx:"1.5",key:"hqg7r1"}],["path",{d:"M5 15.5V14H3.5A1.5 1.5 0 1 0 5 15.5",key:"76g71w"}],["rect",{width:"8",height:"3",x:"14",y:"13",rx:"1.5",key:"1kmz0a"}],["path",{d:"M15.5 19H14v1.5a1.5 1.5 0 1 0 1.5-1.5",key:"jc4sz0"}],["rect",{width:"8",height:"3",x:"2",y:"8",rx:"1.5",key:"1omvl4"}],["path",{d:"M8.5 5H10V3.5A1.5 1.5 0 1 0 8.5 5",key:"16f3cl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yde=re("Slash",[["path",{d:"M22 2 2 22",key:"y4kqgn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vde=re("Slice",[["path",{d:"M11 16.586V19a1 1 0 0 1-1 1H2L18.37 3.63a1 1 0 1 1 3 3l-9.663 9.663a1 1 0 0 1-1.414 0L8 14",key:"1sllp5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const c4=re("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gT=re("SlidersVertical",[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bde=re("SmartphoneCharging",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12.667 8 10 12h4l-2.667 4",key:"h9lk2d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _de=re("SmartphoneNfc",[["rect",{width:"7",height:"12",x:"2",y:"6",rx:"1",key:"5nje8w"}],["path",{d:"M13 8.32a7.43 7.43 0 0 1 0 7.36",key:"1g306n"}],["path",{d:"M16.46 6.21a11.76 11.76 0 0 1 0 11.58",key:"uqvjvo"}],["path",{d:"M19.91 4.1a15.91 15.91 0 0 1 .01 15.8",key:"ujntz3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rg=re("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wde=re("SmilePlus",[["path",{d:"M22 11v1a10 10 0 1 1-9-10",key:"ew0xw9"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}],["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jde=re("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nde=re("Snail",[["path",{d:"M2 13a6 6 0 1 0 12 0 4 4 0 1 0-8 0 2 2 0 0 0 4 0",key:"hneq2s"}],["circle",{cx:"10",cy:"13",r:"8",key:"194lz3"}],["path",{d:"M2 21h12c4.4 0 8-3.6 8-8V7a2 2 0 1 0-4 0v6",key:"ixqyt7"}],["path",{d:"M18 3 19.1 5.2",key:"9tjm43"}],["path",{d:"M22 3 20.9 5.2",key:"j3odrs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mv=re("Snowflake",[["line",{x1:"2",x2:"22",y1:"12",y2:"12",key:"1dnqot"}],["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"m20 16-4-4 4-4",key:"rquw4f"}],["path",{d:"m4 8 4 4-4 4",key:"12s3z9"}],["path",{d:"m16 4-4 4-4-4",key:"1tumq1"}],["path",{d:"m8 20 4-4 4 4",key:"9p200w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kde=re("Sofa",[["path",{d:"M20 9V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v3",key:"1dgpiv"}],["path",{d:"M2 16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",key:"xacw8m"}],["path",{d:"M4 18v2",key:"jwo5n2"}],["path",{d:"M20 18v2",key:"1ar1qi"}],["path",{d:"M12 4v9",key:"oqhhn3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sde=re("Soup",[["path",{d:"M12 21a9 9 0 0 0 9-9H3a9 9 0 0 0 9 9Z",key:"4rw317"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M19.5 12 22 6",key:"shfsr5"}],["path",{d:"M16.25 3c.27.1.8.53.75 1.36-.06.83-.93 1.2-1 2.02-.05.78.34 1.24.73 1.62",key:"rpc6vp"}],["path",{d:"M11.25 3c.27.1.8.53.74 1.36-.05.83-.93 1.2-.98 2.02-.06.78.33 1.24.72 1.62",key:"1lf63m"}],["path",{d:"M6.25 3c.27.1.8.53.75 1.36-.06.83-.93 1.2-1 2.02-.05.78.34 1.24.74 1.62",key:"97tijn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cde=re("Space",[["path",{d:"M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1",key:"lt2kga"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tde=re("Spade",[["path",{d:"M5 9c-1.5 1.5-3 3.2-3 5.5A5.5 5.5 0 0 0 7.5 20c1.8 0 3-.5 4.5-2 1.5 1.5 2.7 2 4.5 2a5.5 5.5 0 0 0 5.5-5.5c0-2.3-1.5-4-3-5.5l-7-7-7 7Z",key:"40bo9n"}],["path",{d:"M12 18v4",key:"jadmvz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tN=re("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const un=re("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ede=re("Speaker",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["circle",{cx:"12",cy:"14",r:"4",key:"1jruaj"}],["path",{d:"M12 14h.01",key:"1etili"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ade=re("Speech",[["path",{d:"M8.8 20v-4.1l1.9.2a2.3 2.3 0 0 0 2.164-2.1V8.3A5.37 5.37 0 0 0 2 8.25c0 2.8.656 3.054 1 4.55a5.77 5.77 0 0 1 .029 2.758L2 20",key:"11atix"}],["path",{d:"M19.8 17.8a7.5 7.5 0 0 0 .003-10.603",key:"yol142"}],["path",{d:"M17 15a3.5 3.5 0 0 0-.025-4.975",key:"ssbmkc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mde=re("SpellCheck2",[["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M4 21c1.1 0 1.1-1 2.3-1s1.1 1 2.3 1c1.1 0 1.1-1 2.3-1 1.1 0 1.1 1 2.3 1 1.1 0 1.1-1 2.3-1 1.1 0 1.1 1 2.3 1 1.1 0 1.1-1 2.3-1",key:"8mdmtu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ide=re("SpellCheck",[["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m16 20 2 2 4-4",key:"13tcca"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pde=re("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lde=re("Split",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M8 3H3v5",key:"15dfkv"}],["path",{d:"M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3",key:"1qrqzj"}],["path",{d:"m15 9 6-6",key:"ko1vev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dde=re("SprayCan",[["path",{d:"M3 3h.01",key:"159qn6"}],["path",{d:"M7 5h.01",key:"1hq22a"}],["path",{d:"M11 7h.01",key:"1osv80"}],["path",{d:"M3 7h.01",key:"1xzrh3"}],["path",{d:"M7 9h.01",key:"19b3jx"}],["path",{d:"M3 11h.01",key:"1eifu7"}],["rect",{width:"4",height:"4",x:"15",y:"5",key:"mri9e4"}],["path",{d:"m19 9 2 2v10c0 .6-.4 1-1 1h-6c-.6 0-1-.4-1-1V11l2-2",key:"aib6hk"}],["path",{d:"m13 14 8-2",key:"1d7bmk"}],["path",{d:"m13 19 8-2",key:"1y2vml"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qA=re("Sprout",[["path",{d:"M7 20h10",key:"e6iznv"}],["path",{d:"M10 20c5.5-2.5.8-6.4 3-10",key:"161w41"}],["path",{d:"M9.5 9.4c1.1.8 1.8 2.2 2.3 3.7-2 .4-3.5.4-4.8-.3-1.2-.6-2.3-1.9-3-4.2 2.8-.5 4.4 0 5.5.8z",key:"9gtqwd"}],["path",{d:"M14.1 6a7 7 0 0 0-1.1 4c1.9-.1 3.3-.6 4.3-1.4 1-1 1.6-2.3 1.7-4.6-2.7.1-4 1-4.9 2z",key:"bkxnd2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yT=re("SquareActivity",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M17 12h-2l-2 5-2-10-2 5H7",key:"15hlnc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vT=re("SquareArrowDownLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m16 8-8 8",key:"166keh"}],["path",{d:"M16 16H8V8",key:"1w2ppm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bT=re("SquareArrowDownRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m8 8 8 8",key:"1imecy"}],["path",{d:"M16 8v8H8",key:"1lbpgo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _T=re("SquareArrowDown",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8 12 4 4 4-4",key:"k98ssh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wT=re("SquareArrowLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m12 8-4 4 4 4",key:"15vm53"}],["path",{d:"M16 12H8",key:"1fr5h0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jT=re("SquareArrowOutDownLeft",[["path",{d:"M13 21h6a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v6",key:"14qz4y"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NT=re("SquareArrowOutDownRight",[["path",{d:"M21 11V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6",key:"14rsvq"}],["path",{d:"m21 21-9-9",key:"1et2py"}],["path",{d:"M21 15v6h-6",key:"1jko0i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kT=re("SquareArrowOutUpLeft",[["path",{d:"M13 3h6a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-6",key:"14mv1t"}],["path",{d:"m3 3 9 9",key:"rks13r"}],["path",{d:"M3 9V3h6",key:"ira0h2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ST=re("SquareArrowOutUpRight",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CT=re("SquareArrowRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TT=re("SquareArrowUpLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 16V8h8",key:"19xb1h"}],["path",{d:"M16 16 8 8",key:"1qdy8n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ET=re("SquareArrowUpRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 8h8v8",key:"b65dnt"}],["path",{d:"m8 16 8-8",key:"13b9ih"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AT=re("SquareArrowUp",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MT=re("SquareAsterisk",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8.5 14 7-4",key:"12hpby"}],["path",{d:"m8.5 10 7 4",key:"wwy2dy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IT=re("SquareBottomDashedScissors",[["path",{d:"M4 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2",key:"1vzg26"}],["path",{d:"M10 22H8",key:"euku7a"}],["path",{d:"M16 22h-2",key:"18d249"}],["circle",{cx:"8",cy:"8",r:"2",key:"14cg06"}],["path",{d:"M9.414 9.414 12 12",key:"qz4lzr"}],["path",{d:"M14.8 14.8 18 18",key:"11flf1"}],["circle",{cx:"8",cy:"16",r:"2",key:"1acxsx"}],["path",{d:"m18 6-8.586 8.586",key:"11kzk1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D_=re("SquareChartGantt",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 8h7",key:"kbo1nt"}],["path",{d:"M8 12h6",key:"ikassy"}],["path",{d:"M11 16h5",key:"oq65wt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A2=re("SquareCheckBig",[["path",{d:"M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.5",key:"1uzm8b"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PT=re("SquareCheck",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LT=re("SquareChevronDown",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m16 10-4 4-4-4",key:"894hmk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DT=re("SquareChevronLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m14 16-4-4 4-4",key:"ojs7w8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RT=re("SquareChevronRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m10 8 4 4-4 4",key:"1wy4r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OT=re("SquareChevronUp",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m8 14 4-4 4 4",key:"fy2ptz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FT=re("SquareCode",[["path",{d:"M10 9.5 8 12l2 2.5",key:"3mjy60"}],["path",{d:"m14 9.5 2 2.5-2 2.5",key:"1bir2l"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rde=re("SquareDashedBottomCode",[["path",{d:"M10 9.5 8 12l2 2.5",key:"3mjy60"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"m14 9.5 2 2.5-2 2.5",key:"1bir2l"}],["path",{d:"M5 21a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2",key:"as5y1o"}],["path",{d:"M9 21h1",key:"15o7lz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ode=re("SquareDashedBottom",[["path",{d:"M5 21a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2",key:"as5y1o"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 21h1",key:"v9vybs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zT=re("SquareDashedKanban",[["path",{d:"M8 7v7",key:"1x2jlm"}],["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M16 7v9",key:"1hp2iy"}],["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M21 14v1",key:"169vum"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M3 9v1",key:"1r0deq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BT=re("SquareDashedMousePointer",[["path",{d:"M12.034 12.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.943l-3.444 1.068a1 1 0 0 0-.66.66l-1.067 3.443a.5.5 0 0 1-.943.033z",key:"xwnzip"}],["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h2",key:"1qve2z"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v2",key:"p14lih"}],["path",{d:"M3 14v1",key:"vnatye"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $T=re("SquareDashed",[["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M21 14v1",key:"169vum"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UT=re("SquareDivide",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}],["line",{x1:"12",x2:"12",y1:"16",y2:"16",key:"aqc6ln"}],["line",{x1:"12",x2:"12",y1:"8",y2:"8",key:"1mkcni"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qT=re("SquareDot",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VT=re("SquareEqual",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 10h10",key:"1101jm"}],["path",{d:"M7 14h10",key:"1mhdw3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HT=re("SquareFunction",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3",key:"m1af9g"}],["path",{d:"M9 11.2h5.7",key:"3zgcl2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GT=re("SquareKanban",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 7v7",key:"1x2jlm"}],["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M16 7v9",key:"1hp2iy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WT=re("SquareLibrary",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 7v10",key:"d5nglc"}],["path",{d:"M11 7v10",key:"pptsnr"}],["path",{d:"m15 7 2 10",key:"1m7qm5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KT=re("SquareM",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 16V8l4 4 4-4v8",key:"141u4e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YT=re("SquareMenu",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 8h10",key:"1jw688"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M7 16h10",key:"wp8him"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZT=re("SquareMinus",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QT=re("SquareMousePointer",[["path",{d:"M12.034 12.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.943l-3.444 1.068a1 1 0 0 0-.66.66l-1.067 3.443a.5.5 0 0 1-.943.033z",key:"xwnzip"}],["path",{d:"M21 11V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6",key:"14rsvq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XT=re("SquareParkingOff",[["path",{d:"M3.6 3.6A2 2 0 0 1 5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-.59 1.41",key:"9l1ft6"}],["path",{d:"M3 8.7V19a2 2 0 0 0 2 2h10.3",key:"17knke"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M13 13a3 3 0 1 0 0-6H9v2",key:"uoagbd"}],["path",{d:"M9 17v-2.3",key:"1jxgo2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JT=re("SquareParking",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 17V7h4a3 3 0 0 1 0 6H9",key:"1dfk2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tu=re("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eE=re("SquarePercent",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tE=re("SquarePi",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 7h10",key:"udp07y"}],["path",{d:"M10 7v10",key:"i1d9ee"}],["path",{d:"M16 17a2 2 0 0 1-2-2V7",key:"ftwdc7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sE=re("SquarePilcrow",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 12H9.5a2.5 2.5 0 0 1 0-5H17",key:"1l9586"}],["path",{d:"M12 7v10",key:"jspqdw"}],["path",{d:"M16 7v10",key:"lavkr4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nE=re("SquarePlay",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m9 8 6 4-6 4Z",key:"f1r3lt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rE=re("SquarePlus",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aE=re("SquarePower",[["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M7.998 9.003a5 5 0 1 0 8-.005",key:"1pek45"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fde=re("SquareRadical",[["path",{d:"M7 12h2l2 5 2-10h4",key:"1fxv6h"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iE=re("SquareScissors",[["rect",{width:"20",height:"20",x:"2",y:"2",rx:"2",key:"1btzen"}],["circle",{cx:"8",cy:"8",r:"2",key:"14cg06"}],["path",{d:"M9.414 9.414 12 12",key:"qz4lzr"}],["path",{d:"M14.8 14.8 18 18",key:"11flf1"}],["circle",{cx:"8",cy:"16",r:"2",key:"1acxsx"}],["path",{d:"m18 6-8.586 8.586",key:"11kzk1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oE=re("SquareSigma",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M16 8.9V7H8l4 5-4 5h8v-1.9",key:"9nih0i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lE=re("SquareSlash",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cE=re("SquareSplitHorizontal",[["path",{d:"M8 19H5c-1 0-2-1-2-2V7c0-1 1-2 2-2h3",key:"lubmu8"}],["path",{d:"M16 5h3c1 0 2 1 2 2v10c0 1-1 2-2 2h-3",key:"1ag34g"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dE=re("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zde=re("SquareSquare",[["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bde=re("SquareStack",[["path",{d:"M4 10c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h4c1.1 0 2 .9 2 2",key:"4i38lg"}],["path",{d:"M10 16c-1.1 0-2-.9-2-2v-4c0-1.1.9-2 2-2h4c1.1 0 2 .9 2 2",key:"mlte4a"}],["rect",{width:"8",height:"8",x:"14",y:"14",rx:"2",key:"1fa9i4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uE=re("SquareTerminal",[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hE=re("SquareUserRound",[["path",{d:"M18 21a6 6 0 0 0-12 0",key:"kaz2du"}],["circle",{cx:"12",cy:"11",r:"4",key:"1gt34v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mE=re("SquareUser",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 21v-2a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2",key:"1m6ac2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pE=re("SquareX",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cy=re("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $de=re("Squircle",[["path",{d:"M12 3c7.2 0 9 1.8 9 9s-1.8 9-9 9-9-1.8-9-9 1.8-9 9-9",key:"garfkc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ude=re("Squirrel",[["path",{d:"M15.236 22a3 3 0 0 0-2.2-5",key:"21bitc"}],["path",{d:"M16 20a3 3 0 0 1 3-3h1a2 2 0 0 0 2-2v-2a4 4 0 0 0-4-4V4",key:"oh0fg0"}],["path",{d:"M18 13h.01",key:"9veqaj"}],["path",{d:"M18 6a4 4 0 0 0-4 4 7 7 0 0 0-7 7c0-5 4-5 4-10.5a4.5 4.5 0 1 0-9 0 2.5 2.5 0 0 0 5 0C7 10 3 11 3 17c0 2.8 2.2 5 5 5h10",key:"980v8a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qde=re("Stamp",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M19.27 13.73A2.5 2.5 0 0 0 17.5 13h-11A2.5 2.5 0 0 0 4 15.5V17a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-1.5c0-.66-.26-1.3-.73-1.77Z",key:"1sy9ra"}],["path",{d:"M14 13V8.5C14 7 15 7 15 5a3 3 0 0 0-3-3c-1.66 0-3 1-3 3s1 2 1 3.5V13",key:"cnxgux"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vde=re("StarHalf",[["path",{d:"M12 18.338a2.1 2.1 0 0 0-.987.244L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.12 2.12 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.12 2.12 0 0 0 1.597-1.16l2.309-4.679A.53.53 0 0 1 12 2",key:"2ksp49"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hde=re("StarOff",[["path",{d:"M8.34 8.34 2 9.27l5 4.87L5.82 21 12 17.77 18.18 21l-.59-3.43",key:"16m0ql"}],["path",{d:"M18.42 12.76 22 9.27l-6.91-1L12 2l-1.44 2.91",key:"1vt8nq"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ua=re("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gde=re("StepBack",[["line",{x1:"18",x2:"18",y1:"20",y2:"4",key:"cun8e5"}],["polygon",{points:"14,20 4,12 14,4",key:"ypakod"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wde=re("StepForward",[["line",{x1:"6",x2:"6",y1:"4",y2:"20",key:"fy8qot"}],["polygon",{points:"10,4 20,12 10,20",key:"1mc1pf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kde=re("Stethoscope",[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yde=re("Sticker",[["path",{d:"M15.5 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V8.5L15.5 3Z",key:"1wis1t"}],["path",{d:"M14 3v4a2 2 0 0 0 2 2h4",key:"36rjfy"}],["path",{d:"M8 13h.01",key:"1sbv64"}],["path",{d:"M16 13h.01",key:"wip0gl"}],["path",{d:"M10 16s.8 1 2 1c1.3 0 2-1 2-1",key:"1vvgv3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M9=re("StickyNote",[["path",{d:"M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8Z",key:"qazsjp"}],["path",{d:"M15 3v4a2 2 0 0 0 2 2h4",key:"40519r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I9=re("Store",[["path",{d:"m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7",key:"ztvudi"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["path",{d:"M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4",key:"2ebpfo"}],["path",{d:"M2 7h20",key:"1fcdvo"}],["path",{d:"M22 7v3a2 2 0 0 1-2 2a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 16 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 12 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 8 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 4 12a2 2 0 0 1-2-2V7",key:"6c3vgh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zde=re("StretchHorizontal",[["rect",{width:"20",height:"6",x:"2",y:"4",rx:"2",key:"qdearl"}],["rect",{width:"20",height:"6",x:"2",y:"14",rx:"2",key:"1xrn6j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qde=re("StretchVertical",[["rect",{width:"6",height:"20",x:"4",y:"2",rx:"2",key:"19qu7m"}],["rect",{width:"6",height:"20",x:"14",y:"2",rx:"2",key:"24v0nk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const P9=re("Strikethrough",[["path",{d:"M16 4H9a3 3 0 0 0-2.83 4",key:"43sutm"}],["path",{d:"M14 12a4 4 0 0 1 0 8H6",key:"nlfj13"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xde=re("Subscript",[["path",{d:"m4 5 8 8",key:"1eunvl"}],["path",{d:"m12 5-8 8",key:"1ah0jp"}],["path",{d:"M20 19h-4c0-1.5.44-2 1.5-2.5S20 15.33 20 14c0-.47-.17-.93-.48-1.29a2.11 2.11 0 0 0-2.62-.44c-.42.24-.74.62-.9 1.07",key:"e8ta8j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jde=re("SunDim",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M20 12h.01",key:"1ykeid"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M4 12h.01",key:"158zrr"}],["path",{d:"M17.657 6.343h.01",key:"31pqzk"}],["path",{d:"M17.657 17.657h.01",key:"jehnf4"}],["path",{d:"M6.343 17.657h.01",key:"gdk6ow"}],["path",{d:"M6.343 6.343h.01",key:"1uurf0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eue=re("SunMedium",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 3v1",key:"1asbbs"}],["path",{d:"M12 20v1",key:"1wcdkc"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M20 12h1",key:"1vloll"}],["path",{d:"m18.364 5.636-.707.707",key:"1hakh0"}],["path",{d:"m6.343 17.657-.707.707",key:"18m9nf"}],["path",{d:"m5.636 5.636.707.707",key:"1xv1c5"}],["path",{d:"m17.657 17.657.707.707",key:"vl76zb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tue=re("SunMoon",[["path",{d:"M12 8a2.83 2.83 0 0 0 4 4 4 4 0 1 1-4-4",key:"1fu5g2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.9 4.9 1.4 1.4",key:"b9915j"}],["path",{d:"m17.7 17.7 1.4 1.4",key:"qc3ed3"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.3 17.7-1.4 1.4",key:"5gca6"}],["path",{d:"m19.1 4.9-1.4 1.4",key:"wpu9u6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sue=re("SunSnow",[["path",{d:"M10 9a3 3 0 1 0 0 6",key:"6zmtdl"}],["path",{d:"M2 12h1",key:"1uaihz"}],["path",{d:"M14 21V3",key:"1llu3z"}],["path",{d:"M10 4V3",key:"pkzwkn"}],["path",{d:"M10 21v-1",key:"1u8rkd"}],["path",{d:"m3.64 18.36.7-.7",key:"105rm9"}],["path",{d:"m4.34 6.34-.7-.7",key:"d3unjp"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"m17 4-3 3",key:"15jcng"}],["path",{d:"m14 17 3 3",key:"6tlq38"}],["path",{d:"m21 15-3-3 3-3",key:"1nlnje"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vb=re("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nue=re("Sunrise",[["path",{d:"M12 2v8",key:"1q4o3n"}],["path",{d:"m4.93 10.93 1.41 1.41",key:"2a7f42"}],["path",{d:"M2 18h2",key:"j10viu"}],["path",{d:"M20 18h2",key:"wocana"}],["path",{d:"m19.07 10.93-1.41 1.41",key:"15zs5n"}],["path",{d:"M22 22H2",key:"19qnx5"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}],["path",{d:"M16 18a4 4 0 0 0-8 0",key:"1lzouq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rue=re("Sunset",[["path",{d:"M12 10V2",key:"16sf7g"}],["path",{d:"m4.93 10.93 1.41 1.41",key:"2a7f42"}],["path",{d:"M2 18h2",key:"j10viu"}],["path",{d:"M20 18h2",key:"wocana"}],["path",{d:"m19.07 10.93-1.41 1.41",key:"15zs5n"}],["path",{d:"M22 22H2",key:"19qnx5"}],["path",{d:"m16 6-4 4-4-4",key:"6wukr"}],["path",{d:"M16 18a4 4 0 0 0-8 0",key:"1lzouq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aue=re("Superscript",[["path",{d:"m4 19 8-8",key:"hr47gm"}],["path",{d:"m12 19-8-8",key:"1dhhmo"}],["path",{d:"M20 12h-4c0-1.5.442-2 1.5-2.5S20 8.334 20 7.002c0-.472-.17-.93-.484-1.29a2.105 2.105 0 0 0-2.617-.436c-.42.239-.738.614-.899 1.06",key:"1dfcux"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iue=re("SwatchBook",[["path",{d:"M11 17a4 4 0 0 1-8 0V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2Z",key:"1ldrpk"}],["path",{d:"M16.7 13H19a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H7",key:"11i5po"}],["path",{d:"M 7 17h.01",key:"1euzgo"}],["path",{d:"m11 8 2.3-2.3a2.4 2.4 0 0 1 3.404.004L18.6 7.6a2.4 2.4 0 0 1 .026 3.434L9.9 19.8",key:"o2gii7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oue=re("SwissFranc",[["path",{d:"M10 21V3h8",key:"br2l0g"}],["path",{d:"M6 16h9",key:"2py0wn"}],["path",{d:"M10 9.5h7",key:"13dmhz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lue=re("SwitchCamera",[["path",{d:"M11 19H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5",key:"mtk2lu"}],["path",{d:"M13 5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-5",key:"120jsl"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m18 22-3-3 3-3",key:"kgdoj7"}],["path",{d:"m6 2 3 3-3 3",key:"1fnbkv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cue=re("Sword",[["polyline",{points:"14.5 17.5 3 6 3 3 6 3 17.5 14.5",key:"1hfsw2"}],["line",{x1:"13",x2:"19",y1:"19",y2:"13",key:"1vrmhu"}],["line",{x1:"16",x2:"20",y1:"16",y2:"20",key:"1bron3"}],["line",{x1:"19",x2:"21",y1:"21",y2:"19",key:"13pww6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const due=re("Swords",[["polyline",{points:"14.5 17.5 3 6 3 3 6 3 17.5 14.5",key:"1hfsw2"}],["line",{x1:"13",x2:"19",y1:"19",y2:"13",key:"1vrmhu"}],["line",{x1:"16",x2:"20",y1:"16",y2:"20",key:"1bron3"}],["line",{x1:"19",x2:"21",y1:"21",y2:"19",key:"13pww6"}],["polyline",{points:"14.5 6.5 18 3 21 3 21 6 17.5 9.5",key:"hbey2j"}],["line",{x1:"5",x2:"9",y1:"14",y2:"18",key:"1hf58s"}],["line",{x1:"7",x2:"4",y1:"17",y2:"20",key:"pidxm4"}],["line",{x1:"3",x2:"5",y1:"19",y2:"21",key:"1pehsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uue=re("Syringe",[["path",{d:"m18 2 4 4",key:"22kx64"}],["path",{d:"m17 7 3-3",key:"1w1zoj"}],["path",{d:"M19 9 8.7 19.3c-1 1-2.5 1-3.4 0l-.6-.6c-1-1-1-2.5 0-3.4L15 5",key:"1exhtz"}],["path",{d:"m9 11 4 4",key:"rovt3i"}],["path",{d:"m5 19-3 3",key:"59f2uf"}],["path",{d:"m14 4 6 6",key:"yqp9t2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _L=re("Table2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hue=re("TableCellsMerge",[["path",{d:"M12 21v-6",key:"lihzve"}],["path",{d:"M12 9V3",key:"da5inc"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M3 9h18",key:"1pudct"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mue=re("TableCellsSplit",[["path",{d:"M12 15V9",key:"8c7uyn"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M3 9h18",key:"1pudct"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pue=re("TableColumnsSplit",[["path",{d:"M14 14v2",key:"w2a1xv"}],["path",{d:"M14 20v2",key:"1lq872"}],["path",{d:"M14 2v2",key:"6buw04"}],["path",{d:"M14 8v2",key:"i67w9a"}],["path",{d:"M2 15h8",key:"82wtch"}],["path",{d:"M2 3h6a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H2",key:"up0l64"}],["path",{d:"M2 9h8",key:"yelfik"}],["path",{d:"M22 15h-4",key:"1es58f"}],["path",{d:"M22 3h-2a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h2",key:"pdjoqf"}],["path",{d:"M22 9h-4",key:"1luja7"}],["path",{d:"M5 3v18",key:"14hmio"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fue=re("TableOfContents",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M21 12h.01",key:"msek7k"}],["path",{d:"M21 18h.01",key:"1e8rq1"}],["path",{d:"M21 6h.01",key:"1koanj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xue=re("TableProperties",[["path",{d:"M15 3v18",key:"14nvp0"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gue=re("TableRowsSplit",[["path",{d:"M14 10h2",key:"1lstlu"}],["path",{d:"M15 22v-8",key:"1fwwgm"}],["path",{d:"M15 2v4",key:"1044rn"}],["path",{d:"M2 10h2",key:"1r8dkt"}],["path",{d:"M20 10h2",key:"1ug425"}],["path",{d:"M3 19h18",key:"awlh7x"}],["path",{d:"M3 22v-6a2 2 135 0 1 2-2h14a2 2 45 0 1 2 2v6",key:"ibqhof"}],["path",{d:"M3 2v2a2 2 45 0 0 2 2h14a2 2 135 0 0 2-2V2",key:"1uenja"}],["path",{d:"M8 10h2",key:"66od0"}],["path",{d:"M9 22v-8",key:"fmnu31"}],["path",{d:"M9 2v4",key:"j1yeou"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wL=re("Table",[["path",{d:"M12 3v18",key:"108xh3"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yue=re("TabletSmartphone",[["rect",{width:"10",height:"14",x:"3",y:"8",rx:"2",key:"1vrsiq"}],["path",{d:"M5 4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2h-2.4",key:"1j4zmg"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jL=re("Tablet",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["line",{x1:"12",x2:"12.01",y1:"18",y2:"18",key:"1dp563"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vue=re("Tablets",[["circle",{cx:"7",cy:"7",r:"5",key:"x29byf"}],["circle",{cx:"17",cy:"17",r:"5",key:"1op1d2"}],["path",{d:"M12 17h10",key:"ls21zv"}],["path",{d:"m3.46 10.54 7.08-7.08",key:"1rehiu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mh=re("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const L9=re("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bue=re("Tally1",[["path",{d:"M4 4v16",key:"6qkkli"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ue=re("Tally2",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wue=re("Tally3",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"M14 4v16",key:"12vmem"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jue=re("Tally4",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"M14 4v16",key:"12vmem"}],["path",{d:"M19 4v16",key:"8ij5ei"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nue=re("Tally5",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"M14 4v16",key:"12vmem"}],["path",{d:"M19 4v16",key:"8ij5ei"}],["path",{d:"M22 6 2 18",key:"h9moai"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kue=re("Tangent",[["circle",{cx:"17",cy:"4",r:"2",key:"y5j2s2"}],["path",{d:"M15.59 5.41 5.41 15.59",key:"l0vprr"}],["circle",{cx:"4",cy:"17",r:"2",key:"9p4efm"}],["path",{d:"M12 22s-4-9-1.5-11.5S22 12 22 12",key:"1twk4o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wc=re("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sue=re("Telescope",[["path",{d:"m10.065 12.493-6.18 1.318a.934.934 0 0 1-1.108-.702l-.537-2.15a1.07 1.07 0 0 1 .691-1.265l13.504-4.44",key:"k4qptu"}],["path",{d:"m13.56 11.747 4.332-.924",key:"19l80z"}],["path",{d:"m16 21-3.105-6.21",key:"7oh9d"}],["path",{d:"M16.485 5.94a2 2 0 0 1 1.455-2.425l1.09-.272a1 1 0 0 1 1.212.727l1.515 6.06a1 1 0 0 1-.727 1.213l-1.09.272a2 2 0 0 1-2.425-1.455z",key:"m7xp4m"}],["path",{d:"m6.158 8.633 1.114 4.456",key:"74o979"}],["path",{d:"m8 21 3.105-6.21",key:"1fvxut"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cue=re("TentTree",[["circle",{cx:"4",cy:"4",r:"2",key:"bt5ra8"}],["path",{d:"m14 5 3-3 3 3",key:"1sorif"}],["path",{d:"m14 10 3-3 3 3",key:"1jyi9h"}],["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M17 14H7l-5 8h20Z",key:"13ar7p"}],["path",{d:"M8 14v8",key:"1ghmqk"}],["path",{d:"m9 14 5 8",key:"13pgi6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tue=re("Tent",[["path",{d:"M3.5 21 14 3",key:"1szst5"}],["path",{d:"M20.5 21 10 3",key:"1310c3"}],["path",{d:"M15.5 21 12 15l-3.5 6",key:"1ddtfw"}],["path",{d:"M2 21h20",key:"1nyx9w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eue=re("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fE=re("TestTubeDiagonal",[["path",{d:"M21 7 6.82 21.18a2.83 2.83 0 0 1-3.99-.01a2.83 2.83 0 0 1 0-4L17 3",key:"1ub6xw"}],["path",{d:"m16 2 6 6",key:"1gw87d"}],["path",{d:"M12 16H4",key:"1cjfip"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Aue=re("TestTube",[["path",{d:"M14.5 2v17.5c0 1.4-1.1 2.5-2.5 2.5c-1.4 0-2.5-1.1-2.5-2.5V2",key:"125lnx"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14.5 16h-5",key:"1ox875"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mue=re("TestTubes",[["path",{d:"M9 2v17.5A2.5 2.5 0 0 1 6.5 22A2.5 2.5 0 0 1 4 19.5V2",key:"1hjrqt"}],["path",{d:"M20 2v17.5a2.5 2.5 0 0 1-2.5 2.5a2.5 2.5 0 0 1-2.5-2.5V2",key:"16lc8n"}],["path",{d:"M3 2h7",key:"7s29d5"}],["path",{d:"M14 2h7",key:"7sicin"}],["path",{d:"M9 16H4",key:"1bfye3"}],["path",{d:"M20 16h-5",key:"ddnjpe"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Iue=re("TextCursorInput",[["path",{d:"M5 4h1a3 3 0 0 1 3 3 3 3 0 0 1 3-3h1",key:"18xjzo"}],["path",{d:"M13 20h-1a3 3 0 0 1-3-3 3 3 0 0 1-3 3H5",key:"fj48gi"}],["path",{d:"M5 16H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h1",key:"1n9rhb"}],["path",{d:"M13 8h7a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-7",key:"13ksps"}],["path",{d:"M9 7v10",key:"1vc8ob"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pue=re("TextCursor",[["path",{d:"M17 22h-1a4 4 0 0 1-4-4V6a4 4 0 0 1 4-4h1",key:"uvaxm9"}],["path",{d:"M7 22h1a4 4 0 0 0 4-4v-1",key:"11xy8d"}],["path",{d:"M7 2h1a4 4 0 0 1 4 4v1",key:"1uw06m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lue=re("TextQuote",[["path",{d:"M17 6H3",key:"16j9eg"}],["path",{d:"M21 12H8",key:"scolzb"}],["path",{d:"M21 18H8",key:"1wfozv"}],["path",{d:"M3 12v6",key:"fv4c87"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Due=re("TextSearch",[["path",{d:"M21 6H3",key:"1jwq7v"}],["path",{d:"M10 12H3",key:"1ulcyk"}],["path",{d:"M10 18H3",key:"13769t"}],["circle",{cx:"17",cy:"15",r:"3",key:"1upz2a"}],["path",{d:"m21 19-1.9-1.9",key:"dwi7p8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xE=re("TextSelect",[["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M21 14v1",key:"169vum"}],["line",{x1:"7",x2:"15",y1:"8",y2:"8",key:"1758g8"}],["line",{x1:"7",x2:"17",y1:"12",y2:"12",key:"197423"}],["line",{x1:"7",x2:"13",y1:"16",y2:"16",key:"37cgm6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rue=re("Text",[["path",{d:"M17 6.1H3",key:"wptmhv"}],["path",{d:"M21 12.1H3",key:"1j38uz"}],["path",{d:"M15.1 18H3",key:"1nb16a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oue=re("Theater",[["path",{d:"M2 10s3-3 3-8",key:"3xiif0"}],["path",{d:"M22 10s-3-3-3-8",key:"ioaa5q"}],["path",{d:"M10 2c0 4.4-3.6 8-8 8",key:"16fkpi"}],["path",{d:"M14 2c0 4.4 3.6 8 8 8",key:"b9eulq"}],["path",{d:"M2 10s2 2 2 5",key:"1au1lb"}],["path",{d:"M22 10s-2 2-2 5",key:"qi2y5e"}],["path",{d:"M8 15h8",key:"45n4r"}],["path",{d:"M2 22v-1a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v1",key:"1vsc2m"}],["path",{d:"M14 22v-1a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v1",key:"hrha4u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fue=re("ThermometerSnowflake",[["path",{d:"M2 12h10",key:"19562f"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"m3 9 3 3-3 3",key:"1sas0l"}],["path",{d:"M12 6 9 9 6 6",key:"pfrgxu"}],["path",{d:"m6 18 3-3 1.5 1.5",key:"1e277p"}],["path",{d:"M20 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"iof6y5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zue=re("ThermometerSun",[["path",{d:"M12 9a4 4 0 0 0-2 7.5",key:"1jvsq6"}],["path",{d:"M12 3v2",key:"1w22ol"}],["path",{d:"m6.6 18.4-1.4 1.4",key:"w2yidj"}],["path",{d:"M20 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"iof6y5"}],["path",{d:"M4 13H2",key:"118le4"}],["path",{d:"M6.34 7.34 4.93 5.93",key:"1brd51"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D9=re("Thermometer",[["path",{d:"M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"17jzev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const R9=re("ThumbsDown",[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hm=re("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bue=re("TicketCheck",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ue=re("TicketMinus",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M9 12h6",key:"1c52cq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uue=re("TicketPercent",[["path",{d:"M2 9a3 3 0 1 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 1 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"1l48ns"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const que=re("TicketPlus",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M9 12h6",key:"1c52cq"}],["path",{d:"M12 9v6",key:"199k2o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vue=re("TicketSlash",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"m9.5 14.5 5-5",key:"qviqfa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hue=re("TicketX",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"m9.5 14.5 5-5",key:"qviqfa"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const O9=re("Ticket",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M13 5v2",key:"dyzc3o"}],["path",{d:"M13 17v2",key:"1ont0d"}],["path",{d:"M13 11v2",key:"1wjjxi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gue=re("TicketsPlane",[["path",{d:"M10.5 17h1.227a2 2 0 0 0 1.345-.52L18 12",key:"16muxl"}],["path",{d:"m12 13.5 3.75.5",key:"1i9qhk"}],["path",{d:"m4.5 8 10.58-5.06a1 1 0 0 1 1.342.488L18.5 8",key:"12lg5p"}],["path",{d:"M6 10V8",key:"1y41hn"}],["path",{d:"M6 14v1",key:"cao2tf"}],["path",{d:"M6 19v2",key:"1loha6"}],["rect",{x:"2",y:"8",width:"20",height:"13",rx:"2",key:"p3bz5l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wue=re("Tickets",[["path",{d:"m4.5 8 10.58-5.06a1 1 0 0 1 1.342.488L18.5 8",key:"12lg5p"}],["path",{d:"M6 10V8",key:"1y41hn"}],["path",{d:"M6 14v1",key:"cao2tf"}],["path",{d:"M6 19v2",key:"1loha6"}],["rect",{x:"2",y:"8",width:"20",height:"13",rx:"2",key:"p3bz5l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kue=re("TimerOff",[["path",{d:"M10 2h4",key:"n1abiw"}],["path",{d:"M4.6 11a8 8 0 0 0 1.7 8.7 8 8 0 0 0 8.7 1.7",key:"10he05"}],["path",{d:"M7.4 7.4a8 8 0 0 1 10.3 1 8 8 0 0 1 .9 10.2",key:"15f7sh"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M12 12v-2",key:"fwoke6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yue=re("TimerReset",[["path",{d:"M10 2h4",key:"n1abiw"}],["path",{d:"M12 14v-4",key:"1evpnu"}],["path",{d:"M4 13a8 8 0 0 1 8-7 8 8 0 1 1-5.3 14L4 17.6",key:"1ts96g"}],["path",{d:"M9 17H4v5",key:"8t5av"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zue=re("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Que=re("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xue=re("ToggleRight",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"16",cy:"12",r:"2",key:"4ma0v8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jue=re("Toilet",[["path",{d:"M7 12h13a1 1 0 0 1 1 1 5 5 0 0 1-5 5h-.598a.5.5 0 0 0-.424.765l1.544 2.47a.5.5 0 0 1-.424.765H5.402a.5.5 0 0 1-.424-.765L7 18",key:"kc4kqr"}],["path",{d:"M8 18a5 5 0 0 1-5-5V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8",key:"1tqs57"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ehe=re("Tornado",[["path",{d:"M21 4H3",key:"1hwok0"}],["path",{d:"M18 8H6",key:"41n648"}],["path",{d:"M19 12H9",key:"1g4lpz"}],["path",{d:"M16 16h-6",key:"1j5d54"}],["path",{d:"M11 20H9",key:"39obr8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const the=re("Torus",[["ellipse",{cx:"12",cy:"11",rx:"3",ry:"2",key:"1b2qxu"}],["ellipse",{cx:"12",cy:"12.5",rx:"10",ry:"8.5",key:"h8emeu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const she=re("TouchpadOff",[["path",{d:"M4 4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16",key:"lnt0bk"}],["path",{d:"M2 14h12",key:"d8icqz"}],["path",{d:"M22 14h-2",key:"jrx26d"}],["path",{d:"M12 20v-6",key:"1rm09r"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M22 16V6a2 2 0 0 0-2-2H10",key:"11y8e4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nhe=re("Touchpad",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M2 14h20",key:"myj16y"}],["path",{d:"M12 20v-6",key:"1rm09r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rhe=re("TowerControl",[["path",{d:"M18.2 12.27 20 6H4l1.8 6.27a1 1 0 0 0 .95.73h10.5a1 1 0 0 0 .96-.73Z",key:"1pledb"}],["path",{d:"M8 13v9",key:"hmv0ci"}],["path",{d:"M16 22v-9",key:"ylnf1u"}],["path",{d:"m9 6 1 7",key:"dpdgam"}],["path",{d:"m15 6-1 7",key:"ls7zgu"}],["path",{d:"M12 6V2",key:"1pj48d"}],["path",{d:"M13 2h-2",key:"mj6ths"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ahe=re("ToyBrick",[["rect",{width:"18",height:"12",x:"3",y:"8",rx:"1",key:"158fvp"}],["path",{d:"M10 8V5c0-.6-.4-1-1-1H6a1 1 0 0 0-1 1v3",key:"s0042v"}],["path",{d:"M19 8V5c0-.6-.4-1-1-1h-3a1 1 0 0 0-1 1v3",key:"9wmeh2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ihe=re("Tractor",[["path",{d:"m10 11 11 .9a1 1 0 0 1 .8 1.1l-.665 4.158a1 1 0 0 1-.988.842H20",key:"she1j9"}],["path",{d:"M16 18h-5",key:"bq60fd"}],["path",{d:"M18 5a1 1 0 0 0-1 1v5.573",key:"1kv8ia"}],["path",{d:"M3 4h8.129a1 1 0 0 1 .99.863L13 11.246",key:"1q1ert"}],["path",{d:"M4 11V4",key:"9ft8pt"}],["path",{d:"M7 15h.01",key:"k5ht0j"}],["path",{d:"M8 10.1V4",key:"1jgyzo"}],["circle",{cx:"18",cy:"18",r:"2",key:"1emm8v"}],["circle",{cx:"7",cy:"15",r:"5",key:"ddtuc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ohe=re("TrafficCone",[["path",{d:"M9.3 6.2a4.55 4.55 0 0 0 5.4 0",key:"flyxqv"}],["path",{d:"M7.9 10.7c.9.8 2.4 1.3 4.1 1.3s3.2-.5 4.1-1.3",key:"1nlxxg"}],["path",{d:"M13.9 3.5a1.93 1.93 0 0 0-3.8-.1l-3 10c-.1.2-.1.4-.1.6 0 1.7 2.2 3 5 3s5-1.3 5-3c0-.2 0-.4-.1-.5Z",key:"vz7x1l"}],["path",{d:"m7.5 12.2-4.7 2.7c-.5.3-.8.7-.8 1.1s.3.8.8 1.1l7.6 4.5c.9.5 2.1.5 3 0l7.6-4.5c.7-.3 1-.7 1-1.1s-.3-.8-.8-1.1l-4.7-2.8",key:"1xfzlw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lhe=re("TrainFrontTunnel",[["path",{d:"M2 22V12a10 10 0 1 1 20 0v10",key:"o0fyp0"}],["path",{d:"M15 6.8v1.4a3 2.8 0 1 1-6 0V6.8",key:"m8q3n9"}],["path",{d:"M10 15h.01",key:"44in9x"}],["path",{d:"M14 15h.01",key:"5mohn5"}],["path",{d:"M10 19a4 4 0 0 1-4-4v-3a6 6 0 1 1 12 0v3a4 4 0 0 1-4 4Z",key:"hckbmu"}],["path",{d:"m9 19-2 3",key:"iij7hm"}],["path",{d:"m15 19 2 3",key:"npx8sa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const che=re("TrainFront",[["path",{d:"M8 3.1V7a4 4 0 0 0 8 0V3.1",key:"1v71zp"}],["path",{d:"m9 15-1-1",key:"1yrq24"}],["path",{d:"m15 15 1-1",key:"1t0d6s"}],["path",{d:"M9 19c-2.8 0-5-2.2-5-5v-4a8 8 0 0 1 16 0v4c0 2.8-2.2 5-5 5Z",key:"1p0hjs"}],["path",{d:"m8 19-2 3",key:"13i0xs"}],["path",{d:"m16 19 2 3",key:"xo31yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dhe=re("TrainTrack",[["path",{d:"M2 17 17 2",key:"18b09t"}],["path",{d:"m2 14 8 8",key:"1gv9hu"}],["path",{d:"m5 11 8 8",key:"189pqp"}],["path",{d:"m8 8 8 8",key:"1imecy"}],["path",{d:"m11 5 8 8",key:"ummqn6"}],["path",{d:"m14 2 8 8",key:"1vk7dn"}],["path",{d:"M7 22 22 7",key:"15mb1i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gE=re("TramFront",[["rect",{width:"16",height:"16",x:"4",y:"3",rx:"2",key:"1wxw4b"}],["path",{d:"M4 11h16",key:"mpoxn0"}],["path",{d:"M12 3v8",key:"1h2ygw"}],["path",{d:"m8 19-2 3",key:"13i0xs"}],["path",{d:"m18 22-2-3",key:"1p0ohu"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M16 15h.01",key:"rnfrdf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bn=re("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uhe=re("Trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hhe=re("TreeDeciduous",[["path",{d:"M8 19a4 4 0 0 1-2.24-7.32A3.5 3.5 0 0 1 9 6.03V6a3 3 0 1 1 6 0v.04a3.5 3.5 0 0 1 3.24 5.65A4 4 0 0 1 16 19Z",key:"oadzkq"}],["path",{d:"M12 19v3",key:"npa21l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yE=re("TreePalm",[["path",{d:"M13 8c0-2.76-2.46-5-5.5-5S2 5.24 2 8h2l1-1 1 1h4",key:"foxbe7"}],["path",{d:"M13 7.14A5.82 5.82 0 0 1 16.5 6c3.04 0 5.5 2.24 5.5 5h-3l-1-1-1 1h-3",key:"18arnh"}],["path",{d:"M5.89 9.71c-2.15 2.15-2.3 5.47-.35 7.43l4.24-4.25.7-.7.71-.71 2.12-2.12c-1.95-1.96-5.27-1.8-7.42.35",key:"ywahnh"}],["path",{d:"M11 15.5c.5 2.5-.17 4.5-1 6.5h4c2-5.5-.5-12-1-14",key:"ft0feo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const d4=re("TreePine",[["path",{d:"m17 14 3 3.3a1 1 0 0 1-.7 1.7H4.7a1 1 0 0 1-.7-1.7L7 14h-.3a1 1 0 0 1-.7-1.7L9 9h-.2A1 1 0 0 1 8 7.3L12 3l4 4.3a1 1 0 0 1-.8 1.7H15l3 3.3a1 1 0 0 1-.7 1.7H17Z",key:"cpyugq"}],["path",{d:"M12 22v-3",key:"kmzjlo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mhe=re("Trees",[["path",{d:"M10 10v.2A3 3 0 0 1 8.9 16H5a3 3 0 0 1-1-5.8V10a3 3 0 0 1 6 0Z",key:"1l6gj6"}],["path",{d:"M7 16v6",key:"1a82de"}],["path",{d:"M13 19v3",key:"13sx9i"}],["path",{d:"M12 19h8.3a1 1 0 0 0 .7-1.7L18 14h.3a1 1 0 0 0 .7-1.7L16 9h.2a1 1 0 0 0 .8-1.7L13 3l-1.4 1.5",key:"1sj9kv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const phe=re("Trello",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["rect",{width:"3",height:"9",x:"7",y:"7",key:"14n3xi"}],["rect",{width:"3",height:"5",x:"14",y:"7",key:"s4azjd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bb=re("TrendingDown",[["polyline",{points:"22 17 13.5 8.5 8.5 13.5 2 7",key:"1r2t7k"}],["polyline",{points:"16 17 22 17 22 11",key:"11uiuu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fhe=re("TrendingUpDown",[["path",{d:"M14.828 14.828 21 21",key:"ar5fw7"}],["path",{d:"M21 16v5h-5",key:"1ck2sf"}],["path",{d:"m21 3-9 9-4-4-6 6",key:"1h02xo"}],["path",{d:"M21 8V3h-5",key:"1qoq8a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mo=re("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dl=re("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xhe=re("TriangleRight",[["path",{d:"M22 18a2 2 0 0 1-2 2H3c-1.1 0-1.3-.6-.4-1.3L20.4 4.3c.9-.7 1.6-.4 1.6.7Z",key:"183wce"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ghe=re("Triangle",[["path",{d:"M13.73 4a2 2 0 0 0-3.46 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z",key:"14u9p9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vo=re("Trophy",[["path",{d:"M6 9H4.5a2.5 2.5 0 0 1 0-5H6",key:"17hqa7"}],["path",{d:"M18 9h1.5a2.5 2.5 0 0 0 0-5H18",key:"lmptdp"}],["path",{d:"M4 22h16",key:"57wxv0"}],["path",{d:"M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22",key:"1nw9bq"}],["path",{d:"M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22",key:"1np0yb"}],["path",{d:"M18 2H6v7a6 6 0 0 0 12 0V2Z",key:"u46fv3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const F9=re("Truck",[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yhe=re("Turtle",[["path",{d:"m12 10 2 4v3a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1v-3a8 8 0 1 0-16 0v3a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1v-3l2-4h4Z",key:"1lbbv7"}],["path",{d:"M4.82 7.9 8 10",key:"m9wose"}],["path",{d:"M15.18 7.9 12 10",key:"p8dp2u"}],["path",{d:"M16.93 10H20a2 2 0 0 1 0 4H2",key:"12nsm7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vhe=re("TvMinimalPlay",[["path",{d:"M10 7.75a.75.75 0 0 1 1.142-.638l3.664 2.249a.75.75 0 0 1 0 1.278l-3.664 2.25a.75.75 0 0 1-1.142-.64z",key:"1pctta"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vE=re("TvMinimal",[["path",{d:"M7 21h10",key:"1b0cd5"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bhe=re("Tv",[["rect",{width:"20",height:"15",x:"2",y:"7",rx:"2",ry:"2",key:"10ag99"}],["polyline",{points:"17 2 12 7 7 2",key:"11pgbg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _he=re("Twitch",[["path",{d:"M21 2H3v16h5v4l4-4h5l4-4V2zm-10 9V7m5 4V7",key:"c0yzno"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const whe=re("Twitter",[["path",{d:"M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z",key:"pff0z6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jhe=re("TypeOutline",[["path",{d:"M14 16.5a.5.5 0 0 0 .5.5h.5a2 2 0 0 1 0 4H9a2 2 0 0 1 0-4h.5a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5V8a2 2 0 0 1-4 0V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v3a2 2 0 0 1-4 0v-.5a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5Z",key:"1reda3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nhe=re("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const khe=re("UmbrellaOff",[["path",{d:"M12 2v1",key:"11qlp1"}],["path",{d:"M15.5 21a1.85 1.85 0 0 1-3.5-1v-8H2a10 10 0 0 1 3.428-6.575",key:"eki10q"}],["path",{d:"M17.5 12H22A10 10 0 0 0 9.004 3.455",key:"n2ayka"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const She=re("Umbrella",[["path",{d:"M22 12a10.06 10.06 1 0 0-20 0Z",key:"1teyop"}],["path",{d:"M12 12v8a2 2 0 0 0 4 0",key:"ulpmoc"}],["path",{d:"M12 2v1",key:"11qlp1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NL=re("Underline",[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const z9=re("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Che=re("UndoDot",[["path",{d:"M21 17a9 9 0 0 0-15-6.7L3 13",key:"8mp6z9"}],["path",{d:"M3 7v6h6",key:"1v2h90"}],["circle",{cx:"12",cy:"17",r:"1",key:"1ixnty"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const u4=re("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const The=re("UnfoldHorizontal",[["path",{d:"M16 12h6",key:"15xry1"}],["path",{d:"M8 12H2",key:"1jqql6"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m19 15 3-3-3-3",key:"wjy7rq"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ehe=re("UnfoldVertical",[["path",{d:"M12 22v-6",key:"6o8u61"}],["path",{d:"M12 8V2",key:"1wkif3"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m15 5-3-3-3 3",key:"itvq4r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ahe=re("Ungroup",[["rect",{width:"8",height:"6",x:"5",y:"4",rx:"1",key:"nzclkv"}],["rect",{width:"8",height:"6",x:"11",y:"14",rx:"1",key:"4tytwb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bE=re("University",[["circle",{cx:"12",cy:"10",r:"1",key:"1gnqs8"}],["path",{d:"M22 20V8h-4l-6-4-6 4H2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2",key:"1qj5sn"}],["path",{d:"M6 17v.01",key:"roodi6"}],["path",{d:"M6 13v.01",key:"67c122"}],["path",{d:"M18 17v.01",key:"12ktxm"}],["path",{d:"M18 13v.01",key:"tn1rt1"}],["path",{d:"M14 22v-5a2 2 0 0 0-2-2a2 2 0 0 0-2 2v5",key:"11g7fi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mhe=re("Unlink2",[["path",{d:"M15 7h2a5 5 0 0 1 0 10h-2m-6 0H7A5 5 0 0 1 7 7h2",key:"1re2ne"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VA=re("Unlink",[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ihe=re("Unplug",[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sa=re("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Phe=re("Usb",[["circle",{cx:"10",cy:"7",r:"1",key:"dypaad"}],["circle",{cx:"4",cy:"20",r:"1",key:"22iqad"}],["path",{d:"M4.7 19.3 19 5",key:"1enqfc"}],["path",{d:"m21 3-3 1 2 2Z",key:"d3ov82"}],["path",{d:"M9.26 7.68 5 12l2 5",key:"1esawj"}],["path",{d:"m10 14 5 2 3.5-3.5",key:"v8oal5"}],["path",{d:"m18 12 1-1 1 1-1 1Z",key:"1bh22v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _b=re("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const B9=re("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $9=re("UserMinus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lhe=re("UserPen",[["path",{d:"M11.5 15H7a4 4 0 0 0-4 4v2",key:"15lzij"}],["path",{d:"M21.378 16.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1817ys"}],["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fo=re("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _E=re("UserRoundCheck",[["path",{d:"M2 21a8 8 0 0 1 13.292-6",key:"bjp14o"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wE=re("UserRoundCog",[["path",{d:"M2 21a8 8 0 0 1 10.434-7.62",key:"1yezr2"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m19.5 14.3-.4.9",key:"1eb35c"}],["path",{d:"m16.9 20.8-.4.9",key:"dfjc4z"}],["path",{d:"m21.7 19.5-.9-.4",key:"q4dx6b"}],["path",{d:"m15.2 16.9-.9-.4",key:"1r0w5f"}],["path",{d:"m21.7 16.5-.9.4",key:"1knoei"}],["path",{d:"m15.2 19.1-.9.4",key:"j188fs"}],["path",{d:"m19.5 21.7-.4-.9",key:"1tonu5"}],["path",{d:"m16.9 15.2-.4-.9",key:"699xu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jE=re("UserRoundMinus",[["path",{d:"M2 21a8 8 0 0 1 13.292-6",key:"bjp14o"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 19h-6",key:"vcuq98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dhe=re("UserRoundPen",[["path",{d:"M2 21a8 8 0 0 1 10.821-7.487",key:"1c8h7z"}],["path",{d:"M21.378 16.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1817ys"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NE=re("UserRoundPlus",[["path",{d:"M2 21a8 8 0 0 1 13.292-6",key:"bjp14o"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M22 19h-6",key:"vcuq98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rhe=re("UserRoundSearch",[["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M2 21a8 8 0 0 1 10.434-7.62",key:"1yezr2"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m22 22-1.9-1.9",key:"1e5ubv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kE=re("UserRoundX",[["path",{d:"M2 21a8 8 0 0 1 11.873-7",key:"74fkxq"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"m17 17 5 5",key:"p7ous7"}],["path",{d:"m22 17-5 5",key:"gqnmv0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SE=re("UserRound",[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ohe=re("UserSearch",[["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}],["path",{d:"M10.3 15H7a4 4 0 0 0-4 4v2",key:"3bnktk"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fhe=re("UserX",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xi=re("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W0=re("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _n=re("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CE=re("UtensilsCrossed",[["path",{d:"m16 2-2.3 2.3a3 3 0 0 0 0 4.2l1.8 1.8a3 3 0 0 0 4.2 0L22 8",key:"n7qcjb"}],["path",{d:"M15 15 3.3 3.3a4.2 4.2 0 0 0 0 6l7.3 7.3c.7.7 2 .7 2.8 0L15 15Zm0 0 7 7",key:"d0u48b"}],["path",{d:"m2.1 21.8 6.4-6.3",key:"yn04lh"}],["path",{d:"m19 5-7 7",key:"194lzd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TE=re("Utensils",[["path",{d:"M3 2v7c0 1.1.9 2 2 2h4a2 2 0 0 0 2-2V2",key:"cjf0a3"}],["path",{d:"M7 2v20",key:"1473qp"}],["path",{d:"M21 15V2a5 5 0 0 0-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7",key:"j28e5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zhe=re("UtilityPole",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M3 3v2",key:"9imdir"}],["path",{d:"M7 3v2",key:"n0os7"}],["path",{d:"M17 3v2",key:"1l2re6"}],["path",{d:"M21 3v2",key:"1duuac"}],["path",{d:"m19 5-7 7-7-7",key:"133zxf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kL=re("Variable",[["path",{d:"M8 21s-4-3-4-9 4-9 4-9",key:"uto9ud"}],["path",{d:"M16 3s4 3 4 9-4 9-4 9",key:"4w2vsq"}],["line",{x1:"15",x2:"9",y1:"9",y2:"15",key:"f7djnv"}],["line",{x1:"9",x2:"15",y1:"9",y2:"15",key:"1shsy8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bhe=re("Vault",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}],["path",{d:"m7.9 7.9 2.7 2.7",key:"hpeyl3"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}],["path",{d:"m13.4 10.6 2.7-2.7",key:"264c1n"}],["circle",{cx:"7.5",cy:"16.5",r:".5",fill:"currentColor",key:"nkw3mc"}],["path",{d:"m7.9 16.1 2.7-2.7",key:"p81g5e"}],["circle",{cx:"16.5",cy:"16.5",r:".5",fill:"currentColor",key:"fubopw"}],["path",{d:"m13.4 13.4 2.7 2.7",key:"abhel3"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $he=re("Vegan",[["path",{d:"M16 8q6 0 6-6-6 0-6 6",key:"qsyyc4"}],["path",{d:"M17.41 3.59a10 10 0 1 0 3 3",key:"41m9h7"}],["path",{d:"M2 2a26.6 26.6 0 0 1 10 20c.9-6.82 1.5-9.5 4-14",key:"qiv7li"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uhe=re("VenetianMask",[["path",{d:"M18 11c-1.5 0-2.5.5-3 2",key:"1fod00"}],["path",{d:"M4 6a2 2 0 0 0-2 2v4a5 5 0 0 0 5 5 8 8 0 0 1 5 2 8 8 0 0 1 5-2 5 5 0 0 0 5-5V8a2 2 0 0 0-2-2h-3a8 8 0 0 0-5 2 8 8 0 0 0-5-2z",key:"d70hit"}],["path",{d:"M6 11c1.5 0 2.5.5 3 2",key:"136fht"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qhe=re("VibrateOff",[["path",{d:"m2 8 2 2-2 2 2 2-2 2",key:"sv1b1"}],["path",{d:"m22 8-2 2 2 2-2 2 2 2",key:"101i4y"}],["path",{d:"M8 8v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2",key:"1hbad5"}],["path",{d:"M16 10.34V6c0-.55-.45-1-1-1h-4.34",key:"1x5tf0"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vhe=re("Vibrate",[["path",{d:"m2 8 2 2-2 2 2 2-2 2",key:"sv1b1"}],["path",{d:"m22 8-2 2 2 2-2 2 2 2",key:"101i4y"}],["rect",{width:"8",height:"14",x:"8",y:"5",rx:"1",key:"1oyrl4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hhe=re("VideoOff",[["path",{d:"M10.66 6H14a2 2 0 0 1 2 2v2.5l5.248-3.062A.5.5 0 0 1 22 7.87v8.196",key:"w8jjjt"}],["path",{d:"M16 16a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h2",key:"1xawa7"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vr=re("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ghe=re("Videotape",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M2 8h20",key:"d11cs7"}],["circle",{cx:"8",cy:"14",r:"2",key:"1k2qr5"}],["path",{d:"M8 12h8",key:"1wcyev"}],["circle",{cx:"16",cy:"14",r:"2",key:"14k7lr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Whe=re("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Khe=re("Voicemail",[["circle",{cx:"6",cy:"12",r:"4",key:"1ehtga"}],["circle",{cx:"18",cy:"12",r:"4",key:"4vafl8"}],["line",{x1:"6",x2:"18",y1:"16",y2:"16",key:"pmt8us"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yhe=re("Volleyball",[["path",{d:"M11.1 7.1a16.55 16.55 0 0 1 10.9 4",key:"2880wi"}],["path",{d:"M12 12a12.6 12.6 0 0 1-8.7 5",key:"113sja"}],["path",{d:"M16.8 13.6a16.55 16.55 0 0 1-9 7.5",key:"1qmsgl"}],["path",{d:"M20.7 17a12.8 12.8 0 0 0-8.7-5 13.3 13.3 0 0 1 0-10",key:"1bmeqp"}],["path",{d:"M6.3 3.8a16.55 16.55 0 0 0 1.9 11.5",key:"iekzv9"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zhe=re("Volume1",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U9=re("Volume2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qhe=re("VolumeOff",[["path",{d:"M16 9a5 5 0 0 1 .95 2.293",key:"1fgyg8"}],["path",{d:"M19.364 5.636a9 9 0 0 1 1.889 9.96",key:"l3zxae"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"m7 7-.587.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298V11",key:"1gbwow"}],["path",{d:"M9.828 4.172A.686.686 0 0 1 11 4.657v.686",key:"s2je0y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q9=re("VolumeX",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xhe=re("Volume",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jhe=re("Vote",[["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}],["path",{d:"M5 7c0-1.1.9-2 2-2h10a2 2 0 0 1 2 2v12H5V7Z",key:"1ezoue"}],["path",{d:"M22 19H2",key:"nuriw5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eme=re("WalletCards",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2",key:"4125el"}],["path",{d:"M3 11h3c.8 0 1.6.3 2.1.9l1.1.9c1.6 1.6 4.1 1.6 5.7 0l1.1-.9c.5-.5 1.3-.9 2.1-.9H21",key:"1dpki6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EE=re("WalletMinimal",[["path",{d:"M17 14h.01",key:"7oqj8z"}],["path",{d:"M7 7h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14",key:"u1rqew"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SL=re("Wallet",[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tme=re("Wallpaper",[["circle",{cx:"8",cy:"9",r:"2",key:"gjzl9d"}],["path",{d:"m9 17 6.1-6.1a2 2 0 0 1 2.81.01L22 15V5a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2",key:"69xh40"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rm=re("WandSparkles",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sme=re("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nme=re("Warehouse",[["path",{d:"M22 8.35V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8.35A2 2 0 0 1 3.26 6.5l8-3.2a2 2 0 0 1 1.48 0l8 3.2A2 2 0 0 1 22 8.35Z",key:"gksnxg"}],["path",{d:"M6 18h12",key:"9pbo8z"}],["path",{d:"M6 14h12",key:"4cwo0f"}],["rect",{width:"12",height:"12",x:"6",y:"10",key:"apd30q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rme=re("WashingMachine",[["path",{d:"M3 6h3",key:"155dbl"}],["path",{d:"M17 6h.01",key:"e2y6kg"}],["rect",{width:"18",height:"20",x:"3",y:"2",rx:"2",key:"od3kk9"}],["circle",{cx:"12",cy:"13",r:"5",key:"nlbqau"}],["path",{d:"M12 18a2.5 2.5 0 0 0 0-5 2.5 2.5 0 0 1 0-5",key:"17lach"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ame=re("Watch",[["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["polyline",{points:"12 10 12 12 13 13",key:"19dquz"}],["path",{d:"m16.13 7.66-.81-4.05a2 2 0 0 0-2-1.61h-2.68a2 2 0 0 0-2 1.61l-.78 4.05",key:"18k57s"}],["path",{d:"m7.88 16.36.8 4a2 2 0 0 0 2 1.61h2.72a2 2 0 0 0 2-1.61l.81-4.05",key:"16ny36"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ime=re("Waves",[["path",{d:"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"knzxuh"}],["path",{d:"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"2jd2cc"}],["path",{d:"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"rd2r6e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ome=re("Waypoints",[["circle",{cx:"12",cy:"4.5",r:"2.5",key:"r5ysbb"}],["path",{d:"m10.2 6.3-3.9 3.9",key:"1nzqf6"}],["circle",{cx:"4.5",cy:"12",r:"2.5",key:"jydg6v"}],["path",{d:"M7 12h10",key:"b7w52i"}],["circle",{cx:"19.5",cy:"12",r:"2.5",key:"1piiel"}],["path",{d:"m13.8 17.7 3.9-3.9",key:"1wyg1y"}],["circle",{cx:"12",cy:"19.5",r:"2.5",key:"13o1pw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lme=re("Webcam",[["circle",{cx:"12",cy:"10",r:"8",key:"1gshiw"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 22h10",key:"10w4w3"}],["path",{d:"M12 22v-4",key:"1utk9m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cme=re("WebhookOff",[["path",{d:"M17 17h-5c-1.09-.02-1.94.92-2.5 1.9A3 3 0 1 1 2.57 15",key:"1tvl6x"}],["path",{d:"M9 3.4a4 4 0 0 1 6.52.66",key:"q04jfq"}],["path",{d:"m6 17 3.1-5.8a2.5 2.5 0 0 0 .057-2.05",key:"azowf0"}],["path",{d:"M20.3 20.3a4 4 0 0 1-2.3.7",key:"5joiws"}],["path",{d:"M18.6 13a4 4 0 0 1 3.357 3.414",key:"cangb8"}],["path",{d:"m12 6 .6 1",key:"tpjl1n"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dme=re("Webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ume=re("Weight",[["circle",{cx:"12",cy:"5",r:"3",key:"rqqgnr"}],["path",{d:"M6.5 8a2 2 0 0 0-1.905 1.46L2.1 18.5A2 2 0 0 0 4 21h16a2 2 0 0 0 1.925-2.54L19.4 9.5A2 2 0 0 0 17.48 8Z",key:"56o5sh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hme=re("WheatOff",[["path",{d:"m2 22 10-10",key:"28ilpk"}],["path",{d:"m16 8-1.17 1.17",key:"1qqm82"}],["path",{d:"M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1rdhi6"}],["path",{d:"m8 8-.53.53a3.5 3.5 0 0 0 0 4.94L9 15l1.53-1.53c.55-.55.88-1.25.98-1.97",key:"4wz8re"}],["path",{d:"M10.91 5.26c.15-.26.34-.51.56-.73L13 3l1.53 1.53a3.5 3.5 0 0 1 .28 4.62",key:"rves66"}],["path",{d:"M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z",key:"19rau1"}],["path",{d:"M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"tc8ph9"}],["path",{d:"m16 16-.53.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.49 3.49 0 0 1 1.97-.98",key:"ak46r"}],["path",{d:"M18.74 13.09c.26-.15.51-.34.73-.56L21 11l-1.53-1.53a3.5 3.5 0 0 0-4.62-.28",key:"1tw520"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mme=re("Wheat",[["path",{d:"M2 22 16 8",key:"60hf96"}],["path",{d:"M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1rdhi6"}],["path",{d:"M7.47 8.53 9 7l1.53 1.53a3.5 3.5 0 0 1 0 4.94L9 15l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1sdzmb"}],["path",{d:"M11.47 4.53 13 3l1.53 1.53a3.5 3.5 0 0 1 0 4.94L13 11l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"eoatbi"}],["path",{d:"M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z",key:"19rau1"}],["path",{d:"M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"tc8ph9"}],["path",{d:"M15.47 13.47 17 15l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"2m8kc5"}],["path",{d:"M19.47 9.47 21 11l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L13 11l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"vex3ng"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pme=re("WholeWord",[["circle",{cx:"7",cy:"12",r:"3",key:"12clwm"}],["path",{d:"M10 9v6",key:"17i7lo"}],["circle",{cx:"17",cy:"12",r:"3",key:"gl7c2s"}],["path",{d:"M14 7v8",key:"dl84cr"}],["path",{d:"M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1",key:"lt2kga"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fme=re("WifiHigh",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xme=re("WifiLow",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gme=re("WifiOff",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yme=re("WifiZero",[["path",{d:"M12 20h.01",key:"zekei9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vme=re("Wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bme=re("WindArrowDown",[["path",{d:"M10 2v8",key:"d4bbey"}],["path",{d:"M12.8 21.6A2 2 0 1 0 14 18H2",key:"19kp1d"}],["path",{d:"M17.5 10a2.5 2.5 0 1 1 2 4H2",key:"19kpjc"}],["path",{d:"m6 6 4 4 4-4",key:"k13n16"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _me=re("Wind",[["path",{d:"M12.8 19.6A2 2 0 1 0 14 16H2",key:"148xed"}],["path",{d:"M17.5 8a2.5 2.5 0 1 1 2 4H2",key:"1u4tom"}],["path",{d:"M9.8 4.4A2 2 0 1 1 11 8H2",key:"75valh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wme=re("WineOff",[["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M7 10h3m7 0h-1.343",key:"v48bem"}],["path",{d:"M12 15v7",key:"t2xh3l"}],["path",{d:"M7.307 7.307A12.33 12.33 0 0 0 7 10a5 5 0 0 0 7.391 4.391M8.638 2.981C8.75 2.668 8.872 2.34 9 2h6c1.5 4 2 6 2 8 0 .407-.05.809-.145 1.198",key:"1ymjlu"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V9=re("Wine",[["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M7 10h10",key:"1101jm"}],["path",{d:"M12 15v7",key:"t2xh3l"}],["path",{d:"M12 15a5 5 0 0 0 5-5c0-2-.5-4-2-8H9c-1.5 4-2 6-2 8a5 5 0 0 0 5 5Z",key:"10ffi3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H9=re("Workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jme=re("Worm",[["path",{d:"m19 12-1.5 3",key:"9bcu4o"}],["path",{d:"M19.63 18.81 22 20",key:"121v98"}],["path",{d:"M6.47 8.23a1.68 1.68 0 0 1 2.44 1.93l-.64 2.08a6.76 6.76 0 0 0 10.16 7.67l.42-.27a1 1 0 1 0-2.73-4.21l-.42.27a1.76 1.76 0 0 1-2.63-1.99l.64-2.08A6.66 6.66 0 0 0 3.94 3.9l-.7.4a1 1 0 1 0 2.55 4.34z",key:"1tij6q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nme=re("WrapText",[["line",{x1:"3",x2:"21",y1:"6",y2:"6",key:"4m8b97"}],["path",{d:"M3 12h15a3 3 0 1 1 0 6h-4",key:"1cl7v7"}],["polyline",{points:"16 16 14 18 16 20",key:"1jznyi"}],["line",{x1:"3",x2:"10",y1:"18",y2:"18",key:"1h33wv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wb=re("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fn=re("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kme=re("Youtube",[["path",{d:"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17",key:"1q2vi4"}],["path",{d:"m10 15 5-3-5-3z",key:"1jp15x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sme=re("ZapOff",[["path",{d:"M10.513 4.856 13.12 2.17a.5.5 0 0 1 .86.46l-1.377 4.317",key:"193nxd"}],["path",{d:"M15.656 10H20a1 1 0 0 1 .78 1.63l-1.72 1.773",key:"27a7lr"}],["path",{d:"M16.273 16.273 10.88 21.83a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14H4a1 1 0 0 1-.78-1.63l4.507-4.643",key:"1e0qe9"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ph=re("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const h4=re("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CL=re("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JMt=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:EW,AArrowUp:AW,ALargeSmall:MW,Accessibility:IW,Activity:am,AirVent:PW,Airplay:LW,AlarmClock:RW,AlarmClockCheck:k3,AlarmClockMinus:S3,AlarmClockOff:DW,AlarmClockPlus:C3,AlarmSmoke:OW,Album:FW,AlignCenter:_A,AlignCenterHorizontal:zW,AlignCenterVertical:BW,AlignEndHorizontal:$W,AlignEndVertical:UW,AlignHorizontalDistributeCenter:qW,AlignHorizontalDistributeEnd:VW,AlignHorizontalDistributeStart:HW,AlignHorizontalJustifyCenter:GW,AlignHorizontalJustifyEnd:WW,AlignHorizontalJustifyStart:KW,AlignHorizontalSpaceAround:YW,AlignHorizontalSpaceBetween:ZW,AlignJustify:QW,AlignLeft:wA,AlignRight:jA,AlignStartHorizontal:XW,AlignStartVertical:JW,AlignVerticalDistributeCenter:eK,AlignVerticalDistributeEnd:tK,AlignVerticalDistributeStart:sK,AlignVerticalJustifyCenter:nK,AlignVerticalJustifyEnd:rK,AlignVerticalJustifyStart:aK,AlignVerticalSpaceAround:iK,AlignVerticalSpaceBetween:oK,Ambulance:lK,Ampersand:cK,Ampersands:dK,Amphora:uK,Anchor:hK,Angry:mK,Annoyed:pK,Antenna:fK,Anvil:xK,Aperture:gK,AppWindow:vK,AppWindowMac:yK,Apple:bK,Archive:im,ArchiveRestore:XP,ArchiveX:_K,Armchair:wK,ArrowBigDown:NK,ArrowBigDownDash:jK,ArrowBigLeft:SK,ArrowBigLeftDash:kK,ArrowBigRight:TK,ArrowBigRightDash:CK,ArrowBigUp:AK,ArrowBigUpDash:EK,ArrowDown:om,ArrowDown01:MK,ArrowDown10:IK,ArrowDownAZ:T3,ArrowDownFromLine:PK,ArrowDownLeft:LK,ArrowDownNarrowWide:DK,ArrowDownRight:W7,ArrowDownToDot:RK,ArrowDownToLine:OK,ArrowDownUp:FK,ArrowDownWideNarrow:E3,ArrowDownZA:A3,ArrowLeft:Wr,ArrowLeftFromLine:zK,ArrowLeftRight:BK,ArrowLeftToLine:$K,ArrowRight:za,ArrowRightFromLine:UK,ArrowRightLeft:pw,ArrowRightToLine:qK,ArrowUp:Bu,ArrowUp01:VK,ArrowUp10:HK,ArrowUpAZ:M3,ArrowUpDown:sm,ArrowUpFromDot:GK,ArrowUpFromLine:WK,ArrowUpLeft:KK,ArrowUpNarrowWide:I3,ArrowUpRight:JP,ArrowUpToLine:YK,ArrowUpWideNarrow:ZK,ArrowUpZA:P3,ArrowsUpFromLine:QK,Asterisk:XK,AtSign:JK,Atom:eY,AudioLines:tY,AudioWaveform:sY,Award:vc,Axe:nY,Axis3d:L3,Baby:rY,Backpack:aY,Badge:_Y,BadgeAlert:iY,BadgeCent:oY,BadgeCheck:D3,BadgeDollarSign:lY,BadgeEuro:cY,BadgeHelp:dY,BadgeIndianRupee:uY,BadgeInfo:hY,BadgeJapaneseYen:mY,BadgeMinus:pY,BadgePercent:fY,BadgePlus:xY,BadgePoundSterling:gY,BadgeRussianRuble:yY,BadgeSwissFranc:vY,BadgeX:bY,BaggageClaim:wY,Ban:eL,Banana:jY,Bandage:NY,Banknote:kY,Barcode:SY,Baseline:CY,Bath:Tp,Battery:PY,BatteryCharging:TY,BatteryFull:EY,BatteryLow:AY,BatteryMedium:MY,BatteryWarning:IY,Beaker:K7,Bean:DY,BeanOff:LY,Bed:ny,BedDouble:G2,BedSingle:RY,Beef:OY,Beer:zY,BeerOff:FY,Bell:lm,BellDot:BY,BellElectric:$Y,BellMinus:UY,BellOff:fw,BellPlus:qY,BellRing:KS,BetweenHorizontalEnd:R3,BetweenHorizontalStart:O3,BetweenVerticalEnd:VY,BetweenVerticalStart:HY,BicepsFlexed:GY,Bike:WY,Binary:KY,Binoculars:YY,Biohazard:ZY,Bird:QY,Bitcoin:XY,Blend:JY,Blinds:eZ,Blocks:tZ,Bluetooth:aZ,BluetoothConnected:sZ,BluetoothOff:nZ,BluetoothSearching:rZ,Bold:YS,Bolt:iZ,Bomb:oZ,Bone:lZ,Book:AZ,BookA:cZ,BookAudio:dZ,BookCheck:uZ,BookCopy:hZ,BookDashed:F3,BookDown:mZ,BookHeadphones:pZ,BookHeart:fZ,BookImage:xZ,BookKey:gZ,BookLock:yZ,BookMarked:vZ,BookMinus:bZ,BookOpen:$u,BookOpenCheck:_Z,BookOpenText:wZ,BookPlus:jZ,BookText:NZ,BookType:kZ,BookUp:CZ,BookUp2:SZ,BookUser:TZ,BookX:EZ,Bookmark:Rv,BookmarkCheck:MZ,BookmarkMinus:IZ,BookmarkPlus:tL,BookmarkX:PZ,BoomBox:LZ,Bot:ZS,BotMessageSquare:DZ,BotOff:RZ,Box:Y7,Boxes:OZ,Braces:z3,Brackets:FZ,Brain:Z7,BrainCircuit:zZ,BrainCog:BZ,BrickWall:$Z,Briefcase:Vm,BriefcaseBusiness:UZ,BriefcaseConveyorBelt:qZ,BriefcaseMedical:VZ,BringToFront:HZ,Brush:GZ,Bug:YZ,BugOff:WZ,BugPlay:KZ,Building:NA,Building2:Ga,Bus:QZ,BusFront:ZZ,Cable:JZ,CableCar:XZ,Cake:hu,CakeSlice:eQ,Calculator:xw,Calendar:yr,Calendar1:tQ,CalendarArrowDown:sQ,CalendarArrowUp:nQ,CalendarCheck:QS,CalendarCheck2:rQ,CalendarClock:cm,CalendarCog:aQ,CalendarDays:Tl,CalendarFold:iQ,CalendarHeart:mb,CalendarMinus:lQ,CalendarMinus2:oQ,CalendarOff:Q7,CalendarPlus:Fg,CalendarPlus2:cQ,CalendarRange:dQ,CalendarSearch:uQ,CalendarSync:hQ,CalendarX:X7,CalendarX2:mQ,Camera:pf,CameraOff:pQ,Candy:gQ,CandyCane:fQ,CandyOff:xQ,Cannabis:yQ,Captions:B3,CaptionsOff:vQ,Car:wQ,CarFront:bQ,CarTaxiFront:_Q,Caravan:jQ,Carrot:NQ,CaseLower:kQ,CaseSensitive:SQ,CaseUpper:CQ,CassetteTape:TQ,Cast:EQ,Castle:AQ,Cat:MQ,Cctv:IQ,ChartArea:$3,ChartBar:q3,ChartBarBig:U3,ChartBarDecreasing:PQ,ChartBarIncreasing:LQ,ChartBarStacked:DQ,ChartCandlestick:V3,ChartColumn:yo,ChartColumnBig:H3,ChartColumnDecreasing:RQ,ChartColumnIncreasing:G3,ChartColumnStacked:OQ,ChartGantt:FQ,ChartLine:W3,ChartNetwork:zQ,ChartNoAxesColumn:Y3,ChartNoAxesColumnDecreasing:BQ,ChartNoAxesColumnIncreasing:K3,ChartNoAxesCombined:$Q,ChartNoAxesGantt:Z3,ChartPie:Q3,ChartScatter:X3,ChartSpline:UQ,Check:Lr,CheckCheck:J7,ChefHat:qQ,Cherry:VQ,ChevronDown:io,ChevronFirst:HQ,ChevronLast:GQ,ChevronLeft:fl,ChevronRight:ga,ChevronUp:sx,ChevronsDown:KQ,ChevronsDownUp:WQ,ChevronsLeft:QQ,ChevronsLeftRight:ZQ,ChevronsLeftRightEllipsis:YQ,ChevronsRight:JQ,ChevronsRightLeft:XQ,ChevronsUp:eX,ChevronsUpDown:Hg,Chrome:kA,Church:tX,Cigarette:nX,CigaretteOff:sX,Circle:dm,CircleAlert:Gi,CircleArrowDown:J3,CircleArrowLeft:e5,CircleArrowOutDownLeft:t5,CircleArrowOutDownRight:s5,CircleArrowOutUpLeft:n5,CircleArrowOutUpRight:r5,CircleArrowRight:a5,CircleArrowUp:i5,CircleCheck:xr,CircleCheckBig:zi,CircleChevronDown:o5,CircleChevronLeft:l5,CircleChevronRight:c5,CircleChevronUp:d5,CircleDashed:rX,CircleDivide:u5,CircleDollarSign:aX,CircleDot:oX,CircleDotDashed:iX,CircleEllipsis:lX,CircleEqual:cX,CircleFadingArrowUp:dX,CircleFadingPlus:uX,CircleGauge:h5,CircleHelp:Y_,CircleMinus:m5,CircleOff:hX,CircleParking:f5,CircleParkingOff:p5,CirclePause:x5,CirclePercent:g5,CirclePlay:Pu,CirclePlus:y5,CirclePower:v5,CircleSlash:mX,CircleSlash2:b5,CircleStop:_5,CircleUser:j5,CircleUserRound:w5,CircleX:Gc,CircuitBoard:pX,Citrus:fX,Clapperboard:xX,Clipboard:jX,ClipboardCheck:W2,ClipboardCopy:gX,ClipboardList:Ov,ClipboardMinus:yX,ClipboardPaste:vX,ClipboardPen:k5,ClipboardPenLine:N5,ClipboardPlus:bX,ClipboardType:_X,ClipboardX:wX,Clock:gr,Clock1:NX,Clock10:kX,Clock11:SX,Clock12:CX,Clock2:TX,Clock3:e9,Clock4:EX,Clock5:AX,Clock6:MX,Clock7:IX,Clock8:PX,Clock9:LX,ClockAlert:DX,ClockArrowDown:RX,ClockArrowUp:OX,Cloud:XX,CloudAlert:FX,CloudCog:zX,CloudDownload:S5,CloudDrizzle:BX,CloudFog:$X,CloudHail:UX,CloudLightning:qX,CloudMoon:HX,CloudMoonRain:VX,CloudOff:GX,CloudRain:KX,CloudRainWind:WX,CloudSnow:YX,CloudSun:QX,CloudSunRain:ZX,CloudUpload:C5,Cloudy:JX,Clover:O2,Club:eJ,Code:SA,CodeXml:T2,Codepen:tJ,Codesandbox:sJ,Coffee:ry,Cog:nJ,Coins:t9,Columns2:T5,Columns3:Yk,Columns4:rJ,Combine:aJ,Command:iJ,Compass:sL,Component:oJ,Computer:lJ,ConciergeBell:cJ,Cone:dJ,Construction:uJ,Contact:CA,ContactRound:E5,Container:hJ,Contrast:mJ,Cookie:pJ,CookingPot:fJ,Copy:ta,CopyCheck:xJ,CopyMinus:gJ,CopyPlus:yJ,CopySlash:vJ,CopyX:bJ,Copyleft:_J,Copyright:wJ,CornerDownLeft:jJ,CornerDownRight:NJ,CornerLeftDown:kJ,CornerLeftUp:SJ,CornerRightDown:CJ,CornerRightUp:TJ,CornerUpLeft:EJ,CornerUpRight:AJ,Cpu:MJ,CreativeCommons:IJ,CreditCard:ff,Croissant:PJ,Crop:LJ,Cross:DJ,Crosshair:RJ,Crown:xf,Cuboid:OJ,CupSoda:FJ,Currency:zJ,Cylinder:BJ,Dam:$J,Database:s9,DatabaseBackup:UJ,DatabaseZap:qJ,Delete:VJ,Dessert:HJ,Diameter:GJ,Diamond:YJ,DiamondMinus:WJ,DiamondPercent:A5,DiamondPlus:KJ,Dice1:ZJ,Dice2:QJ,Dice3:XJ,Dice4:JJ,Dice5:eee,Dice6:tee,Dices:see,Diff:nee,Disc:oee,Disc2:ree,Disc3:aee,DiscAlbum:iee,Divide:lee,Dna:dee,DnaOff:cee,Dock:uee,Dog:hee,DollarSign:Zl,Donut:mee,DoorClosed:pee,DoorOpen:gw,Dot:fee,Download:Da,DraftingCompass:xee,Drama:gee,Dribbble:yee,Drill:vee,Droplet:bee,Droplets:pb,Drum:_ee,Drumstick:wee,Dumbbell:jee,Ear:kee,EarOff:Nee,Earth:M5,EarthLock:See,Eclipse:Cee,Egg:nL,EggFried:Tee,EggOff:Eee,Ellipsis:Xf,EllipsisVertical:Lg,Equal:Iee,EqualApproximately:Aee,EqualNot:Mee,Eraser:Pee,EthernetPort:Lee,Euro:Dee,Expand:Ree,ExternalLink:tr,Eye:Ir,EyeClosed:Oee,EyeOff:gf,Facebook:Oh,Factory:Fee,Fan:zee,FastForward:Bee,Feather:$ee,Fence:Uee,FerrisWheel:qee,Figma:Vee,File:rL,FileArchive:Hee,FileAudio:Wee,FileAudio2:Gee,FileAxis3d:I5,FileBadge:Yee,FileBadge2:Kee,FileBox:Zee,FileChartColumn:L5,FileChartColumnIncreasing:P5,FileChartLine:D5,FileChartPie:R5,FileCheck:n9,FileCheck2:Qee,FileClock:Xee,FileCode:ete,FileCode2:Jee,FileCog:O5,FileDiff:tte,FileDigit:ste,FileDown:TA,FileHeart:nte,FileImage:K2,FileInput:rte,FileJson:ite,FileJson2:ate,FileKey:lte,FileKey2:ote,FileLock:dte,FileLock2:cte,FileMinus:hte,FileMinus2:ute,FileMusic:mte,FileOutput:pte,FilePen:F5,FilePenLine:Zk,FilePlus:xte,FilePlus2:fte,FileQuestion:gte,FileScan:yte,FileSearch:bte,FileSearch2:vte,FileSliders:_te,FileSpreadsheet:yw,FileStack:r9,FileSymlink:wte,FileTerminal:jte,FileText:Nr,FileType:kte,FileType2:Nte,FileUp:Ste,FileUser:Cte,FileVideo:a9,FileVideo2:Tte,FileVolume:Ate,FileVolume2:Ete,FileWarning:Mte,FileX:Pte,FileX2:Ite,Files:Lte,Film:Ph,Filter:Fv,FilterX:Dte,Fingerprint:Rte,FireExtinguisher:Ote,Fish:Bte,FishOff:Fte,FishSymbol:zte,Flag:Y2,FlagOff:$te,FlagTriangleLeft:Ute,FlagTriangleRight:qte,Flame:_c,FlameKindling:Vte,Flashlight:Gte,FlashlightOff:Hte,FlaskConical:XS,FlaskConicalOff:Wte,FlaskRound:Kte,FlipHorizontal:i9,FlipHorizontal2:Yte,FlipVertical:Qte,FlipVertical2:Zte,Flower:Xte,Flower2:lb,Focus:Jte,FoldHorizontal:ese,FoldVertical:tse,Folder:Tse,FolderArchive:sse,FolderCheck:nse,FolderClock:rse,FolderClosed:ase,FolderCode:ise,FolderCog:z5,FolderDot:ose,FolderDown:lse,FolderGit:dse,FolderGit2:cse,FolderHeart:use,FolderInput:hse,FolderKanban:mse,FolderKey:pse,FolderLock:fse,FolderMinus:xse,FolderOpen:yf,FolderOpenDot:gse,FolderOutput:yse,FolderPen:B5,FolderPlus:vse,FolderRoot:bse,FolderSearch:wse,FolderSearch2:_se,FolderSymlink:jse,FolderSync:Nse,FolderTree:kse,FolderUp:Sse,FolderX:Cse,Folders:Ese,Footprints:Ase,Forklift:Mse,Forward:Ise,Frame:Pse,Framer:Lse,Frown:Dse,Fuel:Rse,Fullscreen:Ose,GalleryHorizontal:zse,GalleryHorizontalEnd:Fse,GalleryThumbnails:Bse,GalleryVertical:Use,GalleryVerticalEnd:$se,Gamepad:Vse,Gamepad2:qse,Gauge:Hse,Gavel:Gse,Gem:Wse,Ghost:EA,Gift:Bi,GitBranch:Yse,GitBranchPlus:Kse,GitCommitHorizontal:$5,GitCommitVertical:Zse,GitCompare:Xse,GitCompareArrows:Qse,GitFork:Jse,GitGraph:ene,GitMerge:tne,GitPullRequest:one,GitPullRequestArrow:sne,GitPullRequestClosed:nne,GitPullRequestCreate:ane,GitPullRequestCreateArrow:rne,GitPullRequestDraft:ine,Github:lne,Gitlab:cne,GlassWater:dne,Glasses:une,Globe:lc,GlobeLock:hne,Goal:mne,Grab:pne,GraduationCap:_d,Grape:fne,Grid2x2:q5,Grid2x2Check:xne,Grid2x2Plus:U5,Grid2x2X:gne,Grid3x3:xv,Grip:vne,GripHorizontal:yne,GripVertical:Uu,Group:bne,Guitar:_ne,Ham:wne,Hammer:o9,Hand:l9,HandCoins:jne,HandHeart:AA,HandHelping:sb,HandMetal:Nne,HandPlatter:kne,Handshake:fb,HardDrive:c9,HardDriveDownload:Sne,HardDriveUpload:Cne,HardHat:Tne,Hash:JS,Haze:Ene,HdmiPort:Ane,Heading:Lne,Heading1:aL,Heading2:iL,Heading3:d9,Heading4:Mne,Heading5:Ine,Heading6:Pne,HeadphoneOff:Dne,Headphones:Rne,Headset:One,Heart:yi,HeartCrack:Fne,HeartHandshake:MA,HeartOff:zne,HeartPulse:Bne,Heater:$ne,Hexagon:Une,Highlighter:qne,History:IA,Hop:Hne,HopOff:Vne,Hospital:Gne,Hotel:Wne,Hourglass:Kne,House:zr,HousePlug:Yne,HousePlus:Zne,IceCreamBowl:V5,IceCreamCone:H5,IdCard:Qne,Image:nl,ImageDown:Xne,ImageMinus:Jne,ImageOff:ere,ImagePlay:tre,ImagePlus:ay,ImageUp:sre,ImageUpscale:nre,Images:rre,Import:are,Inbox:Z2,IndentDecrease:G5,IndentIncrease:W5,IndianRupee:ire,Infinity:ore,Info:vw,InspectionPanel:lre,Instagram:mu,Italic:e4,IterationCcw:cre,IterationCw:dre,JapaneseYen:ure,Joystick:hre,Kanban:Q2,Key:Gg,KeyRound:PA,KeySquare:mre,Keyboard:xre,KeyboardMusic:pre,KeyboardOff:fre,Lamp:wre,LampCeiling:gre,LampDesk:yre,LampFloor:vre,LampWallDown:bre,LampWallUp:_re,LandPlot:jre,Landmark:Nre,Languages:kre,Laptop:Cre,LaptopMinimal:K5,LaptopMinimalCheck:Sre,Lasso:Ere,LassoSelect:Tre,Laugh:Are,Layers:u9,Layers2:Mre,Layers3:Ire,LayoutDashboard:t4,LayoutGrid:vf,LayoutList:Pre,LayoutPanelLeft:Lre,LayoutPanelTop:Dre,LayoutTemplate:s4,Leaf:Rre,LeafyGreen:Ore,Lectern:Fre,LetterText:zre,Library:Wg,LibraryBig:Bre,LifeBuoy:oL,Ligature:$re,Lightbulb:bw,LightbulbOff:Ure,Link:tl,Link2:El,Link2Off:qre,Linkedin:bf,List:Ep,ListCheck:Vre,ListChecks:pu,ListCollapse:Hre,ListEnd:Gre,ListFilter:h9,ListMinus:Wre,ListMusic:Kre,ListOrdered:zv,ListPlus:Yre,ListRestart:Zre,ListStart:Qre,ListTodo:Xre,ListTree:Jre,ListVideo:eae,ListX:tae,Loader:nae,LoaderCircle:ss,LoaderPinwheel:sae,Locate:lL,LocateFixed:rae,LocateOff:aae,Lock:Rc,LockKeyhole:iae,LockKeyholeOpen:Y5,LockOpen:Z5,LogIn:LA,LogOut:DA,Logs:oae,Lollipop:lae,Luggage:cae,Magnet:dae,Mail:Hs,MailCheck:cL,MailMinus:uae,MailOpen:dL,MailPlus:m9,MailQuestion:hae,MailSearch:mae,MailWarning:pae,MailX:uL,Mailbox:fae,Mails:xae,Map:RA,MapPin:Ca,MapPinCheck:yae,MapPinCheckInside:gae,MapPinHouse:vae,MapPinMinus:_ae,MapPinMinusInside:bae,MapPinOff:wae,MapPinPlus:Nae,MapPinPlusInside:jae,MapPinX:Sae,MapPinXInside:kae,MapPinned:Cae,Martini:Tae,Maximize:OA,Maximize2:p9,Medal:X2,Megaphone:qd,MegaphoneOff:Eae,Meh:Aae,MemoryStick:Mae,Menu:n4,Merge:Iae,MessageCircle:Ql,MessageCircleCode:Pae,MessageCircleDashed:Lae,MessageCircleHeart:hL,MessageCircleMore:Dae,MessageCircleOff:Rae,MessageCirclePlus:Oae,MessageCircleQuestion:f9,MessageCircleReply:Fae,MessageCircleWarning:zae,MessageCircleX:Bae,MessageSquare:Ci,MessageSquareCode:$ae,MessageSquareDashed:Uae,MessageSquareDiff:qae,MessageSquareDot:Vae,MessageSquareHeart:mL,MessageSquareLock:Hae,MessageSquareMore:x9,MessageSquareOff:Gae,MessageSquarePlus:rw,MessageSquareQuote:_w,MessageSquareReply:Wae,MessageSquareShare:Kae,MessageSquareText:Yae,MessageSquareWarning:Zae,MessageSquareX:Qae,MessagesSquare:pL,Mic:Bv,MicOff:Xae,MicVocal:Q5,Microchip:Jae,Microscope:eie,Microwave:tie,Milestone:sie,Milk:rie,MilkOff:nie,Minimize:iie,Minimize2:aie,Minus:xb,Monitor:gb,MonitorCheck:oie,MonitorCog:lie,MonitorDot:cie,MonitorDown:die,MonitorOff:uie,MonitorPause:hie,MonitorPlay:fL,MonitorSmartphone:mie,MonitorSpeaker:pie,MonitorStop:fie,MonitorUp:FA,MonitorX:xie,Moon:yie,MoonStar:gie,Mountain:bie,MountainSnow:vie,Mouse:Nie,MouseOff:_ie,MousePointer:Fm,MousePointer2:wie,MousePointerBan:jie,MousePointerClick:oc,Move:Oie,Move3d:X5,MoveDiagonal:Sie,MoveDiagonal2:kie,MoveDown:Eie,MoveDownLeft:Cie,MoveDownRight:Tie,MoveHorizontal:Aie,MoveLeft:Mie,MoveRight:Iie,MoveUp:Die,MoveUpLeft:Pie,MoveUpRight:Lie,MoveVertical:Rie,Music:xL,Music2:Fie,Music3:zie,Music4:Bie,Navigation:g9,Navigation2:Uie,Navigation2Off:$ie,NavigationOff:qie,Network:Vie,Newspaper:iy,Nfc:Hie,Notebook:Yie,NotebookPen:Gie,NotebookTabs:Wie,NotebookText:Kie,NotepadText:Qie,NotepadTextDashed:Zie,Nut:Jie,NutOff:Xie,Octagon:toe,OctagonAlert:Z_,OctagonMinus:eoe,OctagonPause:J5,OctagonX:eT,Omega:soe,Option:noe,Orbit:roe,Origami:aoe,Package:Oc,Package2:ioe,PackageCheck:ooe,PackageMinus:loe,PackageOpen:coe,PackagePlus:y9,PackageSearch:doe,PackageX:uoe,PaintBucket:hoe,PaintRoller:moe,Paintbrush:poe,PaintbrushVertical:tT,Palette:xl,PanelBottom:goe,PanelBottomClose:foe,PanelBottomDashed:sT,PanelBottomOpen:xoe,PanelLeft:iT,PanelLeftClose:nT,PanelLeftDashed:rT,PanelLeftOpen:aT,PanelRight:boe,PanelRightClose:yoe,PanelRightDashed:oT,PanelRightOpen:voe,PanelTop:joe,PanelTopClose:_oe,PanelTopDashed:lT,PanelTopOpen:woe,PanelsLeftBottom:Noe,PanelsRightBottom:koe,PanelsTopLeft:E2,Paperclip:r4,Parentheses:Soe,ParkingMeter:Coe,PartyPopper:uh,Pause:_f,PawPrint:Toe,PcCase:Eoe,Pen:Nv,PenLine:nb,PenOff:Aoe,PenTool:a4,Pencil:ja,PencilLine:gL,PencilOff:Moe,PencilRuler:Ioe,Pentagon:Poe,Percent:i4,PersonStanding:Loe,PhilippinePeso:Doe,Phone:Pr,PhoneCall:v9,PhoneForwarded:Roe,PhoneIncoming:Ooe,PhoneMissed:Foe,PhoneOff:zoe,PhoneOutgoing:Boe,Pi:$oe,Piano:Uoe,Pickaxe:qoe,PictureInPicture:Hoe,PictureInPicture2:Voe,PiggyBank:Goe,Pilcrow:Yoe,PilcrowLeft:Woe,PilcrowRight:Koe,Pill:Qoe,PillBottle:Zoe,Pin:o4,PinOff:b9,Pipette:Xoe,Pizza:Joe,Plane:_9,PlaneLanding:ele,PlaneTakeoff:tle,Play:Al,Plug:J2,Plug2:sle,PlugZap:cT,Plus:As,Pocket:rle,PocketKnife:nle,Podcast:ale,Pointer:ole,PointerOff:ile,Popcorn:lle,Popsicle:cle,PoundSterling:dle,Power:w9,PowerOff:ule,Presentation:oy,Printer:j9,PrinterCheck:hle,Projector:mle,Proportions:ple,Puzzle:fle,Pyramid:xle,QrCode:ly,Quote:yb,Rabbit:gle,Radar:zA,Radiation:yle,Radical:vle,Radio:wf,RadioReceiver:ble,RadioTower:_le,Radius:wle,RailSymbol:jle,Rainbow:Nle,Rat:kle,Ratio:Sle,Receipt:Dle,ReceiptCent:Cle,ReceiptEuro:Tle,ReceiptIndianRupee:Ele,ReceiptJapaneseYen:Ale,ReceiptPoundSterling:Mle,ReceiptRussianRuble:Ile,ReceiptSwissFranc:Ple,ReceiptText:Lle,RectangleEllipsis:dT,RectangleHorizontal:Rle,RectangleVertical:Ole,Recycle:Fle,Redo:l4,Redo2:zle,RedoDot:Ble,RefreshCcw:yL,RefreshCcwDot:$le,RefreshCw:Ai,RefreshCwOff:Ule,Refrigerator:qle,Regex:Vle,RemoveFormatting:Hle,Repeat:vL,Repeat1:Gle,Repeat2:Wle,Replace:Yle,ReplaceAll:Kle,Reply:N9,ReplyAll:Zle,Rewind:Qle,Ribbon:Xle,Rocket:nx,RockingChair:Jle,RollerCoaster:ece,Rotate3d:uT,RotateCcw:Fh,RotateCcwSquare:tce,RotateCw:BA,RotateCwSquare:sce,Route:k9,RouteOff:nce,Router:rce,Rows2:hT,Rows3:mT,Rows4:ace,Rss:ice,Ruler:eN,RussianRuble:oce,Sailboat:lce,Salad:cce,Sandwich:dce,Satellite:hce,SatelliteDish:uce,Save:Ho,SaveAll:mce,SaveOff:pce,Scale:S9,Scale3d:pT,Scaling:fce,Scan:jce,ScanBarcode:xce,ScanEye:gce,ScanFace:yce,ScanLine:vce,ScanQrCode:bce,ScanSearch:_ce,ScanText:wce,School:Nce,Scissors:Sce,ScissorsLineDashed:kce,ScreenShare:Tce,ScreenShareOff:Cce,Scroll:Ece,ScrollText:C9,Search:_r,SearchCheck:Ace,SearchCode:Mce,SearchSlash:Ice,SearchX:T9,Section:Pce,Send:cr,SendHorizontal:fT,SendToBack:Lce,SeparatorHorizontal:Dce,SeparatorVertical:Rce,Server:Bce,ServerCog:Oce,ServerCrash:Fce,ServerOff:zce,Settings:Vo,Settings2:E9,Shapes:$ce,Share:A9,Share2:Hl,Sheet:Uce,Shell:qce,Shield:hh,ShieldAlert:bL,ShieldBan:Vce,ShieldCheck:ng,ShieldEllipsis:Hce,ShieldHalf:Gce,ShieldMinus:Wce,ShieldOff:$A,ShieldPlus:Kce,ShieldQuestion:Yce,ShieldX:xT,Ship:Qce,ShipWheel:Zce,Shirt:Xce,ShoppingBag:ww,ShoppingBasket:Jce,ShoppingCart:zg,Shovel:ede,ShowerHead:tde,Shrink:sde,Shrub:nde,Shuffle:UA,Sigma:rde,Signal:cde,SignalHigh:ade,SignalLow:ide,SignalMedium:ode,SignalZero:lde,Signature:dde,Signpost:hde,SignpostBig:ude,Siren:mde,SkipBack:pde,SkipForward:fde,Skull:xde,Slack:gde,Slash:yde,Slice:vde,SlidersHorizontal:c4,SlidersVertical:gT,Smartphone:rg,SmartphoneCharging:bde,SmartphoneNfc:_de,Smile:jde,SmilePlus:wde,Snail:Nde,Snowflake:Mv,Sofa:kde,Soup:Sde,Space:Cde,Spade:Tde,Sparkle:tN,Sparkles:un,Speaker:Ede,Speech:Ade,SpellCheck:Ide,SpellCheck2:Mde,Spline:Pde,Split:Lde,SprayCan:Dde,Sprout:qA,Square:cy,SquareActivity:yT,SquareArrowDown:_T,SquareArrowDownLeft:vT,SquareArrowDownRight:bT,SquareArrowLeft:wT,SquareArrowOutDownLeft:jT,SquareArrowOutDownRight:NT,SquareArrowOutUpLeft:kT,SquareArrowOutUpRight:ST,SquareArrowRight:CT,SquareArrowUp:AT,SquareArrowUpLeft:TT,SquareArrowUpRight:ET,SquareAsterisk:MT,SquareBottomDashedScissors:IT,SquareChartGantt:D_,SquareCheck:PT,SquareCheckBig:A2,SquareChevronDown:LT,SquareChevronLeft:DT,SquareChevronRight:RT,SquareChevronUp:OT,SquareCode:FT,SquareDashed:$T,SquareDashedBottom:Ode,SquareDashedBottomCode:Rde,SquareDashedKanban:zT,SquareDashedMousePointer:BT,SquareDivide:UT,SquareDot:qT,SquareEqual:VT,SquareFunction:HT,SquareKanban:GT,SquareLibrary:WT,SquareM:KT,SquareMenu:YT,SquareMinus:ZT,SquareMousePointer:QT,SquareParking:JT,SquareParkingOff:XT,SquarePen:Tu,SquarePercent:eE,SquarePi:tE,SquarePilcrow:sE,SquarePlay:nE,SquarePlus:rE,SquarePower:aE,SquareRadical:Fde,SquareScissors:iE,SquareSigma:oE,SquareSlash:lE,SquareSplitHorizontal:cE,SquareSplitVertical:dE,SquareSquare:zde,SquareStack:Bde,SquareTerminal:uE,SquareUser:mE,SquareUserRound:hE,SquareX:pE,Squircle:$de,Squirrel:Ude,Stamp:qde,Star:ua,StarHalf:Vde,StarOff:Hde,StepBack:Gde,StepForward:Wde,Stethoscope:Kde,Sticker:Yde,StickyNote:M9,Store:I9,StretchHorizontal:Zde,StretchVertical:Qde,Strikethrough:P9,Subscript:Xde,Sun:vb,SunDim:Jde,SunMedium:eue,SunMoon:tue,SunSnow:sue,Sunrise:nue,Sunset:rue,Superscript:aue,SwatchBook:iue,SwissFranc:oue,SwitchCamera:lue,Sword:cue,Swords:due,Syringe:uue,Table:wL,Table2:_L,TableCellsMerge:hue,TableCellsSplit:mue,TableColumnsSplit:pue,TableOfContents:fue,TableProperties:xue,TableRowsSplit:gue,Tablet:jL,TabletSmartphone:yue,Tablets:vue,Tag:mh,Tags:L9,Tally1:bue,Tally2:_ue,Tally3:wue,Tally4:jue,Tally5:Nue,Tangent:kue,Target:wc,Telescope:Sue,Tent:Tue,TentTree:Cue,Terminal:Eue,TestTube:Aue,TestTubeDiagonal:fE,TestTubes:Mue,Text:Rue,TextCursor:Pue,TextCursorInput:Iue,TextQuote:Lue,TextSearch:Due,TextSelect:xE,Theater:Oue,Thermometer:D9,ThermometerSnowflake:Fue,ThermometerSun:zue,ThumbsDown:R9,ThumbsUp:Hm,Ticket:O9,TicketCheck:Bue,TicketMinus:$ue,TicketPercent:Uue,TicketPlus:que,TicketSlash:Vue,TicketX:Hue,Tickets:Wue,TicketsPlane:Gue,Timer:Zue,TimerOff:Kue,TimerReset:Yue,ToggleLeft:Que,ToggleRight:Xue,Toilet:Jue,Tornado:ehe,Torus:the,Touchpad:nhe,TouchpadOff:she,TowerControl:rhe,ToyBrick:ahe,Tractor:ihe,TrafficCone:ohe,TrainFront:che,TrainFrontTunnel:lhe,TrainTrack:dhe,TramFront:gE,Trash:uhe,Trash2:bn,TreeDeciduous:hhe,TreePalm:yE,TreePine:d4,Trees:mhe,Trello:phe,TrendingDown:bb,TrendingUp:mo,TrendingUpDown:fhe,Triangle:ghe,TriangleAlert:Dl,TriangleRight:xhe,Trophy:vo,Truck:F9,Turtle:yhe,Tv:bhe,TvMinimal:vE,TvMinimalPlay:vhe,Twitch:_he,Twitter:whe,Type:Nhe,TypeOutline:jhe,Umbrella:She,UmbrellaOff:khe,Underline:NL,Undo:u4,Undo2:z9,UndoDot:Che,UnfoldHorizontal:The,UnfoldVertical:Ehe,Ungroup:Ahe,University:bE,Unlink:VA,Unlink2:Mhe,Unplug:Ihe,Upload:Sa,Usb:Phe,User:Xi,UserCheck:_b,UserCog:B9,UserMinus:$9,UserPen:Lhe,UserPlus:Fo,UserRound:SE,UserRoundCheck:_E,UserRoundCog:wE,UserRoundMinus:jE,UserRoundPen:Dhe,UserRoundPlus:NE,UserRoundSearch:Rhe,UserRoundX:kE,UserSearch:Ohe,UserX:Fhe,Users:_n,UsersRound:W0,Utensils:TE,UtensilsCrossed:CE,UtilityPole:zhe,Variable:kL,Vault:Bhe,Vegan:$he,VenetianMask:Uhe,Vibrate:Vhe,VibrateOff:qhe,Video:vr,VideoOff:Hhe,Videotape:Ghe,View:Whe,Voicemail:Khe,Volleyball:Yhe,Volume:Xhe,Volume1:Zhe,Volume2:U9,VolumeOff:Qhe,VolumeX:q9,Vote:Jhe,Wallet:SL,WalletCards:eme,WalletMinimal:EE,Wallpaper:tme,Wand:sme,WandSparkles:Rm,Warehouse:nme,WashingMachine:rme,Watch:ame,Waves:ime,Waypoints:ome,Webcam:lme,Webhook:dme,WebhookOff:cme,Weight:ume,Wheat:mme,WheatOff:hme,WholeWord:pme,Wifi:vme,WifiHigh:fme,WifiLow:xme,WifiOff:gme,WifiZero:yme,Wind:_me,WindArrowDown:bme,Wine:V9,WineOff:wme,Workflow:H9,Worm:jme,WrapText:Nme,Wrench:wb,X:Fn,Youtube:kme,Zap:ph,ZapOff:Sme,ZoomIn:h4,ZoomOut:CL},Symbol.toStringTag,{value:"Module"}));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M0e=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:EW,AArrowDownIcon:EW,AArrowUp:AW,AArrowUpIcon:AW,ALargeSmall:MW,ALargeSmallIcon:MW,Accessibility:IW,AccessibilityIcon:IW,Activity:am,ActivityIcon:am,ActivitySquare:yT,ActivitySquareIcon:yT,AirVent:PW,AirVentIcon:PW,Airplay:LW,AirplayIcon:LW,AlarmCheck:k3,AlarmCheckIcon:k3,AlarmClock:RW,AlarmClockCheck:k3,AlarmClockCheckIcon:k3,AlarmClockIcon:RW,AlarmClockMinus:S3,AlarmClockMinusIcon:S3,AlarmClockOff:DW,AlarmClockOffIcon:DW,AlarmClockPlus:C3,AlarmClockPlusIcon:C3,AlarmMinus:S3,AlarmMinusIcon:S3,AlarmPlus:C3,AlarmPlusIcon:C3,AlarmSmoke:OW,AlarmSmokeIcon:OW,Album:FW,AlbumIcon:FW,AlertCircle:Gi,AlertCircleIcon:Gi,AlertOctagon:Z_,AlertOctagonIcon:Z_,AlertTriangle:Dl,AlertTriangleIcon:Dl,AlignCenter:_A,AlignCenterHorizontal:zW,AlignCenterHorizontalIcon:zW,AlignCenterIcon:_A,AlignCenterVertical:BW,AlignCenterVerticalIcon:BW,AlignEndHorizontal:$W,AlignEndHorizontalIcon:$W,AlignEndVertical:UW,AlignEndVerticalIcon:UW,AlignHorizontalDistributeCenter:qW,AlignHorizontalDistributeCenterIcon:qW,AlignHorizontalDistributeEnd:VW,AlignHorizontalDistributeEndIcon:VW,AlignHorizontalDistributeStart:HW,AlignHorizontalDistributeStartIcon:HW,AlignHorizontalJustifyCenter:GW,AlignHorizontalJustifyCenterIcon:GW,AlignHorizontalJustifyEnd:WW,AlignHorizontalJustifyEndIcon:WW,AlignHorizontalJustifyStart:KW,AlignHorizontalJustifyStartIcon:KW,AlignHorizontalSpaceAround:YW,AlignHorizontalSpaceAroundIcon:YW,AlignHorizontalSpaceBetween:ZW,AlignHorizontalSpaceBetweenIcon:ZW,AlignJustify:QW,AlignJustifyIcon:QW,AlignLeft:wA,AlignLeftIcon:wA,AlignRight:jA,AlignRightIcon:jA,AlignStartHorizontal:XW,AlignStartHorizontalIcon:XW,AlignStartVertical:JW,AlignStartVerticalIcon:JW,AlignVerticalDistributeCenter:eK,AlignVerticalDistributeCenterIcon:eK,AlignVerticalDistributeEnd:tK,AlignVerticalDistributeEndIcon:tK,AlignVerticalDistributeStart:sK,AlignVerticalDistributeStartIcon:sK,AlignVerticalJustifyCenter:nK,AlignVerticalJustifyCenterIcon:nK,AlignVerticalJustifyEnd:rK,AlignVerticalJustifyEndIcon:rK,AlignVerticalJustifyStart:aK,AlignVerticalJustifyStartIcon:aK,AlignVerticalSpaceAround:iK,AlignVerticalSpaceAroundIcon:iK,AlignVerticalSpaceBetween:oK,AlignVerticalSpaceBetweenIcon:oK,Ambulance:lK,AmbulanceIcon:lK,Ampersand:cK,AmpersandIcon:cK,Ampersands:dK,AmpersandsIcon:dK,Amphora:uK,AmphoraIcon:uK,Anchor:hK,AnchorIcon:hK,Angry:mK,AngryIcon:mK,Annoyed:pK,AnnoyedIcon:pK,Antenna:fK,AntennaIcon:fK,Anvil:xK,AnvilIcon:xK,Aperture:gK,ApertureIcon:gK,AppWindow:vK,AppWindowIcon:vK,AppWindowMac:yK,AppWindowMacIcon:yK,Apple:bK,AppleIcon:bK,Archive:im,ArchiveIcon:im,ArchiveRestore:XP,ArchiveRestoreIcon:XP,ArchiveX:_K,ArchiveXIcon:_K,AreaChart:$3,AreaChartIcon:$3,Armchair:wK,ArmchairIcon:wK,ArrowBigDown:NK,ArrowBigDownDash:jK,ArrowBigDownDashIcon:jK,ArrowBigDownIcon:NK,ArrowBigLeft:SK,ArrowBigLeftDash:kK,ArrowBigLeftDashIcon:kK,ArrowBigLeftIcon:SK,ArrowBigRight:TK,ArrowBigRightDash:CK,ArrowBigRightDashIcon:CK,ArrowBigRightIcon:TK,ArrowBigUp:AK,ArrowBigUpDash:EK,ArrowBigUpDashIcon:EK,ArrowBigUpIcon:AK,ArrowDown:om,ArrowDown01:MK,ArrowDown01Icon:MK,ArrowDown10:IK,ArrowDown10Icon:IK,ArrowDownAZ:T3,ArrowDownAZIcon:T3,ArrowDownAz:T3,ArrowDownAzIcon:T3,ArrowDownCircle:J3,ArrowDownCircleIcon:J3,ArrowDownFromLine:PK,ArrowDownFromLineIcon:PK,ArrowDownIcon:om,ArrowDownLeft:LK,ArrowDownLeftFromCircle:t5,ArrowDownLeftFromCircleIcon:t5,ArrowDownLeftFromSquare:jT,ArrowDownLeftFromSquareIcon:jT,ArrowDownLeftIcon:LK,ArrowDownLeftSquare:vT,ArrowDownLeftSquareIcon:vT,ArrowDownNarrowWide:DK,ArrowDownNarrowWideIcon:DK,ArrowDownRight:W7,ArrowDownRightFromCircle:s5,ArrowDownRightFromCircleIcon:s5,ArrowDownRightFromSquare:NT,ArrowDownRightFromSquareIcon:NT,ArrowDownRightIcon:W7,ArrowDownRightSquare:bT,ArrowDownRightSquareIcon:bT,ArrowDownSquare:_T,ArrowDownSquareIcon:_T,ArrowDownToDot:RK,ArrowDownToDotIcon:RK,ArrowDownToLine:OK,ArrowDownToLineIcon:OK,ArrowDownUp:FK,ArrowDownUpIcon:FK,ArrowDownWideNarrow:E3,ArrowDownWideNarrowIcon:E3,ArrowDownZA:A3,ArrowDownZAIcon:A3,ArrowDownZa:A3,ArrowDownZaIcon:A3,ArrowLeft:Wr,ArrowLeftCircle:e5,ArrowLeftCircleIcon:e5,ArrowLeftFromLine:zK,ArrowLeftFromLineIcon:zK,ArrowLeftIcon:Wr,ArrowLeftRight:BK,ArrowLeftRightIcon:BK,ArrowLeftSquare:wT,ArrowLeftSquareIcon:wT,ArrowLeftToLine:$K,ArrowLeftToLineIcon:$K,ArrowRight:za,ArrowRightCircle:a5,ArrowRightCircleIcon:a5,ArrowRightFromLine:UK,ArrowRightFromLineIcon:UK,ArrowRightIcon:za,ArrowRightLeft:pw,ArrowRightLeftIcon:pw,ArrowRightSquare:CT,ArrowRightSquareIcon:CT,ArrowRightToLine:qK,ArrowRightToLineIcon:qK,ArrowUp:Bu,ArrowUp01:VK,ArrowUp01Icon:VK,ArrowUp10:HK,ArrowUp10Icon:HK,ArrowUpAZ:M3,ArrowUpAZIcon:M3,ArrowUpAz:M3,ArrowUpAzIcon:M3,ArrowUpCircle:i5,ArrowUpCircleIcon:i5,ArrowUpDown:sm,ArrowUpDownIcon:sm,ArrowUpFromDot:GK,ArrowUpFromDotIcon:GK,ArrowUpFromLine:WK,ArrowUpFromLineIcon:WK,ArrowUpIcon:Bu,ArrowUpLeft:KK,ArrowUpLeftFromCircle:n5,ArrowUpLeftFromCircleIcon:n5,ArrowUpLeftFromSquare:kT,ArrowUpLeftFromSquareIcon:kT,ArrowUpLeftIcon:KK,ArrowUpLeftSquare:TT,ArrowUpLeftSquareIcon:TT,ArrowUpNarrowWide:I3,ArrowUpNarrowWideIcon:I3,ArrowUpRight:JP,ArrowUpRightFromCircle:r5,ArrowUpRightFromCircleIcon:r5,ArrowUpRightFromSquare:ST,ArrowUpRightFromSquareIcon:ST,ArrowUpRightIcon:JP,ArrowUpRightSquare:ET,ArrowUpRightSquareIcon:ET,ArrowUpSquare:AT,ArrowUpSquareIcon:AT,ArrowUpToLine:YK,ArrowUpToLineIcon:YK,ArrowUpWideNarrow:ZK,ArrowUpWideNarrowIcon:ZK,ArrowUpZA:P3,ArrowUpZAIcon:P3,ArrowUpZa:P3,ArrowUpZaIcon:P3,ArrowsUpFromLine:QK,ArrowsUpFromLineIcon:QK,Asterisk:XK,AsteriskIcon:XK,AsteriskSquare:MT,AsteriskSquareIcon:MT,AtSign:JK,AtSignIcon:JK,Atom:eY,AtomIcon:eY,AudioLines:tY,AudioLinesIcon:tY,AudioWaveform:sY,AudioWaveformIcon:sY,Award:vc,AwardIcon:vc,Axe:nY,AxeIcon:nY,Axis3D:L3,Axis3DIcon:L3,Axis3d:L3,Axis3dIcon:L3,Baby:rY,BabyIcon:rY,Backpack:aY,BackpackIcon:aY,Badge:_Y,BadgeAlert:iY,BadgeAlertIcon:iY,BadgeCent:oY,BadgeCentIcon:oY,BadgeCheck:D3,BadgeCheckIcon:D3,BadgeDollarSign:lY,BadgeDollarSignIcon:lY,BadgeEuro:cY,BadgeEuroIcon:cY,BadgeHelp:dY,BadgeHelpIcon:dY,BadgeIcon:_Y,BadgeIndianRupee:uY,BadgeIndianRupeeIcon:uY,BadgeInfo:hY,BadgeInfoIcon:hY,BadgeJapaneseYen:mY,BadgeJapaneseYenIcon:mY,BadgeMinus:pY,BadgeMinusIcon:pY,BadgePercent:fY,BadgePercentIcon:fY,BadgePlus:xY,BadgePlusIcon:xY,BadgePoundSterling:gY,BadgePoundSterlingIcon:gY,BadgeRussianRuble:yY,BadgeRussianRubleIcon:yY,BadgeSwissFranc:vY,BadgeSwissFrancIcon:vY,BadgeX:bY,BadgeXIcon:bY,BaggageClaim:wY,BaggageClaimIcon:wY,Ban:eL,BanIcon:eL,Banana:jY,BananaIcon:jY,Bandage:NY,BandageIcon:NY,Banknote:kY,BanknoteIcon:kY,BarChart:K3,BarChart2:Y3,BarChart2Icon:Y3,BarChart3:yo,BarChart3Icon:yo,BarChart4:G3,BarChart4Icon:G3,BarChartBig:H3,BarChartBigIcon:H3,BarChartHorizontal:q3,BarChartHorizontalBig:U3,BarChartHorizontalBigIcon:U3,BarChartHorizontalIcon:q3,BarChartIcon:K3,Barcode:SY,BarcodeIcon:SY,Baseline:CY,BaselineIcon:CY,Bath:Tp,BathIcon:Tp,Battery:PY,BatteryCharging:TY,BatteryChargingIcon:TY,BatteryFull:EY,BatteryFullIcon:EY,BatteryIcon:PY,BatteryLow:AY,BatteryLowIcon:AY,BatteryMedium:MY,BatteryMediumIcon:MY,BatteryWarning:IY,BatteryWarningIcon:IY,Beaker:K7,BeakerIcon:K7,Bean:DY,BeanIcon:DY,BeanOff:LY,BeanOffIcon:LY,Bed:ny,BedDouble:G2,BedDoubleIcon:G2,BedIcon:ny,BedSingle:RY,BedSingleIcon:RY,Beef:OY,BeefIcon:OY,Beer:zY,BeerIcon:zY,BeerOff:FY,BeerOffIcon:FY,Bell:lm,BellDot:BY,BellDotIcon:BY,BellElectric:$Y,BellElectricIcon:$Y,BellIcon:lm,BellMinus:UY,BellMinusIcon:UY,BellOff:fw,BellOffIcon:fw,BellPlus:qY,BellPlusIcon:qY,BellRing:KS,BellRingIcon:KS,BetweenHorizonalEnd:R3,BetweenHorizonalEndIcon:R3,BetweenHorizonalStart:O3,BetweenHorizonalStartIcon:O3,BetweenHorizontalEnd:R3,BetweenHorizontalEndIcon:R3,BetweenHorizontalStart:O3,BetweenHorizontalStartIcon:O3,BetweenVerticalEnd:VY,BetweenVerticalEndIcon:VY,BetweenVerticalStart:HY,BetweenVerticalStartIcon:HY,BicepsFlexed:GY,BicepsFlexedIcon:GY,Bike:WY,BikeIcon:WY,Binary:KY,BinaryIcon:KY,Binoculars:YY,BinocularsIcon:YY,Biohazard:ZY,BiohazardIcon:ZY,Bird:QY,BirdIcon:QY,Bitcoin:XY,BitcoinIcon:XY,Blend:JY,BlendIcon:JY,Blinds:eZ,BlindsIcon:eZ,Blocks:tZ,BlocksIcon:tZ,Bluetooth:aZ,BluetoothConnected:sZ,BluetoothConnectedIcon:sZ,BluetoothIcon:aZ,BluetoothOff:nZ,BluetoothOffIcon:nZ,BluetoothSearching:rZ,BluetoothSearchingIcon:rZ,Bold:YS,BoldIcon:YS,Bolt:iZ,BoltIcon:iZ,Bomb:oZ,BombIcon:oZ,Bone:lZ,BoneIcon:lZ,Book:AZ,BookA:cZ,BookAIcon:cZ,BookAudio:dZ,BookAudioIcon:dZ,BookCheck:uZ,BookCheckIcon:uZ,BookCopy:hZ,BookCopyIcon:hZ,BookDashed:F3,BookDashedIcon:F3,BookDown:mZ,BookDownIcon:mZ,BookHeadphones:pZ,BookHeadphonesIcon:pZ,BookHeart:fZ,BookHeartIcon:fZ,BookIcon:AZ,BookImage:xZ,BookImageIcon:xZ,BookKey:gZ,BookKeyIcon:gZ,BookLock:yZ,BookLockIcon:yZ,BookMarked:vZ,BookMarkedIcon:vZ,BookMinus:bZ,BookMinusIcon:bZ,BookOpen:$u,BookOpenCheck:_Z,BookOpenCheckIcon:_Z,BookOpenIcon:$u,BookOpenText:wZ,BookOpenTextIcon:wZ,BookPlus:jZ,BookPlusIcon:jZ,BookTemplate:F3,BookTemplateIcon:F3,BookText:NZ,BookTextIcon:NZ,BookType:kZ,BookTypeIcon:kZ,BookUp:CZ,BookUp2:SZ,BookUp2Icon:SZ,BookUpIcon:CZ,BookUser:TZ,BookUserIcon:TZ,BookX:EZ,BookXIcon:EZ,Bookmark:Rv,BookmarkCheck:MZ,BookmarkCheckIcon:MZ,BookmarkIcon:Rv,BookmarkMinus:IZ,BookmarkMinusIcon:IZ,BookmarkPlus:tL,BookmarkPlusIcon:tL,BookmarkX:PZ,BookmarkXIcon:PZ,BoomBox:LZ,BoomBoxIcon:LZ,Bot:ZS,BotIcon:ZS,BotMessageSquare:DZ,BotMessageSquareIcon:DZ,BotOff:RZ,BotOffIcon:RZ,Box:Y7,BoxIcon:Y7,BoxSelect:$T,BoxSelectIcon:$T,Boxes:OZ,BoxesIcon:OZ,Braces:z3,BracesIcon:z3,Brackets:FZ,BracketsIcon:FZ,Brain:Z7,BrainCircuit:zZ,BrainCircuitIcon:zZ,BrainCog:BZ,BrainCogIcon:BZ,BrainIcon:Z7,BrickWall:$Z,BrickWallIcon:$Z,Briefcase:Vm,BriefcaseBusiness:UZ,BriefcaseBusinessIcon:UZ,BriefcaseConveyorBelt:qZ,BriefcaseConveyorBeltIcon:qZ,BriefcaseIcon:Vm,BriefcaseMedical:VZ,BriefcaseMedicalIcon:VZ,BringToFront:HZ,BringToFrontIcon:HZ,Brush:GZ,BrushIcon:GZ,Bug:YZ,BugIcon:YZ,BugOff:WZ,BugOffIcon:WZ,BugPlay:KZ,BugPlayIcon:KZ,Building:NA,Building2:Ga,Building2Icon:Ga,BuildingIcon:NA,Bus:QZ,BusFront:ZZ,BusFrontIcon:ZZ,BusIcon:QZ,Cable:JZ,CableCar:XZ,CableCarIcon:XZ,CableIcon:JZ,Cake:hu,CakeIcon:hu,CakeSlice:eQ,CakeSliceIcon:eQ,Calculator:xw,CalculatorIcon:xw,Calendar:yr,Calendar1:tQ,Calendar1Icon:tQ,CalendarArrowDown:sQ,CalendarArrowDownIcon:sQ,CalendarArrowUp:nQ,CalendarArrowUpIcon:nQ,CalendarCheck:QS,CalendarCheck2:rQ,CalendarCheck2Icon:rQ,CalendarCheckIcon:QS,CalendarClock:cm,CalendarClockIcon:cm,CalendarCog:aQ,CalendarCogIcon:aQ,CalendarDays:Tl,CalendarDaysIcon:Tl,CalendarFold:iQ,CalendarFoldIcon:iQ,CalendarHeart:mb,CalendarHeartIcon:mb,CalendarIcon:yr,CalendarMinus:lQ,CalendarMinus2:oQ,CalendarMinus2Icon:oQ,CalendarMinusIcon:lQ,CalendarOff:Q7,CalendarOffIcon:Q7,CalendarPlus:Fg,CalendarPlus2:cQ,CalendarPlus2Icon:cQ,CalendarPlusIcon:Fg,CalendarRange:dQ,CalendarRangeIcon:dQ,CalendarSearch:uQ,CalendarSearchIcon:uQ,CalendarSync:hQ,CalendarSyncIcon:hQ,CalendarX:X7,CalendarX2:mQ,CalendarX2Icon:mQ,CalendarXIcon:X7,Camera:pf,CameraIcon:pf,CameraOff:pQ,CameraOffIcon:pQ,CandlestickChart:V3,CandlestickChartIcon:V3,Candy:gQ,CandyCane:fQ,CandyCaneIcon:fQ,CandyIcon:gQ,CandyOff:xQ,CandyOffIcon:xQ,Cannabis:yQ,CannabisIcon:yQ,Captions:B3,CaptionsIcon:B3,CaptionsOff:vQ,CaptionsOffIcon:vQ,Car:wQ,CarFront:bQ,CarFrontIcon:bQ,CarIcon:wQ,CarTaxiFront:_Q,CarTaxiFrontIcon:_Q,Caravan:jQ,CaravanIcon:jQ,Carrot:NQ,CarrotIcon:NQ,CaseLower:kQ,CaseLowerIcon:kQ,CaseSensitive:SQ,CaseSensitiveIcon:SQ,CaseUpper:CQ,CaseUpperIcon:CQ,CassetteTape:TQ,CassetteTapeIcon:TQ,Cast:EQ,CastIcon:EQ,Castle:AQ,CastleIcon:AQ,Cat:MQ,CatIcon:MQ,Cctv:IQ,CctvIcon:IQ,ChartArea:$3,ChartAreaIcon:$3,ChartBar:q3,ChartBarBig:U3,ChartBarBigIcon:U3,ChartBarDecreasing:PQ,ChartBarDecreasingIcon:PQ,ChartBarIcon:q3,ChartBarIncreasing:LQ,ChartBarIncreasingIcon:LQ,ChartBarStacked:DQ,ChartBarStackedIcon:DQ,ChartCandlestick:V3,ChartCandlestickIcon:V3,ChartColumn:yo,ChartColumnBig:H3,ChartColumnBigIcon:H3,ChartColumnDecreasing:RQ,ChartColumnDecreasingIcon:RQ,ChartColumnIcon:yo,ChartColumnIncreasing:G3,ChartColumnIncreasingIcon:G3,ChartColumnStacked:OQ,ChartColumnStackedIcon:OQ,ChartGantt:FQ,ChartGanttIcon:FQ,ChartLine:W3,ChartLineIcon:W3,ChartNetwork:zQ,ChartNetworkIcon:zQ,ChartNoAxesColumn:Y3,ChartNoAxesColumnDecreasing:BQ,ChartNoAxesColumnDecreasingIcon:BQ,ChartNoAxesColumnIcon:Y3,ChartNoAxesColumnIncreasing:K3,ChartNoAxesColumnIncreasingIcon:K3,ChartNoAxesCombined:$Q,ChartNoAxesCombinedIcon:$Q,ChartNoAxesGantt:Z3,ChartNoAxesGanttIcon:Z3,ChartPie:Q3,ChartPieIcon:Q3,ChartScatter:X3,ChartScatterIcon:X3,ChartSpline:UQ,ChartSplineIcon:UQ,Check:Lr,CheckCheck:J7,CheckCheckIcon:J7,CheckCircle:zi,CheckCircle2:xr,CheckCircle2Icon:xr,CheckCircleIcon:zi,CheckIcon:Lr,CheckSquare:A2,CheckSquare2:PT,CheckSquare2Icon:PT,CheckSquareIcon:A2,ChefHat:qQ,ChefHatIcon:qQ,Cherry:VQ,CherryIcon:VQ,ChevronDown:io,ChevronDownCircle:o5,ChevronDownCircleIcon:o5,ChevronDownIcon:io,ChevronDownSquare:LT,ChevronDownSquareIcon:LT,ChevronFirst:HQ,ChevronFirstIcon:HQ,ChevronLast:GQ,ChevronLastIcon:GQ,ChevronLeft:fl,ChevronLeftCircle:l5,ChevronLeftCircleIcon:l5,ChevronLeftIcon:fl,ChevronLeftSquare:DT,ChevronLeftSquareIcon:DT,ChevronRight:ga,ChevronRightCircle:c5,ChevronRightCircleIcon:c5,ChevronRightIcon:ga,ChevronRightSquare:RT,ChevronRightSquareIcon:RT,ChevronUp:sx,ChevronUpCircle:d5,ChevronUpCircleIcon:d5,ChevronUpIcon:sx,ChevronUpSquare:OT,ChevronUpSquareIcon:OT,ChevronsDown:KQ,ChevronsDownIcon:KQ,ChevronsDownUp:WQ,ChevronsDownUpIcon:WQ,ChevronsLeft:QQ,ChevronsLeftIcon:QQ,ChevronsLeftRight:ZQ,ChevronsLeftRightEllipsis:YQ,ChevronsLeftRightEllipsisIcon:YQ,ChevronsLeftRightIcon:ZQ,ChevronsRight:JQ,ChevronsRightIcon:JQ,ChevronsRightLeft:XQ,ChevronsRightLeftIcon:XQ,ChevronsUp:eX,ChevronsUpDown:Hg,ChevronsUpDownIcon:Hg,ChevronsUpIcon:eX,Chrome:kA,ChromeIcon:kA,Church:tX,ChurchIcon:tX,Cigarette:nX,CigaretteIcon:nX,CigaretteOff:sX,CigaretteOffIcon:sX,Circle:dm,CircleAlert:Gi,CircleAlertIcon:Gi,CircleArrowDown:J3,CircleArrowDownIcon:J3,CircleArrowLeft:e5,CircleArrowLeftIcon:e5,CircleArrowOutDownLeft:t5,CircleArrowOutDownLeftIcon:t5,CircleArrowOutDownRight:s5,CircleArrowOutDownRightIcon:s5,CircleArrowOutUpLeft:n5,CircleArrowOutUpLeftIcon:n5,CircleArrowOutUpRight:r5,CircleArrowOutUpRightIcon:r5,CircleArrowRight:a5,CircleArrowRightIcon:a5,CircleArrowUp:i5,CircleArrowUpIcon:i5,CircleCheck:xr,CircleCheckBig:zi,CircleCheckBigIcon:zi,CircleCheckIcon:xr,CircleChevronDown:o5,CircleChevronDownIcon:o5,CircleChevronLeft:l5,CircleChevronLeftIcon:l5,CircleChevronRight:c5,CircleChevronRightIcon:c5,CircleChevronUp:d5,CircleChevronUpIcon:d5,CircleDashed:rX,CircleDashedIcon:rX,CircleDivide:u5,CircleDivideIcon:u5,CircleDollarSign:aX,CircleDollarSignIcon:aX,CircleDot:oX,CircleDotDashed:iX,CircleDotDashedIcon:iX,CircleDotIcon:oX,CircleEllipsis:lX,CircleEllipsisIcon:lX,CircleEqual:cX,CircleEqualIcon:cX,CircleFadingArrowUp:dX,CircleFadingArrowUpIcon:dX,CircleFadingPlus:uX,CircleFadingPlusIcon:uX,CircleGauge:h5,CircleGaugeIcon:h5,CircleHelp:Y_,CircleHelpIcon:Y_,CircleIcon:dm,CircleMinus:m5,CircleMinusIcon:m5,CircleOff:hX,CircleOffIcon:hX,CircleParking:f5,CircleParkingIcon:f5,CircleParkingOff:p5,CircleParkingOffIcon:p5,CirclePause:x5,CirclePauseIcon:x5,CirclePercent:g5,CirclePercentIcon:g5,CirclePlay:Pu,CirclePlayIcon:Pu,CirclePlus:y5,CirclePlusIcon:y5,CirclePower:v5,CirclePowerIcon:v5,CircleSlash:mX,CircleSlash2:b5,CircleSlash2Icon:b5,CircleSlashIcon:mX,CircleSlashed:b5,CircleSlashedIcon:b5,CircleStop:_5,CircleStopIcon:_5,CircleUser:j5,CircleUserIcon:j5,CircleUserRound:w5,CircleUserRoundIcon:w5,CircleX:Gc,CircleXIcon:Gc,CircuitBoard:pX,CircuitBoardIcon:pX,Citrus:fX,CitrusIcon:fX,Clapperboard:xX,ClapperboardIcon:xX,Clipboard:jX,ClipboardCheck:W2,ClipboardCheckIcon:W2,ClipboardCopy:gX,ClipboardCopyIcon:gX,ClipboardEdit:k5,ClipboardEditIcon:k5,ClipboardIcon:jX,ClipboardList:Ov,ClipboardListIcon:Ov,ClipboardMinus:yX,ClipboardMinusIcon:yX,ClipboardPaste:vX,ClipboardPasteIcon:vX,ClipboardPen:k5,ClipboardPenIcon:k5,ClipboardPenLine:N5,ClipboardPenLineIcon:N5,ClipboardPlus:bX,ClipboardPlusIcon:bX,ClipboardSignature:N5,ClipboardSignatureIcon:N5,ClipboardType:_X,ClipboardTypeIcon:_X,ClipboardX:wX,ClipboardXIcon:wX,Clock:gr,Clock1:NX,Clock10:kX,Clock10Icon:kX,Clock11:SX,Clock11Icon:SX,Clock12:CX,Clock12Icon:CX,Clock1Icon:NX,Clock2:TX,Clock2Icon:TX,Clock3:e9,Clock3Icon:e9,Clock4:EX,Clock4Icon:EX,Clock5:AX,Clock5Icon:AX,Clock6:MX,Clock6Icon:MX,Clock7:IX,Clock7Icon:IX,Clock8:PX,Clock8Icon:PX,Clock9:LX,Clock9Icon:LX,ClockAlert:DX,ClockAlertIcon:DX,ClockArrowDown:RX,ClockArrowDownIcon:RX,ClockArrowUp:OX,ClockArrowUpIcon:OX,ClockIcon:gr,Cloud:XX,CloudAlert:FX,CloudAlertIcon:FX,CloudCog:zX,CloudCogIcon:zX,CloudDownload:S5,CloudDownloadIcon:S5,CloudDrizzle:BX,CloudDrizzleIcon:BX,CloudFog:$X,CloudFogIcon:$X,CloudHail:UX,CloudHailIcon:UX,CloudIcon:XX,CloudLightning:qX,CloudLightningIcon:qX,CloudMoon:HX,CloudMoonIcon:HX,CloudMoonRain:VX,CloudMoonRainIcon:VX,CloudOff:GX,CloudOffIcon:GX,CloudRain:KX,CloudRainIcon:KX,CloudRainWind:WX,CloudRainWindIcon:WX,CloudSnow:YX,CloudSnowIcon:YX,CloudSun:QX,CloudSunIcon:QX,CloudSunRain:ZX,CloudSunRainIcon:ZX,CloudUpload:C5,CloudUploadIcon:C5,Cloudy:JX,CloudyIcon:JX,Clover:O2,CloverIcon:O2,Club:eJ,ClubIcon:eJ,Code:SA,Code2:T2,Code2Icon:T2,CodeIcon:SA,CodeSquare:FT,CodeSquareIcon:FT,CodeXml:T2,CodeXmlIcon:T2,Codepen:tJ,CodepenIcon:tJ,Codesandbox:sJ,CodesandboxIcon:sJ,Coffee:ry,CoffeeIcon:ry,Cog:nJ,CogIcon:nJ,Coins:t9,CoinsIcon:t9,Columns:T5,Columns2:T5,Columns2Icon:T5,Columns3:Yk,Columns3Icon:Yk,Columns4:rJ,Columns4Icon:rJ,ColumnsIcon:T5,Combine:aJ,CombineIcon:aJ,Command:iJ,CommandIcon:iJ,Compass:sL,CompassIcon:sL,Component:oJ,ComponentIcon:oJ,Computer:lJ,ComputerIcon:lJ,ConciergeBell:cJ,ConciergeBellIcon:cJ,Cone:dJ,ConeIcon:dJ,Construction:uJ,ConstructionIcon:uJ,Contact:CA,Contact2:E5,Contact2Icon:E5,ContactIcon:CA,ContactRound:E5,ContactRoundIcon:E5,Container:hJ,ContainerIcon:hJ,Contrast:mJ,ContrastIcon:mJ,Cookie:pJ,CookieIcon:pJ,CookingPot:fJ,CookingPotIcon:fJ,Copy:ta,CopyCheck:xJ,CopyCheckIcon:xJ,CopyIcon:ta,CopyMinus:gJ,CopyMinusIcon:gJ,CopyPlus:yJ,CopyPlusIcon:yJ,CopySlash:vJ,CopySlashIcon:vJ,CopyX:bJ,CopyXIcon:bJ,Copyleft:_J,CopyleftIcon:_J,Copyright:wJ,CopyrightIcon:wJ,CornerDownLeft:jJ,CornerDownLeftIcon:jJ,CornerDownRight:NJ,CornerDownRightIcon:NJ,CornerLeftDown:kJ,CornerLeftDownIcon:kJ,CornerLeftUp:SJ,CornerLeftUpIcon:SJ,CornerRightDown:CJ,CornerRightDownIcon:CJ,CornerRightUp:TJ,CornerRightUpIcon:TJ,CornerUpLeft:EJ,CornerUpLeftIcon:EJ,CornerUpRight:AJ,CornerUpRightIcon:AJ,Cpu:MJ,CpuIcon:MJ,CreativeCommons:IJ,CreativeCommonsIcon:IJ,CreditCard:ff,CreditCardIcon:ff,Croissant:PJ,CroissantIcon:PJ,Crop:LJ,CropIcon:LJ,Cross:DJ,CrossIcon:DJ,Crosshair:RJ,CrosshairIcon:RJ,Crown:xf,CrownIcon:xf,Cuboid:OJ,CuboidIcon:OJ,CupSoda:FJ,CupSodaIcon:FJ,CurlyBraces:z3,CurlyBracesIcon:z3,Currency:zJ,CurrencyIcon:zJ,Cylinder:BJ,CylinderIcon:BJ,Dam:$J,DamIcon:$J,Database:s9,DatabaseBackup:UJ,DatabaseBackupIcon:UJ,DatabaseIcon:s9,DatabaseZap:qJ,DatabaseZapIcon:qJ,Delete:VJ,DeleteIcon:VJ,Dessert:HJ,DessertIcon:HJ,Diameter:GJ,DiameterIcon:GJ,Diamond:YJ,DiamondIcon:YJ,DiamondMinus:WJ,DiamondMinusIcon:WJ,DiamondPercent:A5,DiamondPercentIcon:A5,DiamondPlus:KJ,DiamondPlusIcon:KJ,Dice1:ZJ,Dice1Icon:ZJ,Dice2:QJ,Dice2Icon:QJ,Dice3:XJ,Dice3Icon:XJ,Dice4:JJ,Dice4Icon:JJ,Dice5:eee,Dice5Icon:eee,Dice6:tee,Dice6Icon:tee,Dices:see,DicesIcon:see,Diff:nee,DiffIcon:nee,Disc:oee,Disc2:ree,Disc2Icon:ree,Disc3:aee,Disc3Icon:aee,DiscAlbum:iee,DiscAlbumIcon:iee,DiscIcon:oee,Divide:lee,DivideCircle:u5,DivideCircleIcon:u5,DivideIcon:lee,DivideSquare:UT,DivideSquareIcon:UT,Dna:dee,DnaIcon:dee,DnaOff:cee,DnaOffIcon:cee,Dock:uee,DockIcon:uee,Dog:hee,DogIcon:hee,DollarSign:Zl,DollarSignIcon:Zl,Donut:mee,DonutIcon:mee,DoorClosed:pee,DoorClosedIcon:pee,DoorOpen:gw,DoorOpenIcon:gw,Dot:fee,DotIcon:fee,DotSquare:qT,DotSquareIcon:qT,Download:Da,DownloadCloud:S5,DownloadCloudIcon:S5,DownloadIcon:Da,DraftingCompass:xee,DraftingCompassIcon:xee,Drama:gee,DramaIcon:gee,Dribbble:yee,DribbbleIcon:yee,Drill:vee,DrillIcon:vee,Droplet:bee,DropletIcon:bee,Droplets:pb,DropletsIcon:pb,Drum:_ee,DrumIcon:_ee,Drumstick:wee,DrumstickIcon:wee,Dumbbell:jee,DumbbellIcon:jee,Ear:kee,EarIcon:kee,EarOff:Nee,EarOffIcon:Nee,Earth:M5,EarthIcon:M5,EarthLock:See,EarthLockIcon:See,Eclipse:Cee,EclipseIcon:Cee,Edit:Tu,Edit2:Nv,Edit2Icon:Nv,Edit3:nb,Edit3Icon:nb,EditIcon:Tu,Egg:nL,EggFried:Tee,EggFriedIcon:Tee,EggIcon:nL,EggOff:Eee,EggOffIcon:Eee,Ellipsis:Xf,EllipsisIcon:Xf,EllipsisVertical:Lg,EllipsisVerticalIcon:Lg,Equal:Iee,EqualApproximately:Aee,EqualApproximatelyIcon:Aee,EqualIcon:Iee,EqualNot:Mee,EqualNotIcon:Mee,EqualSquare:VT,EqualSquareIcon:VT,Eraser:Pee,EraserIcon:Pee,EthernetPort:Lee,EthernetPortIcon:Lee,Euro:Dee,EuroIcon:Dee,Expand:Ree,ExpandIcon:Ree,ExternalLink:tr,ExternalLinkIcon:tr,Eye:Ir,EyeClosed:Oee,EyeClosedIcon:Oee,EyeIcon:Ir,EyeOff:gf,EyeOffIcon:gf,Facebook:Oh,FacebookIcon:Oh,Factory:Fee,FactoryIcon:Fee,Fan:zee,FanIcon:zee,FastForward:Bee,FastForwardIcon:Bee,Feather:$ee,FeatherIcon:$ee,Fence:Uee,FenceIcon:Uee,FerrisWheel:qee,FerrisWheelIcon:qee,Figma:Vee,FigmaIcon:Vee,File:rL,FileArchive:Hee,FileArchiveIcon:Hee,FileAudio:Wee,FileAudio2:Gee,FileAudio2Icon:Gee,FileAudioIcon:Wee,FileAxis3D:I5,FileAxis3DIcon:I5,FileAxis3d:I5,FileAxis3dIcon:I5,FileBadge:Yee,FileBadge2:Kee,FileBadge2Icon:Kee,FileBadgeIcon:Yee,FileBarChart:P5,FileBarChart2:L5,FileBarChart2Icon:L5,FileBarChartIcon:P5,FileBox:Zee,FileBoxIcon:Zee,FileChartColumn:L5,FileChartColumnIcon:L5,FileChartColumnIncreasing:P5,FileChartColumnIncreasingIcon:P5,FileChartLine:D5,FileChartLineIcon:D5,FileChartPie:R5,FileChartPieIcon:R5,FileCheck:n9,FileCheck2:Qee,FileCheck2Icon:Qee,FileCheckIcon:n9,FileClock:Xee,FileClockIcon:Xee,FileCode:ete,FileCode2:Jee,FileCode2Icon:Jee,FileCodeIcon:ete,FileCog:O5,FileCog2:O5,FileCog2Icon:O5,FileCogIcon:O5,FileDiff:tte,FileDiffIcon:tte,FileDigit:ste,FileDigitIcon:ste,FileDown:TA,FileDownIcon:TA,FileEdit:F5,FileEditIcon:F5,FileHeart:nte,FileHeartIcon:nte,FileIcon:rL,FileImage:K2,FileImageIcon:K2,FileInput:rte,FileInputIcon:rte,FileJson:ite,FileJson2:ate,FileJson2Icon:ate,FileJsonIcon:ite,FileKey:lte,FileKey2:ote,FileKey2Icon:ote,FileKeyIcon:lte,FileLineChart:D5,FileLineChartIcon:D5,FileLock:dte,FileLock2:cte,FileLock2Icon:cte,FileLockIcon:dte,FileMinus:hte,FileMinus2:ute,FileMinus2Icon:ute,FileMinusIcon:hte,FileMusic:mte,FileMusicIcon:mte,FileOutput:pte,FileOutputIcon:pte,FilePen:F5,FilePenIcon:F5,FilePenLine:Zk,FilePenLineIcon:Zk,FilePieChart:R5,FilePieChartIcon:R5,FilePlus:xte,FilePlus2:fte,FilePlus2Icon:fte,FilePlusIcon:xte,FileQuestion:gte,FileQuestionIcon:gte,FileScan:yte,FileScanIcon:yte,FileSearch:bte,FileSearch2:vte,FileSearch2Icon:vte,FileSearchIcon:bte,FileSignature:Zk,FileSignatureIcon:Zk,FileSliders:_te,FileSlidersIcon:_te,FileSpreadsheet:yw,FileSpreadsheetIcon:yw,FileStack:r9,FileStackIcon:r9,FileSymlink:wte,FileSymlinkIcon:wte,FileTerminal:jte,FileTerminalIcon:jte,FileText:Nr,FileTextIcon:Nr,FileType:kte,FileType2:Nte,FileType2Icon:Nte,FileTypeIcon:kte,FileUp:Ste,FileUpIcon:Ste,FileUser:Cte,FileUserIcon:Cte,FileVideo:a9,FileVideo2:Tte,FileVideo2Icon:Tte,FileVideoIcon:a9,FileVolume:Ate,FileVolume2:Ete,FileVolume2Icon:Ete,FileVolumeIcon:Ate,FileWarning:Mte,FileWarningIcon:Mte,FileX:Pte,FileX2:Ite,FileX2Icon:Ite,FileXIcon:Pte,Files:Lte,FilesIcon:Lte,Film:Ph,FilmIcon:Ph,Filter:Fv,FilterIcon:Fv,FilterX:Dte,FilterXIcon:Dte,Fingerprint:Rte,FingerprintIcon:Rte,FireExtinguisher:Ote,FireExtinguisherIcon:Ote,Fish:Bte,FishIcon:Bte,FishOff:Fte,FishOffIcon:Fte,FishSymbol:zte,FishSymbolIcon:zte,Flag:Y2,FlagIcon:Y2,FlagOff:$te,FlagOffIcon:$te,FlagTriangleLeft:Ute,FlagTriangleLeftIcon:Ute,FlagTriangleRight:qte,FlagTriangleRightIcon:qte,Flame:_c,FlameIcon:_c,FlameKindling:Vte,FlameKindlingIcon:Vte,Flashlight:Gte,FlashlightIcon:Gte,FlashlightOff:Hte,FlashlightOffIcon:Hte,FlaskConical:XS,FlaskConicalIcon:XS,FlaskConicalOff:Wte,FlaskConicalOffIcon:Wte,FlaskRound:Kte,FlaskRoundIcon:Kte,FlipHorizontal:i9,FlipHorizontal2:Yte,FlipHorizontal2Icon:Yte,FlipHorizontalIcon:i9,FlipVertical:Qte,FlipVertical2:Zte,FlipVertical2Icon:Zte,FlipVerticalIcon:Qte,Flower:Xte,Flower2:lb,Flower2Icon:lb,FlowerIcon:Xte,Focus:Jte,FocusIcon:Jte,FoldHorizontal:ese,FoldHorizontalIcon:ese,FoldVertical:tse,FoldVerticalIcon:tse,Folder:Tse,FolderArchive:sse,FolderArchiveIcon:sse,FolderCheck:nse,FolderCheckIcon:nse,FolderClock:rse,FolderClockIcon:rse,FolderClosed:ase,FolderClosedIcon:ase,FolderCode:ise,FolderCodeIcon:ise,FolderCog:z5,FolderCog2:z5,FolderCog2Icon:z5,FolderCogIcon:z5,FolderDot:ose,FolderDotIcon:ose,FolderDown:lse,FolderDownIcon:lse,FolderEdit:B5,FolderEditIcon:B5,FolderGit:dse,FolderGit2:cse,FolderGit2Icon:cse,FolderGitIcon:dse,FolderHeart:use,FolderHeartIcon:use,FolderIcon:Tse,FolderInput:hse,FolderInputIcon:hse,FolderKanban:mse,FolderKanbanIcon:mse,FolderKey:pse,FolderKeyIcon:pse,FolderLock:fse,FolderLockIcon:fse,FolderMinus:xse,FolderMinusIcon:xse,FolderOpen:yf,FolderOpenDot:gse,FolderOpenDotIcon:gse,FolderOpenIcon:yf,FolderOutput:yse,FolderOutputIcon:yse,FolderPen:B5,FolderPenIcon:B5,FolderPlus:vse,FolderPlusIcon:vse,FolderRoot:bse,FolderRootIcon:bse,FolderSearch:wse,FolderSearch2:_se,FolderSearch2Icon:_se,FolderSearchIcon:wse,FolderSymlink:jse,FolderSymlinkIcon:jse,FolderSync:Nse,FolderSyncIcon:Nse,FolderTree:kse,FolderTreeIcon:kse,FolderUp:Sse,FolderUpIcon:Sse,FolderX:Cse,FolderXIcon:Cse,Folders:Ese,FoldersIcon:Ese,Footprints:Ase,FootprintsIcon:Ase,ForkKnife:TE,ForkKnifeCrossed:CE,ForkKnifeCrossedIcon:CE,ForkKnifeIcon:TE,Forklift:Mse,ForkliftIcon:Mse,FormInput:dT,FormInputIcon:dT,Forward:Ise,ForwardIcon:Ise,Frame:Pse,FrameIcon:Pse,Framer:Lse,FramerIcon:Lse,Frown:Dse,FrownIcon:Dse,Fuel:Rse,FuelIcon:Rse,Fullscreen:Ose,FullscreenIcon:Ose,FunctionSquare:HT,FunctionSquareIcon:HT,GalleryHorizontal:zse,GalleryHorizontalEnd:Fse,GalleryHorizontalEndIcon:Fse,GalleryHorizontalIcon:zse,GalleryThumbnails:Bse,GalleryThumbnailsIcon:Bse,GalleryVertical:Use,GalleryVerticalEnd:$se,GalleryVerticalEndIcon:$se,GalleryVerticalIcon:Use,Gamepad:Vse,Gamepad2:qse,Gamepad2Icon:qse,GamepadIcon:Vse,GanttChart:Z3,GanttChartIcon:Z3,GanttChartSquare:D_,GanttChartSquareIcon:D_,Gauge:Hse,GaugeCircle:h5,GaugeCircleIcon:h5,GaugeIcon:Hse,Gavel:Gse,GavelIcon:Gse,Gem:Wse,GemIcon:Wse,Ghost:EA,GhostIcon:EA,Gift:Bi,GiftIcon:Bi,GitBranch:Yse,GitBranchIcon:Yse,GitBranchPlus:Kse,GitBranchPlusIcon:Kse,GitCommit:$5,GitCommitHorizontal:$5,GitCommitHorizontalIcon:$5,GitCommitIcon:$5,GitCommitVertical:Zse,GitCommitVerticalIcon:Zse,GitCompare:Xse,GitCompareArrows:Qse,GitCompareArrowsIcon:Qse,GitCompareIcon:Xse,GitFork:Jse,GitForkIcon:Jse,GitGraph:ene,GitGraphIcon:ene,GitMerge:tne,GitMergeIcon:tne,GitPullRequest:one,GitPullRequestArrow:sne,GitPullRequestArrowIcon:sne,GitPullRequestClosed:nne,GitPullRequestClosedIcon:nne,GitPullRequestCreate:ane,GitPullRequestCreateArrow:rne,GitPullRequestCreateArrowIcon:rne,GitPullRequestCreateIcon:ane,GitPullRequestDraft:ine,GitPullRequestDraftIcon:ine,GitPullRequestIcon:one,Github:lne,GithubIcon:lne,Gitlab:cne,GitlabIcon:cne,GlassWater:dne,GlassWaterIcon:dne,Glasses:une,GlassesIcon:une,Globe:lc,Globe2:M5,Globe2Icon:M5,GlobeIcon:lc,GlobeLock:hne,GlobeLockIcon:hne,Goal:mne,GoalIcon:mne,Grab:pne,GrabIcon:pne,GraduationCap:_d,GraduationCapIcon:_d,Grape:fne,GrapeIcon:fne,Grid:xv,Grid2X2:q5,Grid2X2Icon:q5,Grid2X2Plus:U5,Grid2X2PlusIcon:U5,Grid2x2:q5,Grid2x2Check:xne,Grid2x2CheckIcon:xne,Grid2x2Icon:q5,Grid2x2Plus:U5,Grid2x2PlusIcon:U5,Grid2x2X:gne,Grid2x2XIcon:gne,Grid3X3:xv,Grid3X3Icon:xv,Grid3x3:xv,Grid3x3Icon:xv,GridIcon:xv,Grip:vne,GripHorizontal:yne,GripHorizontalIcon:yne,GripIcon:vne,GripVertical:Uu,GripVerticalIcon:Uu,Group:bne,GroupIcon:bne,Guitar:_ne,GuitarIcon:_ne,Ham:wne,HamIcon:wne,Hammer:o9,HammerIcon:o9,Hand:l9,HandCoins:jne,HandCoinsIcon:jne,HandHeart:AA,HandHeartIcon:AA,HandHelping:sb,HandHelpingIcon:sb,HandIcon:l9,HandMetal:Nne,HandMetalIcon:Nne,HandPlatter:kne,HandPlatterIcon:kne,Handshake:fb,HandshakeIcon:fb,HardDrive:c9,HardDriveDownload:Sne,HardDriveDownloadIcon:Sne,HardDriveIcon:c9,HardDriveUpload:Cne,HardDriveUploadIcon:Cne,HardHat:Tne,HardHatIcon:Tne,Hash:JS,HashIcon:JS,Haze:Ene,HazeIcon:Ene,HdmiPort:Ane,HdmiPortIcon:Ane,Heading:Lne,Heading1:aL,Heading1Icon:aL,Heading2:iL,Heading2Icon:iL,Heading3:d9,Heading3Icon:d9,Heading4:Mne,Heading4Icon:Mne,Heading5:Ine,Heading5Icon:Ine,Heading6:Pne,Heading6Icon:Pne,HeadingIcon:Lne,HeadphoneOff:Dne,HeadphoneOffIcon:Dne,Headphones:Rne,HeadphonesIcon:Rne,Headset:One,HeadsetIcon:One,Heart:yi,HeartCrack:Fne,HeartCrackIcon:Fne,HeartHandshake:MA,HeartHandshakeIcon:MA,HeartIcon:yi,HeartOff:zne,HeartOffIcon:zne,HeartPulse:Bne,HeartPulseIcon:Bne,Heater:$ne,HeaterIcon:$ne,HelpCircle:Y_,HelpCircleIcon:Y_,HelpingHand:sb,HelpingHandIcon:sb,Hexagon:Une,HexagonIcon:Une,Highlighter:qne,HighlighterIcon:qne,History:IA,HistoryIcon:IA,Home:zr,HomeIcon:zr,Hop:Hne,HopIcon:Hne,HopOff:Vne,HopOffIcon:Vne,Hospital:Gne,HospitalIcon:Gne,Hotel:Wne,HotelIcon:Wne,Hourglass:Kne,HourglassIcon:Kne,House:zr,HouseIcon:zr,HousePlug:Yne,HousePlugIcon:Yne,HousePlus:Zne,HousePlusIcon:Zne,IceCream:H5,IceCream2:V5,IceCream2Icon:V5,IceCreamBowl:V5,IceCreamBowlIcon:V5,IceCreamCone:H5,IceCreamConeIcon:H5,IceCreamIcon:H5,Icon:Irt,IdCard:Qne,IdCardIcon:Qne,Image:nl,ImageDown:Xne,ImageDownIcon:Xne,ImageIcon:nl,ImageMinus:Jne,ImageMinusIcon:Jne,ImageOff:ere,ImageOffIcon:ere,ImagePlay:tre,ImagePlayIcon:tre,ImagePlus:ay,ImagePlusIcon:ay,ImageUp:sre,ImageUpIcon:sre,ImageUpscale:nre,ImageUpscaleIcon:nre,Images:rre,ImagesIcon:rre,Import:are,ImportIcon:are,Inbox:Z2,InboxIcon:Z2,Indent:W5,IndentDecrease:G5,IndentDecreaseIcon:G5,IndentIcon:W5,IndentIncrease:W5,IndentIncreaseIcon:W5,IndianRupee:ire,IndianRupeeIcon:ire,Infinity:ore,InfinityIcon:ore,Info:vw,InfoIcon:vw,Inspect:QT,InspectIcon:QT,InspectionPanel:lre,InspectionPanelIcon:lre,Instagram:mu,InstagramIcon:mu,Italic:e4,ItalicIcon:e4,IterationCcw:cre,IterationCcwIcon:cre,IterationCw:dre,IterationCwIcon:dre,JapaneseYen:ure,JapaneseYenIcon:ure,Joystick:hre,JoystickIcon:hre,Kanban:Q2,KanbanIcon:Q2,KanbanSquare:GT,KanbanSquareDashed:zT,KanbanSquareDashedIcon:zT,KanbanSquareIcon:GT,Key:Gg,KeyIcon:Gg,KeyRound:PA,KeyRoundIcon:PA,KeySquare:mre,KeySquareIcon:mre,Keyboard:xre,KeyboardIcon:xre,KeyboardMusic:pre,KeyboardMusicIcon:pre,KeyboardOff:fre,KeyboardOffIcon:fre,Lamp:wre,LampCeiling:gre,LampCeilingIcon:gre,LampDesk:yre,LampDeskIcon:yre,LampFloor:vre,LampFloorIcon:vre,LampIcon:wre,LampWallDown:bre,LampWallDownIcon:bre,LampWallUp:_re,LampWallUpIcon:_re,LandPlot:jre,LandPlotIcon:jre,Landmark:Nre,LandmarkIcon:Nre,Languages:kre,LanguagesIcon:kre,Laptop:Cre,Laptop2:K5,Laptop2Icon:K5,LaptopIcon:Cre,LaptopMinimal:K5,LaptopMinimalCheck:Sre,LaptopMinimalCheckIcon:Sre,LaptopMinimalIcon:K5,Lasso:Ere,LassoIcon:Ere,LassoSelect:Tre,LassoSelectIcon:Tre,Laugh:Are,LaughIcon:Are,Layers:u9,Layers2:Mre,Layers2Icon:Mre,Layers3:Ire,Layers3Icon:Ire,LayersIcon:u9,Layout:E2,LayoutDashboard:t4,LayoutDashboardIcon:t4,LayoutGrid:vf,LayoutGridIcon:vf,LayoutIcon:E2,LayoutList:Pre,LayoutListIcon:Pre,LayoutPanelLeft:Lre,LayoutPanelLeftIcon:Lre,LayoutPanelTop:Dre,LayoutPanelTopIcon:Dre,LayoutTemplate:s4,LayoutTemplateIcon:s4,Leaf:Rre,LeafIcon:Rre,LeafyGreen:Ore,LeafyGreenIcon:Ore,Lectern:Fre,LecternIcon:Fre,LetterText:zre,LetterTextIcon:zre,Library:Wg,LibraryBig:Bre,LibraryBigIcon:Bre,LibraryIcon:Wg,LibrarySquare:WT,LibrarySquareIcon:WT,LifeBuoy:oL,LifeBuoyIcon:oL,Ligature:$re,LigatureIcon:$re,Lightbulb:bw,LightbulbIcon:bw,LightbulbOff:Ure,LightbulbOffIcon:Ure,LineChart:W3,LineChartIcon:W3,Link:tl,Link2:El,Link2Icon:El,Link2Off:qre,Link2OffIcon:qre,LinkIcon:tl,Linkedin:bf,LinkedinIcon:bf,List:Ep,ListCheck:Vre,ListCheckIcon:Vre,ListChecks:pu,ListChecksIcon:pu,ListCollapse:Hre,ListCollapseIcon:Hre,ListEnd:Gre,ListEndIcon:Gre,ListFilter:h9,ListFilterIcon:h9,ListIcon:Ep,ListMinus:Wre,ListMinusIcon:Wre,ListMusic:Kre,ListMusicIcon:Kre,ListOrdered:zv,ListOrderedIcon:zv,ListPlus:Yre,ListPlusIcon:Yre,ListRestart:Zre,ListRestartIcon:Zre,ListStart:Qre,ListStartIcon:Qre,ListTodo:Xre,ListTodoIcon:Xre,ListTree:Jre,ListTreeIcon:Jre,ListVideo:eae,ListVideoIcon:eae,ListX:tae,ListXIcon:tae,Loader:nae,Loader2:ss,Loader2Icon:ss,LoaderCircle:ss,LoaderCircleIcon:ss,LoaderIcon:nae,LoaderPinwheel:sae,LoaderPinwheelIcon:sae,Locate:lL,LocateFixed:rae,LocateFixedIcon:rae,LocateIcon:lL,LocateOff:aae,LocateOffIcon:aae,Lock:Rc,LockIcon:Rc,LockKeyhole:iae,LockKeyholeIcon:iae,LockKeyholeOpen:Y5,LockKeyholeOpenIcon:Y5,LockOpen:Z5,LockOpenIcon:Z5,LogIn:LA,LogInIcon:LA,LogOut:DA,LogOutIcon:DA,Logs:oae,LogsIcon:oae,Lollipop:lae,LollipopIcon:lae,LucideAArrowDown:EW,LucideAArrowUp:AW,LucideALargeSmall:MW,LucideAccessibility:IW,LucideActivity:am,LucideActivitySquare:yT,LucideAirVent:PW,LucideAirplay:LW,LucideAlarmCheck:k3,LucideAlarmClock:RW,LucideAlarmClockCheck:k3,LucideAlarmClockMinus:S3,LucideAlarmClockOff:DW,LucideAlarmClockPlus:C3,LucideAlarmMinus:S3,LucideAlarmPlus:C3,LucideAlarmSmoke:OW,LucideAlbum:FW,LucideAlertCircle:Gi,LucideAlertOctagon:Z_,LucideAlertTriangle:Dl,LucideAlignCenter:_A,LucideAlignCenterHorizontal:zW,LucideAlignCenterVertical:BW,LucideAlignEndHorizontal:$W,LucideAlignEndVertical:UW,LucideAlignHorizontalDistributeCenter:qW,LucideAlignHorizontalDistributeEnd:VW,LucideAlignHorizontalDistributeStart:HW,LucideAlignHorizontalJustifyCenter:GW,LucideAlignHorizontalJustifyEnd:WW,LucideAlignHorizontalJustifyStart:KW,LucideAlignHorizontalSpaceAround:YW,LucideAlignHorizontalSpaceBetween:ZW,LucideAlignJustify:QW,LucideAlignLeft:wA,LucideAlignRight:jA,LucideAlignStartHorizontal:XW,LucideAlignStartVertical:JW,LucideAlignVerticalDistributeCenter:eK,LucideAlignVerticalDistributeEnd:tK,LucideAlignVerticalDistributeStart:sK,LucideAlignVerticalJustifyCenter:nK,LucideAlignVerticalJustifyEnd:rK,LucideAlignVerticalJustifyStart:aK,LucideAlignVerticalSpaceAround:iK,LucideAlignVerticalSpaceBetween:oK,LucideAmbulance:lK,LucideAmpersand:cK,LucideAmpersands:dK,LucideAmphora:uK,LucideAnchor:hK,LucideAngry:mK,LucideAnnoyed:pK,LucideAntenna:fK,LucideAnvil:xK,LucideAperture:gK,LucideAppWindow:vK,LucideAppWindowMac:yK,LucideApple:bK,LucideArchive:im,LucideArchiveRestore:XP,LucideArchiveX:_K,LucideAreaChart:$3,LucideArmchair:wK,LucideArrowBigDown:NK,LucideArrowBigDownDash:jK,LucideArrowBigLeft:SK,LucideArrowBigLeftDash:kK,LucideArrowBigRight:TK,LucideArrowBigRightDash:CK,LucideArrowBigUp:AK,LucideArrowBigUpDash:EK,LucideArrowDown:om,LucideArrowDown01:MK,LucideArrowDown10:IK,LucideArrowDownAZ:T3,LucideArrowDownAz:T3,LucideArrowDownCircle:J3,LucideArrowDownFromLine:PK,LucideArrowDownLeft:LK,LucideArrowDownLeftFromCircle:t5,LucideArrowDownLeftFromSquare:jT,LucideArrowDownLeftSquare:vT,LucideArrowDownNarrowWide:DK,LucideArrowDownRight:W7,LucideArrowDownRightFromCircle:s5,LucideArrowDownRightFromSquare:NT,LucideArrowDownRightSquare:bT,LucideArrowDownSquare:_T,LucideArrowDownToDot:RK,LucideArrowDownToLine:OK,LucideArrowDownUp:FK,LucideArrowDownWideNarrow:E3,LucideArrowDownZA:A3,LucideArrowDownZa:A3,LucideArrowLeft:Wr,LucideArrowLeftCircle:e5,LucideArrowLeftFromLine:zK,LucideArrowLeftRight:BK,LucideArrowLeftSquare:wT,LucideArrowLeftToLine:$K,LucideArrowRight:za,LucideArrowRightCircle:a5,LucideArrowRightFromLine:UK,LucideArrowRightLeft:pw,LucideArrowRightSquare:CT,LucideArrowRightToLine:qK,LucideArrowUp:Bu,LucideArrowUp01:VK,LucideArrowUp10:HK,LucideArrowUpAZ:M3,LucideArrowUpAz:M3,LucideArrowUpCircle:i5,LucideArrowUpDown:sm,LucideArrowUpFromDot:GK,LucideArrowUpFromLine:WK,LucideArrowUpLeft:KK,LucideArrowUpLeftFromCircle:n5,LucideArrowUpLeftFromSquare:kT,LucideArrowUpLeftSquare:TT,LucideArrowUpNarrowWide:I3,LucideArrowUpRight:JP,LucideArrowUpRightFromCircle:r5,LucideArrowUpRightFromSquare:ST,LucideArrowUpRightSquare:ET,LucideArrowUpSquare:AT,LucideArrowUpToLine:YK,LucideArrowUpWideNarrow:ZK,LucideArrowUpZA:P3,LucideArrowUpZa:P3,LucideArrowsUpFromLine:QK,LucideAsterisk:XK,LucideAsteriskSquare:MT,LucideAtSign:JK,LucideAtom:eY,LucideAudioLines:tY,LucideAudioWaveform:sY,LucideAward:vc,LucideAxe:nY,LucideAxis3D:L3,LucideAxis3d:L3,LucideBaby:rY,LucideBackpack:aY,LucideBadge:_Y,LucideBadgeAlert:iY,LucideBadgeCent:oY,LucideBadgeCheck:D3,LucideBadgeDollarSign:lY,LucideBadgeEuro:cY,LucideBadgeHelp:dY,LucideBadgeIndianRupee:uY,LucideBadgeInfo:hY,LucideBadgeJapaneseYen:mY,LucideBadgeMinus:pY,LucideBadgePercent:fY,LucideBadgePlus:xY,LucideBadgePoundSterling:gY,LucideBadgeRussianRuble:yY,LucideBadgeSwissFranc:vY,LucideBadgeX:bY,LucideBaggageClaim:wY,LucideBan:eL,LucideBanana:jY,LucideBandage:NY,LucideBanknote:kY,LucideBarChart:K3,LucideBarChart2:Y3,LucideBarChart3:yo,LucideBarChart4:G3,LucideBarChartBig:H3,LucideBarChartHorizontal:q3,LucideBarChartHorizontalBig:U3,LucideBarcode:SY,LucideBaseline:CY,LucideBath:Tp,LucideBattery:PY,LucideBatteryCharging:TY,LucideBatteryFull:EY,LucideBatteryLow:AY,LucideBatteryMedium:MY,LucideBatteryWarning:IY,LucideBeaker:K7,LucideBean:DY,LucideBeanOff:LY,LucideBed:ny,LucideBedDouble:G2,LucideBedSingle:RY,LucideBeef:OY,LucideBeer:zY,LucideBeerOff:FY,LucideBell:lm,LucideBellDot:BY,LucideBellElectric:$Y,LucideBellMinus:UY,LucideBellOff:fw,LucideBellPlus:qY,LucideBellRing:KS,LucideBetweenHorizonalEnd:R3,LucideBetweenHorizonalStart:O3,LucideBetweenHorizontalEnd:R3,LucideBetweenHorizontalStart:O3,LucideBetweenVerticalEnd:VY,LucideBetweenVerticalStart:HY,LucideBicepsFlexed:GY,LucideBike:WY,LucideBinary:KY,LucideBinoculars:YY,LucideBiohazard:ZY,LucideBird:QY,LucideBitcoin:XY,LucideBlend:JY,LucideBlinds:eZ,LucideBlocks:tZ,LucideBluetooth:aZ,LucideBluetoothConnected:sZ,LucideBluetoothOff:nZ,LucideBluetoothSearching:rZ,LucideBold:YS,LucideBolt:iZ,LucideBomb:oZ,LucideBone:lZ,LucideBook:AZ,LucideBookA:cZ,LucideBookAudio:dZ,LucideBookCheck:uZ,LucideBookCopy:hZ,LucideBookDashed:F3,LucideBookDown:mZ,LucideBookHeadphones:pZ,LucideBookHeart:fZ,LucideBookImage:xZ,LucideBookKey:gZ,LucideBookLock:yZ,LucideBookMarked:vZ,LucideBookMinus:bZ,LucideBookOpen:$u,LucideBookOpenCheck:_Z,LucideBookOpenText:wZ,LucideBookPlus:jZ,LucideBookTemplate:F3,LucideBookText:NZ,LucideBookType:kZ,LucideBookUp:CZ,LucideBookUp2:SZ,LucideBookUser:TZ,LucideBookX:EZ,LucideBookmark:Rv,LucideBookmarkCheck:MZ,LucideBookmarkMinus:IZ,LucideBookmarkPlus:tL,LucideBookmarkX:PZ,LucideBoomBox:LZ,LucideBot:ZS,LucideBotMessageSquare:DZ,LucideBotOff:RZ,LucideBox:Y7,LucideBoxSelect:$T,LucideBoxes:OZ,LucideBraces:z3,LucideBrackets:FZ,LucideBrain:Z7,LucideBrainCircuit:zZ,LucideBrainCog:BZ,LucideBrickWall:$Z,LucideBriefcase:Vm,LucideBriefcaseBusiness:UZ,LucideBriefcaseConveyorBelt:qZ,LucideBriefcaseMedical:VZ,LucideBringToFront:HZ,LucideBrush:GZ,LucideBug:YZ,LucideBugOff:WZ,LucideBugPlay:KZ,LucideBuilding:NA,LucideBuilding2:Ga,LucideBus:QZ,LucideBusFront:ZZ,LucideCable:JZ,LucideCableCar:XZ,LucideCake:hu,LucideCakeSlice:eQ,LucideCalculator:xw,LucideCalendar:yr,LucideCalendar1:tQ,LucideCalendarArrowDown:sQ,LucideCalendarArrowUp:nQ,LucideCalendarCheck:QS,LucideCalendarCheck2:rQ,LucideCalendarClock:cm,LucideCalendarCog:aQ,LucideCalendarDays:Tl,LucideCalendarFold:iQ,LucideCalendarHeart:mb,LucideCalendarMinus:lQ,LucideCalendarMinus2:oQ,LucideCalendarOff:Q7,LucideCalendarPlus:Fg,LucideCalendarPlus2:cQ,LucideCalendarRange:dQ,LucideCalendarSearch:uQ,LucideCalendarSync:hQ,LucideCalendarX:X7,LucideCalendarX2:mQ,LucideCamera:pf,LucideCameraOff:pQ,LucideCandlestickChart:V3,LucideCandy:gQ,LucideCandyCane:fQ,LucideCandyOff:xQ,LucideCannabis:yQ,LucideCaptions:B3,LucideCaptionsOff:vQ,LucideCar:wQ,LucideCarFront:bQ,LucideCarTaxiFront:_Q,LucideCaravan:jQ,LucideCarrot:NQ,LucideCaseLower:kQ,LucideCaseSensitive:SQ,LucideCaseUpper:CQ,LucideCassetteTape:TQ,LucideCast:EQ,LucideCastle:AQ,LucideCat:MQ,LucideCctv:IQ,LucideChartArea:$3,LucideChartBar:q3,LucideChartBarBig:U3,LucideChartBarDecreasing:PQ,LucideChartBarIncreasing:LQ,LucideChartBarStacked:DQ,LucideChartCandlestick:V3,LucideChartColumn:yo,LucideChartColumnBig:H3,LucideChartColumnDecreasing:RQ,LucideChartColumnIncreasing:G3,LucideChartColumnStacked:OQ,LucideChartGantt:FQ,LucideChartLine:W3,LucideChartNetwork:zQ,LucideChartNoAxesColumn:Y3,LucideChartNoAxesColumnDecreasing:BQ,LucideChartNoAxesColumnIncreasing:K3,LucideChartNoAxesCombined:$Q,LucideChartNoAxesGantt:Z3,LucideChartPie:Q3,LucideChartScatter:X3,LucideChartSpline:UQ,LucideCheck:Lr,LucideCheckCheck:J7,LucideCheckCircle:zi,LucideCheckCircle2:xr,LucideCheckSquare:A2,LucideCheckSquare2:PT,LucideChefHat:qQ,LucideCherry:VQ,LucideChevronDown:io,LucideChevronDownCircle:o5,LucideChevronDownSquare:LT,LucideChevronFirst:HQ,LucideChevronLast:GQ,LucideChevronLeft:fl,LucideChevronLeftCircle:l5,LucideChevronLeftSquare:DT,LucideChevronRight:ga,LucideChevronRightCircle:c5,LucideChevronRightSquare:RT,LucideChevronUp:sx,LucideChevronUpCircle:d5,LucideChevronUpSquare:OT,LucideChevronsDown:KQ,LucideChevronsDownUp:WQ,LucideChevronsLeft:QQ,LucideChevronsLeftRight:ZQ,LucideChevronsLeftRightEllipsis:YQ,LucideChevronsRight:JQ,LucideChevronsRightLeft:XQ,LucideChevronsUp:eX,LucideChevronsUpDown:Hg,LucideChrome:kA,LucideChurch:tX,LucideCigarette:nX,LucideCigaretteOff:sX,LucideCircle:dm,LucideCircleAlert:Gi,LucideCircleArrowDown:J3,LucideCircleArrowLeft:e5,LucideCircleArrowOutDownLeft:t5,LucideCircleArrowOutDownRight:s5,LucideCircleArrowOutUpLeft:n5,LucideCircleArrowOutUpRight:r5,LucideCircleArrowRight:a5,LucideCircleArrowUp:i5,LucideCircleCheck:xr,LucideCircleCheckBig:zi,LucideCircleChevronDown:o5,LucideCircleChevronLeft:l5,LucideCircleChevronRight:c5,LucideCircleChevronUp:d5,LucideCircleDashed:rX,LucideCircleDivide:u5,LucideCircleDollarSign:aX,LucideCircleDot:oX,LucideCircleDotDashed:iX,LucideCircleEllipsis:lX,LucideCircleEqual:cX,LucideCircleFadingArrowUp:dX,LucideCircleFadingPlus:uX,LucideCircleGauge:h5,LucideCircleHelp:Y_,LucideCircleMinus:m5,LucideCircleOff:hX,LucideCircleParking:f5,LucideCircleParkingOff:p5,LucideCirclePause:x5,LucideCirclePercent:g5,LucideCirclePlay:Pu,LucideCirclePlus:y5,LucideCirclePower:v5,LucideCircleSlash:mX,LucideCircleSlash2:b5,LucideCircleSlashed:b5,LucideCircleStop:_5,LucideCircleUser:j5,LucideCircleUserRound:w5,LucideCircleX:Gc,LucideCircuitBoard:pX,LucideCitrus:fX,LucideClapperboard:xX,LucideClipboard:jX,LucideClipboardCheck:W2,LucideClipboardCopy:gX,LucideClipboardEdit:k5,LucideClipboardList:Ov,LucideClipboardMinus:yX,LucideClipboardPaste:vX,LucideClipboardPen:k5,LucideClipboardPenLine:N5,LucideClipboardPlus:bX,LucideClipboardSignature:N5,LucideClipboardType:_X,LucideClipboardX:wX,LucideClock:gr,LucideClock1:NX,LucideClock10:kX,LucideClock11:SX,LucideClock12:CX,LucideClock2:TX,LucideClock3:e9,LucideClock4:EX,LucideClock5:AX,LucideClock6:MX,LucideClock7:IX,LucideClock8:PX,LucideClock9:LX,LucideClockAlert:DX,LucideClockArrowDown:RX,LucideClockArrowUp:OX,LucideCloud:XX,LucideCloudAlert:FX,LucideCloudCog:zX,LucideCloudDownload:S5,LucideCloudDrizzle:BX,LucideCloudFog:$X,LucideCloudHail:UX,LucideCloudLightning:qX,LucideCloudMoon:HX,LucideCloudMoonRain:VX,LucideCloudOff:GX,LucideCloudRain:KX,LucideCloudRainWind:WX,LucideCloudSnow:YX,LucideCloudSun:QX,LucideCloudSunRain:ZX,LucideCloudUpload:C5,LucideCloudy:JX,LucideClover:O2,LucideClub:eJ,LucideCode:SA,LucideCode2:T2,LucideCodeSquare:FT,LucideCodeXml:T2,LucideCodepen:tJ,LucideCodesandbox:sJ,LucideCoffee:ry,LucideCog:nJ,LucideCoins:t9,LucideColumns:T5,LucideColumns2:T5,LucideColumns3:Yk,LucideColumns4:rJ,LucideCombine:aJ,LucideCommand:iJ,LucideCompass:sL,LucideComponent:oJ,LucideComputer:lJ,LucideConciergeBell:cJ,LucideCone:dJ,LucideConstruction:uJ,LucideContact:CA,LucideContact2:E5,LucideContactRound:E5,LucideContainer:hJ,LucideContrast:mJ,LucideCookie:pJ,LucideCookingPot:fJ,LucideCopy:ta,LucideCopyCheck:xJ,LucideCopyMinus:gJ,LucideCopyPlus:yJ,LucideCopySlash:vJ,LucideCopyX:bJ,LucideCopyleft:_J,LucideCopyright:wJ,LucideCornerDownLeft:jJ,LucideCornerDownRight:NJ,LucideCornerLeftDown:kJ,LucideCornerLeftUp:SJ,LucideCornerRightDown:CJ,LucideCornerRightUp:TJ,LucideCornerUpLeft:EJ,LucideCornerUpRight:AJ,LucideCpu:MJ,LucideCreativeCommons:IJ,LucideCreditCard:ff,LucideCroissant:PJ,LucideCrop:LJ,LucideCross:DJ,LucideCrosshair:RJ,LucideCrown:xf,LucideCuboid:OJ,LucideCupSoda:FJ,LucideCurlyBraces:z3,LucideCurrency:zJ,LucideCylinder:BJ,LucideDam:$J,LucideDatabase:s9,LucideDatabaseBackup:UJ,LucideDatabaseZap:qJ,LucideDelete:VJ,LucideDessert:HJ,LucideDiameter:GJ,LucideDiamond:YJ,LucideDiamondMinus:WJ,LucideDiamondPercent:A5,LucideDiamondPlus:KJ,LucideDice1:ZJ,LucideDice2:QJ,LucideDice3:XJ,LucideDice4:JJ,LucideDice5:eee,LucideDice6:tee,LucideDices:see,LucideDiff:nee,LucideDisc:oee,LucideDisc2:ree,LucideDisc3:aee,LucideDiscAlbum:iee,LucideDivide:lee,LucideDivideCircle:u5,LucideDivideSquare:UT,LucideDna:dee,LucideDnaOff:cee,LucideDock:uee,LucideDog:hee,LucideDollarSign:Zl,LucideDonut:mee,LucideDoorClosed:pee,LucideDoorOpen:gw,LucideDot:fee,LucideDotSquare:qT,LucideDownload:Da,LucideDownloadCloud:S5,LucideDraftingCompass:xee,LucideDrama:gee,LucideDribbble:yee,LucideDrill:vee,LucideDroplet:bee,LucideDroplets:pb,LucideDrum:_ee,LucideDrumstick:wee,LucideDumbbell:jee,LucideEar:kee,LucideEarOff:Nee,LucideEarth:M5,LucideEarthLock:See,LucideEclipse:Cee,LucideEdit:Tu,LucideEdit2:Nv,LucideEdit3:nb,LucideEgg:nL,LucideEggFried:Tee,LucideEggOff:Eee,LucideEllipsis:Xf,LucideEllipsisVertical:Lg,LucideEqual:Iee,LucideEqualApproximately:Aee,LucideEqualNot:Mee,LucideEqualSquare:VT,LucideEraser:Pee,LucideEthernetPort:Lee,LucideEuro:Dee,LucideExpand:Ree,LucideExternalLink:tr,LucideEye:Ir,LucideEyeClosed:Oee,LucideEyeOff:gf,LucideFacebook:Oh,LucideFactory:Fee,LucideFan:zee,LucideFastForward:Bee,LucideFeather:$ee,LucideFence:Uee,LucideFerrisWheel:qee,LucideFigma:Vee,LucideFile:rL,LucideFileArchive:Hee,LucideFileAudio:Wee,LucideFileAudio2:Gee,LucideFileAxis3D:I5,LucideFileAxis3d:I5,LucideFileBadge:Yee,LucideFileBadge2:Kee,LucideFileBarChart:P5,LucideFileBarChart2:L5,LucideFileBox:Zee,LucideFileChartColumn:L5,LucideFileChartColumnIncreasing:P5,LucideFileChartLine:D5,LucideFileChartPie:R5,LucideFileCheck:n9,LucideFileCheck2:Qee,LucideFileClock:Xee,LucideFileCode:ete,LucideFileCode2:Jee,LucideFileCog:O5,LucideFileCog2:O5,LucideFileDiff:tte,LucideFileDigit:ste,LucideFileDown:TA,LucideFileEdit:F5,LucideFileHeart:nte,LucideFileImage:K2,LucideFileInput:rte,LucideFileJson:ite,LucideFileJson2:ate,LucideFileKey:lte,LucideFileKey2:ote,LucideFileLineChart:D5,LucideFileLock:dte,LucideFileLock2:cte,LucideFileMinus:hte,LucideFileMinus2:ute,LucideFileMusic:mte,LucideFileOutput:pte,LucideFilePen:F5,LucideFilePenLine:Zk,LucideFilePieChart:R5,LucideFilePlus:xte,LucideFilePlus2:fte,LucideFileQuestion:gte,LucideFileScan:yte,LucideFileSearch:bte,LucideFileSearch2:vte,LucideFileSignature:Zk,LucideFileSliders:_te,LucideFileSpreadsheet:yw,LucideFileStack:r9,LucideFileSymlink:wte,LucideFileTerminal:jte,LucideFileText:Nr,LucideFileType:kte,LucideFileType2:Nte,LucideFileUp:Ste,LucideFileUser:Cte,LucideFileVideo:a9,LucideFileVideo2:Tte,LucideFileVolume:Ate,LucideFileVolume2:Ete,LucideFileWarning:Mte,LucideFileX:Pte,LucideFileX2:Ite,LucideFiles:Lte,LucideFilm:Ph,LucideFilter:Fv,LucideFilterX:Dte,LucideFingerprint:Rte,LucideFireExtinguisher:Ote,LucideFish:Bte,LucideFishOff:Fte,LucideFishSymbol:zte,LucideFlag:Y2,LucideFlagOff:$te,LucideFlagTriangleLeft:Ute,LucideFlagTriangleRight:qte,LucideFlame:_c,LucideFlameKindling:Vte,LucideFlashlight:Gte,LucideFlashlightOff:Hte,LucideFlaskConical:XS,LucideFlaskConicalOff:Wte,LucideFlaskRound:Kte,LucideFlipHorizontal:i9,LucideFlipHorizontal2:Yte,LucideFlipVertical:Qte,LucideFlipVertical2:Zte,LucideFlower:Xte,LucideFlower2:lb,LucideFocus:Jte,LucideFoldHorizontal:ese,LucideFoldVertical:tse,LucideFolder:Tse,LucideFolderArchive:sse,LucideFolderCheck:nse,LucideFolderClock:rse,LucideFolderClosed:ase,LucideFolderCode:ise,LucideFolderCog:z5,LucideFolderCog2:z5,LucideFolderDot:ose,LucideFolderDown:lse,LucideFolderEdit:B5,LucideFolderGit:dse,LucideFolderGit2:cse,LucideFolderHeart:use,LucideFolderInput:hse,LucideFolderKanban:mse,LucideFolderKey:pse,LucideFolderLock:fse,LucideFolderMinus:xse,LucideFolderOpen:yf,LucideFolderOpenDot:gse,LucideFolderOutput:yse,LucideFolderPen:B5,LucideFolderPlus:vse,LucideFolderRoot:bse,LucideFolderSearch:wse,LucideFolderSearch2:_se,LucideFolderSymlink:jse,LucideFolderSync:Nse,LucideFolderTree:kse,LucideFolderUp:Sse,LucideFolderX:Cse,LucideFolders:Ese,LucideFootprints:Ase,LucideForkKnife:TE,LucideForkKnifeCrossed:CE,LucideForklift:Mse,LucideFormInput:dT,LucideForward:Ise,LucideFrame:Pse,LucideFramer:Lse,LucideFrown:Dse,LucideFuel:Rse,LucideFullscreen:Ose,LucideFunctionSquare:HT,LucideGalleryHorizontal:zse,LucideGalleryHorizontalEnd:Fse,LucideGalleryThumbnails:Bse,LucideGalleryVertical:Use,LucideGalleryVerticalEnd:$se,LucideGamepad:Vse,LucideGamepad2:qse,LucideGanttChart:Z3,LucideGanttChartSquare:D_,LucideGauge:Hse,LucideGaugeCircle:h5,LucideGavel:Gse,LucideGem:Wse,LucideGhost:EA,LucideGift:Bi,LucideGitBranch:Yse,LucideGitBranchPlus:Kse,LucideGitCommit:$5,LucideGitCommitHorizontal:$5,LucideGitCommitVertical:Zse,LucideGitCompare:Xse,LucideGitCompareArrows:Qse,LucideGitFork:Jse,LucideGitGraph:ene,LucideGitMerge:tne,LucideGitPullRequest:one,LucideGitPullRequestArrow:sne,LucideGitPullRequestClosed:nne,LucideGitPullRequestCreate:ane,LucideGitPullRequestCreateArrow:rne,LucideGitPullRequestDraft:ine,LucideGithub:lne,LucideGitlab:cne,LucideGlassWater:dne,LucideGlasses:une,LucideGlobe:lc,LucideGlobe2:M5,LucideGlobeLock:hne,LucideGoal:mne,LucideGrab:pne,LucideGraduationCap:_d,LucideGrape:fne,LucideGrid:xv,LucideGrid2X2:q5,LucideGrid2X2Plus:U5,LucideGrid2x2:q5,LucideGrid2x2Check:xne,LucideGrid2x2Plus:U5,LucideGrid2x2X:gne,LucideGrid3X3:xv,LucideGrid3x3:xv,LucideGrip:vne,LucideGripHorizontal:yne,LucideGripVertical:Uu,LucideGroup:bne,LucideGuitar:_ne,LucideHam:wne,LucideHammer:o9,LucideHand:l9,LucideHandCoins:jne,LucideHandHeart:AA,LucideHandHelping:sb,LucideHandMetal:Nne,LucideHandPlatter:kne,LucideHandshake:fb,LucideHardDrive:c9,LucideHardDriveDownload:Sne,LucideHardDriveUpload:Cne,LucideHardHat:Tne,LucideHash:JS,LucideHaze:Ene,LucideHdmiPort:Ane,LucideHeading:Lne,LucideHeading1:aL,LucideHeading2:iL,LucideHeading3:d9,LucideHeading4:Mne,LucideHeading5:Ine,LucideHeading6:Pne,LucideHeadphoneOff:Dne,LucideHeadphones:Rne,LucideHeadset:One,LucideHeart:yi,LucideHeartCrack:Fne,LucideHeartHandshake:MA,LucideHeartOff:zne,LucideHeartPulse:Bne,LucideHeater:$ne,LucideHelpCircle:Y_,LucideHelpingHand:sb,LucideHexagon:Une,LucideHighlighter:qne,LucideHistory:IA,LucideHome:zr,LucideHop:Hne,LucideHopOff:Vne,LucideHospital:Gne,LucideHotel:Wne,LucideHourglass:Kne,LucideHouse:zr,LucideHousePlug:Yne,LucideHousePlus:Zne,LucideIceCream:H5,LucideIceCream2:V5,LucideIceCreamBowl:V5,LucideIceCreamCone:H5,LucideIdCard:Qne,LucideImage:nl,LucideImageDown:Xne,LucideImageMinus:Jne,LucideImageOff:ere,LucideImagePlay:tre,LucideImagePlus:ay,LucideImageUp:sre,LucideImageUpscale:nre,LucideImages:rre,LucideImport:are,LucideInbox:Z2,LucideIndent:W5,LucideIndentDecrease:G5,LucideIndentIncrease:W5,LucideIndianRupee:ire,LucideInfinity:ore,LucideInfo:vw,LucideInspect:QT,LucideInspectionPanel:lre,LucideInstagram:mu,LucideItalic:e4,LucideIterationCcw:cre,LucideIterationCw:dre,LucideJapaneseYen:ure,LucideJoystick:hre,LucideKanban:Q2,LucideKanbanSquare:GT,LucideKanbanSquareDashed:zT,LucideKey:Gg,LucideKeyRound:PA,LucideKeySquare:mre,LucideKeyboard:xre,LucideKeyboardMusic:pre,LucideKeyboardOff:fre,LucideLamp:wre,LucideLampCeiling:gre,LucideLampDesk:yre,LucideLampFloor:vre,LucideLampWallDown:bre,LucideLampWallUp:_re,LucideLandPlot:jre,LucideLandmark:Nre,LucideLanguages:kre,LucideLaptop:Cre,LucideLaptop2:K5,LucideLaptopMinimal:K5,LucideLaptopMinimalCheck:Sre,LucideLasso:Ere,LucideLassoSelect:Tre,LucideLaugh:Are,LucideLayers:u9,LucideLayers2:Mre,LucideLayers3:Ire,LucideLayout:E2,LucideLayoutDashboard:t4,LucideLayoutGrid:vf,LucideLayoutList:Pre,LucideLayoutPanelLeft:Lre,LucideLayoutPanelTop:Dre,LucideLayoutTemplate:s4,LucideLeaf:Rre,LucideLeafyGreen:Ore,LucideLectern:Fre,LucideLetterText:zre,LucideLibrary:Wg,LucideLibraryBig:Bre,LucideLibrarySquare:WT,LucideLifeBuoy:oL,LucideLigature:$re,LucideLightbulb:bw,LucideLightbulbOff:Ure,LucideLineChart:W3,LucideLink:tl,LucideLink2:El,LucideLink2Off:qre,LucideLinkedin:bf,LucideList:Ep,LucideListCheck:Vre,LucideListChecks:pu,LucideListCollapse:Hre,LucideListEnd:Gre,LucideListFilter:h9,LucideListMinus:Wre,LucideListMusic:Kre,LucideListOrdered:zv,LucideListPlus:Yre,LucideListRestart:Zre,LucideListStart:Qre,LucideListTodo:Xre,LucideListTree:Jre,LucideListVideo:eae,LucideListX:tae,LucideLoader:nae,LucideLoader2:ss,LucideLoaderCircle:ss,LucideLoaderPinwheel:sae,LucideLocate:lL,LucideLocateFixed:rae,LucideLocateOff:aae,LucideLock:Rc,LucideLockKeyhole:iae,LucideLockKeyholeOpen:Y5,LucideLockOpen:Z5,LucideLogIn:LA,LucideLogOut:DA,LucideLogs:oae,LucideLollipop:lae,LucideLuggage:cae,LucideMSquare:KT,LucideMagnet:dae,LucideMail:Hs,LucideMailCheck:cL,LucideMailMinus:uae,LucideMailOpen:dL,LucideMailPlus:m9,LucideMailQuestion:hae,LucideMailSearch:mae,LucideMailWarning:pae,LucideMailX:uL,LucideMailbox:fae,LucideMails:xae,LucideMap:RA,LucideMapPin:Ca,LucideMapPinCheck:yae,LucideMapPinCheckInside:gae,LucideMapPinHouse:vae,LucideMapPinMinus:_ae,LucideMapPinMinusInside:bae,LucideMapPinOff:wae,LucideMapPinPlus:Nae,LucideMapPinPlusInside:jae,LucideMapPinX:Sae,LucideMapPinXInside:kae,LucideMapPinned:Cae,LucideMartini:Tae,LucideMaximize:OA,LucideMaximize2:p9,LucideMedal:X2,LucideMegaphone:qd,LucideMegaphoneOff:Eae,LucideMeh:Aae,LucideMemoryStick:Mae,LucideMenu:n4,LucideMenuSquare:YT,LucideMerge:Iae,LucideMessageCircle:Ql,LucideMessageCircleCode:Pae,LucideMessageCircleDashed:Lae,LucideMessageCircleHeart:hL,LucideMessageCircleMore:Dae,LucideMessageCircleOff:Rae,LucideMessageCirclePlus:Oae,LucideMessageCircleQuestion:f9,LucideMessageCircleReply:Fae,LucideMessageCircleWarning:zae,LucideMessageCircleX:Bae,LucideMessageSquare:Ci,LucideMessageSquareCode:$ae,LucideMessageSquareDashed:Uae,LucideMessageSquareDiff:qae,LucideMessageSquareDot:Vae,LucideMessageSquareHeart:mL,LucideMessageSquareLock:Hae,LucideMessageSquareMore:x9,LucideMessageSquareOff:Gae,LucideMessageSquarePlus:rw,LucideMessageSquareQuote:_w,LucideMessageSquareReply:Wae,LucideMessageSquareShare:Kae,LucideMessageSquareText:Yae,LucideMessageSquareWarning:Zae,LucideMessageSquareX:Qae,LucideMessagesSquare:pL,LucideMic:Bv,LucideMic2:Q5,LucideMicOff:Xae,LucideMicVocal:Q5,LucideMicrochip:Jae,LucideMicroscope:eie,LucideMicrowave:tie,LucideMilestone:sie,LucideMilk:rie,LucideMilkOff:nie,LucideMinimize:iie,LucideMinimize2:aie,LucideMinus:xb,LucideMinusCircle:m5,LucideMinusSquare:ZT,LucideMonitor:gb,LucideMonitorCheck:oie,LucideMonitorCog:lie,LucideMonitorDot:cie,LucideMonitorDown:die,LucideMonitorOff:uie,LucideMonitorPause:hie,LucideMonitorPlay:fL,LucideMonitorSmartphone:mie,LucideMonitorSpeaker:pie,LucideMonitorStop:fie,LucideMonitorUp:FA,LucideMonitorX:xie,LucideMoon:yie,LucideMoonStar:gie,LucideMoreHorizontal:Xf,LucideMoreVertical:Lg,LucideMountain:bie,LucideMountainSnow:vie,LucideMouse:Nie,LucideMouseOff:_ie,LucideMousePointer:Fm,LucideMousePointer2:wie,LucideMousePointerBan:jie,LucideMousePointerClick:oc,LucideMousePointerSquareDashed:BT,LucideMove:Oie,LucideMove3D:X5,LucideMove3d:X5,LucideMoveDiagonal:Sie,LucideMoveDiagonal2:kie,LucideMoveDown:Eie,LucideMoveDownLeft:Cie,LucideMoveDownRight:Tie,LucideMoveHorizontal:Aie,LucideMoveLeft:Mie,LucideMoveRight:Iie,LucideMoveUp:Die,LucideMoveUpLeft:Pie,LucideMoveUpRight:Lie,LucideMoveVertical:Rie,LucideMusic:xL,LucideMusic2:Fie,LucideMusic3:zie,LucideMusic4:Bie,LucideNavigation:g9,LucideNavigation2:Uie,LucideNavigation2Off:$ie,LucideNavigationOff:qie,LucideNetwork:Vie,LucideNewspaper:iy,LucideNfc:Hie,LucideNotebook:Yie,LucideNotebookPen:Gie,LucideNotebookTabs:Wie,LucideNotebookText:Kie,LucideNotepadText:Qie,LucideNotepadTextDashed:Zie,LucideNut:Jie,LucideNutOff:Xie,LucideOctagon:toe,LucideOctagonAlert:Z_,LucideOctagonMinus:eoe,LucideOctagonPause:J5,LucideOctagonX:eT,LucideOmega:soe,LucideOption:noe,LucideOrbit:roe,LucideOrigami:aoe,LucideOutdent:G5,LucidePackage:Oc,LucidePackage2:ioe,LucidePackageCheck:ooe,LucidePackageMinus:loe,LucidePackageOpen:coe,LucidePackagePlus:y9,LucidePackageSearch:doe,LucidePackageX:uoe,LucidePaintBucket:hoe,LucidePaintRoller:moe,LucidePaintbrush:poe,LucidePaintbrush2:tT,LucidePaintbrushVertical:tT,LucidePalette:xl,LucidePalmtree:yE,LucidePanelBottom:goe,LucidePanelBottomClose:foe,LucidePanelBottomDashed:sT,LucidePanelBottomInactive:sT,LucidePanelBottomOpen:xoe,LucidePanelLeft:iT,LucidePanelLeftClose:nT,LucidePanelLeftDashed:rT,LucidePanelLeftInactive:rT,LucidePanelLeftOpen:aT,LucidePanelRight:boe,LucidePanelRightClose:yoe,LucidePanelRightDashed:oT,LucidePanelRightInactive:oT,LucidePanelRightOpen:voe,LucidePanelTop:joe,LucidePanelTopClose:_oe,LucidePanelTopDashed:lT,LucidePanelTopInactive:lT,LucidePanelTopOpen:woe,LucidePanelsLeftBottom:Noe,LucidePanelsLeftRight:Yk,LucidePanelsRightBottom:koe,LucidePanelsTopBottom:mT,LucidePanelsTopLeft:E2,LucidePaperclip:r4,LucideParentheses:Soe,LucideParkingCircle:f5,LucideParkingCircleOff:p5,LucideParkingMeter:Coe,LucideParkingSquare:JT,LucideParkingSquareOff:XT,LucidePartyPopper:uh,LucidePause:_f,LucidePauseCircle:x5,LucidePauseOctagon:J5,LucidePawPrint:Toe,LucidePcCase:Eoe,LucidePen:Nv,LucidePenBox:Tu,LucidePenLine:nb,LucidePenOff:Aoe,LucidePenSquare:Tu,LucidePenTool:a4,LucidePencil:ja,LucidePencilLine:gL,LucidePencilOff:Moe,LucidePencilRuler:Ioe,LucidePentagon:Poe,LucidePercent:i4,LucidePercentCircle:g5,LucidePercentDiamond:A5,LucidePercentSquare:eE,LucidePersonStanding:Loe,LucidePhilippinePeso:Doe,LucidePhone:Pr,LucidePhoneCall:v9,LucidePhoneForwarded:Roe,LucidePhoneIncoming:Ooe,LucidePhoneMissed:Foe,LucidePhoneOff:zoe,LucidePhoneOutgoing:Boe,LucidePi:$oe,LucidePiSquare:tE,LucidePiano:Uoe,LucidePickaxe:qoe,LucidePictureInPicture:Hoe,LucidePictureInPicture2:Voe,LucidePieChart:Q3,LucidePiggyBank:Goe,LucidePilcrow:Yoe,LucidePilcrowLeft:Woe,LucidePilcrowRight:Koe,LucidePilcrowSquare:sE,LucidePill:Qoe,LucidePillBottle:Zoe,LucidePin:o4,LucidePinOff:b9,LucidePipette:Xoe,LucidePizza:Joe,LucidePlane:_9,LucidePlaneLanding:ele,LucidePlaneTakeoff:tle,LucidePlay:Al,LucidePlayCircle:Pu,LucidePlaySquare:nE,LucidePlug:J2,LucidePlug2:sle,LucidePlugZap:cT,LucidePlugZap2:cT,LucidePlus:As,LucidePlusCircle:y5,LucidePlusSquare:rE,LucidePocket:rle,LucidePocketKnife:nle,LucidePodcast:ale,LucidePointer:ole,LucidePointerOff:ile,LucidePopcorn:lle,LucidePopsicle:cle,LucidePoundSterling:dle,LucidePower:w9,LucidePowerCircle:v5,LucidePowerOff:ule,LucidePowerSquare:aE,LucidePresentation:oy,LucidePrinter:j9,LucidePrinterCheck:hle,LucideProjector:mle,LucideProportions:ple,LucidePuzzle:fle,LucidePyramid:xle,LucideQrCode:ly,LucideQuote:yb,LucideRabbit:gle,LucideRadar:zA,LucideRadiation:yle,LucideRadical:vle,LucideRadio:wf,LucideRadioReceiver:ble,LucideRadioTower:_le,LucideRadius:wle,LucideRailSymbol:jle,LucideRainbow:Nle,LucideRat:kle,LucideRatio:Sle,LucideReceipt:Dle,LucideReceiptCent:Cle,LucideReceiptEuro:Tle,LucideReceiptIndianRupee:Ele,LucideReceiptJapaneseYen:Ale,LucideReceiptPoundSterling:Mle,LucideReceiptRussianRuble:Ile,LucideReceiptSwissFranc:Ple,LucideReceiptText:Lle,LucideRectangleEllipsis:dT,LucideRectangleHorizontal:Rle,LucideRectangleVertical:Ole,LucideRecycle:Fle,LucideRedo:l4,LucideRedo2:zle,LucideRedoDot:Ble,LucideRefreshCcw:yL,LucideRefreshCcwDot:$le,LucideRefreshCw:Ai,LucideRefreshCwOff:Ule,LucideRefrigerator:qle,LucideRegex:Vle,LucideRemoveFormatting:Hle,LucideRepeat:vL,LucideRepeat1:Gle,LucideRepeat2:Wle,LucideReplace:Yle,LucideReplaceAll:Kle,LucideReply:N9,LucideReplyAll:Zle,LucideRewind:Qle,LucideRibbon:Xle,LucideRocket:nx,LucideRockingChair:Jle,LucideRollerCoaster:ece,LucideRotate3D:uT,LucideRotate3d:uT,LucideRotateCcw:Fh,LucideRotateCcwSquare:tce,LucideRotateCw:BA,LucideRotateCwSquare:sce,LucideRoute:k9,LucideRouteOff:nce,LucideRouter:rce,LucideRows:hT,LucideRows2:hT,LucideRows3:mT,LucideRows4:ace,LucideRss:ice,LucideRuler:eN,LucideRussianRuble:oce,LucideSailboat:lce,LucideSalad:cce,LucideSandwich:dce,LucideSatellite:hce,LucideSatelliteDish:uce,LucideSave:Ho,LucideSaveAll:mce,LucideSaveOff:pce,LucideScale:S9,LucideScale3D:pT,LucideScale3d:pT,LucideScaling:fce,LucideScan:jce,LucideScanBarcode:xce,LucideScanEye:gce,LucideScanFace:yce,LucideScanLine:vce,LucideScanQrCode:bce,LucideScanSearch:_ce,LucideScanText:wce,LucideScatterChart:X3,LucideSchool:Nce,LucideSchool2:bE,LucideScissors:Sce,LucideScissorsLineDashed:kce,LucideScissorsSquare:iE,LucideScissorsSquareDashedBottom:IT,LucideScreenShare:Tce,LucideScreenShareOff:Cce,LucideScroll:Ece,LucideScrollText:C9,LucideSearch:_r,LucideSearchCheck:Ace,LucideSearchCode:Mce,LucideSearchSlash:Ice,LucideSearchX:T9,LucideSection:Pce,LucideSend:cr,LucideSendHorizonal:fT,LucideSendHorizontal:fT,LucideSendToBack:Lce,LucideSeparatorHorizontal:Dce,LucideSeparatorVertical:Rce,LucideServer:Bce,LucideServerCog:Oce,LucideServerCrash:Fce,LucideServerOff:zce,LucideSettings:Vo,LucideSettings2:E9,LucideShapes:$ce,LucideShare:A9,LucideShare2:Hl,LucideSheet:Uce,LucideShell:qce,LucideShield:hh,LucideShieldAlert:bL,LucideShieldBan:Vce,LucideShieldCheck:ng,LucideShieldClose:xT,LucideShieldEllipsis:Hce,LucideShieldHalf:Gce,LucideShieldMinus:Wce,LucideShieldOff:$A,LucideShieldPlus:Kce,LucideShieldQuestion:Yce,LucideShieldX:xT,LucideShip:Qce,LucideShipWheel:Zce,LucideShirt:Xce,LucideShoppingBag:ww,LucideShoppingBasket:Jce,LucideShoppingCart:zg,LucideShovel:ede,LucideShowerHead:tde,LucideShrink:sde,LucideShrub:nde,LucideShuffle:UA,LucideSidebar:iT,LucideSidebarClose:nT,LucideSidebarOpen:aT,LucideSigma:rde,LucideSigmaSquare:oE,LucideSignal:cde,LucideSignalHigh:ade,LucideSignalLow:ide,LucideSignalMedium:ode,LucideSignalZero:lde,LucideSignature:dde,LucideSignpost:hde,LucideSignpostBig:ude,LucideSiren:mde,LucideSkipBack:pde,LucideSkipForward:fde,LucideSkull:xde,LucideSlack:gde,LucideSlash:yde,LucideSlashSquare:lE,LucideSlice:vde,LucideSliders:gT,LucideSlidersHorizontal:c4,LucideSlidersVertical:gT,LucideSmartphone:rg,LucideSmartphoneCharging:bde,LucideSmartphoneNfc:_de,LucideSmile:jde,LucideSmilePlus:wde,LucideSnail:Nde,LucideSnowflake:Mv,LucideSofa:kde,LucideSortAsc:I3,LucideSortDesc:E3,LucideSoup:Sde,LucideSpace:Cde,LucideSpade:Tde,LucideSparkle:tN,LucideSparkles:un,LucideSpeaker:Ede,LucideSpeech:Ade,LucideSpellCheck:Ide,LucideSpellCheck2:Mde,LucideSpline:Pde,LucideSplit:Lde,LucideSplitSquareHorizontal:cE,LucideSplitSquareVertical:dE,LucideSprayCan:Dde,LucideSprout:qA,LucideSquare:cy,LucideSquareActivity:yT,LucideSquareArrowDown:_T,LucideSquareArrowDownLeft:vT,LucideSquareArrowDownRight:bT,LucideSquareArrowLeft:wT,LucideSquareArrowOutDownLeft:jT,LucideSquareArrowOutDownRight:NT,LucideSquareArrowOutUpLeft:kT,LucideSquareArrowOutUpRight:ST,LucideSquareArrowRight:CT,LucideSquareArrowUp:AT,LucideSquareArrowUpLeft:TT,LucideSquareArrowUpRight:ET,LucideSquareAsterisk:MT,LucideSquareBottomDashedScissors:IT,LucideSquareChartGantt:D_,LucideSquareCheck:PT,LucideSquareCheckBig:A2,LucideSquareChevronDown:LT,LucideSquareChevronLeft:DT,LucideSquareChevronRight:RT,LucideSquareChevronUp:OT,LucideSquareCode:FT,LucideSquareDashed:$T,LucideSquareDashedBottom:Ode,LucideSquareDashedBottomCode:Rde,LucideSquareDashedKanban:zT,LucideSquareDashedMousePointer:BT,LucideSquareDivide:UT,LucideSquareDot:qT,LucideSquareEqual:VT,LucideSquareFunction:HT,LucideSquareGanttChart:D_,LucideSquareKanban:GT,LucideSquareLibrary:WT,LucideSquareM:KT,LucideSquareMenu:YT,LucideSquareMinus:ZT,LucideSquareMousePointer:QT,LucideSquareParking:JT,LucideSquareParkingOff:XT,LucideSquarePen:Tu,LucideSquarePercent:eE,LucideSquarePi:tE,LucideSquarePilcrow:sE,LucideSquarePlay:nE,LucideSquarePlus:rE,LucideSquarePower:aE,LucideSquareRadical:Fde,LucideSquareScissors:iE,LucideSquareSigma:oE,LucideSquareSlash:lE,LucideSquareSplitHorizontal:cE,LucideSquareSplitVertical:dE,LucideSquareSquare:zde,LucideSquareStack:Bde,LucideSquareTerminal:uE,LucideSquareUser:mE,LucideSquareUserRound:hE,LucideSquareX:pE,LucideSquircle:$de,LucideSquirrel:Ude,LucideStamp:qde,LucideStar:ua,LucideStarHalf:Vde,LucideStarOff:Hde,LucideStars:un,LucideStepBack:Gde,LucideStepForward:Wde,LucideStethoscope:Kde,LucideSticker:Yde,LucideStickyNote:M9,LucideStopCircle:_5,LucideStore:I9,LucideStretchHorizontal:Zde,LucideStretchVertical:Qde,LucideStrikethrough:P9,LucideSubscript:Xde,LucideSubtitles:B3,LucideSun:vb,LucideSunDim:Jde,LucideSunMedium:eue,LucideSunMoon:tue,LucideSunSnow:sue,LucideSunrise:nue,LucideSunset:rue,LucideSuperscript:aue,LucideSwatchBook:iue,LucideSwissFranc:oue,LucideSwitchCamera:lue,LucideSword:cue,LucideSwords:due,LucideSyringe:uue,LucideTable:wL,LucideTable2:_L,LucideTableCellsMerge:hue,LucideTableCellsSplit:mue,LucideTableColumnsSplit:pue,LucideTableOfContents:fue,LucideTableProperties:xue,LucideTableRowsSplit:gue,LucideTablet:jL,LucideTabletSmartphone:yue,LucideTablets:vue,LucideTag:mh,LucideTags:L9,LucideTally1:bue,LucideTally2:_ue,LucideTally3:wue,LucideTally4:jue,LucideTally5:Nue,LucideTangent:kue,LucideTarget:wc,LucideTelescope:Sue,LucideTent:Tue,LucideTentTree:Cue,LucideTerminal:Eue,LucideTerminalSquare:uE,LucideTestTube:Aue,LucideTestTube2:fE,LucideTestTubeDiagonal:fE,LucideTestTubes:Mue,LucideText:Rue,LucideTextCursor:Pue,LucideTextCursorInput:Iue,LucideTextQuote:Lue,LucideTextSearch:Due,LucideTextSelect:xE,LucideTextSelection:xE,LucideTheater:Oue,LucideThermometer:D9,LucideThermometerSnowflake:Fue,LucideThermometerSun:zue,LucideThumbsDown:R9,LucideThumbsUp:Hm,LucideTicket:O9,LucideTicketCheck:Bue,LucideTicketMinus:$ue,LucideTicketPercent:Uue,LucideTicketPlus:que,LucideTicketSlash:Vue,LucideTicketX:Hue,LucideTickets:Wue,LucideTicketsPlane:Gue,LucideTimer:Zue,LucideTimerOff:Kue,LucideTimerReset:Yue,LucideToggleLeft:Que,LucideToggleRight:Xue,LucideToilet:Jue,LucideTornado:ehe,LucideTorus:the,LucideTouchpad:nhe,LucideTouchpadOff:she,LucideTowerControl:rhe,LucideToyBrick:ahe,LucideTractor:ihe,LucideTrafficCone:ohe,LucideTrain:gE,LucideTrainFront:che,LucideTrainFrontTunnel:lhe,LucideTrainTrack:dhe,LucideTramFront:gE,LucideTrash:uhe,LucideTrash2:bn,LucideTreeDeciduous:hhe,LucideTreePalm:yE,LucideTreePine:d4,LucideTrees:mhe,LucideTrello:phe,LucideTrendingDown:bb,LucideTrendingUp:mo,LucideTrendingUpDown:fhe,LucideTriangle:ghe,LucideTriangleAlert:Dl,LucideTriangleRight:xhe,LucideTrophy:vo,LucideTruck:F9,LucideTurtle:yhe,LucideTv:bhe,LucideTv2:vE,LucideTvMinimal:vE,LucideTvMinimalPlay:vhe,LucideTwitch:_he,LucideTwitter:whe,LucideType:Nhe,LucideTypeOutline:jhe,LucideUmbrella:She,LucideUmbrellaOff:khe,LucideUnderline:NL,LucideUndo:u4,LucideUndo2:z9,LucideUndoDot:Che,LucideUnfoldHorizontal:The,LucideUnfoldVertical:Ehe,LucideUngroup:Ahe,LucideUniversity:bE,LucideUnlink:VA,LucideUnlink2:Mhe,LucideUnlock:Z5,LucideUnlockKeyhole:Y5,LucideUnplug:Ihe,LucideUpload:Sa,LucideUploadCloud:C5,LucideUsb:Phe,LucideUser:Xi,LucideUser2:SE,LucideUserCheck:_b,LucideUserCheck2:_E,LucideUserCircle:j5,LucideUserCircle2:w5,LucideUserCog:B9,LucideUserCog2:wE,LucideUserMinus:$9,LucideUserMinus2:jE,LucideUserPen:Lhe,LucideUserPlus:Fo,LucideUserPlus2:NE,LucideUserRound:SE,LucideUserRoundCheck:_E,LucideUserRoundCog:wE,LucideUserRoundMinus:jE,LucideUserRoundPen:Dhe,LucideUserRoundPlus:NE,LucideUserRoundSearch:Rhe,LucideUserRoundX:kE,LucideUserSearch:Ohe,LucideUserSquare:mE,LucideUserSquare2:hE,LucideUserX:Fhe,LucideUserX2:kE,LucideUsers:_n,LucideUsers2:W0,LucideUsersRound:W0,LucideUtensils:TE,LucideUtensilsCrossed:CE,LucideUtilityPole:zhe,LucideVariable:kL,LucideVault:Bhe,LucideVegan:$he,LucideVenetianMask:Uhe,LucideVerified:D3,LucideVibrate:Vhe,LucideVibrateOff:qhe,LucideVideo:vr,LucideVideoOff:Hhe,LucideVideotape:Ghe,LucideView:Whe,LucideVoicemail:Khe,LucideVolleyball:Yhe,LucideVolume:Xhe,LucideVolume1:Zhe,LucideVolume2:U9,LucideVolumeOff:Qhe,LucideVolumeX:q9,LucideVote:Jhe,LucideWallet:SL,LucideWallet2:EE,LucideWalletCards:eme,LucideWalletMinimal:EE,LucideWallpaper:tme,LucideWand:sme,LucideWand2:Rm,LucideWandSparkles:Rm,LucideWarehouse:nme,LucideWashingMachine:rme,LucideWatch:ame,LucideWaves:ime,LucideWaypoints:ome,LucideWebcam:lme,LucideWebhook:dme,LucideWebhookOff:cme,LucideWeight:ume,LucideWheat:mme,LucideWheatOff:hme,LucideWholeWord:pme,LucideWifi:vme,LucideWifiHigh:fme,LucideWifiLow:xme,LucideWifiOff:gme,LucideWifiZero:yme,LucideWind:_me,LucideWindArrowDown:bme,LucideWine:V9,LucideWineOff:wme,LucideWorkflow:H9,LucideWorm:jme,LucideWrapText:Nme,LucideWrench:wb,LucideX:Fn,LucideXCircle:Gc,LucideXOctagon:eT,LucideXSquare:pE,LucideYoutube:kme,LucideZap:ph,LucideZapOff:Sme,LucideZoomIn:h4,LucideZoomOut:CL,Luggage:cae,LuggageIcon:cae,MSquare:KT,MSquareIcon:KT,Magnet:dae,MagnetIcon:dae,Mail:Hs,MailCheck:cL,MailCheckIcon:cL,MailIcon:Hs,MailMinus:uae,MailMinusIcon:uae,MailOpen:dL,MailOpenIcon:dL,MailPlus:m9,MailPlusIcon:m9,MailQuestion:hae,MailQuestionIcon:hae,MailSearch:mae,MailSearchIcon:mae,MailWarning:pae,MailWarningIcon:pae,MailX:uL,MailXIcon:uL,Mailbox:fae,MailboxIcon:fae,Mails:xae,MailsIcon:xae,Map:RA,MapIcon:RA,MapPin:Ca,MapPinCheck:yae,MapPinCheckIcon:yae,MapPinCheckInside:gae,MapPinCheckInsideIcon:gae,MapPinHouse:vae,MapPinHouseIcon:vae,MapPinIcon:Ca,MapPinMinus:_ae,MapPinMinusIcon:_ae,MapPinMinusInside:bae,MapPinMinusInsideIcon:bae,MapPinOff:wae,MapPinOffIcon:wae,MapPinPlus:Nae,MapPinPlusIcon:Nae,MapPinPlusInside:jae,MapPinPlusInsideIcon:jae,MapPinX:Sae,MapPinXIcon:Sae,MapPinXInside:kae,MapPinXInsideIcon:kae,MapPinned:Cae,MapPinnedIcon:Cae,Martini:Tae,MartiniIcon:Tae,Maximize:OA,Maximize2:p9,Maximize2Icon:p9,MaximizeIcon:OA,Medal:X2,MedalIcon:X2,Megaphone:qd,MegaphoneIcon:qd,MegaphoneOff:Eae,MegaphoneOffIcon:Eae,Meh:Aae,MehIcon:Aae,MemoryStick:Mae,MemoryStickIcon:Mae,Menu:n4,MenuIcon:n4,MenuSquare:YT,MenuSquareIcon:YT,Merge:Iae,MergeIcon:Iae,MessageCircle:Ql,MessageCircleCode:Pae,MessageCircleCodeIcon:Pae,MessageCircleDashed:Lae,MessageCircleDashedIcon:Lae,MessageCircleHeart:hL,MessageCircleHeartIcon:hL,MessageCircleIcon:Ql,MessageCircleMore:Dae,MessageCircleMoreIcon:Dae,MessageCircleOff:Rae,MessageCircleOffIcon:Rae,MessageCirclePlus:Oae,MessageCirclePlusIcon:Oae,MessageCircleQuestion:f9,MessageCircleQuestionIcon:f9,MessageCircleReply:Fae,MessageCircleReplyIcon:Fae,MessageCircleWarning:zae,MessageCircleWarningIcon:zae,MessageCircleX:Bae,MessageCircleXIcon:Bae,MessageSquare:Ci,MessageSquareCode:$ae,MessageSquareCodeIcon:$ae,MessageSquareDashed:Uae,MessageSquareDashedIcon:Uae,MessageSquareDiff:qae,MessageSquareDiffIcon:qae,MessageSquareDot:Vae,MessageSquareDotIcon:Vae,MessageSquareHeart:mL,MessageSquareHeartIcon:mL,MessageSquareIcon:Ci,MessageSquareLock:Hae,MessageSquareLockIcon:Hae,MessageSquareMore:x9,MessageSquareMoreIcon:x9,MessageSquareOff:Gae,MessageSquareOffIcon:Gae,MessageSquarePlus:rw,MessageSquarePlusIcon:rw,MessageSquareQuote:_w,MessageSquareQuoteIcon:_w,MessageSquareReply:Wae,MessageSquareReplyIcon:Wae,MessageSquareShare:Kae,MessageSquareShareIcon:Kae,MessageSquareText:Yae,MessageSquareTextIcon:Yae,MessageSquareWarning:Zae,MessageSquareWarningIcon:Zae,MessageSquareX:Qae,MessageSquareXIcon:Qae,MessagesSquare:pL,MessagesSquareIcon:pL,Mic:Bv,Mic2:Q5,Mic2Icon:Q5,MicIcon:Bv,MicOff:Xae,MicOffIcon:Xae,MicVocal:Q5,MicVocalIcon:Q5,Microchip:Jae,MicrochipIcon:Jae,Microscope:eie,MicroscopeIcon:eie,Microwave:tie,MicrowaveIcon:tie,Milestone:sie,MilestoneIcon:sie,Milk:rie,MilkIcon:rie,MilkOff:nie,MilkOffIcon:nie,Minimize:iie,Minimize2:aie,Minimize2Icon:aie,MinimizeIcon:iie,Minus:xb,MinusCircle:m5,MinusCircleIcon:m5,MinusIcon:xb,MinusSquare:ZT,MinusSquareIcon:ZT,Monitor:gb,MonitorCheck:oie,MonitorCheckIcon:oie,MonitorCog:lie,MonitorCogIcon:lie,MonitorDot:cie,MonitorDotIcon:cie,MonitorDown:die,MonitorDownIcon:die,MonitorIcon:gb,MonitorOff:uie,MonitorOffIcon:uie,MonitorPause:hie,MonitorPauseIcon:hie,MonitorPlay:fL,MonitorPlayIcon:fL,MonitorSmartphone:mie,MonitorSmartphoneIcon:mie,MonitorSpeaker:pie,MonitorSpeakerIcon:pie,MonitorStop:fie,MonitorStopIcon:fie,MonitorUp:FA,MonitorUpIcon:FA,MonitorX:xie,MonitorXIcon:xie,Moon:yie,MoonIcon:yie,MoonStar:gie,MoonStarIcon:gie,MoreHorizontal:Xf,MoreHorizontalIcon:Xf,MoreVertical:Lg,MoreVerticalIcon:Lg,Mountain:bie,MountainIcon:bie,MountainSnow:vie,MountainSnowIcon:vie,Mouse:Nie,MouseIcon:Nie,MouseOff:_ie,MouseOffIcon:_ie,MousePointer:Fm,MousePointer2:wie,MousePointer2Icon:wie,MousePointerBan:jie,MousePointerBanIcon:jie,MousePointerClick:oc,MousePointerClickIcon:oc,MousePointerIcon:Fm,MousePointerSquareDashed:BT,MousePointerSquareDashedIcon:BT,Move:Oie,Move3D:X5,Move3DIcon:X5,Move3d:X5,Move3dIcon:X5,MoveDiagonal:Sie,MoveDiagonal2:kie,MoveDiagonal2Icon:kie,MoveDiagonalIcon:Sie,MoveDown:Eie,MoveDownIcon:Eie,MoveDownLeft:Cie,MoveDownLeftIcon:Cie,MoveDownRight:Tie,MoveDownRightIcon:Tie,MoveHorizontal:Aie,MoveHorizontalIcon:Aie,MoveIcon:Oie,MoveLeft:Mie,MoveLeftIcon:Mie,MoveRight:Iie,MoveRightIcon:Iie,MoveUp:Die,MoveUpIcon:Die,MoveUpLeft:Pie,MoveUpLeftIcon:Pie,MoveUpRight:Lie,MoveUpRightIcon:Lie,MoveVertical:Rie,MoveVerticalIcon:Rie,Music:xL,Music2:Fie,Music2Icon:Fie,Music3:zie,Music3Icon:zie,Music4:Bie,Music4Icon:Bie,MusicIcon:xL,Navigation:g9,Navigation2:Uie,Navigation2Icon:Uie,Navigation2Off:$ie,Navigation2OffIcon:$ie,NavigationIcon:g9,NavigationOff:qie,NavigationOffIcon:qie,Network:Vie,NetworkIcon:Vie,Newspaper:iy,NewspaperIcon:iy,Nfc:Hie,NfcIcon:Hie,Notebook:Yie,NotebookIcon:Yie,NotebookPen:Gie,NotebookPenIcon:Gie,NotebookTabs:Wie,NotebookTabsIcon:Wie,NotebookText:Kie,NotebookTextIcon:Kie,NotepadText:Qie,NotepadTextDashed:Zie,NotepadTextDashedIcon:Zie,NotepadTextIcon:Qie,Nut:Jie,NutIcon:Jie,NutOff:Xie,NutOffIcon:Xie,Octagon:toe,OctagonAlert:Z_,OctagonAlertIcon:Z_,OctagonIcon:toe,OctagonMinus:eoe,OctagonMinusIcon:eoe,OctagonPause:J5,OctagonPauseIcon:J5,OctagonX:eT,OctagonXIcon:eT,Omega:soe,OmegaIcon:soe,Option:noe,OptionIcon:noe,Orbit:roe,OrbitIcon:roe,Origami:aoe,OrigamiIcon:aoe,Outdent:G5,OutdentIcon:G5,Package:Oc,Package2:ioe,Package2Icon:ioe,PackageCheck:ooe,PackageCheckIcon:ooe,PackageIcon:Oc,PackageMinus:loe,PackageMinusIcon:loe,PackageOpen:coe,PackageOpenIcon:coe,PackagePlus:y9,PackagePlusIcon:y9,PackageSearch:doe,PackageSearchIcon:doe,PackageX:uoe,PackageXIcon:uoe,PaintBucket:hoe,PaintBucketIcon:hoe,PaintRoller:moe,PaintRollerIcon:moe,Paintbrush:poe,Paintbrush2:tT,Paintbrush2Icon:tT,PaintbrushIcon:poe,PaintbrushVertical:tT,PaintbrushVerticalIcon:tT,Palette:xl,PaletteIcon:xl,Palmtree:yE,PalmtreeIcon:yE,PanelBottom:goe,PanelBottomClose:foe,PanelBottomCloseIcon:foe,PanelBottomDashed:sT,PanelBottomDashedIcon:sT,PanelBottomIcon:goe,PanelBottomInactive:sT,PanelBottomInactiveIcon:sT,PanelBottomOpen:xoe,PanelBottomOpenIcon:xoe,PanelLeft:iT,PanelLeftClose:nT,PanelLeftCloseIcon:nT,PanelLeftDashed:rT,PanelLeftDashedIcon:rT,PanelLeftIcon:iT,PanelLeftInactive:rT,PanelLeftInactiveIcon:rT,PanelLeftOpen:aT,PanelLeftOpenIcon:aT,PanelRight:boe,PanelRightClose:yoe,PanelRightCloseIcon:yoe,PanelRightDashed:oT,PanelRightDashedIcon:oT,PanelRightIcon:boe,PanelRightInactive:oT,PanelRightInactiveIcon:oT,PanelRightOpen:voe,PanelRightOpenIcon:voe,PanelTop:joe,PanelTopClose:_oe,PanelTopCloseIcon:_oe,PanelTopDashed:lT,PanelTopDashedIcon:lT,PanelTopIcon:joe,PanelTopInactive:lT,PanelTopInactiveIcon:lT,PanelTopOpen:woe,PanelTopOpenIcon:woe,PanelsLeftBottom:Noe,PanelsLeftBottomIcon:Noe,PanelsLeftRight:Yk,PanelsLeftRightIcon:Yk,PanelsRightBottom:koe,PanelsRightBottomIcon:koe,PanelsTopBottom:mT,PanelsTopBottomIcon:mT,PanelsTopLeft:E2,PanelsTopLeftIcon:E2,Paperclip:r4,PaperclipIcon:r4,Parentheses:Soe,ParenthesesIcon:Soe,ParkingCircle:f5,ParkingCircleIcon:f5,ParkingCircleOff:p5,ParkingCircleOffIcon:p5,ParkingMeter:Coe,ParkingMeterIcon:Coe,ParkingSquare:JT,ParkingSquareIcon:JT,ParkingSquareOff:XT,ParkingSquareOffIcon:XT,PartyPopper:uh,PartyPopperIcon:uh,Pause:_f,PauseCircle:x5,PauseCircleIcon:x5,PauseIcon:_f,PauseOctagon:J5,PauseOctagonIcon:J5,PawPrint:Toe,PawPrintIcon:Toe,PcCase:Eoe,PcCaseIcon:Eoe,Pen:Nv,PenBox:Tu,PenBoxIcon:Tu,PenIcon:Nv,PenLine:nb,PenLineIcon:nb,PenOff:Aoe,PenOffIcon:Aoe,PenSquare:Tu,PenSquareIcon:Tu,PenTool:a4,PenToolIcon:a4,Pencil:ja,PencilIcon:ja,PencilLine:gL,PencilLineIcon:gL,PencilOff:Moe,PencilOffIcon:Moe,PencilRuler:Ioe,PencilRulerIcon:Ioe,Pentagon:Poe,PentagonIcon:Poe,Percent:i4,PercentCircle:g5,PercentCircleIcon:g5,PercentDiamond:A5,PercentDiamondIcon:A5,PercentIcon:i4,PercentSquare:eE,PercentSquareIcon:eE,PersonStanding:Loe,PersonStandingIcon:Loe,PhilippinePeso:Doe,PhilippinePesoIcon:Doe,Phone:Pr,PhoneCall:v9,PhoneCallIcon:v9,PhoneForwarded:Roe,PhoneForwardedIcon:Roe,PhoneIcon:Pr,PhoneIncoming:Ooe,PhoneIncomingIcon:Ooe,PhoneMissed:Foe,PhoneMissedIcon:Foe,PhoneOff:zoe,PhoneOffIcon:zoe,PhoneOutgoing:Boe,PhoneOutgoingIcon:Boe,Pi:$oe,PiIcon:$oe,PiSquare:tE,PiSquareIcon:tE,Piano:Uoe,PianoIcon:Uoe,Pickaxe:qoe,PickaxeIcon:qoe,PictureInPicture:Hoe,PictureInPicture2:Voe,PictureInPicture2Icon:Voe,PictureInPictureIcon:Hoe,PieChart:Q3,PieChartIcon:Q3,PiggyBank:Goe,PiggyBankIcon:Goe,Pilcrow:Yoe,PilcrowIcon:Yoe,PilcrowLeft:Woe,PilcrowLeftIcon:Woe,PilcrowRight:Koe,PilcrowRightIcon:Koe,PilcrowSquare:sE,PilcrowSquareIcon:sE,Pill:Qoe,PillBottle:Zoe,PillBottleIcon:Zoe,PillIcon:Qoe,Pin:o4,PinIcon:o4,PinOff:b9,PinOffIcon:b9,Pipette:Xoe,PipetteIcon:Xoe,Pizza:Joe,PizzaIcon:Joe,Plane:_9,PlaneIcon:_9,PlaneLanding:ele,PlaneLandingIcon:ele,PlaneTakeoff:tle,PlaneTakeoffIcon:tle,Play:Al,PlayCircle:Pu,PlayCircleIcon:Pu,PlayIcon:Al,PlaySquare:nE,PlaySquareIcon:nE,Plug:J2,Plug2:sle,Plug2Icon:sle,PlugIcon:J2,PlugZap:cT,PlugZap2:cT,PlugZap2Icon:cT,PlugZapIcon:cT,Plus:As,PlusCircle:y5,PlusCircleIcon:y5,PlusIcon:As,PlusSquare:rE,PlusSquareIcon:rE,Pocket:rle,PocketIcon:rle,PocketKnife:nle,PocketKnifeIcon:nle,Podcast:ale,PodcastIcon:ale,Pointer:ole,PointerIcon:ole,PointerOff:ile,PointerOffIcon:ile,Popcorn:lle,PopcornIcon:lle,Popsicle:cle,PopsicleIcon:cle,PoundSterling:dle,PoundSterlingIcon:dle,Power:w9,PowerCircle:v5,PowerCircleIcon:v5,PowerIcon:w9,PowerOff:ule,PowerOffIcon:ule,PowerSquare:aE,PowerSquareIcon:aE,Presentation:oy,PresentationIcon:oy,Printer:j9,PrinterCheck:hle,PrinterCheckIcon:hle,PrinterIcon:j9,Projector:mle,ProjectorIcon:mle,Proportions:ple,ProportionsIcon:ple,Puzzle:fle,PuzzleIcon:fle,Pyramid:xle,PyramidIcon:xle,QrCode:ly,QrCodeIcon:ly,Quote:yb,QuoteIcon:yb,Rabbit:gle,RabbitIcon:gle,Radar:zA,RadarIcon:zA,Radiation:yle,RadiationIcon:yle,Radical:vle,RadicalIcon:vle,Radio:wf,RadioIcon:wf,RadioReceiver:ble,RadioReceiverIcon:ble,RadioTower:_le,RadioTowerIcon:_le,Radius:wle,RadiusIcon:wle,RailSymbol:jle,RailSymbolIcon:jle,Rainbow:Nle,RainbowIcon:Nle,Rat:kle,RatIcon:kle,Ratio:Sle,RatioIcon:Sle,Receipt:Dle,ReceiptCent:Cle,ReceiptCentIcon:Cle,ReceiptEuro:Tle,ReceiptEuroIcon:Tle,ReceiptIcon:Dle,ReceiptIndianRupee:Ele,ReceiptIndianRupeeIcon:Ele,ReceiptJapaneseYen:Ale,ReceiptJapaneseYenIcon:Ale,ReceiptPoundSterling:Mle,ReceiptPoundSterlingIcon:Mle,ReceiptRussianRuble:Ile,ReceiptRussianRubleIcon:Ile,ReceiptSwissFranc:Ple,ReceiptSwissFrancIcon:Ple,ReceiptText:Lle,ReceiptTextIcon:Lle,RectangleEllipsis:dT,RectangleEllipsisIcon:dT,RectangleHorizontal:Rle,RectangleHorizontalIcon:Rle,RectangleVertical:Ole,RectangleVerticalIcon:Ole,Recycle:Fle,RecycleIcon:Fle,Redo:l4,Redo2:zle,Redo2Icon:zle,RedoDot:Ble,RedoDotIcon:Ble,RedoIcon:l4,RefreshCcw:yL,RefreshCcwDot:$le,RefreshCcwDotIcon:$le,RefreshCcwIcon:yL,RefreshCw:Ai,RefreshCwIcon:Ai,RefreshCwOff:Ule,RefreshCwOffIcon:Ule,Refrigerator:qle,RefrigeratorIcon:qle,Regex:Vle,RegexIcon:Vle,RemoveFormatting:Hle,RemoveFormattingIcon:Hle,Repeat:vL,Repeat1:Gle,Repeat1Icon:Gle,Repeat2:Wle,Repeat2Icon:Wle,RepeatIcon:vL,Replace:Yle,ReplaceAll:Kle,ReplaceAllIcon:Kle,ReplaceIcon:Yle,Reply:N9,ReplyAll:Zle,ReplyAllIcon:Zle,ReplyIcon:N9,Rewind:Qle,RewindIcon:Qle,Ribbon:Xle,RibbonIcon:Xle,Rocket:nx,RocketIcon:nx,RockingChair:Jle,RockingChairIcon:Jle,RollerCoaster:ece,RollerCoasterIcon:ece,Rotate3D:uT,Rotate3DIcon:uT,Rotate3d:uT,Rotate3dIcon:uT,RotateCcw:Fh,RotateCcwIcon:Fh,RotateCcwSquare:tce,RotateCcwSquareIcon:tce,RotateCw:BA,RotateCwIcon:BA,RotateCwSquare:sce,RotateCwSquareIcon:sce,Route:k9,RouteIcon:k9,RouteOff:nce,RouteOffIcon:nce,Router:rce,RouterIcon:rce,Rows:hT,Rows2:hT,Rows2Icon:hT,Rows3:mT,Rows3Icon:mT,Rows4:ace,Rows4Icon:ace,RowsIcon:hT,Rss:ice,RssIcon:ice,Ruler:eN,RulerIcon:eN,RussianRuble:oce,RussianRubleIcon:oce,Sailboat:lce,SailboatIcon:lce,Salad:cce,SaladIcon:cce,Sandwich:dce,SandwichIcon:dce,Satellite:hce,SatelliteDish:uce,SatelliteDishIcon:uce,SatelliteIcon:hce,Save:Ho,SaveAll:mce,SaveAllIcon:mce,SaveIcon:Ho,SaveOff:pce,SaveOffIcon:pce,Scale:S9,Scale3D:pT,Scale3DIcon:pT,Scale3d:pT,Scale3dIcon:pT,ScaleIcon:S9,Scaling:fce,ScalingIcon:fce,Scan:jce,ScanBarcode:xce,ScanBarcodeIcon:xce,ScanEye:gce,ScanEyeIcon:gce,ScanFace:yce,ScanFaceIcon:yce,ScanIcon:jce,ScanLine:vce,ScanLineIcon:vce,ScanQrCode:bce,ScanQrCodeIcon:bce,ScanSearch:_ce,ScanSearchIcon:_ce,ScanText:wce,ScanTextIcon:wce,ScatterChart:X3,ScatterChartIcon:X3,School:Nce,School2:bE,School2Icon:bE,SchoolIcon:Nce,Scissors:Sce,ScissorsIcon:Sce,ScissorsLineDashed:kce,ScissorsLineDashedIcon:kce,ScissorsSquare:iE,ScissorsSquareDashedBottom:IT,ScissorsSquareDashedBottomIcon:IT,ScissorsSquareIcon:iE,ScreenShare:Tce,ScreenShareIcon:Tce,ScreenShareOff:Cce,ScreenShareOffIcon:Cce,Scroll:Ece,ScrollIcon:Ece,ScrollText:C9,ScrollTextIcon:C9,Search:_r,SearchCheck:Ace,SearchCheckIcon:Ace,SearchCode:Mce,SearchCodeIcon:Mce,SearchIcon:_r,SearchSlash:Ice,SearchSlashIcon:Ice,SearchX:T9,SearchXIcon:T9,Section:Pce,SectionIcon:Pce,Send:cr,SendHorizonal:fT,SendHorizonalIcon:fT,SendHorizontal:fT,SendHorizontalIcon:fT,SendIcon:cr,SendToBack:Lce,SendToBackIcon:Lce,SeparatorHorizontal:Dce,SeparatorHorizontalIcon:Dce,SeparatorVertical:Rce,SeparatorVerticalIcon:Rce,Server:Bce,ServerCog:Oce,ServerCogIcon:Oce,ServerCrash:Fce,ServerCrashIcon:Fce,ServerIcon:Bce,ServerOff:zce,ServerOffIcon:zce,Settings:Vo,Settings2:E9,Settings2Icon:E9,SettingsIcon:Vo,Shapes:$ce,ShapesIcon:$ce,Share:A9,Share2:Hl,Share2Icon:Hl,ShareIcon:A9,Sheet:Uce,SheetIcon:Uce,Shell:qce,ShellIcon:qce,Shield:hh,ShieldAlert:bL,ShieldAlertIcon:bL,ShieldBan:Vce,ShieldBanIcon:Vce,ShieldCheck:ng,ShieldCheckIcon:ng,ShieldClose:xT,ShieldCloseIcon:xT,ShieldEllipsis:Hce,ShieldEllipsisIcon:Hce,ShieldHalf:Gce,ShieldHalfIcon:Gce,ShieldIcon:hh,ShieldMinus:Wce,ShieldMinusIcon:Wce,ShieldOff:$A,ShieldOffIcon:$A,ShieldPlus:Kce,ShieldPlusIcon:Kce,ShieldQuestion:Yce,ShieldQuestionIcon:Yce,ShieldX:xT,ShieldXIcon:xT,Ship:Qce,ShipIcon:Qce,ShipWheel:Zce,ShipWheelIcon:Zce,Shirt:Xce,ShirtIcon:Xce,ShoppingBag:ww,ShoppingBagIcon:ww,ShoppingBasket:Jce,ShoppingBasketIcon:Jce,ShoppingCart:zg,ShoppingCartIcon:zg,Shovel:ede,ShovelIcon:ede,ShowerHead:tde,ShowerHeadIcon:tde,Shrink:sde,ShrinkIcon:sde,Shrub:nde,ShrubIcon:nde,Shuffle:UA,ShuffleIcon:UA,Sidebar:iT,SidebarClose:nT,SidebarCloseIcon:nT,SidebarIcon:iT,SidebarOpen:aT,SidebarOpenIcon:aT,Sigma:rde,SigmaIcon:rde,SigmaSquare:oE,SigmaSquareIcon:oE,Signal:cde,SignalHigh:ade,SignalHighIcon:ade,SignalIcon:cde,SignalLow:ide,SignalLowIcon:ide,SignalMedium:ode,SignalMediumIcon:ode,SignalZero:lde,SignalZeroIcon:lde,Signature:dde,SignatureIcon:dde,Signpost:hde,SignpostBig:ude,SignpostBigIcon:ude,SignpostIcon:hde,Siren:mde,SirenIcon:mde,SkipBack:pde,SkipBackIcon:pde,SkipForward:fde,SkipForwardIcon:fde,Skull:xde,SkullIcon:xde,Slack:gde,SlackIcon:gde,Slash:yde,SlashIcon:yde,SlashSquare:lE,SlashSquareIcon:lE,Slice:vde,SliceIcon:vde,Sliders:gT,SlidersHorizontal:c4,SlidersHorizontalIcon:c4,SlidersIcon:gT,SlidersVertical:gT,SlidersVerticalIcon:gT,Smartphone:rg,SmartphoneCharging:bde,SmartphoneChargingIcon:bde,SmartphoneIcon:rg,SmartphoneNfc:_de,SmartphoneNfcIcon:_de,Smile:jde,SmileIcon:jde,SmilePlus:wde,SmilePlusIcon:wde,Snail:Nde,SnailIcon:Nde,Snowflake:Mv,SnowflakeIcon:Mv,Sofa:kde,SofaIcon:kde,SortAsc:I3,SortAscIcon:I3,SortDesc:E3,SortDescIcon:E3,Soup:Sde,SoupIcon:Sde,Space:Cde,SpaceIcon:Cde,Spade:Tde,SpadeIcon:Tde,Sparkle:tN,SparkleIcon:tN,Sparkles:un,SparklesIcon:un,Speaker:Ede,SpeakerIcon:Ede,Speech:Ade,SpeechIcon:Ade,SpellCheck:Ide,SpellCheck2:Mde,SpellCheck2Icon:Mde,SpellCheckIcon:Ide,Spline:Pde,SplineIcon:Pde,Split:Lde,SplitIcon:Lde,SplitSquareHorizontal:cE,SplitSquareHorizontalIcon:cE,SplitSquareVertical:dE,SplitSquareVerticalIcon:dE,SprayCan:Dde,SprayCanIcon:Dde,Sprout:qA,SproutIcon:qA,Square:cy,SquareActivity:yT,SquareActivityIcon:yT,SquareArrowDown:_T,SquareArrowDownIcon:_T,SquareArrowDownLeft:vT,SquareArrowDownLeftIcon:vT,SquareArrowDownRight:bT,SquareArrowDownRightIcon:bT,SquareArrowLeft:wT,SquareArrowLeftIcon:wT,SquareArrowOutDownLeft:jT,SquareArrowOutDownLeftIcon:jT,SquareArrowOutDownRight:NT,SquareArrowOutDownRightIcon:NT,SquareArrowOutUpLeft:kT,SquareArrowOutUpLeftIcon:kT,SquareArrowOutUpRight:ST,SquareArrowOutUpRightIcon:ST,SquareArrowRight:CT,SquareArrowRightIcon:CT,SquareArrowUp:AT,SquareArrowUpIcon:AT,SquareArrowUpLeft:TT,SquareArrowUpLeftIcon:TT,SquareArrowUpRight:ET,SquareArrowUpRightIcon:ET,SquareAsterisk:MT,SquareAsteriskIcon:MT,SquareBottomDashedScissors:IT,SquareBottomDashedScissorsIcon:IT,SquareChartGantt:D_,SquareChartGanttIcon:D_,SquareCheck:PT,SquareCheckBig:A2,SquareCheckBigIcon:A2,SquareCheckIcon:PT,SquareChevronDown:LT,SquareChevronDownIcon:LT,SquareChevronLeft:DT,SquareChevronLeftIcon:DT,SquareChevronRight:RT,SquareChevronRightIcon:RT,SquareChevronUp:OT,SquareChevronUpIcon:OT,SquareCode:FT,SquareCodeIcon:FT,SquareDashed:$T,SquareDashedBottom:Ode,SquareDashedBottomCode:Rde,SquareDashedBottomCodeIcon:Rde,SquareDashedBottomIcon:Ode,SquareDashedIcon:$T,SquareDashedKanban:zT,SquareDashedKanbanIcon:zT,SquareDashedMousePointer:BT,SquareDashedMousePointerIcon:BT,SquareDivide:UT,SquareDivideIcon:UT,SquareDot:qT,SquareDotIcon:qT,SquareEqual:VT,SquareEqualIcon:VT,SquareFunction:HT,SquareFunctionIcon:HT,SquareGanttChart:D_,SquareGanttChartIcon:D_,SquareIcon:cy,SquareKanban:GT,SquareKanbanIcon:GT,SquareLibrary:WT,SquareLibraryIcon:WT,SquareM:KT,SquareMIcon:KT,SquareMenu:YT,SquareMenuIcon:YT,SquareMinus:ZT,SquareMinusIcon:ZT,SquareMousePointer:QT,SquareMousePointerIcon:QT,SquareParking:JT,SquareParkingIcon:JT,SquareParkingOff:XT,SquareParkingOffIcon:XT,SquarePen:Tu,SquarePenIcon:Tu,SquarePercent:eE,SquarePercentIcon:eE,SquarePi:tE,SquarePiIcon:tE,SquarePilcrow:sE,SquarePilcrowIcon:sE,SquarePlay:nE,SquarePlayIcon:nE,SquarePlus:rE,SquarePlusIcon:rE,SquarePower:aE,SquarePowerIcon:aE,SquareRadical:Fde,SquareRadicalIcon:Fde,SquareScissors:iE,SquareScissorsIcon:iE,SquareSigma:oE,SquareSigmaIcon:oE,SquareSlash:lE,SquareSlashIcon:lE,SquareSplitHorizontal:cE,SquareSplitHorizontalIcon:cE,SquareSplitVertical:dE,SquareSplitVerticalIcon:dE,SquareSquare:zde,SquareSquareIcon:zde,SquareStack:Bde,SquareStackIcon:Bde,SquareTerminal:uE,SquareTerminalIcon:uE,SquareUser:mE,SquareUserIcon:mE,SquareUserRound:hE,SquareUserRoundIcon:hE,SquareX:pE,SquareXIcon:pE,Squircle:$de,SquircleIcon:$de,Squirrel:Ude,SquirrelIcon:Ude,Stamp:qde,StampIcon:qde,Star:ua,StarHalf:Vde,StarHalfIcon:Vde,StarIcon:ua,StarOff:Hde,StarOffIcon:Hde,Stars:un,StarsIcon:un,StepBack:Gde,StepBackIcon:Gde,StepForward:Wde,StepForwardIcon:Wde,Stethoscope:Kde,StethoscopeIcon:Kde,Sticker:Yde,StickerIcon:Yde,StickyNote:M9,StickyNoteIcon:M9,StopCircle:_5,StopCircleIcon:_5,Store:I9,StoreIcon:I9,StretchHorizontal:Zde,StretchHorizontalIcon:Zde,StretchVertical:Qde,StretchVerticalIcon:Qde,Strikethrough:P9,StrikethroughIcon:P9,Subscript:Xde,SubscriptIcon:Xde,Subtitles:B3,SubtitlesIcon:B3,Sun:vb,SunDim:Jde,SunDimIcon:Jde,SunIcon:vb,SunMedium:eue,SunMediumIcon:eue,SunMoon:tue,SunMoonIcon:tue,SunSnow:sue,SunSnowIcon:sue,Sunrise:nue,SunriseIcon:nue,Sunset:rue,SunsetIcon:rue,Superscript:aue,SuperscriptIcon:aue,SwatchBook:iue,SwatchBookIcon:iue,SwissFranc:oue,SwissFrancIcon:oue,SwitchCamera:lue,SwitchCameraIcon:lue,Sword:cue,SwordIcon:cue,Swords:due,SwordsIcon:due,Syringe:uue,SyringeIcon:uue,Table:wL,Table2:_L,Table2Icon:_L,TableCellsMerge:hue,TableCellsMergeIcon:hue,TableCellsSplit:mue,TableCellsSplitIcon:mue,TableColumnsSplit:pue,TableColumnsSplitIcon:pue,TableIcon:wL,TableOfContents:fue,TableOfContentsIcon:fue,TableProperties:xue,TablePropertiesIcon:xue,TableRowsSplit:gue,TableRowsSplitIcon:gue,Tablet:jL,TabletIcon:jL,TabletSmartphone:yue,TabletSmartphoneIcon:yue,Tablets:vue,TabletsIcon:vue,Tag:mh,TagIcon:mh,Tags:L9,TagsIcon:L9,Tally1:bue,Tally1Icon:bue,Tally2:_ue,Tally2Icon:_ue,Tally3:wue,Tally3Icon:wue,Tally4:jue,Tally4Icon:jue,Tally5:Nue,Tally5Icon:Nue,Tangent:kue,TangentIcon:kue,Target:wc,TargetIcon:wc,Telescope:Sue,TelescopeIcon:Sue,Tent:Tue,TentIcon:Tue,TentTree:Cue,TentTreeIcon:Cue,Terminal:Eue,TerminalIcon:Eue,TerminalSquare:uE,TerminalSquareIcon:uE,TestTube:Aue,TestTube2:fE,TestTube2Icon:fE,TestTubeDiagonal:fE,TestTubeDiagonalIcon:fE,TestTubeIcon:Aue,TestTubes:Mue,TestTubesIcon:Mue,Text:Rue,TextCursor:Pue,TextCursorIcon:Pue,TextCursorInput:Iue,TextCursorInputIcon:Iue,TextIcon:Rue,TextQuote:Lue,TextQuoteIcon:Lue,TextSearch:Due,TextSearchIcon:Due,TextSelect:xE,TextSelectIcon:xE,TextSelection:xE,TextSelectionIcon:xE,Theater:Oue,TheaterIcon:Oue,Thermometer:D9,ThermometerIcon:D9,ThermometerSnowflake:Fue,ThermometerSnowflakeIcon:Fue,ThermometerSun:zue,ThermometerSunIcon:zue,ThumbsDown:R9,ThumbsDownIcon:R9,ThumbsUp:Hm,ThumbsUpIcon:Hm,Ticket:O9,TicketCheck:Bue,TicketCheckIcon:Bue,TicketIcon:O9,TicketMinus:$ue,TicketMinusIcon:$ue,TicketPercent:Uue,TicketPercentIcon:Uue,TicketPlus:que,TicketPlusIcon:que,TicketSlash:Vue,TicketSlashIcon:Vue,TicketX:Hue,TicketXIcon:Hue,Tickets:Wue,TicketsIcon:Wue,TicketsPlane:Gue,TicketsPlaneIcon:Gue,Timer:Zue,TimerIcon:Zue,TimerOff:Kue,TimerOffIcon:Kue,TimerReset:Yue,TimerResetIcon:Yue,ToggleLeft:Que,ToggleLeftIcon:Que,ToggleRight:Xue,ToggleRightIcon:Xue,Toilet:Jue,ToiletIcon:Jue,Tornado:ehe,TornadoIcon:ehe,Torus:the,TorusIcon:the,Touchpad:nhe,TouchpadIcon:nhe,TouchpadOff:she,TouchpadOffIcon:she,TowerControl:rhe,TowerControlIcon:rhe,ToyBrick:ahe,ToyBrickIcon:ahe,Tractor:ihe,TractorIcon:ihe,TrafficCone:ohe,TrafficConeIcon:ohe,Train:gE,TrainFront:che,TrainFrontIcon:che,TrainFrontTunnel:lhe,TrainFrontTunnelIcon:lhe,TrainIcon:gE,TrainTrack:dhe,TrainTrackIcon:dhe,TramFront:gE,TramFrontIcon:gE,Trash:uhe,Trash2:bn,Trash2Icon:bn,TrashIcon:uhe,TreeDeciduous:hhe,TreeDeciduousIcon:hhe,TreePalm:yE,TreePalmIcon:yE,TreePine:d4,TreePineIcon:d4,Trees:mhe,TreesIcon:mhe,Trello:phe,TrelloIcon:phe,TrendingDown:bb,TrendingDownIcon:bb,TrendingUp:mo,TrendingUpDown:fhe,TrendingUpDownIcon:fhe,TrendingUpIcon:mo,Triangle:ghe,TriangleAlert:Dl,TriangleAlertIcon:Dl,TriangleIcon:ghe,TriangleRight:xhe,TriangleRightIcon:xhe,Trophy:vo,TrophyIcon:vo,Truck:F9,TruckIcon:F9,Turtle:yhe,TurtleIcon:yhe,Tv:bhe,Tv2:vE,Tv2Icon:vE,TvIcon:bhe,TvMinimal:vE,TvMinimalIcon:vE,TvMinimalPlay:vhe,TvMinimalPlayIcon:vhe,Twitch:_he,TwitchIcon:_he,Twitter:whe,TwitterIcon:whe,Type:Nhe,TypeIcon:Nhe,TypeOutline:jhe,TypeOutlineIcon:jhe,Umbrella:She,UmbrellaIcon:She,UmbrellaOff:khe,UmbrellaOffIcon:khe,Underline:NL,UnderlineIcon:NL,Undo:u4,Undo2:z9,Undo2Icon:z9,UndoDot:Che,UndoDotIcon:Che,UndoIcon:u4,UnfoldHorizontal:The,UnfoldHorizontalIcon:The,UnfoldVertical:Ehe,UnfoldVerticalIcon:Ehe,Ungroup:Ahe,UngroupIcon:Ahe,University:bE,UniversityIcon:bE,Unlink:VA,Unlink2:Mhe,Unlink2Icon:Mhe,UnlinkIcon:VA,Unlock:Z5,UnlockIcon:Z5,UnlockKeyhole:Y5,UnlockKeyholeIcon:Y5,Unplug:Ihe,UnplugIcon:Ihe,Upload:Sa,UploadCloud:C5,UploadCloudIcon:C5,UploadIcon:Sa,Usb:Phe,UsbIcon:Phe,User:Xi,User2:SE,User2Icon:SE,UserCheck:_b,UserCheck2:_E,UserCheck2Icon:_E,UserCheckIcon:_b,UserCircle:j5,UserCircle2:w5,UserCircle2Icon:w5,UserCircleIcon:j5,UserCog:B9,UserCog2:wE,UserCog2Icon:wE,UserCogIcon:B9,UserIcon:Xi,UserMinus:$9,UserMinus2:jE,UserMinus2Icon:jE,UserMinusIcon:$9,UserPen:Lhe,UserPenIcon:Lhe,UserPlus:Fo,UserPlus2:NE,UserPlus2Icon:NE,UserPlusIcon:Fo,UserRound:SE,UserRoundCheck:_E,UserRoundCheckIcon:_E,UserRoundCog:wE,UserRoundCogIcon:wE,UserRoundIcon:SE,UserRoundMinus:jE,UserRoundMinusIcon:jE,UserRoundPen:Dhe,UserRoundPenIcon:Dhe,UserRoundPlus:NE,UserRoundPlusIcon:NE,UserRoundSearch:Rhe,UserRoundSearchIcon:Rhe,UserRoundX:kE,UserRoundXIcon:kE,UserSearch:Ohe,UserSearchIcon:Ohe,UserSquare:mE,UserSquare2:hE,UserSquare2Icon:hE,UserSquareIcon:mE,UserX:Fhe,UserX2:kE,UserX2Icon:kE,UserXIcon:Fhe,Users:_n,Users2:W0,Users2Icon:W0,UsersIcon:_n,UsersRound:W0,UsersRoundIcon:W0,Utensils:TE,UtensilsCrossed:CE,UtensilsCrossedIcon:CE,UtensilsIcon:TE,UtilityPole:zhe,UtilityPoleIcon:zhe,Variable:kL,VariableIcon:kL,Vault:Bhe,VaultIcon:Bhe,Vegan:$he,VeganIcon:$he,VenetianMask:Uhe,VenetianMaskIcon:Uhe,Verified:D3,VerifiedIcon:D3,Vibrate:Vhe,VibrateIcon:Vhe,VibrateOff:qhe,VibrateOffIcon:qhe,Video:vr,VideoIcon:vr,VideoOff:Hhe,VideoOffIcon:Hhe,Videotape:Ghe,VideotapeIcon:Ghe,View:Whe,ViewIcon:Whe,Voicemail:Khe,VoicemailIcon:Khe,Volleyball:Yhe,VolleyballIcon:Yhe,Volume:Xhe,Volume1:Zhe,Volume1Icon:Zhe,Volume2:U9,Volume2Icon:U9,VolumeIcon:Xhe,VolumeOff:Qhe,VolumeOffIcon:Qhe,VolumeX:q9,VolumeXIcon:q9,Vote:Jhe,VoteIcon:Jhe,Wallet:SL,Wallet2:EE,Wallet2Icon:EE,WalletCards:eme,WalletCardsIcon:eme,WalletIcon:SL,WalletMinimal:EE,WalletMinimalIcon:EE,Wallpaper:tme,WallpaperIcon:tme,Wand:sme,Wand2:Rm,Wand2Icon:Rm,WandIcon:sme,WandSparkles:Rm,WandSparklesIcon:Rm,Warehouse:nme,WarehouseIcon:nme,WashingMachine:rme,WashingMachineIcon:rme,Watch:ame,WatchIcon:ame,Waves:ime,WavesIcon:ime,Waypoints:ome,WaypointsIcon:ome,Webcam:lme,WebcamIcon:lme,Webhook:dme,WebhookIcon:dme,WebhookOff:cme,WebhookOffIcon:cme,Weight:ume,WeightIcon:ume,Wheat:mme,WheatIcon:mme,WheatOff:hme,WheatOffIcon:hme,WholeWord:pme,WholeWordIcon:pme,Wifi:vme,WifiHigh:fme,WifiHighIcon:fme,WifiIcon:vme,WifiLow:xme,WifiLowIcon:xme,WifiOff:gme,WifiOffIcon:gme,WifiZero:yme,WifiZeroIcon:yme,Wind:_me,WindArrowDown:bme,WindArrowDownIcon:bme,WindIcon:_me,Wine:V9,WineIcon:V9,WineOff:wme,WineOffIcon:wme,Workflow:H9,WorkflowIcon:H9,Worm:jme,WormIcon:jme,WrapText:Nme,WrapTextIcon:Nme,Wrench:wb,WrenchIcon:wb,X:Fn,XCircle:Gc,XCircleIcon:Gc,XIcon:Fn,XOctagon:eT,XOctagonIcon:eT,XSquare:pE,XSquareIcon:pE,Youtube:kme,YoutubeIcon:kme,Zap:ph,ZapIcon:ph,ZapOff:Sme,ZapOffIcon:Sme,ZoomIn:h4,ZoomInIcon:h4,ZoomOut:CL,ZoomOutIcon:CL,createLucideIcon:re,icons:JMt},Symbol.toStringTag,{value:"Module"})),xAe="-",e6t=s=>{const t=s6t(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(xAe);return o[0]===""&&o.length!==1&&o.shift(),Prt(o,t)||t6t(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},Prt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?Prt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(xAe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},eze=/^\[(.+)\]$/,t6t=s=>{if(eze.test(s)){const t=eze.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},s6t=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return r6t(Object.entries(s.classGroups),n).forEach(([i,l])=>{USe(l,r,i,t)}),r},USe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:tze(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(n6t(a)){USe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{USe(l,tze(t,i),n,r)})})},tze=(s,t)=>{let n=s;return t.split(xAe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},n6t=s=>s.isThemeGetter,r6t=(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,a6t=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)}}},Lrt="!",i6t=s=>{const{separator:t,experimentalParseClassName:n}=s,r=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,u=0,h;for(let v=0;vu?h-u:void 0;return{modifiers:c,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:b}};return n?o=>n({className:o,parseClassName:l}):l},o6t=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},l6t=s=>({cache:a6t(s.cacheSize),parseClassName:i6t(s),...e6t(s)}),c6t=/\s+/,d6t=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(c6t);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:p,maybePostfixModifierPosition:f}=n(d);let g=!!f,b=r(g?p.substring(0,f):p);if(!b){if(!g){o=d+(o.length>0?" "+o:o);continue}if(b=r(p),!b){o=d+(o.length>0?" "+o:o);continue}g=!1}const v=o6t(u).join(":"),j=h?v+Lrt:v,_=j+b;if(i.includes(_))continue;i.push(_);const S=a(b,g);for(let A=0;A0?" "+o:o)}return o};function u6t(){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=l6t(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=d6t(c,n);return a(c,u),u}return function(){return i(u6t.apply(null,arguments))}}const Pd=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},Rrt=/^\[(?:([a-z-]+):)?(.+)\]$/i,m6t=/^\d+\/\d+$/,p6t=new Set(["px","full","screen"]),f6t=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,x6t=/\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$/,g6t=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,y6t=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,v6t=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,n2=s=>TL(s)||p6t.has(s)||m6t.test(s),wk=s=>PD(s,"length",C6t),TL=s=>!!s&&!Number.isNaN(Number(s)),$we=s=>PD(s,"number",TL),tF=s=>!!s&&Number.isInteger(Number(s)),b6t=s=>s.endsWith("%")&&TL(s.slice(0,-1)),Uo=s=>Rrt.test(s),jk=s=>f6t.test(s),_6t=new Set(["length","size","percentage"]),w6t=s=>PD(s,_6t,Ort),j6t=s=>PD(s,"position",Ort),N6t=new Set(["image","url"]),k6t=s=>PD(s,N6t,E6t),S6t=s=>PD(s,"",T6t),sF=()=>!0,PD=(s,t,n)=>{const r=Rrt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},C6t=s=>x6t.test(s)&&!g6t.test(s),Ort=()=>!1,T6t=s=>y6t.test(s),E6t=s=>v6t.test(s),A6t=()=>{const s=Pd("colors"),t=Pd("spacing"),n=Pd("blur"),r=Pd("brightness"),a=Pd("borderColor"),i=Pd("borderRadius"),l=Pd("borderSpacing"),o=Pd("borderWidth"),c=Pd("contrast"),d=Pd("grayscale"),u=Pd("hueRotate"),h=Pd("invert"),p=Pd("gap"),f=Pd("gradientColorStops"),g=Pd("gradientColorStopPositions"),b=Pd("inset"),v=Pd("margin"),j=Pd("opacity"),_=Pd("padding"),S=Pd("saturate"),A=Pd("scale"),T=Pd("sepia"),D=Pd("skew"),L=Pd("space"),M=Pd("translate"),F=()=>["auto","contain","none"],z=()=>["auto","hidden","clip","visible","scroll"],V=()=>["auto",Uo,t],W=()=>[Uo,t],K=()=>["",n2,wk],Y=()=>["auto",TL,Uo],ee=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],ne=()=>["solid","dashed","dotted","double","none"],oe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],pe=()=>["start","end","center","between","around","evenly","stretch"],ce=()=>["","0",Uo],de=()=>["auto","avoid","all","avoid-page","page","left","right","column"],ie=()=>[TL,Uo];return{cacheSize:500,separator:":",theme:{colors:[sF],spacing:[n2,wk],blur:["none","",jk,Uo],brightness:ie(),borderColor:[s],borderRadius:["none","","full",jk,Uo],borderSpacing:W(),borderWidth:K(),contrast:ie(),grayscale:ce(),hueRotate:ie(),invert:ce(),gap:W(),gradientColorStops:[s],gradientColorStopPositions:[b6t,wk],inset:V(),margin:V(),opacity:ie(),padding:W(),saturate:ie(),scale:ie(),sepia:ce(),skew:ie(),space:W(),translate:W()},classGroups:{aspect:[{aspect:["auto","square","video",Uo]}],container:["container"],columns:[{columns:[jk]}],"break-after":[{"break-after":de()}],"break-before":[{"break-before":de()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ee(),Uo]}],overflow:[{overflow:z()}],"overflow-x":[{"overflow-x":z()}],"overflow-y":[{"overflow-y":z()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[b]}],"inset-x":[{"inset-x":[b]}],"inset-y":[{"inset-y":[b]}],start:[{start:[b]}],end:[{end:[b]}],top:[{top:[b]}],right:[{right:[b]}],bottom:[{bottom:[b]}],left:[{left:[b]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",tF,Uo]}],basis:[{basis:V()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Uo]}],grow:[{grow:ce()}],shrink:[{shrink:ce()}],order:[{order:["first","last","none",tF,Uo]}],"grid-cols":[{"grid-cols":[sF]}],"col-start-end":[{col:["auto",{span:["full",tF,Uo]},Uo]}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":[sF]}],"row-start-end":[{row:["auto",{span:[tF,Uo]},Uo]}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Uo]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Uo]}],gap:[{gap:[p]}],"gap-x":[{"gap-x":[p]}],"gap-y":[{"gap-y":[p]}],"justify-content":[{justify:["normal",...pe()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...pe(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...pe(),"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:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"space-x":[{"space-x":[L]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[L]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Uo,t]}],"min-w":[{"min-w":[Uo,t,"min","max","fit"]}],"max-w":[{"max-w":[Uo,t,"none","full","min","max","fit","prose",{screen:[jk]},jk]}],h:[{h:[Uo,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Uo,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Uo,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Uo,t,"auto","min","max","fit"]}],"font-size":[{text:["base",jk,wk]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",$we]}],"font-family":[{font:[sF]}],"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",Uo]}],"line-clamp":[{"line-clamp":["none",TL,$we]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",n2,Uo]}],"list-image":[{"list-image":["none",Uo]}],"list-style-type":[{list:["none","disc","decimal",Uo]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[j]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ne(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",n2,wk]}],"underline-offset":[{"underline-offset":["auto",n2,Uo]}],"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:W()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Uo]}],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",Uo]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[j]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ee(),j6t]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",w6t]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},k6t]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[f]}],"gradient-via":[{via:[f]}],"gradient-to":[{to:[f]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[j]}],"border-style":[{border:[...ne(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[j]}],"divide-style":[{divide:ne()}],"border-color":[{border:[a]}],"border-color-x":[{"border-x":[a]}],"border-color-y":[{"border-y":[a]}],"border-color-s":[{"border-s":[a]}],"border-color-e":[{"border-e":[a]}],"border-color-t":[{"border-t":[a]}],"border-color-r":[{"border-r":[a]}],"border-color-b":[{"border-b":[a]}],"border-color-l":[{"border-l":[a]}],"divide-color":[{divide:[a]}],"outline-style":[{outline:["",...ne()]}],"outline-offset":[{"outline-offset":[n2,Uo]}],"outline-w":[{outline:[n2,wk]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[n2,wk]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",jk,S6t]}],"shadow-color":[{shadow:[sF]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...oe(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":oe()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",jk,Uo]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[S]}],sepia:[{sepia:[T]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[S]}],"backdrop-sepia":[{"backdrop-sepia":[T]}],"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",Uo]}],duration:[{duration:ie()}],ease:[{ease:["linear","in","out","in-out",Uo]}],delay:[{delay:ie()}],animate:[{animate:["none","spin","ping","pulse","bounce",Uo]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[A]}],"scale-x":[{"scale-x":[A]}],"scale-y":[{"scale-y":[A]}],rotate:[{rotate:[tF,Uo]}],"translate-x":[{"translate-x":[M]}],"translate-y":[{"translate-y":[M]}],"skew-x":[{"skew-x":[D]}],"skew-y":[{"skew-y":[D]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Uo]}],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",Uo]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":W()}],"scroll-mx":[{"scroll-mx":W()}],"scroll-my":[{"scroll-my":W()}],"scroll-ms":[{"scroll-ms":W()}],"scroll-me":[{"scroll-me":W()}],"scroll-mt":[{"scroll-mt":W()}],"scroll-mr":[{"scroll-mr":W()}],"scroll-mb":[{"scroll-mb":W()}],"scroll-ml":[{"scroll-ml":W()}],"scroll-p":[{"scroll-p":W()}],"scroll-px":[{"scroll-px":W()}],"scroll-py":[{"scroll-py":W()}],"scroll-ps":[{"scroll-ps":W()}],"scroll-pe":[{"scroll-pe":W()}],"scroll-pt":[{"scroll-pt":W()}],"scroll-pr":[{"scroll-pr":W()}],"scroll-pb":[{"scroll-pb":W()}],"scroll-pl":[{"scroll-pl":W()}],"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",Uo]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[n2,wk,$we]}],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"]}}},M6t=h6t(A6t);function Et(...s){return M6t(So(s))}function gc(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 sze(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function tB(s){return s?s.replace(/<[^>]*>/g,""):""}const I6t=ZMt,Frt=N.forwardRef(({className:s,...t},n)=>e.jsx(Nrt,{ref:n,className:Et("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}));Frt.displayName=Nrt.displayName;const P6t=qM("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"}}),zrt=N.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(krt,{ref:r,className:Et(P6t({variant:t}),s),...n}));zrt.displayName=krt.displayName;const L6t=N.forwardRef(({className:s,...t},n)=>e.jsx(Trt,{ref:n,className:Et("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}));L6t.displayName=Trt.displayName;const Brt=N.forwardRef(({className:s,...t},n)=>e.jsx(Ert,{ref:n,className:Et("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(Fn,{className:"h-4 w-4"})}));Brt.displayName=Ert.displayName;const $rt=N.forwardRef(({className:s,...t},n)=>e.jsx(Srt,{ref:n,className:Et("text-sm font-semibold",s),...t}));$rt.displayName=Srt.displayName;const Urt=N.forwardRef(({className:s,...t},n)=>e.jsx(Crt,{ref:n,className:Et("text-sm opacity-90",s),...t}));Urt.displayName=Crt.displayName;function D6t(){const{toasts:s}=Ua();return e.jsxs(I6t,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(zrt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx($rt,{children:n}),r&&e.jsx(Urt,{children:r})]}),a,e.jsx(Brt,{})]},t)}),e.jsx(Frt,{})]})}var nze=["light","dark"],R6t="(prefers-color-scheme: dark)",O6t=N.createContext(void 0),F6t={setTheme:s=>{},themes:[]},z6t=()=>{var s;return(s=N.useContext(O6t))!=null?s:F6t};N.memo(({forcedTheme:s,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(g=>`'${g}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?nze.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",p=(g,b=!1,v=!0)=>{let j=l?l[g]:g,_=b?g+"|| ''":`'${j}'`,S="";return a&&v&&!b&&nze.includes(g)&&(S+=`d.style.colorScheme = '${g}';`),n==="class"?b||j?S+=`c.add(${_})`:S+="null":j&&(S+=`d[s](n,${_})`),S},f=s?`!function(){${u}${p(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${R6t}',m=window.matchMedia(t);if(m.media!==t||m.matches){${p("dark")}}else{${p("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${p(l?"x[e]":"e",!0)}}${d?"":"else{"+p(i,!1,!1)+"}"}${h}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${p(l?"x[e]":"e",!0)}}else{${p(i,!1,!1)};}${h}}catch(t){}}();`;return N.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:f}})});var B6t=s=>{switch(s){case"success":return q6t;case"info":return H6t;case"warning":return V6t;case"error":return G6t;default:return null}},$6t=Array(12).fill(0),U6t=({visible:s,className:t})=>Nt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Nt.createElement("div",{className:"sonner-spinner"},$6t.map((n,r)=>Nt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),q6t=Nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Nt.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"})),V6t=Nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Nt.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"})),H6t=Nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Nt.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"})),G6t=Nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Nt.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"})),W6t=Nt.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"},Nt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Nt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),K6t=()=>{let[s,t]=Nt.useState(document.hidden);return Nt.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},qSe=1,Y6t=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:qSe++,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],Nt.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(Q6t(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)||qSe++;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}},Ig=new Y6t,Z6t=(s,t)=>{let n=(t==null?void 0:t.id)||qSe++;return Ig.addToast({title:s,...t,id:n}),n},Q6t=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",X6t=Z6t,J6t=()=>Ig.toasts,eIt=()=>Ig.getActiveToasts(),ae=Object.assign(X6t,{success:Ig.success,info:Ig.info,warning:Ig.warning,error:Ig.error,custom:Ig.custom,message:Ig.message,promise:Ig.promise,dismiss:Ig.dismiss,loading:Ig.loading},{getHistory:J6t,getToasts:eIt});function tIt(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))}tIt(`: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 qV(s){return s.label!==void 0}var sIt=3,nIt="32px",rIt="16px",rze=4e3,aIt=356,iIt=14,oIt=20,lIt=200;function F1(...s){return s.filter(Boolean).join(" ")}function cIt(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var dIt=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:p,toast:f,unstyled:g,interacting:b,setHeights:v,visibleToasts:j,heights:_,index:S,toasts:A,expanded:T,removeToast:D,defaultRichColors:L,closeButton:M,style:F,cancelButtonStyle:z,actionButtonStyle:V,className:W="",descriptionClassName:K="",duration:Y,position:ee,gap:ne,loadingIcon:oe,expandByDefault:pe,classNames:ce,icons:de,closeButtonAriaLabel:ie="Close toast",pauseWhenPageIsHidden:ye}=s,[_e,Me]=Nt.useState(null),[Te,Ce]=Nt.useState(null),[Ee,De]=Nt.useState(!1),[Ie,Fe]=Nt.useState(!1),[qe,ve]=Nt.useState(!1),[Je,we]=Nt.useState(!1),[it,Ne]=Nt.useState(!1),[He,$e]=Nt.useState(0),[Ye,Ke]=Nt.useState(0),rt=Nt.useRef(f.duration||Y||rze),tt=Nt.useRef(null),at=Nt.useRef(null),Ge=S===0,dt=S+1<=j,Bt=f.type,kt=f.dismissible!==!1,Qt=f.className||"",ns=f.descriptionClassName||"",$s=Nt.useMemo(()=>_.findIndex(fn=>fn.toastId===f.id)||0,[_,f.id]),Ds=Nt.useMemo(()=>{var fn;return(fn=f.closeButton)!=null?fn:M},[f.closeButton,M]),Dt=Nt.useMemo(()=>f.duration||Y||rze,[f.duration,Y]),St=Nt.useRef(0),$t=Nt.useRef(0),ht=Nt.useRef(0),Ut=Nt.useRef(null),[Es,Xt]=ee.split("-"),Ys=Nt.useMemo(()=>_.reduce((fn,Sn,Gn)=>Gn>=$s?fn:fn+Sn.height,0),[_,$s]),Ss=K6t(),Bs=f.invert||p,Us=Bt==="loading";$t.current=Nt.useMemo(()=>$s*ne+Ys,[$s,Ys]),Nt.useEffect(()=>{rt.current=Dt},[Dt]),Nt.useEffect(()=>{De(!0)},[]),Nt.useEffect(()=>{let fn=at.current;if(fn){let Sn=fn.getBoundingClientRect().height;return Ke(Sn),v(Gn=>[{toastId:f.id,height:Sn,position:f.position},...Gn]),()=>v(Gn=>Gn.filter(Hr=>Hr.toastId!==f.id))}},[v,f.id]),Nt.useLayoutEffect(()=>{if(!Ee)return;let fn=at.current,Sn=fn.style.height;fn.style.height="auto";let Gn=fn.getBoundingClientRect().height;fn.style.height=Sn,Ke(Gn),v(Hr=>Hr.find(pi=>pi.toastId===f.id)?Hr.map(pi=>pi.toastId===f.id?{...pi,height:Gn}:pi):[{toastId:f.id,height:Gn,position:f.position},...Hr])},[Ee,f.title,f.description,v,f.id]);let sn=Nt.useCallback(()=>{Fe(!0),$e($t.current),v(fn=>fn.filter(Sn=>Sn.toastId!==f.id)),setTimeout(()=>{D(f)},lIt)},[f,D,v,$t]);Nt.useEffect(()=>{if(f.promise&&Bt==="loading"||f.duration===1/0||f.type==="loading")return;let fn;return T||b||ye&&Ss?(()=>{if(ht.current{var Sn;(Sn=f.onAutoClose)==null||Sn.call(f,f),sn()},rt.current)),()=>clearTimeout(fn)},[T,b,f,Bt,ye,Ss,sn]),Nt.useEffect(()=>{f.delete&&sn()},[sn,f.delete]);function Jn(){var fn,Sn,Gn;return de!=null&&de.loading?Nt.createElement("div",{className:F1(ce==null?void 0:ce.loader,(fn=f==null?void 0:f.classNames)==null?void 0:fn.loader,"sonner-loader"),"data-visible":Bt==="loading"},de.loading):oe?Nt.createElement("div",{className:F1(ce==null?void 0:ce.loader,(Sn=f==null?void 0:f.classNames)==null?void 0:Sn.loader,"sonner-loader"),"data-visible":Bt==="loading"},oe):Nt.createElement(U6t,{className:F1(ce==null?void 0:ce.loader,(Gn=f==null?void 0:f.classNames)==null?void 0:Gn.loader),visible:Bt==="loading"})}return Nt.createElement("li",{tabIndex:0,ref:at,className:F1(W,Qt,ce==null?void 0:ce.toast,(t=f==null?void 0:f.classNames)==null?void 0:t.toast,ce==null?void 0:ce.default,ce==null?void 0:ce[Bt],(n=f==null?void 0:f.classNames)==null?void 0:n[Bt]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:L,"data-styled":!(f.jsx||f.unstyled||g),"data-mounted":Ee,"data-promise":!!f.promise,"data-swiped":it,"data-removed":Ie,"data-visible":dt,"data-y-position":Es,"data-x-position":Xt,"data-index":S,"data-front":Ge,"data-swiping":qe,"data-dismissible":kt,"data-type":Bt,"data-invert":Bs,"data-swipe-out":Je,"data-swipe-direction":Te,"data-expanded":!!(T||pe&&Ee),style:{"--index":S,"--toasts-before":S,"--z-index":A.length-S,"--offset":`${Ie?He:$t.current}px`,"--initial-height":pe?"auto":`${Ye}px`,...F,...f.style},onDragEnd:()=>{ve(!1),Me(null),Ut.current=null},onPointerDown:fn=>{Us||!kt||(tt.current=new Date,$e($t.current),fn.target.setPointerCapture(fn.pointerId),fn.target.tagName!=="BUTTON"&&(ve(!0),Ut.current={x:fn.clientX,y:fn.clientY}))},onPointerUp:()=>{var fn,Sn,Gn,Hr;if(Je||!kt)return;Ut.current=null;let pi=Number(((fn=at.current)==null?void 0:fn.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Ms=Number(((Sn=at.current)==null?void 0:Sn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),bi=new Date().getTime()-((Gn=tt.current)==null?void 0:Gn.getTime()),Rr=_e==="x"?pi:Ms,er=Math.abs(Rr)/bi;if(Math.abs(Rr)>=oIt||er>.11){$e($t.current),(Hr=f.onDismiss)==null||Hr.call(f,f),Ce(_e==="x"?pi>0?"right":"left":Ms>0?"down":"up"),sn(),we(!0),Ne(!1);return}ve(!1),Me(null)},onPointerMove:fn=>{var Sn,Gn,Hr,pi;if(!Ut.current||!kt||((Sn=window.getSelection())==null?void 0:Sn.toString().length)>0)return;let Ms=fn.clientY-Ut.current.y,bi=fn.clientX-Ut.current.x,Rr=(Gn=s.swipeDirections)!=null?Gn:cIt(ee);!_e&&(Math.abs(bi)>1||Math.abs(Ms)>1)&&Me(Math.abs(bi)>Math.abs(Ms)?"x":"y");let er={x:0,y:0};_e==="y"?(Rr.includes("top")||Rr.includes("bottom"))&&(Rr.includes("top")&&Ms<0||Rr.includes("bottom")&&Ms>0)&&(er.y=Ms):_e==="x"&&(Rr.includes("left")||Rr.includes("right"))&&(Rr.includes("left")&&bi<0||Rr.includes("right")&&bi>0)&&(er.x=bi),(Math.abs(er.x)>0||Math.abs(er.y)>0)&&Ne(!0),(Hr=at.current)==null||Hr.style.setProperty("--swipe-amount-x",`${er.x}px`),(pi=at.current)==null||pi.style.setProperty("--swipe-amount-y",`${er.y}px`)}},Ds&&!f.jsx?Nt.createElement("button",{"aria-label":ie,"data-disabled":Us,"data-close-button":!0,onClick:Us||!kt?()=>{}:()=>{var fn;sn(),(fn=f.onDismiss)==null||fn.call(f,f)},className:F1(ce==null?void 0:ce.closeButton,(a=f==null?void 0:f.classNames)==null?void 0:a.closeButton)},(i=de==null?void 0:de.close)!=null?i:W6t):null,f.jsx||N.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:Nt.createElement(Nt.Fragment,null,Bt||f.icon||f.promise?Nt.createElement("div",{"data-icon":"",className:F1(ce==null?void 0:ce.icon,(l=f==null?void 0:f.classNames)==null?void 0:l.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||Jn():null,f.type!=="loading"?f.icon||(de==null?void 0:de[Bt])||B6t(Bt):null):null,Nt.createElement("div",{"data-content":"",className:F1(ce==null?void 0:ce.content,(o=f==null?void 0:f.classNames)==null?void 0:o.content)},Nt.createElement("div",{"data-title":"",className:F1(ce==null?void 0:ce.title,(c=f==null?void 0:f.classNames)==null?void 0:c.title)},typeof f.title=="function"?f.title():f.title),f.description?Nt.createElement("div",{"data-description":"",className:F1(K,ns,ce==null?void 0:ce.description,(d=f==null?void 0:f.classNames)==null?void 0:d.description)},typeof f.description=="function"?f.description():f.description):null),N.isValidElement(f.cancel)?f.cancel:f.cancel&&qV(f.cancel)?Nt.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||z,onClick:fn=>{var Sn,Gn;qV(f.cancel)&&kt&&((Gn=(Sn=f.cancel).onClick)==null||Gn.call(Sn,fn),sn())},className:F1(ce==null?void 0:ce.cancelButton,(u=f==null?void 0:f.classNames)==null?void 0:u.cancelButton)},f.cancel.label):null,N.isValidElement(f.action)?f.action:f.action&&qV(f.action)?Nt.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||V,onClick:fn=>{var Sn,Gn;qV(f.action)&&((Gn=(Sn=f.action).onClick)==null||Gn.call(Sn,fn),!fn.defaultPrevented&&sn())},className:F1(ce==null?void 0:ce.actionButton,(h=f==null?void 0:f.classNames)==null?void 0:h.actionButton)},f.action.label):null))};function aze(){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 uIt(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?rIt:nIt;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 hIt=N.forwardRef(function(s,t){let{invert:n,position:r="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:u="light",richColors:h,duration:p,style:f,visibleToasts:g=sIt,toastOptions:b,dir:v=aze(),gap:j=iIt,loadingIcon:_,icons:S,containerAriaLabel:A="Notifications",pauseWhenPageIsHidden:T}=s,[D,L]=Nt.useState([]),M=Nt.useMemo(()=>Array.from(new Set([r].concat(D.filter(ye=>ye.position).map(ye=>ye.position)))),[D,r]),[F,z]=Nt.useState([]),[V,W]=Nt.useState(!1),[K,Y]=Nt.useState(!1),[ee,ne]=Nt.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),oe=Nt.useRef(null),pe=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ce=Nt.useRef(null),de=Nt.useRef(!1),ie=Nt.useCallback(ye=>{L(_e=>{var Me;return(Me=_e.find(Te=>Te.id===ye.id))!=null&&Me.delete||Ig.dismiss(ye.id),_e.filter(({id:Te})=>Te!==ye.id)})},[]);return Nt.useEffect(()=>Ig.subscribe(ye=>{if(ye.dismiss){L(_e=>_e.map(Me=>Me.id===ye.id?{...Me,delete:!0}:Me));return}setTimeout(()=>{dAe.flushSync(()=>{L(_e=>{let Me=_e.findIndex(Te=>Te.id===ye.id);return Me!==-1?[..._e.slice(0,Me),{..._e[Me],...ye},..._e.slice(Me+1)]:[ye,..._e]})})})}),[]),Nt.useEffect(()=>{if(u!=="system"){ne(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ne("dark"):ne("light")),typeof window>"u")return;let ye=window.matchMedia("(prefers-color-scheme: dark)");try{ye.addEventListener("change",({matches:_e})=>{ne(_e?"dark":"light")})}catch{ye.addListener(({matches:Me})=>{try{ne(Me?"dark":"light")}catch(Te){console.error(Te)}})}},[u]),Nt.useEffect(()=>{D.length<=1&&W(!1)},[D]),Nt.useEffect(()=>{let ye=_e=>{var Me,Te;a.every(Ce=>_e[Ce]||_e.code===Ce)&&(W(!0),(Me=oe.current)==null||Me.focus()),_e.code==="Escape"&&(document.activeElement===oe.current||(Te=oe.current)!=null&&Te.contains(document.activeElement))&&W(!1)};return document.addEventListener("keydown",ye),()=>document.removeEventListener("keydown",ye)},[a]),Nt.useEffect(()=>{if(oe.current)return()=>{ce.current&&(ce.current.focus({preventScroll:!0}),ce.current=null,de.current=!1)}},[oe.current]),Nt.createElement("section",{ref:t,"aria-label":`${A} ${pe}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((ye,_e)=>{var Me;let[Te,Ce]=ye.split("-");return D.length?Nt.createElement("ol",{key:ye,dir:v==="auto"?aze():v,tabIndex:-1,ref:oe,className:o,"data-sonner-toaster":!0,"data-theme":ee,"data-y-position":Te,"data-lifted":V&&D.length>1&&!i,"data-x-position":Ce,style:{"--front-toast-height":`${((Me=F[0])==null?void 0:Me.height)||0}px`,"--width":`${aIt}px`,"--gap":`${j}px`,...f,...uIt(c,d)},onBlur:Ee=>{de.current&&!Ee.currentTarget.contains(Ee.relatedTarget)&&(de.current=!1,ce.current&&(ce.current.focus({preventScroll:!0}),ce.current=null))},onFocus:Ee=>{Ee.target instanceof HTMLElement&&Ee.target.dataset.dismissible==="false"||de.current||(de.current=!0,ce.current=Ee.relatedTarget)},onMouseEnter:()=>W(!0),onMouseMove:()=>W(!0),onMouseLeave:()=>{K||W(!1)},onDragEnd:()=>W(!1),onPointerDown:Ee=>{Ee.target instanceof HTMLElement&&Ee.target.dataset.dismissible==="false"||Y(!0)},onPointerUp:()=>Y(!1)},D.filter(Ee=>!Ee.position&&_e===0||Ee.position===ye).map((Ee,De)=>{var Ie,Fe;return Nt.createElement(dIt,{key:Ee.id,icons:S,index:De,toast:Ee,defaultRichColors:h,duration:(Ie=b==null?void 0:b.duration)!=null?Ie:p,className:b==null?void 0:b.className,descriptionClassName:b==null?void 0:b.descriptionClassName,invert:n,visibleToasts:g,closeButton:(Fe=b==null?void 0:b.closeButton)!=null?Fe:l,interacting:K,position:ye,style:b==null?void 0:b.style,unstyled:b==null?void 0:b.unstyled,classNames:b==null?void 0:b.classNames,cancelButtonStyle:b==null?void 0:b.cancelButtonStyle,actionButtonStyle:b==null?void 0:b.actionButtonStyle,removeToast:ie,toasts:D.filter(qe=>qe.position==Ee.position),heights:F.filter(qe=>qe.position==Ee.position),setHeights:z,expandByDefault:i,gap:j,loadingIcon:_,expanded:V,pauseWhenPageIsHidden:T,swipeDirections:s.swipeDirections})})):null}))});const mIt=({...s})=>{const{theme:t="system"}=z6t();return e.jsx(hIt,{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 pIt=vEe[" useId ".trim().toString()]||(()=>{}),fIt=0;function um(s){const[t,n]=N.useState(pIt());return fh(()=>{s||n(r=>r??String(fIt++))},[s]),s||(t?`radix-${t}`:"")}const xIt=["top","right","bottom","left"],T4=Math.min,K0=Math.max,Gpe=Math.round,VV=Math.floor,E4=s=>({x:s,y:s}),gIt={left:"right",right:"left",bottom:"top",top:"bottom"},yIt={start:"end",end:"start"};function VSe(s,t,n){return K0(s,T4(t,n))}function mN(s,t){return typeof s=="function"?s(t):s}function pN(s){return s.split("-")[0]}function LD(s){return s.split("-")[1]}function gAe(s){return s==="x"?"y":"x"}function yAe(s){return s==="y"?"height":"width"}function A4(s){return["top","bottom"].includes(pN(s))?"y":"x"}function vAe(s){return gAe(A4(s))}function vIt(s,t,n){n===void 0&&(n=!1);const r=LD(s),a=vAe(s),i=yAe(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=Wpe(l)),[l,Wpe(l)]}function bIt(s){const t=Wpe(s);return[HSe(s),t,HSe(t)]}function HSe(s){return s.replace(/start|end/g,t=>yIt[t])}function _It(s,t,n){const r=["left","right"],a=["right","left"],i=["top","bottom"],l=["bottom","top"];switch(s){case"top":case"bottom":return n?t?a:r:t?r:a;case"left":case"right":return t?i:l;default:return[]}}function wIt(s,t,n,r){const a=LD(s);let i=_It(pN(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(HSe)))),i}function Wpe(s){return s.replace(/left|right|bottom|top/g,t=>gIt[t])}function jIt(s){return{top:0,right:0,bottom:0,left:0,...s}}function qrt(s){return typeof s!="number"?jIt(s):{top:s,right:s,bottom:s,left:s}}function Kpe(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 ize(s,t,n){let{reference:r,floating:a}=s;const i=A4(t),l=vAe(t),o=yAe(l),c=pN(t),d=i==="y",u=r.x+r.width/2-a.width/2,h=r.y+r.height/2-a.height/2,p=r[o]/2-a[o]/2;let f;switch(c){case"top":f={x:u,y:r.y-a.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:h};break;case"left":f={x:r.x-a.width,y:h};break;default:f={x:r.x,y:r.y}}switch(LD(t)){case"start":f[l]-=p*(n&&d?-1:1);break;case"end":f[l]+=p*(n&&d?-1:1);break}return f}const NIt=async(s,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:l}=n,o=i.filter(Boolean),c=await(l.isRTL==null?void 0:l.isRTL(t));let d=await l.getElementRects({reference:s,floating:t,strategy:a}),{x:u,y:h}=ize(d,r,c),p=r,f={},g=0;for(let b=0;b({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}=mN(s,t)||{};if(d==null)return{};const h=qrt(u),p={x:n,y:r},f=vAe(a),g=yAe(f),b=await l.getDimensions(d),v=f==="y",j=v?"top":"left",_=v?"bottom":"right",S=v?"clientHeight":"clientWidth",A=i.reference[g]+i.reference[f]-p[f]-i.floating[g],T=p[f]-i.reference[f],D=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let L=D?D[S]:0;(!L||!await(l.isElement==null?void 0:l.isElement(D)))&&(L=o.floating[S]||i.floating[g]);const M=A/2-T/2,F=L/2-b[g]/2-1,z=T4(h[j],F),V=T4(h[_],F),W=z,K=L-b[g]-V,Y=L/2-b[g]/2+M,ee=VSe(W,Y,K),ne=!c.arrow&&LD(a)!=null&&Y!==ee&&i.reference[g]/2-(YY<=0)){var V,W;const Y=(((V=i.flip)==null?void 0:V.index)||0)+1,ee=L[Y];if(ee)return{data:{index:Y,overflows:z},reset:{placement:ee}};let ne=(W=z.filter(oe=>oe.overflows[0]<=0).sort((oe,pe)=>oe.overflows[1]-pe.overflows[1])[0])==null?void 0:W.placement;if(!ne)switch(f){case"bestFit":{var K;const oe=(K=z.filter(pe=>{if(D){const ce=A4(pe.placement);return ce===_||ce==="y"}return!0}).map(pe=>[pe.placement,pe.overflows.filter(ce=>ce>0).reduce((ce,de)=>ce+de,0)]).sort((pe,ce)=>pe[1]-ce[1])[0])==null?void 0:K[0];oe&&(ne=oe);break}case"initialPlacement":ne=o;break}if(a!==ne)return{reset:{placement:ne}}}return{}}}};function oze(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function lze(s){return xIt.some(t=>s[t]>=0)}const CIt=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...a}=mN(s,t);switch(r){case"referenceHidden":{const i=await sB(t,{...a,elementContext:"reference"}),l=oze(i,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:lze(l)}}}case"escaped":{const i=await sB(t,{...a,altBoundary:!0}),l=oze(i,n.floating);return{data:{escapedOffsets:l,escaped:lze(l)}}}default:return{}}}}};async function TIt(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=pN(n),o=LD(n),c=A4(n)==="y",d=["left","top"].includes(l)?-1:1,u=i&&c?-1:1,h=mN(t,s);let{mainAxis:p,crossAxis:f,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"&&(f=o==="end"?g*-1:g),c?{x:f*u,y:p*d}:{x:p*d,y:f*u}}const EIt=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 TIt(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}}}}},AIt=function(s){return s===void 0&&(s={}),{name:"shift",options:s,async fn(t){const{x:n,y:r,placement:a}=t,{mainAxis:i=!0,crossAxis:l=!1,limiter:o={fn:v=>{let{x:j,y:_}=v;return{x:j,y:_}}},...c}=mN(s,t),d={x:n,y:r},u=await sB(t,c),h=A4(pN(a)),p=gAe(h);let f=d[p],g=d[h];if(i){const v=p==="y"?"top":"left",j=p==="y"?"bottom":"right",_=f+u[v],S=f-u[j];f=VSe(_,f,S)}if(l){const v=h==="y"?"top":"left",j=h==="y"?"bottom":"right",_=g+u[v],S=g-u[j];g=VSe(_,g,S)}const b=o.fn({...t,[p]:f,[h]:g});return{...b,data:{x:b.x-n,y:b.y-r,enabled:{[p]:i,[h]:l}}}}}},MIt=function(s){return s===void 0&&(s={}),{options:s,fn(t){const{x:n,y:r,placement:a,rects:i,middlewareData:l}=t,{offset:o=0,mainAxis:c=!0,crossAxis:d=!0}=mN(s,t),u={x:n,y:r},h=A4(a),p=gAe(h);let f=u[p],g=u[h];const b=mN(o,t),v=typeof b=="number"?{mainAxis:b,crossAxis:0}:{mainAxis:0,crossAxis:0,...b};if(c){const S=p==="y"?"height":"width",A=i.reference[p]-i.floating[S]+v.mainAxis,T=i.reference[p]+i.reference[S]-v.mainAxis;fT&&(f=T)}if(d){var j,_;const S=p==="y"?"width":"height",A=["top","left"].includes(pN(a)),T=i.reference[h]-i.floating[S]+(A&&((j=l.offset)==null?void 0:j[h])||0)+(A?0:v.crossAxis),D=i.reference[h]+i.reference[S]+(A?0:((_=l.offset)==null?void 0:_[h])||0)-(A?v.crossAxis:0);gD&&(g=D)}return{[p]:f,[h]:g}}}},IIt=function(s){return s===void 0&&(s={}),{name:"size",options:s,async fn(t){var n,r;const{placement:a,rects:i,platform:l,elements:o}=t,{apply:c=()=>{},...d}=mN(s,t),u=await sB(t,d),h=pN(a),p=LD(a),f=A4(a)==="y",{width:g,height:b}=i.floating;let v,j;h==="top"||h==="bottom"?(v=h,j=p===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(j=h,v=p==="end"?"top":"bottom");const _=b-u.top-u.bottom,S=g-u.left-u.right,A=T4(b-u[v],_),T=T4(g-u[j],S),D=!t.middlewareData.shift;let L=A,M=T;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(L=_),D&&!p){const z=K0(u.left,0),V=K0(u.right,0),W=K0(u.top,0),K=K0(u.bottom,0);f?M=g-2*(z!==0||V!==0?z+V:K0(u.left,u.right)):L=b-2*(W!==0||K!==0?W+K:K0(u.top,u.bottom))}await c({...t,availableWidth:M,availableHeight:L});const F=await l.getDimensions(o.floating);return g!==F.width||b!==F.height?{reset:{rects:!0}}:{}}}};function I0e(){return typeof window<"u"}function DD(s){return Vrt(s)?(s.nodeName||"").toLowerCase():"#document"}function dy(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function Gw(s){var t;return(t=(Vrt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function Vrt(s){return I0e()?s instanceof Node||s instanceof dy(s).Node:!1}function Tb(s){return I0e()?s instanceof Element||s instanceof dy(s).Element:!1}function Mw(s){return I0e()?s instanceof HTMLElement||s instanceof dy(s).HTMLElement:!1}function cze(s){return!I0e()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof dy(s).ShadowRoot}function U$(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=Eb(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(a)}function PIt(s){return["table","td","th"].includes(DD(s))}function P0e(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function bAe(s){const t=_Ae(),n=Tb(s)?Eb(s):s;return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function LIt(s){let t=M4(s);for(;Mw(t)&&!y8(t);){if(bAe(t))return t;if(P0e(t))return null;t=M4(t)}return null}function _Ae(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function y8(s){return["html","body","#document"].includes(DD(s))}function Eb(s){return dy(s).getComputedStyle(s)}function L0e(s){return Tb(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function M4(s){if(DD(s)==="html")return s;const t=s.assignedSlot||s.parentNode||cze(s)&&s.host||Gw(s);return cze(t)?t.host:t}function Hrt(s){const t=M4(s);return y8(t)?s.ownerDocument?s.ownerDocument.body:s.body:Mw(t)&&U$(t)?t:Hrt(t)}function nB(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=Hrt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=dy(a);if(i){const o=GSe(l);return t.concat(l,l.visualViewport||[],U$(a)?a:[],o&&n?nB(o):[])}return t.concat(a,nB(a,[],n))}function GSe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function Grt(s){const t=Eb(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=Mw(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=Gpe(n)!==i||Gpe(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function wAe(s){return Tb(s)?s:s.contextElement}function EL(s){const t=wAe(s);if(!Mw(t))return E4(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=Grt(t);let l=(i?Gpe(n.width):n.width)/r,o=(i?Gpe(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const DIt=E4(0);function Wrt(s){const t=dy(s);return!_Ae()||!t.visualViewport?DIt:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function RIt(s,t,n){return t===void 0&&(t=!1),!n||t&&n!==dy(s)?!1:t}function mM(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=wAe(s);let l=E4(1);t&&(r?Tb(r)&&(l=EL(r)):l=EL(s));const o=RIt(i,n,r)?Wrt(i):E4(0);let c=(a.left+o.x)/l.x,d=(a.top+o.y)/l.y,u=a.width/l.x,h=a.height/l.y;if(i){const p=dy(i),f=r&&Tb(r)?dy(r):r;let g=p,b=GSe(g);for(;b&&r&&f!==g;){const v=EL(b),j=b.getBoundingClientRect(),_=Eb(b),S=j.left+(b.clientLeft+parseFloat(_.paddingLeft))*v.x,A=j.top+(b.clientTop+parseFloat(_.paddingTop))*v.y;c*=v.x,d*=v.y,u*=v.x,h*=v.y,c+=S,d+=A,g=dy(b),b=GSe(g)}}return Kpe({width:u,height:h,x:c,y:d})}function OIt(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=Gw(r),o=t?P0e(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=E4(1);const u=E4(0),h=Mw(r);if((h||!h&&!i)&&((DD(r)!=="body"||U$(l))&&(c=L0e(r)),Mw(r))){const p=mM(r);d=EL(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-c.scrollLeft*d.x+u.x,y:n.y*d.y-c.scrollTop*d.y+u.y}}function FIt(s){return Array.from(s.getClientRects())}function WSe(s,t){const n=L0e(s).scrollLeft;return t?t.left+n:mM(Gw(s)).left+n}function zIt(s){const t=Gw(s),n=L0e(s),r=s.ownerDocument.body,a=K0(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=K0(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+WSe(s);const o=-n.scrollTop;return Eb(r).direction==="rtl"&&(l+=K0(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:l,y:o}}function BIt(s,t){const n=dy(s),r=Gw(s),a=n.visualViewport;let i=r.clientWidth,l=r.clientHeight,o=0,c=0;if(a){i=a.width,l=a.height;const d=_Ae();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function $It(s,t){const n=mM(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=Mw(s)?EL(s):E4(1),l=s.clientWidth*i.x,o=s.clientHeight*i.y,c=a*i.x,d=r*i.y;return{width:l,height:o,x:c,y:d}}function dze(s,t,n){let r;if(t==="viewport")r=BIt(s,n);else if(t==="document")r=zIt(Gw(s));else if(Tb(t))r=$It(t,n);else{const a=Wrt(s);r={...t,x:t.x-a.x,y:t.y-a.y}}return Kpe(r)}function Krt(s,t){const n=M4(s);return n===t||!Tb(n)||y8(n)?!1:Eb(n).position==="fixed"||Krt(n,t)}function UIt(s,t){const n=t.get(s);if(n)return n;let r=nB(s,[],!1).filter(o=>Tb(o)&&DD(o)!=="body"),a=null;const i=Eb(s).position==="fixed";let l=i?M4(s):s;for(;Tb(l)&&!y8(l);){const o=Eb(l),c=bAe(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||U$(l)&&!c&&Krt(s,l))?r=r.filter(u=>u!==l):a=o,l=M4(l)}return t.set(s,r),r}function qIt(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?P0e(t)?[]:UIt(t,this._c):[].concat(n),r],o=l[0],c=l.reduce((d,u)=>{const h=dze(t,u,a);return d.top=K0(h.top,d.top),d.right=T4(h.right,d.right),d.bottom=T4(h.bottom,d.bottom),d.left=K0(h.left,d.left),d},dze(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function VIt(s){const{width:t,height:n}=Grt(s);return{width:t,height:n}}function HIt(s,t,n){const r=Mw(t),a=Gw(t),i=n==="fixed",l=mM(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=E4(0);if(r||!r&&!i)if((DD(t)!=="body"||U$(a))&&(o=L0e(t)),r){const f=mM(t,!0,i,t);c.x=f.x+t.clientLeft,c.y=f.y+t.clientTop}else a&&(c.x=WSe(a));let d=0,u=0;if(a&&!r&&!i){const f=a.getBoundingClientRect();u=f.top+o.scrollTop,d=f.left+o.scrollLeft-WSe(a,f)}const h=l.left+o.scrollLeft-c.x-d,p=l.top+o.scrollTop-c.y-u;return{x:h,y:p,width:l.width,height:l.height}}function Uwe(s){return Eb(s).position==="static"}function uze(s,t){if(!Mw(s)||Eb(s).position==="fixed")return null;if(t)return t(s);let n=s.offsetParent;return Gw(s)===n&&(n=n.ownerDocument.body),n}function Yrt(s,t){const n=dy(s);if(P0e(s))return n;if(!Mw(s)){let a=M4(s);for(;a&&!y8(a);){if(Tb(a)&&!Uwe(a))return a;a=M4(a)}return n}let r=uze(s,t);for(;r&&PIt(r)&&Uwe(r);)r=uze(r,t);return r&&y8(r)&&Uwe(r)&&!bAe(r)?n:r||LIt(s)||n}const GIt=async function(s){const t=this.getOffsetParent||Yrt,n=this.getDimensions,r=await n(s.floating);return{reference:HIt(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function WIt(s){return Eb(s).direction==="rtl"}const KIt={convertOffsetParentRelativeRectToViewportRelativeRect:OIt,getDocumentElement:Gw,getClippingRect:qIt,getOffsetParent:Yrt,getElementRects:GIt,getClientRects:FIt,getDimensions:VIt,getScale:EL,isElement:Tb,isRTL:WIt};function YIt(s,t){let n=null,r;const a=Gw(s);function i(){var o;clearTimeout(r),(o=n)==null||o.disconnect(),n=null}function l(o,c){o===void 0&&(o=!1),c===void 0&&(c=1),i();const{left:d,top:u,width:h,height:p}=s.getBoundingClientRect();if(o||t(),!h||!p)return;const f=VV(u),g=VV(a.clientWidth-(d+h)),b=VV(a.clientHeight-(u+p)),v=VV(d),_={rootMargin:-f+"px "+-g+"px "+-b+"px "+-v+"px",threshold:K0(0,T4(1,c))||1};let S=!0;function A(T){const D=T[0].intersectionRatio;if(D!==c){if(!S)return l();D?l(!1,D):r=setTimeout(()=>{l(!1,1e-7)},1e3)}S=!1}try{n=new IntersectionObserver(A,{..._,root:a.ownerDocument})}catch{n=new IntersectionObserver(A,_)}n.observe(s)}return l(!0),i}function ZIt(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=wAe(s),u=a||i?[...d?nB(d):[],...nB(t)]:[];u.forEach(j=>{a&&j.addEventListener("scroll",n,{passive:!0}),i&&j.addEventListener("resize",n)});const h=d&&o?YIt(d,n):null;let p=-1,f=null;l&&(f=new ResizeObserver(j=>{let[_]=j;_&&_.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var S;(S=f)==null||S.observe(t)})),n()}),d&&!c&&f.observe(d),f.observe(t));let g,b=c?mM(s):null;c&&v();function v(){const j=mM(s);b&&(j.x!==b.x||j.y!==b.y||j.width!==b.width||j.height!==b.height)&&n(),b=j,g=requestAnimationFrame(v)}return n(),()=>{var j;u.forEach(_=>{a&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),h==null||h(),(j=f)==null||j.disconnect(),f=null,c&&cancelAnimationFrame(g)}}const QIt=EIt,XIt=AIt,JIt=SIt,ePt=IIt,tPt=CIt,hze=kIt,sPt=MIt,nPt=(s,t,n)=>{const r=new Map,a={platform:KIt,...n},i={...a.platform,_c:r};return NIt(s,t,{...a,platform:i})};var Cme=typeof document<"u"?N.useLayoutEffect:N.useEffect;function Ype(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(!Ype(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)&&!Ype(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function Zrt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function mze(s,t){const n=Zrt(s);return Math.round(t*n)/n}function qwe(s){const t=N.useRef(s);return Cme(()=>{t.current=s}),t}function rPt(s){s===void 0&&(s={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:l}={},transform:o=!0,whileElementsMounted:c,open:d}=s,[u,h]=N.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,f]=N.useState(r);Ype(p,r)||f(r);const[g,b]=N.useState(null),[v,j]=N.useState(null),_=N.useCallback(pe=>{pe!==D.current&&(D.current=pe,b(pe))},[]),S=N.useCallback(pe=>{pe!==L.current&&(L.current=pe,j(pe))},[]),A=i||g,T=l||v,D=N.useRef(null),L=N.useRef(null),M=N.useRef(u),F=c!=null,z=qwe(c),V=qwe(a),W=qwe(d),K=N.useCallback(()=>{if(!D.current||!L.current)return;const pe={placement:t,strategy:n,middleware:p};V.current&&(pe.platform=V.current),nPt(D.current,L.current,pe).then(ce=>{const de={...ce,isPositioned:W.current!==!1};Y.current&&!Ype(M.current,de)&&(M.current=de,Gx.flushSync(()=>{h(de)}))})},[p,t,n,V,W]);Cme(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,h(pe=>({...pe,isPositioned:!1})))},[d]);const Y=N.useRef(!1);Cme(()=>(Y.current=!0,()=>{Y.current=!1}),[]),Cme(()=>{if(A&&(D.current=A),T&&(L.current=T),A&&T){if(z.current)return z.current(A,T,K);K()}},[A,T,K,z,F]);const ee=N.useMemo(()=>({reference:D,floating:L,setReference:_,setFloating:S}),[_,S]),ne=N.useMemo(()=>({reference:A,floating:T}),[A,T]),oe=N.useMemo(()=>{const pe={position:n,left:0,top:0};if(!ne.floating)return pe;const ce=mze(ne.floating,u.x),de=mze(ne.floating,u.y);return o?{...pe,transform:"translate("+ce+"px, "+de+"px)",...Zrt(ne.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ce,top:de}},[n,o,ne.floating,u.x,u.y]);return N.useMemo(()=>({...u,update:K,refs:ee,elements:ne,floatingStyles:oe}),[u,K,ee,ne,oe])}const aPt=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?hze({element:r.current,padding:a}).fn(n):{}:r?hze({element:r,padding:a}).fn(n):{}}}},iPt=(s,t)=>({...QIt(s),options:[s,t]}),oPt=(s,t)=>({...XIt(s),options:[s,t]}),lPt=(s,t)=>({...sPt(s),options:[s,t]}),cPt=(s,t)=>({...JIt(s),options:[s,t]}),dPt=(s,t)=>({...ePt(s),options:[s,t]}),uPt=(s,t)=>({...tPt(s),options:[s,t]}),hPt=(s,t)=>({...aPt(s),options:[s,t]});var mPt="Arrow",Qrt=N.forwardRef((s,t)=>{const{children:n,width:r=10,height:a=5,...i}=s;return e.jsx(sa.svg,{...i,ref:t,width:r,height:a,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:s.asChild?n:e.jsx("polygon",{points:"0,0 30,0 15,10"})})});Qrt.displayName=mPt;var pPt=Qrt;function q$(s){const[t,n]=N.useState(void 0);return fh(()=>{if(s){n({width:s.offsetWidth,height:s.offsetHeight});const r=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let l,o;if("borderBoxSize"in i){const c=i.borderBoxSize,d=Array.isArray(c)?c[0]:c;l=d.inlineSize,o=d.blockSize}else l=s.offsetWidth,o=s.offsetHeight;n({width:l,height:o})});return r.observe(s,{box:"border-box"}),()=>r.unobserve(s)}else n(void 0)},[s]),t}var jAe="Popper",[Xrt,Ww]=gu(jAe),[fPt,Jrt]=Xrt(jAe),eat=s=>{const{__scopePopper:t,children:n}=s,[r,a]=N.useState(null);return e.jsx(fPt,{scope:t,anchor:r,onAnchorChange:a,children:n})};eat.displayName=jAe;var tat="PopperAnchor",sat=N.forwardRef((s,t)=>{const{__scopePopper:n,virtualRef:r,...a}=s,i=Jrt(tat,n),l=N.useRef(null),o=Ti(t,l);return N.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||l.current)}),r?null:e.jsx(sa.div,{...a,ref:o})});sat.displayName=tat;var NAe="PopperContent",[xPt,gPt]=Xrt(NAe),nat=N.forwardRef((s,t)=>{var Ee,De,Ie,Fe,qe,ve;const{__scopePopper:n,side:r="bottom",sideOffset:a=0,align:i="center",alignOffset:l=0,arrowPadding:o=0,avoidCollisions:c=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:h="partial",hideWhenDetached:p=!1,updatePositionStrategy:f="optimized",onPlaced:g,...b}=s,v=Jrt(NAe,n),[j,_]=N.useState(null),S=Ti(t,Je=>_(Je)),[A,T]=N.useState(null),D=q$(A),L=(D==null?void 0:D.width)??0,M=(D==null?void 0:D.height)??0,F=r+(i!=="center"?"-"+i:""),z=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},V=Array.isArray(d)?d:[d],W=V.length>0,K={padding:z,boundary:V.filter(vPt),altBoundary:W},{refs:Y,floatingStyles:ee,placement:ne,isPositioned:oe,middlewareData:pe}=rPt({strategy:"fixed",placement:F,whileElementsMounted:(...Je)=>ZIt(...Je,{animationFrame:f==="always"}),elements:{reference:v.anchor},middleware:[iPt({mainAxis:a+M,alignmentAxis:l}),c&&oPt({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?lPt():void 0,...K}),c&&cPt({...K}),dPt({...K,apply:({elements:Je,rects:we,availableWidth:it,availableHeight:Ne})=>{const{width:He,height:$e}=we.reference,Ye=Je.floating.style;Ye.setProperty("--radix-popper-available-width",`${it}px`),Ye.setProperty("--radix-popper-available-height",`${Ne}px`),Ye.setProperty("--radix-popper-anchor-width",`${He}px`),Ye.setProperty("--radix-popper-anchor-height",`${$e}px`)}}),A&&hPt({element:A,padding:o}),bPt({arrowWidth:L,arrowHeight:M}),p&&uPt({strategy:"referenceHidden",...K})]}),[ce,de]=iat(ne),ie=dh(g);fh(()=>{oe&&(ie==null||ie())},[oe,ie]);const ye=(Ee=pe.arrow)==null?void 0:Ee.x,_e=(De=pe.arrow)==null?void 0:De.y,Me=((Ie=pe.arrow)==null?void 0:Ie.centerOffset)!==0,[Te,Ce]=N.useState();return fh(()=>{j&&Ce(window.getComputedStyle(j).zIndex)},[j]),e.jsx("div",{ref:Y.setFloating,"data-radix-popper-content-wrapper":"",style:{...ee,transform:oe?ee.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Te,"--radix-popper-transform-origin":[(Fe=pe.transformOrigin)==null?void 0:Fe.x,(qe=pe.transformOrigin)==null?void 0:qe.y].join(" "),...((ve=pe.hide)==null?void 0:ve.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(xPt,{scope:n,placedSide:ce,onArrowChange:T,arrowX:ye,arrowY:_e,shouldHideArrow:Me,children:e.jsx(sa.div,{"data-side":ce,"data-align":de,...b,ref:S,style:{...b.style,animation:oe?void 0:"none"}})})})});nat.displayName=NAe;var rat="PopperArrow",yPt={top:"bottom",right:"left",bottom:"top",left:"right"},aat=N.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=gPt(rat,r),l=yPt[i.placedSide];return e.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[l]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:e.jsx(pPt,{...a,ref:n,style:{...a.style,display:"block"}})})});aat.displayName=rat;function vPt(s){return s!==null}var bPt=s=>({name:"transformOrigin",options:s,fn(t){var v,j,_;const{placement:n,rects:r,middlewareData:a}=t,l=((v=a.arrow)==null?void 0:v.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=iat(n),h={start:"0%",center:"50%",end:"100%"}[u],p=(((j=a.arrow)==null?void 0:j.x)??0)+o/2,f=(((_=a.arrow)==null?void 0:_.y)??0)+c/2;let g="",b="";return d==="bottom"?(g=l?h:`${p}px`,b=`${-c}px`):d==="top"?(g=l?h:`${p}px`,b=`${r.floating.height+c}px`):d==="right"?(g=`${-c}px`,b=l?h:`${f}px`):d==="left"&&(g=`${r.floating.width+c}px`,b=l?h:`${f}px`),{data:{x:g,y:b}}}});function iat(s){const[t,n="center"]=s.split("-");return[t,n]}var V$=eat,RD=sat,H$=nat,G$=aat,[D0e,Nxn]=gu("Tooltip",[Ww]),R0e=Ww(),oat="TooltipProvider",_Pt=700,KSe="tooltip.open",[wPt,kAe]=D0e(oat),lat=s=>{const{__scopeTooltip:t,delayDuration:n=_Pt,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:i}=s,l=N.useRef(!0),o=N.useRef(!1),c=N.useRef(0);return N.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(wPt,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:N.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:N.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,r)},[r]),isPointerInTransitRef:o,onPointerInTransitChange:N.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})};lat.displayName=oat;var rB="Tooltip",[jPt,O0e]=D0e(rB),cat=s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=kAe(rB,s.__scopeTooltip),d=R0e(t),[u,h]=N.useState(null),p=um(),f=N.useRef(0),g=l??c.disableHoverableContent,b=o??c.delayDuration,v=N.useRef(!1),[j,_]=mm({prop:r,defaultProp:a??!1,onChange:L=>{L?(c.onOpen(),document.dispatchEvent(new CustomEvent(KSe))):c.onClose(),i==null||i(L)},caller:rB}),S=N.useMemo(()=>j?v.current?"delayed-open":"instant-open":"closed",[j]),A=N.useCallback(()=>{window.clearTimeout(f.current),f.current=0,v.current=!1,_(!0)},[_]),T=N.useCallback(()=>{window.clearTimeout(f.current),f.current=0,_(!1)},[_]),D=N.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{v.current=!0,_(!0),f.current=0},b)},[b,_]);return N.useEffect(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),e.jsx(V$,{...d,children:e.jsx(jPt,{scope:t,contentId:p,open:j,stateAttribute:S,trigger:u,onTriggerChange:h,onTriggerEnter:N.useCallback(()=>{c.isOpenDelayedRef.current?D():A()},[c.isOpenDelayedRef,D,A]),onTriggerLeave:N.useCallback(()=>{g?T():(window.clearTimeout(f.current),f.current=0)},[T,g]),onOpen:A,onClose:T,disableHoverableContent:g,children:n})})};cat.displayName=rB;var YSe="TooltipTrigger",dat=N.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=O0e(YSe,n),i=kAe(YSe,n),l=R0e(n),o=N.useRef(null),c=Ti(t,o,a.onTriggerChange),d=N.useRef(!1),u=N.useRef(!1),h=N.useCallback(()=>d.current=!1,[]);return N.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),e.jsx(RD,{asChild:!0,...l,children:e.jsx(sa.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:c,onPointerMove:wr(s.onPointerMove,p=>{p.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:wr(s.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:wr(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:wr(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:wr(s.onBlur,a.onClose),onClick:wr(s.onClick,a.onClose)})})});dat.displayName=YSe;var NPt="TooltipPortal",[kxn,kPt]=D0e(NPt,{forceMount:void 0}),v8="TooltipContent",uat=N.forwardRef((s,t)=>{const n=kPt(v8,s.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...i}=s,l=O0e(v8,s.__scopeTooltip);return e.jsx(Bh,{present:r||l.open,children:l.disableHoverableContent?e.jsx(hat,{side:a,...i,ref:t}):e.jsx(SPt,{side:a,...i,ref:t})})}),SPt=N.forwardRef((s,t)=>{const n=O0e(v8,s.__scopeTooltip),r=kAe(v8,s.__scopeTooltip),a=N.useRef(null),i=Ti(t,a),[l,o]=N.useState(null),{trigger:c,onClose:d}=n,u=a.current,{onPointerInTransitChange:h}=r,p=N.useCallback(()=>{o(null),h(!1)},[h]),f=N.useCallback((g,b)=>{const v=g.currentTarget,j={x:g.clientX,y:g.clientY},_=MPt(j,v.getBoundingClientRect()),S=IPt(j,_),A=PPt(b.getBoundingClientRect()),T=DPt([...S,...A]);o(T),h(!0)},[h]);return N.useEffect(()=>()=>p(),[p]),N.useEffect(()=>{if(c&&u){const g=v=>f(v,u),b=v=>f(v,c);return c.addEventListener("pointerleave",g),u.addEventListener("pointerleave",b),()=>{c.removeEventListener("pointerleave",g),u.removeEventListener("pointerleave",b)}}},[c,u,f,p]),N.useEffect(()=>{if(l){const g=b=>{const v=b.target,j={x:b.clientX,y:b.clientY},_=(c==null?void 0:c.contains(v))||(u==null?void 0:u.contains(v)),S=!LPt(j,l);_?p():S&&(p(),d())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[c,u,l,d,p]),e.jsx(hat,{...s,ref:i})}),[CPt,TPt]=D0e(rB,{isInside:!1}),EPt=irt("TooltipContent"),hat=N.forwardRef((s,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=O0e(v8,n),d=R0e(n),{onClose:u}=c;return N.useEffect(()=>(document.addEventListener(KSe,u),()=>document.removeEventListener(KSe,u)),[u]),N.useEffect(()=>{if(c.trigger){const h=p=>{const f=p.target;f!=null&&f.contains(c.trigger)&&u()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[c.trigger,u]),e.jsx(G4,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:h=>h.preventDefault(),onDismiss:u,children:e.jsxs(H$,{"data-state":c.stateAttribute,...d,...o,ref:t,style:{...o.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[e.jsx(EPt,{children:r}),e.jsx(CPt,{scope:n,isInside:!0,children:e.jsx(IMt,{id:c.contentId,role:"tooltip",children:a||r})})]})})});uat.displayName=v8;var mat="TooltipArrow",APt=N.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=R0e(n);return TPt(mat,n).isInside?null:e.jsx(G$,{...a,...r,ref:t})});APt.displayName=mat;function MPt(s,t){const n=Math.abs(t.top-s.y),r=Math.abs(t.bottom-s.y),a=Math.abs(t.right-s.x),i=Math.abs(t.left-s.x);switch(Math.min(n,r,a,i)){case i:return"left";case a:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function IPt(s,t,n=5){const r=[];switch(t){case"top":r.push({x:s.x-n,y:s.y+n},{x:s.x+n,y:s.y+n});break;case"bottom":r.push({x:s.x-n,y:s.y-n},{x:s.x+n,y:s.y-n});break;case"left":r.push({x:s.x+n,y:s.y-n},{x:s.x+n,y:s.y+n});break;case"right":r.push({x:s.x-n,y:s.y-n},{x:s.x-n,y:s.y+n});break}return r}function PPt(s){const{top:t,right:n,bottom:r,left:a}=s;return[{x:a,y:t},{x:n,y:t},{x:n,y:r},{x:a,y:r}]}function LPt(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=p>r&&n<(h-d)*(r-u)/(p-u)+d&&(a=!a)}return a}function DPt(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),RPt(t)}function RPt(s){if(s.length<=1)return s.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],l=t[t.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))t.pop();else break}t.push(a)}t.pop();const n=[];for(let r=s.length-1;r>=0;r--){const a=s[r];for(;n.length>=2;){const i=n[n.length-1],l=n[n.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))n.pop();else break}n.push(a)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var OPt=lat,FPt=cat,zPt=dat,pat=uat;const Kw=OPt,Ac=FPt,Mc=zPt,yc=N.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(pat,{ref:r,sideOffset:t,className:Et("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}));yc.displayName=pat.displayName;var OD=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(){}},pM=typeof window>"u"||"Deno"in globalThis;function Vx(){}function BPt(s,t){return typeof s=="function"?s(t):s}function ZSe(s){return typeof s=="number"&&s>=0&&s!==1/0}function fat(s,t){return Math.max(s+(t||0)-Date.now(),0)}function m4(s,t){return typeof s=="function"?s(t):s}function vv(s,t){return typeof s=="function"?s(t):s}function pze(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==SAe(l,t.options))return!1}else if(!aB(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 fze(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(fM(t.options.mutationKey)!==fM(i))return!1}else if(!aB(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function SAe(s,t){return((t==null?void 0:t.queryKeyHashFn)||fM)(s)}function fM(s){return JSON.stringify(s,(t,n)=>QSe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function aB(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(n=>aB(s[n],t[n])):!1}function xat(s,t){if(s===t)return s;const n=xze(s)&&xze(t);if(n||QSe(s)&&QSe(t)){const r=n?s:Object.keys(s),a=r.length,i=n?t:Object.keys(t),l=i.length,o=n?[]:{},c=new Set(r);let d=0;for(let u=0;u{setTimeout(t,s)})}function XSe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?xat(s,t):t}function UPt(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function qPt(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}var CAe=Symbol();function gat(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===CAe?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function yat(s,t){return typeof s=="function"?s(...t):!!s}var cA,vS,JL,Dtt,VPt=(Dtt=class extends OD{constructor(){super();qi(this,cA);qi(this,vS);qi(this,JL);Ha(this,JL,t=>{if(!pM&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){Xs(this,vS)||this.setEventListener(Xs(this,JL))}onUnsubscribe(){var t;this.hasListeners()||((t=Xs(this,vS))==null||t.call(this),Ha(this,vS,void 0))}setEventListener(t){var n;Ha(this,JL,t),(n=Xs(this,vS))==null||n.call(this),Ha(this,vS,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){Xs(this,cA)!==t&&(Ha(this,cA,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof Xs(this,cA)=="boolean"?Xs(this,cA):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},cA=new WeakMap,vS=new WeakMap,JL=new WeakMap,Dtt),TAe=new VPt,e8,bS,t8,Rtt,HPt=(Rtt=class extends OD{constructor(){super();qi(this,e8,!0);qi(this,bS);qi(this,t8);Ha(this,t8,t=>{if(!pM&&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(){Xs(this,bS)||this.setEventListener(Xs(this,t8))}onUnsubscribe(){var t;this.hasListeners()||((t=Xs(this,bS))==null||t.call(this),Ha(this,bS,void 0))}setEventListener(t){var n;Ha(this,t8,t),(n=Xs(this,bS))==null||n.call(this),Ha(this,bS,t(this.setOnline.bind(this)))}setOnline(t){Xs(this,e8)!==t&&(Ha(this,e8,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return Xs(this,e8)}},e8=new WeakMap,bS=new WeakMap,t8=new WeakMap,Rtt),Qpe=new HPt;function JSe(){let s,t;const n=new Promise((a,i)=>{s=a,t=i});n.status="pending",n.catch(()=>{});function r(a){Object.assign(n,a),delete n.resolve,delete n.reject}return n.resolve=a=>{r({status:"fulfilled",value:a}),s(a)},n.reject=a=>{r({status:"rejected",reason:a}),t(a)},n}function GPt(s){return Math.min(1e3*2**s,3e4)}function vat(s){return(s??"online")==="online"?Qpe.isOnline():!0}var bat=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function Vwe(s){return s instanceof bat}function _at(s){let t=!1,n=0,r=!1,a;const i=JSe(),l=b=>{var v;r||(p(new bat(b)),(v=s.abort)==null||v.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>TAe.isFocused()&&(s.networkMode==="always"||Qpe.isOnline())&&s.canRun(),u=()=>vat(s.networkMode)&&s.canRun(),h=b=>{var v;r||(r=!0,(v=s.onSuccess)==null||v.call(s,b),a==null||a(),i.resolve(b))},p=b=>{var v;r||(r=!0,(v=s.onError)==null||v.call(s,b),a==null||a(),i.reject(b))},f=()=>new Promise(b=>{var v;a=j=>{(r||d())&&b(j)},(v=s.onPause)==null||v.call(s)}).then(()=>{var b;a=void 0,r||(b=s.onContinue)==null||b.call(s)}),g=()=>{if(r)return;let b;const v=n===0?s.initialPromise:void 0;try{b=v??s.fn()}catch(j){b=Promise.reject(j)}Promise.resolve(b).then(h).catch(j=>{var D;if(r)return;const _=s.retry??(pM?0:3),S=s.retryDelay??GPt,A=typeof S=="function"?S(n,j):S,T=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,j);if(t||!T){p(j);return}n++,(D=s.onFail)==null||D.call(s,n,j),$Pt(A).then(()=>d()?void 0:f()).then(()=>{t?p(j):g()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?g():f().then(g),i)}}var WPt=s=>setTimeout(s,0);function KPt(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=WPt;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 Om=KPt(),dA,Ott,wat=(Ott=class{constructor(){qi(this,dA)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ZSe(this.gcTime)&&Ha(this,dA,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(pM?1/0:5*60*1e3))}clearGcTimeout(){Xs(this,dA)&&(clearTimeout(Xs(this,dA)),Ha(this,dA,void 0))}},dA=new WeakMap,Ott),s8,uA,yv,hA,Wf,I$,mA,W1,x2,Ftt,YPt=(Ftt=class extends wat{constructor(t){super();qi(this,W1);qi(this,s8);qi(this,uA);qi(this,yv);qi(this,hA);qi(this,Wf);qi(this,I$);qi(this,mA);Ha(this,mA,!1),Ha(this,I$,t.defaultOptions),this.setOptions(t.options),this.observers=[],Ha(this,hA,t.client),Ha(this,yv,Xs(this,hA).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Ha(this,s8,ZPt(this.options)),this.state=t.state??Xs(this,s8),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=Xs(this,Wf))==null?void 0:t.promise}setOptions(t){this.options={...Xs(this,I$),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Xs(this,yv).remove(this)}setData(t,n){const r=XSe(this.state.data,t,this.options);return Xo(this,W1,x2).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Xo(this,W1,x2).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=Xs(this,Wf))==null?void 0:r.promise;return(a=Xs(this,Wf))==null||a.cancel(t),n?n.then(Vx).catch(Vx):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Xs(this,s8))}isActive(){return this.observers.some(t=>vv(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===CAe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>m4(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:!fat(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=Xs(this,Wf))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=Xs(this,Wf))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),Xs(this,yv).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(Xs(this,Wf)&&(Xs(this,mA)?Xs(this,Wf).cancel({revert:!0}):Xs(this,Wf).cancelRetry()),this.scheduleGc()),Xs(this,yv).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Xo(this,W1,x2).call(this,{type:"invalidate"})}fetch(t,n){var d,u,h;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(Xs(this,Wf))return Xs(this,Wf).continueRetry(),Xs(this,Wf).promise}if(t&&this.setOptions(t),!this.options.queryFn){const p=this.observers.find(f=>f.options.queryFn);p&&this.setOptions(p.options)}const r=new AbortController,a=p=>{Object.defineProperty(p,"signal",{enumerable:!0,get:()=>(Ha(this,mA,!0),r.signal)})},i=()=>{const p=gat(this.options,n),g=(()=>{const b={client:Xs(this,hA),queryKey:this.queryKey,meta:this.meta};return a(b),b})();return Ha(this,mA,!1),this.options.persister?this.options.persister(p,g,this):p(g)},o=(()=>{const p={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:Xs(this,hA),state:this.state,fetchFn:i};return a(p),p})();(d=this.options.behavior)==null||d.onFetch(o,this),Ha(this,uA,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Xo(this,W1,x2).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta});const c=p=>{var f,g,b,v;Vwe(p)&&p.silent||Xo(this,W1,x2).call(this,{type:"error",error:p}),Vwe(p)||((g=(f=Xs(this,yv).config).onError)==null||g.call(f,p,this),(v=(b=Xs(this,yv).config).onSettled)==null||v.call(b,this.state.data,p,this)),this.scheduleGc()};return Ha(this,Wf,_at({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:p=>{var f,g,b,v;if(p===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(p)}catch(j){c(j);return}(g=(f=Xs(this,yv).config).onSuccess)==null||g.call(f,p,this),(v=(b=Xs(this,yv).config).onSettled)==null||v.call(b,p,this.state.error,this),this.scheduleGc()},onError:c,onFail:(p,f)=>{Xo(this,W1,x2).call(this,{type:"failed",failureCount:p,error:f})},onPause:()=>{Xo(this,W1,x2).call(this,{type:"pause"})},onContinue:()=>{Xo(this,W1,x2).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),Xs(this,Wf).start()}},s8=new WeakMap,uA=new WeakMap,yv=new WeakMap,hA=new WeakMap,Wf=new WeakMap,I$=new WeakMap,mA=new WeakMap,W1=new WeakSet,x2=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,...jat(r.data,this.options),fetchMeta:t.meta??null};case"success":return Ha(this,uA,void 0),{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const a=t.error;return Vwe(a)&&a.revert&&Xs(this,uA)?{...Xs(this,uA),fetchStatus:"idle"}:{...r,error:a,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),Om.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),Xs(this,yv).notify({query:this,type:"updated",action:t})})},Ftt);function jat(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:vat(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function ZPt(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 G_,ztt,QPt=(ztt=class extends OD{constructor(t={}){super();qi(this,G_);this.config=t,Ha(this,G_,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??SAe(a,n);let l=this.get(i);return l||(l=new YPt({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){Xs(this,G_).has(t.queryHash)||(Xs(this,G_).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=Xs(this,G_).get(t.queryHash);n&&(t.destroy(),n===t&&Xs(this,G_).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Om.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return Xs(this,G_).get(t)}getAll(){return[...Xs(this,G_).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>pze(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>pze(t,r)):n}notify(t){Om.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Om.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Om.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},G_=new WeakMap,ztt),W_,$x,pA,K_,Ok,Btt,XPt=(Btt=class extends wat{constructor(t){super();qi(this,K_);qi(this,W_);qi(this,$x);qi(this,pA);this.mutationId=t.mutationId,Ha(this,$x,t.mutationCache),Ha(this,W_,[]),this.state=t.state||Nat(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){Xs(this,W_).includes(t)||(Xs(this,W_).push(t),this.clearGcTimeout(),Xs(this,$x).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Ha(this,W_,Xs(this,W_).filter(n=>n!==t)),this.scheduleGc(),Xs(this,$x).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){Xs(this,W_).length||(this.state.status==="pending"?this.scheduleGc():Xs(this,$x).remove(this))}continue(){var t;return((t=Xs(this,pA))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,u,h,p,f,g,b,v,j,_,S,A,T,D,L,M;const n=()=>{Xo(this,K_,Ok).call(this,{type:"continue"})};Ha(this,pA,_at({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(F,z)=>{Xo(this,K_,Ok).call(this,{type:"failed",failureCount:F,error:z})},onPause:()=>{Xo(this,K_,Ok).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Xs(this,$x).canRun(this)}));const r=this.state.status==="pending",a=!Xs(this,pA).canStart();try{if(r)n();else{Xo(this,K_,Ok).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=Xs(this,$x).config).onMutate)==null?void 0:l.call(i,t,this));const z=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t));z!==this.state.context&&Xo(this,K_,Ok).call(this,{type:"pending",context:z,variables:t,isPaused:a})}const F=await Xs(this,pA).start();return await((u=(d=Xs(this,$x).config).onSuccess)==null?void 0:u.call(d,F,t,this.state.context,this)),await((p=(h=this.options).onSuccess)==null?void 0:p.call(h,F,t,this.state.context)),await((g=(f=Xs(this,$x).config).onSettled)==null?void 0:g.call(f,F,null,this.state.variables,this.state.context,this)),await((v=(b=this.options).onSettled)==null?void 0:v.call(b,F,null,t,this.state.context)),Xo(this,K_,Ok).call(this,{type:"success",data:F}),F}catch(F){try{throw await((_=(j=Xs(this,$x).config).onError)==null?void 0:_.call(j,F,t,this.state.context,this)),await((A=(S=this.options).onError)==null?void 0:A.call(S,F,t,this.state.context)),await((D=(T=Xs(this,$x).config).onSettled)==null?void 0:D.call(T,void 0,F,this.state.variables,this.state.context,this)),await((M=(L=this.options).onSettled)==null?void 0:M.call(L,void 0,F,t,this.state.context)),F}finally{Xo(this,K_,Ok).call(this,{type:"error",error:F})}}finally{Xs(this,$x).runNext(this)}}},W_=new WeakMap,$x=new WeakMap,pA=new WeakMap,K_=new WeakSet,Ok=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),Om.batch(()=>{Xs(this,W_).forEach(r=>{r.onMutationUpdate(t)}),Xs(this,$x).notify({mutation:this,type:"updated",action:t})})},Btt);function Nat(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var M2,K1,P$,$tt,JPt=($tt=class extends OD{constructor(t={}){super();qi(this,M2);qi(this,K1);qi(this,P$);this.config=t,Ha(this,M2,new Set),Ha(this,K1,new Map),Ha(this,P$,0)}build(t,n,r){const a=new XPt({mutationCache:this,mutationId:++jV(this,P$)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){Xs(this,M2).add(t);const n=HV(t);if(typeof n=="string"){const r=Xs(this,K1).get(n);r?r.push(t):Xs(this,K1).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(Xs(this,M2).delete(t)){const n=HV(t);if(typeof n=="string"){const r=Xs(this,K1).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&Xs(this,K1).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=HV(t);if(typeof n=="string"){const r=Xs(this,K1).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=HV(t);if(typeof n=="string"){const a=(r=Xs(this,K1).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(){Om.batch(()=>{Xs(this,M2).forEach(t=>{this.notify({type:"removed",mutation:t})}),Xs(this,M2).clear(),Xs(this,K1).clear()})}getAll(){return Array.from(Xs(this,M2))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>fze(n,r))}findAll(t={}){return this.getAll().filter(n=>fze(t,n))}notify(t){Om.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Om.batch(()=>Promise.all(t.map(n=>n.continue().catch(Vx))))}},M2=new WeakMap,K1=new WeakMap,P$=new WeakMap,$tt);function HV(s){var t;return(t=s.options.scope)==null?void 0:t.id}function Xpe(s){return{onFetch:(t,n)=>{var u,h,p,f,g;const r=t.options,a=(p=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:p.direction,i=((f=t.state.data)==null?void 0:f.pages)||[],l=((g=t.state.data)==null?void 0:g.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let b=!1;const v=S=>{Object.defineProperty(S,"signal",{enumerable:!0,get:()=>(t.signal.aborted?b=!0:t.signal.addEventListener("abort",()=>{b=!0}),t.signal)})},j=gat(t.options,t.fetchOptions),_=async(S,A,T)=>{if(b)return Promise.reject();if(A==null&&S.pages.length)return Promise.resolve(S);const L=(()=>{const V={client:t.client,queryKey:t.queryKey,pageParam:A,direction:T?"backward":"forward",meta:t.options.meta};return v(V),V})(),M=await j(L),{maxPages:F}=t.options,z=T?qPt:UPt;return{pages:z(S.pages,M,F),pageParams:z(S.pageParams,A,F)}};if(a&&i.length){const S=a==="backward",A=S?kat:e4e,T={pages:i,pageParams:l},D=A(r,T);o=await _(T,D,S)}else{const S=s??i.length;do{const A=c===0?l[0]??r.initialPageParam:e4e(r,o);if(c>0&&A==null)break;o=await _(o,A),c++}while(c{var b,v;return(v=(b=t.options).persister)==null?void 0:v.call(b,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function e4e(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 kat(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 eLt(s,t){return t?e4e(s,t)!=null:!1}function tLt(s,t){return!t||!s.getPreviousPageParam?!1:kat(s,t)!=null}var rh,_S,wS,n8,r8,jS,a8,i8,Utt,sLt=(Utt=class{constructor(s={}){qi(this,rh);qi(this,_S);qi(this,wS);qi(this,n8);qi(this,r8);qi(this,jS);qi(this,a8);qi(this,i8);Ha(this,rh,s.queryCache||new QPt),Ha(this,_S,s.mutationCache||new JPt),Ha(this,wS,s.defaultOptions||{}),Ha(this,n8,new Map),Ha(this,r8,new Map),Ha(this,jS,0)}mount(){jV(this,jS)._++,Xs(this,jS)===1&&(Ha(this,a8,TAe.subscribe(async s=>{s&&(await this.resumePausedMutations(),Xs(this,rh).onFocus())})),Ha(this,i8,Qpe.subscribe(async s=>{s&&(await this.resumePausedMutations(),Xs(this,rh).onOnline())})))}unmount(){var s,t;jV(this,jS)._--,Xs(this,jS)===0&&((s=Xs(this,a8))==null||s.call(this),Ha(this,a8,void 0),(t=Xs(this,i8))==null||t.call(this),Ha(this,i8,void 0))}isFetching(s){return Xs(this,rh).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return Xs(this,_S).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=Xs(this,rh).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=Xs(this,rh).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(m4(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return Xs(this,rh).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=Xs(this,rh).get(r.queryHash),i=a==null?void 0:a.state.data,l=BPt(t,i);if(l!==void 0)return Xs(this,rh).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(s,t,n){return Om.batch(()=>Xs(this,rh).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=Xs(this,rh).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=Xs(this,rh);Om.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=Xs(this,rh);return Om.batch(()=>(n.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const n={revert:!0,...t},r=Om.batch(()=>Xs(this,rh).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(Vx).catch(Vx)}invalidateQueries(s,t={}){return Om.batch(()=>(Xs(this,rh).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=Om.batch(()=>Xs(this,rh).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(Vx)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Vx)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=Xs(this,rh).build(this,t);return n.isStaleByTime(m4(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(Vx).catch(Vx)}fetchInfiniteQuery(s){return s.behavior=Xpe(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(Vx).catch(Vx)}ensureInfiniteQueryData(s){return s.behavior=Xpe(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return Qpe.isOnline()?Xs(this,_S).resumePausedMutations():Promise.resolve()}getQueryCache(){return Xs(this,rh)}getMutationCache(){return Xs(this,_S)}getDefaultOptions(){return Xs(this,wS)}setDefaultOptions(s){Ha(this,wS,s)}setQueryDefaults(s,t){Xs(this,n8).set(fM(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...Xs(this,n8).values()],n={};return t.forEach(r=>{aB(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){Xs(this,r8).set(fM(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...Xs(this,r8).values()],n={};return t.forEach(r=>{aB(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...Xs(this,wS).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=SAe(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===CAe&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...Xs(this,wS).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){Xs(this,rh).clear(),Xs(this,_S).clear()}},rh=new WeakMap,_S=new WeakMap,wS=new WeakMap,n8=new WeakMap,r8=new WeakMap,jS=new WeakMap,a8=new WeakMap,i8=new WeakMap,Utt),Eg,Sl,L$,Ux,fA,o8,NS,kS,D$,l8,c8,xA,gA,SS,d8,bc,u7,t4e,s4e,n4e,r4e,a4e,i4e,o4e,Cat,qtt,Sat=(qtt=class extends OD{constructor(t,n){super();qi(this,bc);qi(this,Eg);qi(this,Sl);qi(this,L$);qi(this,Ux);qi(this,fA);qi(this,o8);qi(this,NS);qi(this,kS);qi(this,D$);qi(this,l8);qi(this,c8);qi(this,xA);qi(this,gA);qi(this,SS);qi(this,d8,new Set);this.options=n,Ha(this,Eg,t),Ha(this,kS,null),Ha(this,NS,JSe()),this.options.experimental_prefetchInRender||Xs(this,NS).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Xs(this,Sl).addObserver(this),yze(Xs(this,Sl),this.options)?Xo(this,bc,u7).call(this):this.updateResult(),Xo(this,bc,r4e).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return l4e(Xs(this,Sl),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return l4e(Xs(this,Sl),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Xo(this,bc,a4e).call(this),Xo(this,bc,i4e).call(this),Xs(this,Sl).removeObserver(this)}setOptions(t){const n=this.options,r=Xs(this,Sl);if(this.options=Xs(this,Eg).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof vv(this.options.enabled,Xs(this,Sl))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Xo(this,bc,o4e).call(this),Xs(this,Sl).setOptions(this.options),n._defaulted&&!Zpe(this.options,n)&&Xs(this,Eg).getQueryCache().notify({type:"observerOptionsUpdated",query:Xs(this,Sl),observer:this});const a=this.hasListeners();a&&vze(Xs(this,Sl),r,this.options,n)&&Xo(this,bc,u7).call(this),this.updateResult(),a&&(Xs(this,Sl)!==r||vv(this.options.enabled,Xs(this,Sl))!==vv(n.enabled,Xs(this,Sl))||m4(this.options.staleTime,Xs(this,Sl))!==m4(n.staleTime,Xs(this,Sl)))&&Xo(this,bc,t4e).call(this);const i=Xo(this,bc,s4e).call(this);a&&(Xs(this,Sl)!==r||vv(this.options.enabled,Xs(this,Sl))!==vv(n.enabled,Xs(this,Sl))||i!==Xs(this,SS))&&Xo(this,bc,n4e).call(this,i)}getOptimisticResult(t){const n=Xs(this,Eg).getQueryCache().build(Xs(this,Eg),t),r=this.createResult(n,t);return rLt(this,r)&&(Ha(this,Ux,r),Ha(this,o8,this.options),Ha(this,fA,Xs(this,Sl).state)),r}getCurrentResult(){return Xs(this,Ux)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),Reflect.get(r,a))})}trackProp(t){Xs(this,d8).add(t)}getCurrentQuery(){return Xs(this,Sl)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=Xs(this,Eg).defaultQueryOptions(t),r=Xs(this,Eg).getQueryCache().build(Xs(this,Eg),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Xo(this,bc,u7).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),Xs(this,Ux)))}createResult(t,n){var F;const r=Xs(this,Sl),a=this.options,i=Xs(this,Ux),l=Xs(this,fA),o=Xs(this,o8),d=t!==r?t.state:Xs(this,L$),{state:u}=t;let h={...u},p=!1,f;if(n._optimisticResults){const z=this.hasListeners(),V=!z&&yze(t,n),W=z&&vze(t,r,n,a);(V||W)&&(h={...h,...jat(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:g,errorUpdatedAt:b,status:v}=h;f=h.data;let j=!1;if(n.placeholderData!==void 0&&f===void 0&&v==="pending"){let z;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(z=i.data,j=!0):z=typeof n.placeholderData=="function"?n.placeholderData((F=Xs(this,c8))==null?void 0:F.state.data,Xs(this,c8)):n.placeholderData,z!==void 0&&(v="success",f=XSe(i==null?void 0:i.data,z,n),p=!0)}if(n.select&&f!==void 0&&!j)if(i&&f===(l==null?void 0:l.data)&&n.select===Xs(this,D$))f=Xs(this,l8);else try{Ha(this,D$,n.select),f=n.select(f),f=XSe(i==null?void 0:i.data,f,n),Ha(this,l8,f),Ha(this,kS,null)}catch(z){Ha(this,kS,z)}Xs(this,kS)&&(g=Xs(this,kS),f=Xs(this,l8),b=Date.now(),v="error");const _=h.fetchStatus==="fetching",S=v==="pending",A=v==="error",T=S&&_,D=f!==void 0,M={status:v,fetchStatus:h.fetchStatus,isPending:S,isSuccess:v==="success",isError:A,isInitialLoading:T,isLoading:T,data:f,dataUpdatedAt:h.dataUpdatedAt,error:g,errorUpdatedAt:b,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:_,isRefetching:_&&!S,isLoadingError:A&&!D,isPaused:h.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:A&&D,isStale:EAe(t,n),refetch:this.refetch,promise:Xs(this,NS),isEnabled:vv(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const z=K=>{M.status==="error"?K.reject(M.error):M.data!==void 0&&K.resolve(M.data)},V=()=>{const K=Ha(this,NS,M.promise=JSe());z(K)},W=Xs(this,NS);switch(W.status){case"pending":t.queryHash===r.queryHash&&z(W);break;case"fulfilled":(M.status==="error"||M.data!==W.value)&&V();break;case"rejected":(M.status!=="error"||M.error!==W.reason)&&V();break}}return M}updateResult(){const t=Xs(this,Ux),n=this.createResult(Xs(this,Sl),this.options);if(Ha(this,fA,Xs(this,Sl).state),Ha(this,o8,this.options),Xs(this,fA).data!==void 0&&Ha(this,c8,Xs(this,Sl)),Zpe(n,t))return;Ha(this,Ux,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!Xs(this,d8).size)return!0;const l=new Set(i??Xs(this,d8));return this.options.throwOnError&&l.add("error"),Object.keys(Xs(this,Ux)).some(o=>{const c=o;return Xs(this,Ux)[c]!==t[c]&&l.has(c)})};Xo(this,bc,Cat).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Xo(this,bc,r4e).call(this)}},Eg=new WeakMap,Sl=new WeakMap,L$=new WeakMap,Ux=new WeakMap,fA=new WeakMap,o8=new WeakMap,NS=new WeakMap,kS=new WeakMap,D$=new WeakMap,l8=new WeakMap,c8=new WeakMap,xA=new WeakMap,gA=new WeakMap,SS=new WeakMap,d8=new WeakMap,bc=new WeakSet,u7=function(t){Xo(this,bc,o4e).call(this);let n=Xs(this,Sl).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Vx)),n},t4e=function(){Xo(this,bc,a4e).call(this);const t=m4(this.options.staleTime,Xs(this,Sl));if(pM||Xs(this,Ux).isStale||!ZSe(t))return;const r=fat(Xs(this,Ux).dataUpdatedAt,t)+1;Ha(this,xA,setTimeout(()=>{Xs(this,Ux).isStale||this.updateResult()},r))},s4e=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Xs(this,Sl)):this.options.refetchInterval)??!1},n4e=function(t){Xo(this,bc,i4e).call(this),Ha(this,SS,t),!(pM||vv(this.options.enabled,Xs(this,Sl))===!1||!ZSe(Xs(this,SS))||Xs(this,SS)===0)&&Ha(this,gA,setInterval(()=>{(this.options.refetchIntervalInBackground||TAe.isFocused())&&Xo(this,bc,u7).call(this)},Xs(this,SS)))},r4e=function(){Xo(this,bc,t4e).call(this),Xo(this,bc,n4e).call(this,Xo(this,bc,s4e).call(this))},a4e=function(){Xs(this,xA)&&(clearTimeout(Xs(this,xA)),Ha(this,xA,void 0))},i4e=function(){Xs(this,gA)&&(clearInterval(Xs(this,gA)),Ha(this,gA,void 0))},o4e=function(){const t=Xs(this,Eg).getQueryCache().build(Xs(this,Eg),this.options);if(t===Xs(this,Sl))return;const n=Xs(this,Sl);Ha(this,Sl,t),Ha(this,L$,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},Cat=function(t){Om.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(Xs(this,Ux))}),Xs(this,Eg).getQueryCache().notify({query:Xs(this,Sl),type:"observerResultsUpdated"})})},qtt);function nLt(s,t){return vv(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function yze(s,t){return nLt(s,t)||s.state.data!==void 0&&l4e(s,t,t.refetchOnMount)}function l4e(s,t,n){if(vv(t.enabled,s)!==!1&&m4(t.staleTime,s)!=="static"){const r=typeof n=="function"?n(s):n;return r==="always"||r!==!1&&EAe(s,t)}return!1}function vze(s,t,n,r){return(s!==t||vv(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&EAe(s,n)}function EAe(s,t){return vv(t.enabled,s)!==!1&&s.isStaleByTime(m4(t.staleTime,s))}function rLt(s,t){return!Zpe(s.getCurrentResult(),t)}var aLt=class extends Sat{constructor(s,t){super(s,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(s){super.setOptions({...s,behavior:Xpe()})}getOptimisticResult(s){return s.behavior=Xpe(),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,b;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(b=(g=n.fetchMeta)==null?void 0:g.fetchMore)==null?void 0:b.direction,d=l&&c==="forward",u=a&&c==="forward",h=l&&c==="backward",p=a&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:eLt(t,n.data),hasPreviousPage:tLt(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:p,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!p}}},CS,TS,Ag,I2,oN,Tme,c4e,Vtt,iLt=(Vtt=class extends OD{constructor(n,r){super();qi(this,oN);qi(this,CS);qi(this,TS);qi(this,Ag);qi(this,I2);Ha(this,CS,n),this.setOptions(r),this.bindMethods(),Xo(this,oN,Tme).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=Xs(this,CS).defaultMutationOptions(n),Zpe(this.options,r)||Xs(this,CS).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Xs(this,Ag),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&fM(r.mutationKey)!==fM(this.options.mutationKey)?this.reset():((a=Xs(this,Ag))==null?void 0:a.state.status)==="pending"&&Xs(this,Ag).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=Xs(this,Ag))==null||n.removeObserver(this)}onMutationUpdate(n){Xo(this,oN,Tme).call(this),Xo(this,oN,c4e).call(this,n)}getCurrentResult(){return Xs(this,TS)}reset(){var n;(n=Xs(this,Ag))==null||n.removeObserver(this),Ha(this,Ag,void 0),Xo(this,oN,Tme).call(this),Xo(this,oN,c4e).call(this)}mutate(n,r){var a;return Ha(this,I2,r),(a=Xs(this,Ag))==null||a.removeObserver(this),Ha(this,Ag,Xs(this,CS).getMutationCache().build(Xs(this,CS),this.options)),Xs(this,Ag).addObserver(this),Xs(this,Ag).execute(n)}},CS=new WeakMap,TS=new WeakMap,Ag=new WeakMap,I2=new WeakMap,oN=new WeakSet,Tme=function(){var r;const n=((r=Xs(this,Ag))==null?void 0:r.state)??Nat();Ha(this,TS,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},c4e=function(n){Om.batch(()=>{var r,a,i,l,o,c,d,u;if(Xs(this,I2)&&this.hasListeners()){const h=Xs(this,TS).variables,p=Xs(this,TS).context;(n==null?void 0:n.type)==="success"?((a=(r=Xs(this,I2)).onSuccess)==null||a.call(r,n.data,h,p),(l=(i=Xs(this,I2)).onSettled)==null||l.call(i,n.data,null,h,p)):(n==null?void 0:n.type)==="error"&&((c=(o=Xs(this,I2)).onError)==null||c.call(o,n.error,h,p),(u=(d=Xs(this,I2)).onSettled)==null||u.call(d,void 0,n.error,h,p))}this.listeners.forEach(h=>{h(Xs(this,TS))})})},Vtt),Tat=N.createContext(void 0),Gt=s=>{const t=N.useContext(Tat);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},oLt=({client:s,children:t})=>(N.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(Tat.Provider,{value:s,children:t})),Eat=N.createContext(!1),lLt=()=>N.useContext(Eat);Eat.Provider;function cLt(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var dLt=N.createContext(cLt()),uLt=()=>N.useContext(dLt),hLt=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},mLt=s=>{N.useEffect(()=>{s.clearReset()},[s])},pLt=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||yat(n,[s.error,r])),fLt=s=>{if(s.suspense){const t=r=>r==="static"?r:Math.max(r??1e3,1e3),n=s.staleTime;s.staleTime=typeof n=="function"?(...r)=>t(n(...r)):t(n),typeof s.gcTime=="number"&&(s.gcTime=Math.max(s.gcTime,1e3))}},xLt=(s,t)=>s.isLoading&&s.isFetching&&!t,gLt=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,bze=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function Aat(s,t,n){var h,p,f,g,b;const r=lLt(),a=uLt(),i=Gt(),l=i.defaultQueryOptions(s);(p=(h=i.getDefaultOptions().queries)==null?void 0:h._experimental_beforeQuery)==null||p.call(h,l),l._optimisticResults=r?"isRestoring":"optimistic",fLt(l),hLt(l,a),mLt(a);const o=!i.getQueryCache().get(l.queryHash),[c]=N.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),u=!r&&s.subscribed!==!1;if(N.useSyncExternalStore(N.useCallback(v=>{const j=u?c.subscribe(Om.batchCalls(v)):Vx;return c.updateResult(),j},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),N.useEffect(()=>{c.setOptions(l)},[l,c]),gLt(l,d))throw bze(l,c,a);if(pLt({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((g=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_afterQuery)==null||g.call(f,l,d),l.experimental_prefetchInRender&&!pM&&xLt(d,r)){const v=o?bze(l,c,a):(b=i.getQueryCache().get(l.queryHash))==null?void 0:b.promise;v==null||v.catch(Vx).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function lt(s,t){return Aat(s,Sat)}function gt(s,t){const n=Gt(),[r]=N.useState(()=>new iLt(n,s));N.useEffect(()=>{r.setOptions(s)},[r,s]);const a=N.useSyncExternalStore(N.useCallback(l=>r.subscribe(Om.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=N.useCallback((l,o)=>{r.mutate(l,o).catch(Vx)},[r]);if(a.error&&yat(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function yLt(s,t){return Aat(s,aLt)}/** * @remix-run/router v1.23.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function iB(){return iB=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function Mat(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function bLt(){return Math.random().toString(36).substr(2,8)}function wze(s,t){return{usr:s.state,key:s.key,idx:t}}function d4e(s,t,n,r){return n===void 0&&(n=null),iB({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?FD(t):t,{state:n,key:t&&t.key||r||bLt()})}function Jpe(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 FD(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 _Lt(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=MS.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(iB({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=MS.Pop;let v=u(),j=v==null?null:v-d;d=v,c&&c({action:o,location:b.location,delta:j})}function p(v,j){o=MS.Push;let _=d4e(b.location,v,j);d=u()+1;let S=wze(_,d),A=b.createHref(_);try{l.pushState(S,"",A)}catch(T){if(T instanceof DOMException&&T.name==="DataCloneError")throw T;a.location.assign(A)}i&&c&&c({action:o,location:b.location,delta:1})}function f(v,j){o=MS.Replace;let _=d4e(b.location,v,j);d=u();let S=wze(_,d),A=b.createHref(_);l.replaceState(S,"",A),i&&c&&c({action:o,location:b.location,delta:0})}function g(v){let j=a.location.origin!=="null"?a.location.origin:a.location.href,_=typeof v=="string"?v:Jpe(v);return _=_.replace(/ $/,"%20"),qu(j,"No window.location.(origin|href) available to create URL for href: "+_),new URL(_,j)}let b={get action(){return o},get location(){return s(a,l)},listen(v){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(_ze,h),c=v,()=>{a.removeEventListener(_ze,h),c=null}},createHref(v){return t(a,v)},createURL:g,encodeLocation(v){let j=g(v);return{pathname:j.pathname,search:j.search,hash:j.hash}},push:p,replace:f,go(v){return l.go(v)}};return b}var jze;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(jze||(jze={}));function wLt(s,t,n){return n===void 0&&(n="/"),jLt(s,t,n,!1)}function jLt(s,t,n,r){let a=typeof t=="string"?FD(t):t,i=b8(a.pathname||"/",n);if(i==null)return null;let l=Iat(s);NLt(l);let o=null;for(let c=0;o==null&&c{let c={relativePath:o===void 0?i.path||"":o,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};c.relativePath.startsWith("/")&&(qu(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=p4([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(qu(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),Iat(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:MLt(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 Pat(i.path))a(i,l,c)}),t}function Pat(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=Pat(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 NLt(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:ILt(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const kLt=/^:[\w-]+$/,SLt=3,CLt=2,TLt=1,ELt=10,ALt=-2,Nze=s=>s==="*";function MLt(s,t){let n=s.split("/"),r=n.length;return n.some(Nze)&&(r+=ALt),t&&(r+=CLt),n.filter(a=>!Nze(a)).reduce((a,i)=>a+(kLt.test(i)?SLt:i===""?TLt:ELt),r)}function ILt(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 PLt(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:p,isOptional:f}=u;if(p==="*"){let b=o[h]||"";l=i.slice(0,i.length-b.length).replace(/(.)\/+$/,"$1")}const g=o[h];return f&&!g?d[p]=void 0:d[p]=(g||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function LLt(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Mat(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 DLt(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Mat(!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 b8(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 RLt(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?FD(s):s;return{pathname:n?n.startsWith("/")?n:OLt(n,t):t,search:BLt(r),hash:$Lt(a)}}function OLt(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 Hwe(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 FLt(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function AAe(s,t){let n=FLt(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function MAe(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=FD(s):(a=iB({},s),qu(!a.pathname||!a.pathname.includes("?"),Hwe("?","pathname","search",a)),qu(!a.pathname||!a.pathname.includes("#"),Hwe("#","pathname","hash",a)),qu(!a.search||!a.search.includes("#"),Hwe("#","search","hash",a)));let i=s===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=n;else{let h=t.length-1;if(!r&&l.startsWith("..")){let p=l.split("/");for(;p[0]==="..";)p.shift(),h-=1;a.pathname=p.join("/")}o=h>=0?t[h]:"/"}let c=RLt(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const p4=s=>s.join("/").replace(/\/\/+/g,"/"),zLt=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),BLt=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,$Lt=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function ULt(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const Lat=["post","put","patch","delete"];new Set(Lat);const qLt=["get",...Lat];new Set(qLt);/** * React Router v6.30.1 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function oB(){return oB=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),N.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=MAe(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:p4([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const GLt=N.createContext(null);function WLt(s){let t=N.useContext(Yw).outlet;return t&&N.createElement(GLt.Provider,{value:s},t)}function _i(){let{matches:s}=N.useContext(Yw),t=s[s.length-1];return t?t.params:{}}function B0e(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=N.useContext(NN),{matches:a}=N.useContext(Yw),{pathname:i}=Jl(),l=JSON.stringify(AAe(a,r.v7_relativeSplatPath));return N.useMemo(()=>MAe(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function KLt(s,t){return YLt(s,t)}function YLt(s,t,n,r){zD()||qu(!1);let{navigator:a}=N.useContext(NN),{matches:i}=N.useContext(Yw),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Jl(),u;if(t){var h;let v=typeof t=="string"?FD(t):t;c==="/"||(h=v.pathname)!=null&&h.startsWith(c)||qu(!1),u=v}else u=d;let p=u.pathname||"/",f=p;if(c!=="/"){let v=c.replace(/^\//,"").split("/");f="/"+p.replace(/^\//,"").split("/").slice(v.length).join("/")}let g=wLt(s,{pathname:f}),b=e8t(g&&g.map(v=>Object.assign({},v,{params:Object.assign({},o,v.params),pathname:p4([c,a.encodeLocation?a.encodeLocation(v.pathname).pathname:v.pathname]),pathnameBase:v.pathnameBase==="/"?c:p4([c,a.encodeLocation?a.encodeLocation(v.pathnameBase).pathname:v.pathnameBase])})),i,n,r);return t&&b?N.createElement(z0e.Provider,{value:{location:oB({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:MS.Pop}},b):b}function ZLt(){let s=r8t(),t=ULt(s)?s.status+" "+s.statusText:s instanceof Error?s.message:JSON.stringify(s),n=s instanceof Error?s.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return N.createElement(N.Fragment,null,N.createElement("h2",null,"Unexpected Application Error!"),N.createElement("h3",{style:{fontStyle:"italic"}},t),n?N.createElement("pre",{style:a},n):null,null)}const QLt=N.createElement(ZLt,null);class XLt extends N.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?N.createElement(Yw.Provider,{value:this.props.routeContext},N.createElement(Rat.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function JLt(s){let{routeContext:t,match:n,children:r}=s,a=N.useContext(F0e);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),N.createElement(Yw.Provider,{value:t},r)}function e8t(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||qu(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,p)=>{let f,g=!1,b=null,v=null;n&&(f=o&&h.route.id?o[h.route.id]:void 0,b=h.route.errorElement||QLt,c&&(d<0&&p===0?(g=!0,v=null):d===p&&(g=!0,v=h.route.hydrateFallbackElement||null)));let j=t.concat(l.slice(0,p+1)),_=()=>{let S;return f?S=b:g?S=v:h.route.Component?S=N.createElement(h.route.Component,null):h.route.element?S=h.route.element:S=u,N.createElement(JLt,{match:h,routeContext:{outlet:u,matches:j,isDataRoute:n!=null},children:S})};return n&&(h.route.ErrorBoundary||h.route.errorElement||p===0)?N.createElement(XLt,{location:n.location,revalidation:n.revalidation,component:b,error:f,children:_(),routeContext:{outlet:null,matches:j,isDataRoute:!0}}):_()},null)}var Fat=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(Fat||{}),tfe=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}(tfe||{});function t8t(s){let t=N.useContext(F0e);return t||qu(!1),t}function s8t(s){let t=N.useContext(Dat);return t||qu(!1),t}function n8t(s){let t=N.useContext(Yw);return t||qu(!1),t}function zat(s){let t=n8t(),n=t.matches[t.matches.length-1];return n.route.id||qu(!1),n.route.id}function r8t(){var s;let t=N.useContext(Rat),n=s8t(tfe.UseRouteError),r=zat(tfe.UseRouteError);return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function a8t(){let{router:s}=t8t(Fat.UseNavigateStable),t=zat(tfe.UseNavigateStable),n=N.useRef(!1);return Oat(()=>{n.current=!0}),N.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,oB({fromRouteId:t},i)))},[s,t])}function i8t(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function f4(s){let{to:t,replace:n,state:r,relative:a}=s;zD()||qu(!1);let{future:i,static:l}=N.useContext(NN),{matches:o}=N.useContext(Yw),{pathname:c}=Jl(),d=In(),u=MAe(t,AAe(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return N.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function Bat(s){return WLt(s.context)}function is(s){qu(!1)}function o8t(s){let{basename:t="/",children:n=null,location:r,navigationType:a=MS.Pop,navigator:i,static:l=!1,future:o}=s;zD()&&qu(!1);let c=t.replace(/^\/*/,"/"),d=N.useMemo(()=>({basename:c,navigator:i,static:l,future:oB({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=FD(r));let{pathname:u="/",search:h="",hash:p="",state:f=null,key:g="default"}=r,b=N.useMemo(()=>{let v=b8(u,c);return v==null?null:{location:{pathname:v,search:h,hash:p,state:f,key:g},navigationType:a}},[c,u,h,p,f,g,a]);return b==null?null:N.createElement(NN.Provider,{value:d},N.createElement(z0e.Provider,{children:n,value:b}))}function sfe(s){let{children:t,location:n}=s;return KLt(u4e(t),n)}new Promise(()=>{});function u4e(s,t){t===void 0&&(t=[]);let n=[];return N.Children.forEach(s,(r,a)=>{if(!N.isValidElement(r))return;let i=[...t,a];if(r.type===N.Fragment){n.push.apply(n,u4e(r.props.children,i));return}r.type!==is&&qu(!1),!r.props.index||!r.props.children||qu(!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=u4e(r.props.children,i)),n.push(l)}),n}/** * React Router DOM v6.30.1 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function nfe(){return nfe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(n[a]=s[a]);return n}function l8t(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function c8t(s,t){return s.button===0&&(!t||t==="_self")&&!l8t(s)}function h4e(s){return s===void 0&&(s=""),new URLSearchParams(typeof s=="string"||Array.isArray(s)||s instanceof URLSearchParams?s:Object.keys(s).reduce((t,n)=>{let r=s[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function d8t(s,t){let n=h4e(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const u8t=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],h8t=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],m8t="6";try{window.__reactRouterVersion=m8t}catch{}const p8t=N.createContext({isTransitioning:!1}),f8t="startTransition",kze=vEe[f8t];function x8t(s){let{basename:t,children:n,future:r,window:a}=s,i=N.useRef();i.current==null&&(i.current=vLt({window:a,v5Compat:!0}));let l=i.current,[o,c]=N.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=N.useCallback(h=>{d&&kze?kze(()=>c(h)):c(h)},[c,d]);return N.useLayoutEffect(()=>l.listen(u),[l,u]),N.useEffect(()=>i8t(r),[r]),N.createElement(o8t,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const g8t=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",y8t=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Ln=N.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=t,p=$at(t,u8t),{basename:f}=N.useContext(NN),g,b=!1;if(typeof d=="string"&&y8t.test(d)&&(g=d,g8t))try{let S=new URL(window.location.href),A=d.startsWith("//")?new URL(S.protocol+d):new URL(d),T=b8(A.pathname,f);A.origin===S.origin&&T!=null?d=T+A.search+A.hash:b=!0}catch{}let v=VLt(d,{relative:a}),j=b8t(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function _(S){r&&r(S),S.defaultPrevented||j(S)}return N.createElement("a",nfe({},p,{href:g||v,onClick:b||i?r:_,ref:n,target:c}))}),nF=N.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:a=!1,className:i="",end:l=!1,style:o,to:c,viewTransition:d,children:u}=t,h=$at(t,h8t),p=B0e(c,{relative:h.relative}),f=Jl(),g=N.useContext(Dat),{navigator:b,basename:v}=N.useContext(NN),j=g!=null&&_8t(p)&&d===!0,_=b.encodeLocation?b.encodeLocation(p).pathname:p.pathname,S=f.pathname,A=g&&g.navigation&&g.navigation.location?g.navigation.location.pathname:null;a||(S=S.toLowerCase(),A=A?A.toLowerCase():null,_=_.toLowerCase()),A&&v&&(A=b8(A,v)||A);const T=_!=="/"&&_.endsWith("/")?_.length-1:_.length;let D=S===_||!l&&S.startsWith(_)&&S.charAt(T)==="/",L=A!=null&&(A===_||!l&&A.startsWith(_)&&A.charAt(_.length)==="/"),M={isActive:D,isPending:L,isTransitioning:j},F=D?r:void 0,z;typeof i=="function"?z=i(M):z=[i,D?"active":null,L?"pending":null,j?"transitioning":null].filter(Boolean).join(" ");let V=typeof o=="function"?o(M):o;return N.createElement(Ln,nfe({},h,{"aria-current":F,className:z,ref:n,style:V,to:c,viewTransition:d}),typeof u=="function"?u(M):u)});var m4e;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(m4e||(m4e={}));var Sze;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(Sze||(Sze={}));function v8t(s){let t=N.useContext(F0e);return t||qu(!1),t}function b8t(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=In(),d=Jl(),u=B0e(s,{relative:l});return N.useCallback(h=>{if(c8t(h,n)){h.preventDefault();let p=r!==void 0?r:Jpe(d)===Jpe(u);c(s,{replace:p,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function yl(s){let t=N.useRef(h4e(s)),n=N.useRef(!1),r=Jl(),a=N.useMemo(()=>d8t(r.search,n.current?null:t.current),[r.search]),i=In(),l=N.useCallback((o,c)=>{const d=h4e(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function _8t(s,t){t===void 0&&(t={});let n=N.useContext(p8t);n==null&&qu(!1);let{basename:r}=v8t(m4e.useViewTransitionState),a=B0e(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=b8(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=b8(n.nextLocation.pathname,r)||n.nextLocation.pathname;return efe(a.pathname,l)!=null||efe(a.pathname,i)!=null}var w8t=typeof Element<"u",j8t=typeof Map=="function",N8t=typeof Set=="function",k8t=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function Eme(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(!Eme(s[r],t[r]))return!1;return!0}var i;if(j8t&&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(!Eme(r.value[1],t.get(r.value[0])))return!1;return!0}if(N8t&&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(k8t&&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(w8t&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!Eme(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var S8t=function(t,n){try{return Eme(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 C8t=jl(S8t);var T8t=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}},E8t=T8t;const Cze=jl(E8t);var A8t=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))(Uat||{}),Gwe={link:{rel:["amphtml","canonical","alternate"]},script:{type:["application/ld+json"]},meta:{charset:"",name:["generator","robots","description"],property:["og:type","og:title","og:url","og:image","og:image:alt","og:description","twitter:url","twitter:title","twitter:description","twitter:image","twitter:image:alt","twitter:card","twitter:site"]}},Tze=Object.values(Uat),IAe={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},I8t=Object.entries(IAe).reduce((s,[t,n])=>(s[n]=t,s),{}),cb="data-rh",AL={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},ML=(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},P8t=s=>{let t=ML(s,"title");const n=ML(s,AL.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=ML(s,AL.DEFAULT_TITLE);return t||r||void 0},L8t=s=>ML(s,AL.ON_CHANGE_CLIENT_STATE)||(()=>{}),Wwe=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),D8t=(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),rF=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&R8t(`Helmet: ${s} should be of type "Array". Instead found type "${typeof a[s]}"`),!1)).map(a=>a[s]).reverse().reduce((a,i)=>{const l={};i.filter(c=>{let d;const u=Object.keys(c);for(let p=0;pa.push(c));const o=Object.keys(l);for(let c=0;c{if(Array.isArray(s)&&s.length){for(let n=0;n({baseTag:D8t(["href"],s),bodyAttributes:Wwe("bodyAttributes",s),defer:ML(s,AL.DEFER),encode:ML(s,AL.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:Wwe("htmlAttributes",s),linkTags:rF("link",["rel","href"],s),metaTags:rF("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:rF("noscript",["innerHTML"],s),onChangeClientState:L8t(s),scriptTags:rF("script",["src","innerHTML"],s),styleTags:rF("style",["cssText"],s),title:P8t(s),titleAttributes:Wwe("titleAttributes",s),prioritizeSeoTags:O8t(s,AL.PRIORITIZE_SEO_TAGS)}),qat=s=>Array.isArray(s)?s.join(""):s,z8t=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(z8t(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},Eze=(s,t)=>({...s,[t]:void 0}),B8t=["noscript","script","style"],p4e=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),Vat=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),$8t=(s,t,n,r)=>{const a=Vat(n),i=qat(t);return a?`<${s} ${cb}="true" ${a}>${p4e(i,r)}`:`<${s} ${cb}="true">${p4e(i,r)}`},U8t=(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}="${p4e(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=B8t.indexOf(s)===-1;return`${r}<${s} ${cb}="true" ${l}${c?"/>":`>${o}`}`},""),Hat=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=IAe[r];return n[a||r]=s[r],n},t),q8t=(s,t,n)=>{const r={key:t,[cb]:!0},a=Hat(n,r);return[Nt.createElement("title",a,t)]},Ame=(s,t)=>t.map((n,r)=>{const a={key:r,[cb]:!0};return Object.keys(n).forEach(i=>{const o=IAe[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),Nt.createElement(s,a)}),gv=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>q8t(s,t.title,t.titleAttributes),toString:()=>$8t(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>Hat(t),toString:()=>Vat(t)};default:return{toComponent:()=>Ame(s,t),toString:()=>U8t(s,t,n)}}},V8t=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=Kwe(s,Gwe.meta),i=Kwe(t,Gwe.link),l=Kwe(n,Gwe.script);return{priorityMethods:{toComponent:()=>[...Ame("meta",a.priority),...Ame("link",i.priority),...Ame("script",l.priority)],toString:()=>`${gv("meta",a.priority,r)} ${gv("link",i.priority,r)} ${gv("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},H8t=s=>{const{baseTag:t,bodyAttributes:n,encode:r=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:u,metaTags:h,scriptTags:p}=s,f={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:f,linkTags:u,metaTags:h,scriptTags:p}=V8t(s)),{priority:f,base:gv("base",t,r),bodyAttributes:gv("bodyAttributes",n,r),htmlAttributes:gv("htmlAttributes",a,r),link:gv("link",u,r),meta:gv("meta",h,r),noscript:gv("noscript",i,r),script:gv("script",p,r),style:gv("style",l,r),title:gv("title",{title:o,titleAttributes:c},r)}},f4e=H8t,GV=[],Gat=!!(typeof window<"u"&&window.document&&window.document.createElement),x4e=class{constructor(s,t){Pa(this,"instances",[]);Pa(this,"canUseDOM",Gat);Pa(this,"context");Pa(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?GV:this.instances,add:s=>{(this.canUseDOM?GV:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?GV:this.instances).indexOf(s);(this.canUseDOM?GV:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=f4e({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},G8t={},Wat=Nt.createContext(G8t),yA,Kat=(yA=class extends N.Component{constructor(n){super(n);Pa(this,"helmetData");this.helmetData=new x4e(this.props.context||{},yA.canUseDOM)}render(){return Nt.createElement(Wat.Provider,{value:this.helmetData.value},this.props.children)}},Pa(yA,"canUseDOM",Gat),yA),mI=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${cb}]`),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(cb,"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}},g4e=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(cb),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(cb):n.getAttribute(cb)!==l.join(",")&&n.setAttribute(cb,l.join(","))},W8t=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=qat(s)),g4e("title",t)},Aze=(s,t)=>{const{baseTag:n,bodyAttributes:r,htmlAttributes:a,linkTags:i,metaTags:l,noscriptTags:o,onChangeClientState:c,scriptTags:d,styleTags:u,title:h,titleAttributes:p}=s;g4e("body",r),g4e("html",a),W8t(h,p);const f={baseTag:mI("base",n),linkTags:mI("link",i),metaTags:mI("meta",l),noscriptTags:mI("noscript",o),scriptTags:mI("script",d),styleTags:mI("style",u)},g={},b={};Object.keys(f).forEach(v=>{const{newTags:j,oldTags:_}=f[v];j.length&&(g[v]=j),_.length&&(b[v]=f[v].oldTags)}),t&&t(),c(s,g,b)},aF=null,K8t=s=>{aF&&cancelAnimationFrame(aF),s.defer?aF=requestAnimationFrame(()=>{Aze(s,()=>{aF=null})}):(Aze(s),aF=null)},Y8t=K8t,Mze=class extends N.Component{constructor(){super(...arguments);Pa(this,"rendered",!1)}shouldComponentUpdate(t){return!M8t(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=F8t(t.get().map(i=>{const l={...i.props};return delete l.context,l}));Kat.canUseDOM?Y8t(a):f4e&&(r=f4e(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}},Hke,Yo=(Hke=class extends N.Component{shouldComponentUpdate(s){return!C8t(Eze(this.props,"helmetData"),Eze(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 Cze(Tze.some(n=>s.type===n),typeof s.type=="function"?"You may be attempting to nest components within each other, which is not allowed. Refer to our API for more information.":`Only elements types ${Tze.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),Cze(!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 Nt.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[I8t[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 x4e)){const a=r;r=new x4e(a.context,!0),delete n.helmetData}return r?Nt.createElement(Mze,{...n,context:r.value}):Nt.createElement(Wat.Consumer,null,a=>Nt.createElement(Mze,{...n,context:a}))}},Pa(Hke,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),Hke);const Z8t=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>vi(async()=>{const{default:r}=await Promise.resolve().then(()=>BD);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class PAe extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class Q8t extends PAe{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class X8t extends PAe{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class J8t extends PAe{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var y4e;(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"})(y4e||(y4e={}));var eDt=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 tDt{constructor(t,{headers:n={},customFetch:r,region:a=y4e.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=Z8t(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return eDt(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 Q8t(g)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new X8t(u);if(!u.ok)throw new J8t(u);let p=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return p==="application/json"?f=yield u.json():p==="application/octet-stream"?f=yield u.blob():p==="text/event-stream"?f=u:p==="multipart/form-data"?f=yield u.formData():f=yield u.text(),{data:f,error:null}}catch(a){return{data:null,error:a}}})}}var Dg={},LAe={},$0e={},W$={},U0e={},q0e={},sDt=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")},_8=sDt();const nDt=_8.fetch,Yat=_8.fetch.bind(_8),Zat=_8.Headers,rDt=_8.Request,aDt=_8.Response,BD=Object.freeze(Object.defineProperty({__proto__:null,Headers:Zat,Request:rDt,Response:aDt,default:Yat,fetch:nDt},Symbol.toStringTag,{value:"Module"})),iDt=PTt(BD);var V0e={};Object.defineProperty(V0e,"__esModule",{value:!0});let oDt=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};V0e.default=oDt;var Qat=Ih&&Ih.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(q0e,"__esModule",{value:!0});const lDt=Qat(iDt),cDt=Qat(V0e);let dDt=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=lDt.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,n){return this.headers=Object.assign({},this.headers),this.headers[t]=n,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let a=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var l,o,c;let d=null,u=null,h=null,p=i.status,f=i.statusText;if(i.ok){if(this.method!=="HEAD"){const j=await i.text();j===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=j:u=JSON.parse(j))}const b=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),v=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");b&&v&&v.length>1&&(h=parseInt(v[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(d={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,p=406,f="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const b=await i.text();try{d=JSON.parse(b),Array.isArray(d)&&i.status===404&&(u=[],d=null,p=200,f="OK")}catch{i.status===404&&b===""?(p=204,f="No Content"):d={message:b}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,p=200,f="OK"),d&&this.shouldThrowOnError)throw new cDt.default(d)}return{error:d,data:u,count:h,status:p,statusText:f}});return this.shouldThrowOnError||(a=a.catch(i=>{var l,o,c;return{error:{message:`${(l=i==null?void 0:i.name)!==null&&l!==void 0?l:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(o=i==null?void 0:i.stack)!==null&&o!==void 0?o:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),a.then(t,n)}returns(){return this}overrideTypes(){return this}};q0e.default=dDt;var uDt=Ih&&Ih.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(U0e,"__esModule",{value:!0});const hDt=uDt(q0e);let mDt=class extends hDt.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}};U0e.default=mDt;var pDt=Ih&&Ih.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(W$,"__esModule",{value:!0});const fDt=pDt(U0e);let xDt=class extends fDt.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}};W$.default=xDt;var gDt=Ih&&Ih.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($0e,"__esModule",{value:!0});const iF=gDt(W$);let yDt=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 iF.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 iF.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 iF.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 iF.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 iF.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};$0e.default=yDt;var H0e={},G0e={};Object.defineProperty(G0e,"__esModule",{value:!0});G0e.version=void 0;G0e.version="0.0.0-automated";Object.defineProperty(H0e,"__esModule",{value:!0});H0e.DEFAULT_HEADERS=void 0;const vDt=G0e;H0e.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${vDt.version}`};var Xat=Ih&&Ih.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(LAe,"__esModule",{value:!0});const bDt=Xat($0e),_Dt=Xat(W$),wDt=H0e;let jDt=class Jat{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},wDt.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new bDt.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new Jat(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 _Dt.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};LAe.default=jDt;var $D=Ih&&Ih.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Dg,"__esModule",{value:!0});Dg.PostgrestError=Dg.PostgrestBuilder=Dg.PostgrestTransformBuilder=Dg.PostgrestFilterBuilder=Dg.PostgrestQueryBuilder=Dg.PostgrestClient=void 0;const eit=$D(LAe);Dg.PostgrestClient=eit.default;const tit=$D($0e);Dg.PostgrestQueryBuilder=tit.default;const sit=$D(W$);Dg.PostgrestFilterBuilder=sit.default;const nit=$D(U0e);Dg.PostgrestTransformBuilder=nit.default;const rit=$D(q0e);Dg.PostgrestBuilder=rit.default;const ait=$D(V0e);Dg.PostgrestError=ait.default;var NDt=Dg.default={PostgrestClient:eit.default,PostgrestQueryBuilder:tit.default,PostgrestFilterBuilder:sit.default,PostgrestTransformBuilder:nit.default,PostgrestBuilder:rit.default,PostgrestError:ait.default};const{PostgrestClient:kDt,PostgrestQueryBuilder:Ixn,PostgrestFilterBuilder:Pxn,PostgrestTransformBuilder:Lxn,PostgrestBuilder:Dxn,PostgrestError:Rxn}=NDt;let v4e;typeof window>"u"?v4e=require("ws"):v4e=window.WebSocket;const SDt=v4e,CDt="2.11.10",TDt={"X-Client-Info":`realtime-js/${CDt}`},EDt="1.0.0",iit=1e4,ADt=1e3;var IL;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(IL||(IL={}));var Bx;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(Bx||(Bx={}));var Z1;(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"})(Z1||(Z1={}));var b4e;(function(s){s.websocket="websocket"})(b4e||(b4e={}));var BE;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(BE||(BE={}));class MDt{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 oit{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 fd;(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"})(fd||(fd={}));const Ize=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=IDt(l,s,t,a),i),{})},IDt=(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)?lit(i,l):_4e(l)},lit=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return RDt(t,n)}switch(s){case fd.bool:return PDt(t);case fd.float4:case fd.float8:case fd.int2:case fd.int4:case fd.int8:case fd.numeric:case fd.oid:return LDt(t);case fd.json:case fd.jsonb:return DDt(t);case fd.timestamp:return ODt(t);case fd.abstime:case fd.date:case fd.daterange:case fd.int4range:case fd.int8range:case fd.money:case fd.reltime:case fd.text:case fd.time:case fd.timestamptz:case fd.timetz:case fd.tsrange:case fd.tstzrange:return _4e(t);default:return _4e(t)}},_4e=s=>s,PDt=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},LDt=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},DDt=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},RDt=(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=>lit(t,o))}return s},ODt=s=>typeof s=="string"?s.replace(" ","T"):s,cit=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class Ywe{constructor(t,n,r={},a=iit){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 Pze;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Pze||(Pze={}));class G9{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=G9.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=G9.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=G9.syncDiff(this.state,a,i,l),o())}),this.onJoin((a,i,l)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:l})}),this.onLeave((a,i,l)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:l})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,a){const i=this.cloneDeep(t),l=this.transformState(n),o={},c={};return this.map(i,(d,u)=>{l[d]||(c[d]=u)}),this.map(l,(d,u)=>{const h=i[d];if(h){const p=u.map(v=>v.presence_ref),f=h.map(v=>v.presence_ref),g=u.filter(v=>f.indexOf(v.presence_ref)<0),b=h.filter(v=>p.indexOf(v.presence_ref)<0);g.length>0&&(o[d]=g),b.length>0&&(c[d]=b)}else o[d]=u}),this.syncDiff(i,{joins:o,leaves:c},r,a)}static syncDiff(t,n,r,a){const{joins:i,leaves:l}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const u=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),u.length>0){const h=t[o].map(f=>f.presence_ref),p=u.filter(f=>h.indexOf(f.presence_ref)<0);t[o].unshift(...p)}r(o,u,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const u=c.map(h=>h.presence_ref);d=d.filter(h=>u.indexOf(h.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const a=t[r];return"metas"in a?n[r]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=a,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Lze;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Lze||(Lze={}));var Dze;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(Dze||(Dze={}));var w2;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(w2||(w2={}));class DAe{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=Bx.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 Ywe(this,Z1.join,this.params,this.timeout),this.rejoinTimer=new oit(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Bx.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=Bx.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Bx.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Bx.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Z1.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new G9(this),this.broadcastEndpointURL=cit(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(w2.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(w2.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(w2.SUBSCRIBED);return}else{const p=this.bindings.postgres_changes,f=(h=p==null?void 0:p.length)!==null&&h!==void 0?h:0,g=[];for(let b=0;b{this.state=Bx.errored,t==null||t(w2.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(w2.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=Bx.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Z1.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new Ywe(this,Z1.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 Ywe(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}=Z1;if(r&&[o,c,d,u].indexOf(l)>=0&&r!==this._joinRef())return;let p=this._onMessage(l,n,r);if(n&&!p)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(l)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(f=>{var g,b,v;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((v=(b=f.filter)===null||b===void 0?void 0:b.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===l}).map(f=>f.callback(p,r)):(i=this.bindings[l])===null||i===void 0||i.filter(f=>{var g,b,v,j,_,S;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in f){const A=f.id,T=(g=f.filter)===null||g===void 0?void 0:g.event;return A&&((b=n.ids)===null||b===void 0?void 0:b.includes(A))&&(T==="*"||(T==null?void 0:T.toLocaleLowerCase())===((v=n.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{const A=(_=(j=f==null?void 0:f.filter)===null||j===void 0?void 0:j.event)===null||_===void 0?void 0:_.toLocaleLowerCase();return A==="*"||A===((S=n==null?void 0:n.event)===null||S===void 0?void 0:S.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===l}).map(f=>{if(typeof p=="object"&&"ids"in p){const g=p.data,{schema:b,table:v,commit_timestamp:j,type:_,errors:S}=g;p=Object.assign(Object.assign({},{schema:b,table:v,commit_timestamp:j,eventType:_,new:{},old:{},errors:S}),this._getPayloadRecords(g))}f.callback(p,r)})}_isClosed(){return this.state===Bx.closed}_isJoined(){return this.state===Bx.joined}_isJoining(){return this.state===Bx.joining}_isLeaving(){return this.state===Bx.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const a=t.toLocaleLowerCase(),i={type:a,filter:n,callback:r};return this.bindings[a]?this.bindings[a].push(i):this.bindings[a]=[i],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(a=>{var i;return!(((i=a.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&DAe.isEqual(a.filter,n))}),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(Z1.close,{},t)}_onError(t){this._on(Z1.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Bx.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=Ize(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=Ize(t.columns,t.old_record)),n}}const Rze=()=>{},FDt=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class zDt{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=TDt,this.params={},this.timeout=iit,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Rze,this.ref=0,this.logger=Rze,this.conn=null,this.sendBuffer=[],this.serializer=new MDt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>vi(async()=>{const{default:c}=await Promise.resolve().then(()=>BD);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${b4e.websocket}`,this.httpEndpoint=cit(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 oit(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=SDt),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 BDt(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:EDt}))}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 IL.connecting:return BE.Connecting;case IL.open:return BE.Open;case IL.closing:return BE.Closing;default:return BE.Closed}}isConnected(){return this.connectionState()===BE.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new DAe(`realtime:${t}`,n,this);return this.channels.push(i),i}}push(t){const{topic:n,event:r,payload:a,ref:i}=t,l=()=>{this.encode(t,o=>{var c;(c=this.conn)===null||c===void 0||c.send(o)})};this.log("push",`${n} ${r} (${i})`,a),this.isConnected()?l():this.sendBuffer.push(l)}async setAuth(t=null){let n=t||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(r=>{n&&r.updateJoinPayload({access_token:n,version:this.headers&&this.headers["X-Client-Info"]}),r.joinedOnce&&r._isJoined()&&r._push(Z1.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(ADt,"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(Z1.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([FDt],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class BDt{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=IL.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class RAe extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function vp(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class $Dt extends RAe{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class w4e extends RAe{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var UDt=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 dit=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>vi(async()=>{const{default:r}=await Promise.resolve().then(()=>BD);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},qDt=()=>UDt(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield vi(()=>Promise.resolve().then(()=>BD),void 0)).Response:Response}),j4e=s=>{if(Array.isArray(s))return s.map(n=>j4e(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]=j4e(r)}),t};var VM=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 Zwe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),VDt=(s,t,n)=>VM(void 0,void 0,void 0,function*(){const r=yield qDt();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new $Dt(Zwe(a),s.status||500))}).catch(a=>{t(new w4e(Zwe(a),a))}):t(new w4e(Zwe(s),s))}),HDt=(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 K$(s,t,n,r,a,i){return VM(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,HDt(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=>VDt(c,o,r))})})}function rfe(s,t,n,r){return VM(this,void 0,void 0,function*(){return K$(s,"GET",t,n,r)})}function Qk(s,t,n,r,a){return VM(this,void 0,void 0,function*(){return K$(s,"POST",t,r,a,n)})}function GDt(s,t,n,r,a){return VM(this,void 0,void 0,function*(){return K$(s,"PUT",t,r,a,n)})}function WDt(s,t,n,r){return VM(this,void 0,void 0,function*(){return K$(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function uit(s,t,n,r,a){return VM(this,void 0,void 0,function*(){return K$(s,"DELETE",t,r,a,n)})}var kg=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 KDt={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Oze={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class YDt{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=dit(a)}uploadOrUpdate(t,n,r,a){return kg(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},Oze),a);let o=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(l.upsert)});const c=l.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=r,o["cache-control"]=`max-age=${l.cacheControl}`,o["content-type"]=l.contentType,c&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),a!=null&&a.headers&&(o=Object.assign(Object.assign({},o),a.headers));const d=this._removeEmptyFolders(n),u=this._getFinalPath(d),h=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:t,body:i,headers:o},l!=null&&l.duplex?{duplex:l.duplex}:{})),p=yield h.json();return h.ok?{data:{path:d,id:p.Id,fullPath:p.Key},error:null}:{data:null,error:p}}catch(i){if(vp(i))return{data:null,error:i};throw i}})}upload(t,n,r){return kg(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return kg(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:Oze.upsert},a),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",d.cacheControl)):(c=r,u["cache-control"]=`max-age=${d.cacheControl}`,u["content-type"]=d.contentType);const h=yield this.fetch(o.toString(),{method:"PUT",body:c,headers:u}),p=yield h.json();return h.ok?{data:{path:i,fullPath:p.Key},error:null}:{data:null,error:p}}catch(c){if(vp(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return kg(this,void 0,void 0,function*(){try{let r=this._getFinalPath(t);const a=Object.assign({},this.headers);n!=null&&n.upsert&&(a["x-upsert"]="true");const i=yield Qk(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:a}),l=new URL(this.url+i.url),o=l.searchParams.get("token");if(!o)throw new RAe("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(vp(r))return{data:null,error:r};throw r}})}update(t,n,r){return kg(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return kg(this,void 0,void 0,function*(){try{return{data:yield Qk(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers}),error:null}}catch(a){if(vp(a))return{data:null,error:a};throw a}})}copy(t,n,r){return kg(this,void 0,void 0,function*(){try{return{data:{path:(yield Qk(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers})).Key},error:null}}catch(a){if(vp(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return kg(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield Qk(this.fetch,`${this.url}/object/sign/${a}`,Object.assign({expiresIn:n},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const l=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${l}`)},{data:i,error:null}}catch(a){if(vp(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return kg(this,void 0,void 0,function*(){try{const a=yield Qk(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:n,paths:t},{headers:this.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:a.map(l=>Object.assign(Object.assign({},l),{signedUrl:l.signedURL?encodeURI(`${this.url}${l.signedURL}${i}`):null})),error:null}}catch(a){if(vp(a))return{data:null,error:a};throw a}})}download(t,n){return kg(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 rfe(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(vp(o))return{data:null,error:o};throw o}})}info(t){return kg(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield rfe(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:j4e(r),error:null}}catch(r){if(vp(r))return{data:null,error:r};throw r}})}exists(t){return kg(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield WDt(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(vp(r)&&r instanceof w4e){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 kg(this,void 0,void 0,function*(){try{return{data:yield uit(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(vp(n))return{data:null,error:n};throw n}})}list(t,n,r){return kg(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},KDt),n),{prefix:t||""});return{data:yield Qk(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(vp(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 ZDt="2.7.1",QDt={"X-Client-Info":`storage-js/${ZDt}`};var pI=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 XDt{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},QDt),n),this.fetch=dit(r)}listBuckets(){return pI(this,void 0,void 0,function*(){try{return{data:yield rfe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(vp(t))return{data:null,error:t};throw t}})}getBucket(t){return pI(this,void 0,void 0,function*(){try{return{data:yield rfe(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(vp(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return pI(this,void 0,void 0,function*(){try{return{data:yield Qk(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(vp(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return pI(this,void 0,void 0,function*(){try{return{data:yield GDt(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(vp(r))return{data:null,error:r};throw r}})}emptyBucket(t){return pI(this,void 0,void 0,function*(){try{return{data:yield Qk(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(vp(n))return{data:null,error:n};throw n}})}deleteBucket(t){return pI(this,void 0,void 0,function*(){try{return{data:yield uit(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(vp(n))return{data:null,error:n};throw n}})}}class JDt extends XDt{constructor(t,n={},r){super(t,n,r)}from(t){return new YDt(this.url,this.headers,t,this.fetch)}}const eRt="2.49.10";let h7="";typeof Deno<"u"?h7="deno":typeof document<"u"?h7="web":typeof navigator<"u"&&navigator.product==="ReactNative"?h7="react-native":h7="node";const tRt={"X-Client-Info":`supabase-js-${h7}/${eRt}`},sRt={headers:tRt},nRt={schema:"public"},rRt={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},aRt={};var iRt=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 oRt=s=>{let t;return s?t=s:typeof fetch>"u"?t=Yat:t=fetch,(...n)=>t(...n)},lRt=()=>typeof Headers>"u"?Zat:Headers,cRt=(s,t,n)=>{const r=oRt(n),a=lRt();return(i,l)=>iRt(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 dRt=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 uRt(s){return s.endsWith("/")?s:s+"/"}function hRt(s,t){var n,r;const{db:a,auth:i,realtime:l,global:o}=s,{db:c,auth:d,realtime:u,global:h}=t,p={db:Object.assign(Object.assign({},c),a),auth:Object.assign(Object.assign({},d),i),realtime:Object.assign(Object.assign({},u),l),global:Object.assign(Object.assign(Object.assign({},h),o),{headers:Object.assign(Object.assign({},(n=h==null?void 0:h.headers)!==null&&n!==void 0?n:{}),(r=o==null?void 0:o.headers)!==null&&r!==void 0?r:{})}),accessToken:()=>dRt(this,void 0,void 0,function*(){return""})};return s.accessToken?p.accessToken=s.accessToken:delete p.accessToken,p}const hit="2.69.1",aP=30*1e3,N4e=3,Qwe=N4e*aP,mRt="http://localhost:9999",pRt="supabase.auth.token",fRt={"X-Client-Info":`gotrue-js/${hit}`},k4e="X-Supabase-Api-Version",mit={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},xRt=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,gRt=6e5;class OAe extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function qo(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class yRt extends OAe{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function vRt(s){return qo(s)&&s.name==="AuthApiError"}class pit extends OAe{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class W4 extends OAe{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class Fk extends W4{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function bRt(s){return qo(s)&&s.name==="AuthSessionMissingError"}class Xwe extends W4{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class WV extends W4{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class KV extends W4{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 _Rt(s){return qo(s)&&s.name==="AuthImplicitGrantRedirectError"}class Fze extends W4{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class S4e extends W4{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function Jwe(s){return qo(s)&&s.name==="AuthRetryableFetchError"}class zze extends W4{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class W9 extends W4{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const Bze="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),$ze=` \r=`.split(""),wRt=(()=>{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 Uze(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{kRt(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 NRt(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}jRt(r,t)}}function kRt(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 SRt(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function TRt(s){return Math.round(Date.now()/1e3)+s}function ERt(){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 R_=()=>typeof window<"u"&&typeof document<"u",c3={tested:!1,writable:!1},K9=()=>{if(!R_())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(c3.tested)return c3.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),c3.tested=!0,c3.writable=!0}catch{c3.tested=!0,c3.writable=!1}return c3.writable};function ARt(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 xit=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>vi(async()=>{const{default:r}=await Promise.resolve().then(()=>BD);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},MRt=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",git=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},YV=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},ZV=async(s,t)=>{await s.removeItem(t)};class W0e{constructor(){this.promise=new W0e.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}W0e.promiseConstructor=Promise;function eje(s){const t=s.split(".");if(t.length!==3)throw new W9("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function PRt(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 LRt(s){return("0"+s.toString(16)).substr(-2)}function DRt(){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,LRt).join("")}async function RRt(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 ORt(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 RRt(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function fI(s,t,n=!1){const r=DRt();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await git(s,`${t}-code-verifier`,a);const i=await ORt(r);return[i,r===i?"plain":"s256"]}const FRt=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function zRt(s){const t=s.headers.get(k4e);if(!t||!t.match(FRt))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function BRt(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 $Rt(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 URt=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);as.msg||s.message||s.error_description||s.error||JSON.stringify(s),qRt=[502,503,504];async function qze(s){var t;if(!MRt(s))throw new S4e(AE(s),0);if(qRt.includes(s.status))throw new S4e(AE(s),s.status);let n;try{n=await s.json()}catch(i){throw new pit(AE(i),i)}let r;const a=zRt(s);if(a&&a.getTime()>=mit["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 zze(AE(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new Fk}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 zze(AE(n),s.status,n.weak_password.reasons);throw new yRt(AE(n),s.status||500,r)}const VRt=(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 wl(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[k4e]||(i[k4e]=mit["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 HRt(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 HRt(s,t,n,r,a,i){const l=VRt(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new S4e(AE(c),0)}if(o.ok||await qze(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await qze(c)}}function zk(s){var t;let n=null;YRt(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=TRt(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function Vze(s){const t=zk(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 hS(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function GRt(s){return{data:s,error:null}}function WRt(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=URt(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 KRt(s){return s}function YRt(s){return s.access_token&&s.refresh_token&&s.expires_in}var ZRt=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);a0&&(f.forEach(g=>{const b=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(g.split(";")[1].split("=")[1]);d[`${v}Page`]=b}),d.total=parseInt(p)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(qo(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await wl(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:hS})}catch(n){if(qo(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await wl(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:hS})}catch(r){if(qo(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await wl(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:hS})}catch(r){if(qo(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await wl(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(qo(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await wl(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(qo(n))return{data:null,error:n};throw n}}}const XRt={getItem:s=>K9()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{K9()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{K9()&&globalThis.localStorage.removeItem(s)}};function Hze(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function JRt(){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 xI={debug:!!(globalThis&&K9()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class yit extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class eOt extends yit{}async function tOt(s,t,n){xI.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),xI.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){xI.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{xI.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw xI.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new eOt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(xI.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()}}))}JRt();const sOt={url:mRt,storageKey:pRt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:fRt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Gze(s,t,n){return await n()}class lB{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=lB.nextInstanceID,lB.nextInstanceID+=1,this.instanceID>0&&R_()&&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({},sOt),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 QRt({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=xit(a.fetch),this.lock=a.lock||Gze,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:R_()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=tOt:this.lock=Gze,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:K9()?this.storage=XRt:(this.memoryStorage={},this.storage=Hze(this.memoryStorage)):(this.memoryStorage={},this.storage=Hze(this.memoryStorage)),R_()&&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} (${hit}) ${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=ARt(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),R_()&&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),_Rt(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 qo(n)?{error:n}:{error:new pit("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await wl(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:zk}),{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(qo(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var n,r,a;try{let i;if("email"in t){const{email:u,password:h,options:p}=t;let f=null,g=null;this.flowType==="pkce"&&([f,g]=await fI(this.storage,this.storageKey)),i=await wl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p==null?void 0:p.emailRedirectTo,body:{email:u,password:h,data:(n=p==null?void 0:p.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken},code_challenge:f,code_challenge_method:g},xform:zk})}else if("phone"in t){const{phone:u,password:h,options:p}=t;i=await wl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(r=p==null?void 0:p.data)!==null&&r!==void 0?r:{},channel:(a=p==null?void 0:p.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken}},xform:zk})}else throw new WV("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(qo(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 wl(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:Vze})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await wl(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:Vze})}else throw new WV("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 Xwe}:(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(qo(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 YV(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await wl(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:zk});if(await ZV(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Xwe}:(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(qo(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 wl(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:zk}),{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 Xwe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(qo(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 fI(this.storage,this.storageKey));const{error:h}=await wl(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 wl(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 WV("You must provide either an email or phone number.")}catch(o){if(qo(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 wl(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:zk});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(qo(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 fI(this.storage,this.storageKey)),await wl(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:GRt})}catch(i){if(qo(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 Fk;const{error:a}=await wl(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(qo(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 wl(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 wl(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 WV("You must provide either an email or phone number and a type")}catch(n){if(qo(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 YV(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 wl(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:hS}):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 Fk}:await wl(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:hS})})}catch(n){if(qo(n))return bRt(n)&&(await this._removeSession(),await ZV(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 Fk;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await fI(this.storage,this.storageKey));const{data:d,error:u}=await wl(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:hS});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(qo(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 Fk;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=eje(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(qo(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 Fk;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(qo(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!R_())throw new KV("No browser detected.");if(t.error||t.error_description||t.error_code)throw new KV(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 Fze("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new KV("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 Fze("No code detected.");const{data:_,error:S}=await this._exchangeCodeForSession(t.code);if(S)throw S;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:_.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 KV("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(o);let p=u+h;c&&(p=parseInt(c));const f=p-u;f*1e3<=aP&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const g=p-h;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,p,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,p,u);const{data:b,error:v}=await this._getUser(i);if(v)throw v;const j={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:p,refresh_token:l,token_type:d,user:b.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:j,redirectType:t.type},error:null}}catch(r){if(qo(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 YV(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&&!(vRt(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await ZV(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=ERt(),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 fI(this.storage,this.storageKey,!0));try{return await wl(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(qo(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(qo(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:a}=await this._useSession(async i=>{var l,o,c,d,u;const{data:h,error:p}=i;if(p)throw p;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(l=t.options)===null||l===void 0?void 0:l.redirectTo,scopes:(o=t.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=t.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await wl(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(d=h.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return R_()&&!(!((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(qo(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 wl(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(qo(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 PRt(async a=>(a>0&&await IRt(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await wl(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:zk})),(a,i)=>{const l=200*Math.pow(2,a);return i&&Jwe(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(),aP);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)/aP);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${aP}ms, refresh threshold is ${N4e} ticks`),a<=N4e&&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 yit)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!R_()||!(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 fI(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 wl(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(qo(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 wl(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(qo(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 wl(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(qo(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 wl(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(qo(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}=eje(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+gRt>Date.now()))return r;const{data:a,error:i}=await wl(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 W9("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new W9("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:f,error:g}=await this.getSession();if(g||!f.session)return{data:null,error:g};r=f.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=eje(r);if(BRt(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:i,header:a,signature:l},error:null}}const d=$Rt(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,CRt(`${o}.${c}`)))throw new W9("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(qo(r))return{data:null,error:r};throw r}}}lB.nextInstanceID=0;const nOt=lB;class rOt extends nOt{constructor(t){super(t)}}var aOt=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 iOt{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=uRt(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:nRt,realtime:aRt,auth:Object.assign(Object.assign({},rRt),{storageKey:d}),global:sRt},h=hRt(r??{},u);this.storageKey=(a=h.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(p,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=h.auth)!==null&&l!==void 0?l:{},this.headers,h.global.fetch),this.fetch=cRt(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 kDt(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new tDt(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new JDt(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 aOt(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 rOt({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 zDt(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 oOt=(s,t,n)=>new iOt(s,t,n),lOt="https://relzejiswnotikjgvjhz.supabase.co",cOt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",q=oOt(lOt,cOt,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),dOt=Object.freeze(Object.defineProperty({__proto__:null,supabase:q},Symbol.toStringTag,{value:"Module"})),vit=N.createContext(void 0),uOt=({children:s})=>{const[t,n]=N.useState(null),[r,a]=N.useState(null),[i,l]=N.useState(!0),[o,c]=N.useState(!0),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,g]=N.useState(!1),[b,v]=N.useState(null),[j,_]=N.useState([]),[S,A]=N.useState(null),T=N.useRef(null),D=N.useRef(!1),L=N.useRef(!1),M=In(),F=()=>{u(!1),p(!1),g(!1),v(null),_([]),A(null),T.current=null,D.current=!1},z=async Y=>{if(!(D.current&&T.current===Y)&&!L.current){L.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",Y);const[{data:ee,error:ne},{data:oe,error:pe},{data:ce,error:de}]=await Promise.all([q.rpc("has_role",{_user_id:Y,_role:"admin"}),q.rpc("has_role",{_user_id:Y,_role:"brokerage_manager"}),q.rpc("has_role",{_user_id:Y,_role:"coach"})]);if(ne||pe)console.error("Role RPC errors:",{isAdminError:ne,isBrokerError:pe,isCoachError:de}),u(!1),p(!1),g(!1);else{const _e=!!ee,Me=!!oe,Te=!!ce;console.log("RPC roles result:",{adminValue:_e,brokerValue:Me,coachValue:Te}),u(_e),p(Me),g(Te)}const{data:ie,error:ye}=await q.from("profiles").select("brokerage_id").eq("id",Y).single();if(v(!ye&&ie?ie.brokerage_id:null),oe){console.log("Fetching managed brokerages for user:",Y);const{data:_e,error:Me}=await q.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",Y);if(console.log("Managed brokerage assignments result:",{assignments:_e,assignmentsError:Me}),Me||!_e){console.error("Error fetching managed brokerage assignments:",Me),_([]);return}const Te=Array.from(new Set(_e.map(Ie=>Ie.brokerage_id).filter(Boolean)));if(Te.length===0){_([]);return}const{data:Ce,error:Ee}=await q.from("brokerages").select("id, name").in("id",Te);if(console.log("Managed brokerages details result:",{brokeragesData:Ce,brokeragesError:Ee}),Ee||!Ce){console.error("Error fetching managed brokerages details:",Ee),_([]);return}const De=Ce.map(Ie=>({id:Ie.id,name:Ie.name})).sort((Ie,Fe)=>Te.indexOf(Ie.id)-Te.indexOf(Fe.id));console.log("Parsed managed brokerages:",De),_(De),De.length>0&&A(Ie=>Ie??De[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),_([]);T.current=Y,D.current=!0}catch(ee){console.error("Unexpected error in checkRoles:",ee),F()}finally{L.current=!1,c(!1)}}};N.useEffect(()=>{let Y=!0,ee=!1;const ne=()=>{!Y||ee||(ee=!0,l(!1))},{data:{subscription:oe}}=q.auth.onAuthStateChange((de,ie)=>{console.log("Auth event:",de),Y&&(a(ie),n((ie==null?void 0:ie.user)??null),ne(),de==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{M("/profile?reset=true")},100)),ie!=null&&ie.user?(!D.current||T.current!==ie.user.id)&&setTimeout(()=>{z(ie.user.id)},0):(F(),c(!1)))}),pe=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),ne()},4e3);return(async()=>{try{const{data:{session:de}}=await q.auth.getSession();if(!Y)return;a(de),n((de==null?void 0:de.user)??null),de!=null&&de.user?await z(de.user.id):F()}catch(de){console.error("Error restoring auth session:",de),Y&&(a(null),n(null),F())}finally{ne()}})(),()=>{Y=!1,window.clearTimeout(pe),oe.unsubscribe()}},[]);const V=async(Y,ee)=>{const{error:ne}=await q.auth.signInWithPassword({email:Y,password:ee});if(ne)throw ae.error(ne.message),ne;ae.success("Welcome back!")},W=async(Y,ee,ne)=>{var ie;const oe=`${window.location.origin}/dashboard`,pe=localStorage.getItem("levelup_referral_code")||null,{data:ce,error:de}=await q.auth.signUp({email:Y,password:ee,options:{emailRedirectTo:oe,data:{name:ne,referred_by_code:pe}}});if(de)throw ae.error(de.message),de;if(pe&&((ie=ce.user)!=null&&ie.id))try{await q.from("profiles").update({referred_by_code:pe}).eq("id",ce.user.id),localStorage.removeItem("levelup_referral_code")}catch(ye){console.warn("Failed to attach referral code to profile",ye)}ae.success("Account created! Welcome to LevelUp."),M("/dashboard")},K=async()=>{try{const{data:{session:Y}}=await q.auth.getSession();if(Y){const{error:ee}=await q.auth.signOut();ee?ee.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",ee.message):(console.error("Sign out error:",ee),ae.error(ee.message)):ae.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),p(!1),v(null),_([]),A(null),M("/auth")}catch(Y){console.error("Unexpected sign out error:",Y),M("/auth")}};return e.jsx(vit.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:V,signUp:W,signOut:K,isAdmin:d,isBrokerageManager:h,isCoach:f,brokerageId:b,managedBrokerages:j,selectedBrokerageId:S,setSelectedBrokerageId:A},children:s})},gs=()=>{const s=N.useContext(vit);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},bit=N.createContext({onlineUsers:[],totalOnline:0}),hOt=async s=>{try{const{data:t}=await q.storage.from("avatars").list(`${s}`);if(t&&t.length>0){const{data:n}=q.storage.from("avatars").getPublicUrl(`${s}/${t[0].name}`);return n.publicUrl}}catch{}},mOt=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=gs(),[a,i]=N.useState([]),[l,o]=N.useState(null);N.useEffect(()=>{if(!t)return;let d=!1;q.auth.getSession().then(({data:h})=>{var f;const p=(f=h.session)==null?void 0:f.access_token;if(p)try{q.realtime.setAuth(p)}catch{}});const u=q.channel("app-presence-v2",{config:{presence:{key:t.id},broadcast:{self:!0}}});return u.on("presence",{event:"sync"},()=>{const h=u.presenceState(),p=[];Object.entries(h).forEach(([f,g])=>{if(g&&g.length>0){const b=g[0];p.push({id:f,name:b.name||"Unknown",avatarUrl:b.avatarUrl,brokerageId:b.brokerageId,onlineSince:b.onlineSince})}}),console.log("[Presence] sync, users:",p.length,p),i(p)}).on("presence",{event:"join"},({key:h,newPresences:p})=>{console.log("[Presence] join",h,p)}).on("presence",{event:"leave"},({key:h})=>{console.log("[Presence] leave",h)}).subscribe(async(h,p)=>{var f;if(console.log("[Presence] subscribe status:",h,p),h==="SUBSCRIBED"&&!d){const{data:g}=await q.from("profiles").select("name, brokerage_id").eq("id",t.id).maybeSingle(),b=await hOt(t.id),v=await u.track({name:(g==null?void 0:g.name)||((f=t.email)==null?void 0:f.split("@")[0])||"User",avatarUrl:b,brokerageId:g==null?void 0:g.brokerage_id,onlineSince:new Date().toISOString()});console.log("[Presence] track result:",v)}}),o(u),()=>{d=!0;try{u.untrack()}catch{}q.removeChannel(u)}},[t==null?void 0:t.id]);const c=a.filter(d=>d.id===(t==null?void 0:t.id)?!1:!!(r||n&&d.brokerageId===n||!n&&!d.brokerageId));return e.jsx(bit.Provider,{value:{onlineUsers:c,totalOnline:a.length},children:s})},_it=()=>N.useContext(bit),wit=N.createContext(void 0),d3="levelup_admin_session",Nk="levelup_impersonation",tje="levelup_impersonation_return",pOt=({children:s})=>{const[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(!1);N.useEffect(()=>{const d=sessionStorage.getItem(Nk);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(Nk)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)return ae.error("No active session found"),!1;const p={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(d3,JSON.stringify(p)),u&&sessionStorage.setItem(tje,u);const f=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({targetUserId:d})}),g=await f.json();if(!f.ok)throw new Error(g.error||"Failed to impersonate user");const b={id:g.targetUser.id,name:g.targetUser.name,email:g.targetUser.email};if(sessionStorage.setItem(Nk,JSON.stringify(b)),g.method==="session"){const{error:v}=await q.auth.setSession({access_token:g.access_token,refresh_token:g.refresh_token});if(v)throw console.error("Set session error:",v),sessionStorage.removeItem(d3),sessionStorage.removeItem(Nk),new Error("Failed to establish impersonation session")}else{const v=g.type||"recovery",{error:j}=await q.auth.verifyOtp({token_hash:g.token_hash,type:v});if(j)throw console.error("Verify OTP error:",j),sessionStorage.removeItem(d3),sessionStorage.removeItem(Nk),new Error("Failed to establish impersonation session")}return n(!0),a(b),ae.success(`Now viewing as ${b.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),ae.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(d3),sessionStorage.removeItem(Nk),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(d3);if(!d){await q.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await q.auth.signOut();const{error:h}=await q.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(d3),sessionStorage.removeItem(Nk),h){console.error("Failed to restore admin session:",h),ae.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),ae.success("Returned to your account");const p=sessionStorage.getItem(tje)||"/admin/members";sessionStorage.removeItem(tje),window.location.href=p}catch(d){console.error("Stop impersonation error:",d),ae.error("Failed to restore admin session"),sessionStorage.removeItem(d3),sessionStorage.removeItem(Nk),window.location.href="/auth"}finally{l(!1)}};return e.jsx(wit.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},K0e=()=>{const s=N.useContext(wit);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},w8=qM("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-full px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),B=N.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?uAe:"button";return e.jsx(l,{className:Et(w8({variant:t,size:n,className:s})),ref:i,...a})});B.displayName="Button";const fOt=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=K0e();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(Dl,{className:"h-5 w-5 flex-shrink-0"}),e.jsxs("span",{className:"font-medium text-sm md:text-base",children:[e.jsx("span",{className:"hidden sm:inline",children:"You are viewing as "}),e.jsx("strong",{children:t.name}),e.jsxs("span",{className:"hidden md:inline text-amber-800",children:[" (",t.email,")"]})]})]}),e.jsx(B,{size:"sm",variant:"secondary",onClick:n,disabled:r,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:r?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Fn,{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"})]})})]})})},jit=N.createContext(void 0),gI="levelup_acting_as",QV="levelup_acting_as_self",xOt=({children:s})=>{const{user:t}=gs(),[n,r]=N.useState(!1),[a,i]=N.useState([]),[l,o]=N.useState(null),[c,d]=N.useState({}),[u,h]=N.useState(!0),[p,f]=N.useState(()=>sessionStorage.getItem(QV)==="true");N.useEffect(()=>{if(!(t!=null&&t.id)){r(!1),i([]),o(null),d({}),h(!1);return}(async()=>{h(!0);try{const{data:S}=await q.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!S){r(!1),i([]),o(null),d({}),h(!1);return}r(!0);const{data:A,error:T}=await q.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(T||!A||A.length===0){i([]),h(!1);return}const D=A.map(F=>F.agent_id),{data:L}=await q.from("profiles").select("id, name, email, avatar_url").in("id",D),M=(L||[]).map(F=>({id:F.id,name:F.name||F.email||"Unknown",email:F.email||"",avatar_url:F.avatar_url}));if(i(M),sessionStorage.getItem(QV)==="true")f(!0),o(null),d({});else{const F=sessionStorage.getItem(gI);if(F){const z=M.find(V=>V.id===F);if(z){o(z);const V=A.find(W=>W.agent_id===F);d((V==null?void 0:V.permissions)||{})}else if(M.length>0){o(M[0]);const V=A.find(W=>W.agent_id===M[0].id);d((V==null?void 0:V.permissions)||{}),sessionStorage.setItem(gI,M[0].id)}}else if(M.length>0){o(M[0]);const z=A.find(V=>V.agent_id===M[0].id);d((z==null?void 0:z.permissions)||{}),sessionStorage.setItem(gI,M[0].id)}}}catch(S){console.error("Error loading assistant data:",S)}finally{h(!1)}})()},[t==null?void 0:t.id]);const g=_=>{o(_),f(!1),sessionStorage.removeItem(QV),_?(sessionStorage.setItem(gI,_.id),q.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",_.id).single().then(({data:S})=>{d((S==null?void 0:S.permissions)||{})})):(sessionStorage.removeItem(gI),d({}))},b=()=>{f(!0),o(null),d({}),sessionStorage.setItem(QV,"true"),sessionStorage.removeItem(gI)},v=_=>!n||p?!0:c[_]===!0,j=n&&l&&!p?l.id:(t==null?void 0:t.id)||null;return e.jsx(jit.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:g,effectiveUserId:j,permissions:c,hasPermission:v,isLoading:u,isActingAsSelf:p,setActingAsSelf:b},children:s})},Y0e=()=>{const s=N.useContext(jit);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},fa=()=>{const{effectiveUserId:s}=Y0e();return s};var Nit={exports:{}},kit={};/** * @license React * use-sync-external-store-shim.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var j8=N;function gOt(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var yOt=typeof Object.is=="function"?Object.is:gOt,vOt=j8.useState,bOt=j8.useEffect,_Ot=j8.useLayoutEffect,wOt=j8.useDebugValue;function jOt(s,t){var n=t(),r=vOt({inst:{value:n,getSnapshot:t}}),a=r[0].inst,i=r[1];return _Ot(function(){a.value=n,a.getSnapshot=t,sje(a)&&i({inst:a})},[s,n,t]),bOt(function(){return sje(a)&&i({inst:a}),s(function(){sje(a)&&i({inst:a})})},[s]),wOt(n),n}function sje(s){var t=s.getSnapshot;s=s.value;try{var n=t();return!yOt(s,n)}catch{return!0}}function NOt(s,t){return t()}var kOt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?NOt:jOt;kit.useSyncExternalStore=j8.useSyncExternalStore!==void 0?j8.useSyncExternalStore:kOt;Nit.exports=kit;var SOt=Nit.exports;function COt(){return SOt.useSyncExternalStore(TOt,()=>!0,()=>!1)}function TOt(){return()=>{}}var FAe="Avatar",[EOt,Oxn]=gu(FAe),[AOt,Sit]=EOt(FAe),Cit=N.forwardRef((s,t)=>{const{__scopeAvatar:n,...r}=s,[a,i]=N.useState("idle");return e.jsx(AOt,{scope:n,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(sa.span,{...r,ref:t})})});Cit.displayName=FAe;var Tit="AvatarImage",Eit=N.forwardRef((s,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:a=()=>{},...i}=s,l=Sit(Tit,n),o=MOt(r,i),c=dh(d=>{a(d),l.onImageLoadingStatusChange(d)});return fh(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(sa.img,{...i,ref:t,src:r}):null});Eit.displayName=Tit;var Ait="AvatarFallback",Mit=N.forwardRef((s,t)=>{const{__scopeAvatar:n,delayMs:r,...a}=s,i=Sit(Ait,n),[l,o]=N.useState(r===void 0);return N.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>o(!0),r);return()=>window.clearTimeout(c)}},[r]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(sa.span,{...a,ref:t}):null});Mit.displayName=Ait;function Wze(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function MOt(s,{referrerPolicy:t,crossOrigin:n}){const r=COt(),a=N.useRef(null),i=r?(a.current||(a.current=new window.Image),a.current):null,[l,o]=N.useState(()=>Wze(i,s));return fh(()=>{o(Wze(i,s))},[i,s]),fh(()=>{const c=h=>()=>{o(h)};if(!i)return;const d=c("loaded"),u=c("error");return i.addEventListener("load",d),i.addEventListener("error",u),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",u)}},[i,n,t]),l}var Iit=Cit,Pit=Eit,Lit=Mit;const aa=N.forwardRef(({className:s,...t},n)=>e.jsx(Iit,{ref:n,className:Et("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));aa.displayName=Iit.displayName;const ri=N.forwardRef(({className:s,...t},n)=>e.jsx(Pit,{ref:n,className:Et("aspect-square h-full w-full",s),...t}));ri.displayName=Pit.displayName;const ia=N.forwardRef(({className:s,...t},n)=>e.jsx(Lit,{ref:n,className:Et("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));ia.displayName=Lit.displayName;const IOt=qM("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 ze({className:s,variant:t,...n}){return e.jsx("div",{className:Et(IOt({variant:t}),s),...n})}var POt=N.createContext(void 0);function kN(s){const t=N.useContext(POt);return s||t||"ltr"}var nje=0;function Z0e(){N.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??Kze()),document.body.insertAdjacentElement("beforeend",s[1]??Kze()),nje++,()=>{nje===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),nje--}},[])}function Kze(){const s=document.createElement("span");return s.setAttribute("data-radix-focus-guard",""),s.tabIndex=0,s.style.outline="none",s.style.opacity="0",s.style.position="fixed",s.style.pointerEvents="none",s}var rje="focusScope.autoFocusOnMount",aje="focusScope.autoFocusOnUnmount",Yze={bubbles:!1,cancelable:!0},LOt="FocusScope",Y$=N.forwardRef((s,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=N.useState(null),d=dh(a),u=dh(i),h=N.useRef(null),p=Ti(t,b=>c(b)),f=N.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;N.useEffect(()=>{if(r){let b=function(S){if(f.paused||!o)return;const A=S.target;o.contains(A)?h.current=A:Bk(h.current,{select:!0})},v=function(S){if(f.paused||!o)return;const A=S.relatedTarget;A!==null&&(o.contains(A)||Bk(h.current,{select:!0}))},j=function(S){if(document.activeElement===document.body)for(const T of S)T.removedNodes.length>0&&Bk(o)};document.addEventListener("focusin",b),document.addEventListener("focusout",v);const _=new MutationObserver(j);return o&&_.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",v),_.disconnect()}}},[r,o,f.paused]),N.useEffect(()=>{if(o){Qze.add(f);const b=document.activeElement;if(!o.contains(b)){const j=new CustomEvent(rje,Yze);o.addEventListener(rje,d),o.dispatchEvent(j),j.defaultPrevented||(DOt(BOt(Dit(o)),{select:!0}),document.activeElement===b&&Bk(o))}return()=>{o.removeEventListener(rje,d),setTimeout(()=>{const j=new CustomEvent(aje,Yze);o.addEventListener(aje,u),o.dispatchEvent(j),j.defaultPrevented||Bk(b??document.body,{select:!0}),o.removeEventListener(aje,u),Qze.remove(f)},0)}}},[o,d,u,f]);const g=N.useCallback(b=>{if(!n&&!r||f.paused)return;const v=b.key==="Tab"&&!b.altKey&&!b.ctrlKey&&!b.metaKey,j=document.activeElement;if(v&&j){const _=b.currentTarget,[S,A]=ROt(_);S&&A?!b.shiftKey&&j===A?(b.preventDefault(),n&&Bk(S,{select:!0})):b.shiftKey&&j===S&&(b.preventDefault(),n&&Bk(A,{select:!0})):j===_&&b.preventDefault()}},[n,r,f.paused]);return e.jsx(sa.div,{tabIndex:-1,...l,ref:p,onKeyDown:g})});Y$.displayName=LOt;function DOt(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(Bk(r,{select:t}),document.activeElement!==n)return}function ROt(s){const t=Dit(s),n=Zze(t,s),r=Zze(t.reverse(),s);return[n,r]}function Dit(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Zze(s,t){for(const n of s)if(!OOt(n,{upTo:t}))return n}function OOt(s,{upTo:t}){if(getComputedStyle(s).visibility==="hidden")return!0;for(;s;){if(t!==void 0&&s===t)return!1;if(getComputedStyle(s).display==="none")return!0;s=s.parentElement}return!1}function FOt(s){return s instanceof HTMLInputElement&&"select"in s}function Bk(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&FOt(s)&&t&&s.select()}}var Qze=zOt();function zOt(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=Xze(s,t),s.unshift(t)},remove(t){var n;s=Xze(s,t),(n=s[0])==null||n.resume()}}}function Xze(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function BOt(s){return s.filter(t=>t.tagName!=="A")}var ije="rovingFocusGroup.onEntryFocus",$Ot={bubbles:!1,cancelable:!0},Z$="RovingFocusGroup",[C4e,Rit,UOt]=MD(Z$),[qOt,K4]=gu(Z$,[UOt]),[VOt,HOt]=qOt(Z$),Oit=N.forwardRef((s,t)=>e.jsx(C4e.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(C4e.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(GOt,{...s,ref:t})})}));Oit.displayName=Z$;var GOt=N.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:a=!1,dir:i,currentTabStopId:l,defaultCurrentTabStopId:o,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...h}=s,p=N.useRef(null),f=Ti(t,p),g=kN(i),[b,v]=mm({prop:l,defaultProp:o??null,onChange:c,caller:Z$}),[j,_]=N.useState(!1),S=dh(d),A=Rit(n),T=N.useRef(!1),[D,L]=N.useState(0);return N.useEffect(()=>{const M=p.current;if(M)return M.addEventListener(ije,S),()=>M.removeEventListener(ije,S)},[S]),e.jsx(VOt,{scope:n,orientation:r,dir:g,loop:a,currentTabStopId:b,onItemFocus:N.useCallback(M=>v(M),[v]),onItemShiftTab:N.useCallback(()=>_(!0),[]),onFocusableItemAdd:N.useCallback(()=>L(M=>M+1),[]),onFocusableItemRemove:N.useCallback(()=>L(M=>M-1),[]),children:e.jsx(sa.div,{tabIndex:j||D===0?-1:0,"data-orientation":r,...h,ref:f,style:{outline:"none",...s.style},onMouseDown:wr(s.onMouseDown,()=>{T.current=!0}),onFocus:wr(s.onFocus,M=>{const F=!T.current;if(M.target===M.currentTarget&&F&&!j){const z=new CustomEvent(ije,$Ot);if(M.currentTarget.dispatchEvent(z),!z.defaultPrevented){const V=A().filter(ne=>ne.focusable),W=V.find(ne=>ne.active),K=V.find(ne=>ne.id===b),ee=[W,K,...V].filter(Boolean).map(ne=>ne.ref.current);Bit(ee,u)}}T.current=!1}),onBlur:wr(s.onBlur,()=>_(!1))})})}),Fit="RovingFocusGroupItem",zit=N.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=um(),d=i||c,u=HOt(Fit,n),h=u.currentTabStopId===d,p=Rit(n),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:b}=u;return N.useEffect(()=>{if(r)return f(),()=>g()},[r,f,g]),e.jsx(C4e.ItemSlot,{scope:n,id:d,focusable:r,active:a,children:e.jsx(sa.span,{tabIndex:h?0:-1,"data-orientation":u.orientation,...o,ref:t,onMouseDown:wr(s.onMouseDown,v=>{r?u.onItemFocus(d):v.preventDefault()}),onFocus:wr(s.onFocus,()=>u.onItemFocus(d)),onKeyDown:wr(s.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){u.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const j=YOt(v,u.orientation,u.dir);if(j!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let S=p().filter(A=>A.focusable).map(A=>A.ref.current);if(j==="last")S.reverse();else if(j==="prev"||j==="next"){j==="prev"&&S.reverse();const A=S.indexOf(v.currentTarget);S=u.loop?ZOt(S,A+1):S.slice(A+1)}setTimeout(()=>Bit(S))}}),children:typeof l=="function"?l({isCurrentTabStop:h,hasTabStop:b!=null}):l})})});zit.displayName=Fit;var WOt={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function KOt(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function YOt(s,t,n){const r=KOt(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return WOt[r]}function Bit(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function ZOt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var Q0e=Oit,X0e=zit,QOt=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},yI=new WeakMap,XV=new WeakMap,JV={},oje=0,$it=function(s){return s&&(s.host||$it(s.parentNode))},XOt=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=$it(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})},JOt=function(s,t,n,r){var a=XOt(t,Array.isArray(s)?s:[s]);JV[n]||(JV[n]=new WeakMap);var i=JV[n],l=[],o=new Set,c=new Set(a),d=function(h){!h||o.has(h)||(o.add(h),d(h.parentNode))};a.forEach(d);var u=function(h){!h||c.has(h)||Array.prototype.forEach.call(h.children,function(p){if(o.has(p))u(p);else try{var f=p.getAttribute(r),g=f!==null&&f!=="false",b=(yI.get(p)||0)+1,v=(i.get(p)||0)+1;yI.set(p,b),i.set(p,v),l.push(p),b===1&&g&&XV.set(p,!0),v===1&&p.setAttribute(n,"true"),g||p.setAttribute(r,"true")}catch(j){console.error("aria-hidden: cannot operate on ",p,j)}})};return u(t),o.clear(),oje++,function(){l.forEach(function(h){var p=yI.get(h)-1,f=i.get(h)-1;yI.set(h,p),i.set(h,f),p||(XV.has(h)||h.removeAttribute(r),XV.delete(h)),f||h.removeAttribute(n)}),oje--,oje||(yI=new WeakMap,yI=new WeakMap,XV=new WeakMap,JV={})}},J0e=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=QOt(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live]"))),JOt(r,a,n,"aria-hidden")):function(){return null}},ew=function(){return ew=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return xFt;var t=gFt(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])}},vFt=Hit(),PL="data-scroll-locked",bFt=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(tFt,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(PL,`] { 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(Mme,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(Ime,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(Mme," .").concat(Mme,` { right: 0 `).concat(r,`; } .`).concat(Ime," .").concat(Ime,` { margin-right: 0 `).concat(r,`; } body[`).concat(PL,`] { `).concat(sFt,": ").concat(o,`px; } `)},eBe=function(){var s=parseInt(document.body.getAttribute(PL)||"0",10);return isFinite(s)?s:0},_Ft=function(){N.useEffect(function(){return document.body.setAttribute(PL,(eBe()+1).toString()),function(){var s=eBe()-1;s<=0?document.body.removeAttribute(PL):document.body.setAttribute(PL,s.toString())}},[])},wFt=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;_Ft();var i=N.useMemo(function(){return yFt(a)},[a]);return N.createElement(vFt,{styles:bFt(i,!t,a,n?"":"!important")})},T4e=!1;if(typeof window<"u")try{var eH=Object.defineProperty({},"passive",{get:function(){return T4e=!0,!0}});window.addEventListener("test",eH,eH),window.removeEventListener("test",eH,eH)}catch{T4e=!1}var vI=T4e?{passive:!1}:!1,jFt=function(s){return s.tagName==="TEXTAREA"},Git=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!jFt(s)&&n[t]==="visible")},NFt=function(s){return Git(s,"overflowY")},kFt=function(s){return Git(s,"overflowX")},tBe=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=Wit(s,r);if(a){var i=Kit(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},SFt=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},CFt=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},Wit=function(s,t){return s==="v"?NFt(t):kFt(t)},Kit=function(s,t){return s==="v"?SFt(t):CFt(t)},TFt=function(s,t){return s==="h"&&t==="rtl"?-1:1},EFt=function(s,t,n,r,a){var i=TFt(s,window.getComputedStyle(t).direction),l=i*r,o=n.target,c=t.contains(o),d=!1,u=l>0,h=0,p=0;do{if(!o)break;var f=Kit(s,o),g=f[0],b=f[1],v=f[2],j=b-v-i*g;(g||j)&&Wit(s,o)&&(h+=j,p+=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||!a)||!u&&(Math.abs(p)<1||!a))&&(d=!0),d},tH=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},sBe=function(s){return[s.deltaX,s.deltaY]},nBe=function(s){return s&&"current"in s?s.current:s},AFt=function(s,t){return s[0]===t[0]&&s[1]===t[1]},MFt=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},IFt=0,bI=[];function PFt(s){var t=N.useRef([]),n=N.useRef([0,0]),r=N.useRef(),a=N.useState(IFt++)[0],i=N.useState(Hit)[0],l=N.useRef(s);N.useEffect(function(){l.current=s},[s]),N.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var b=eFt([s.lockRef.current],(s.shards||[]).map(nBe),!0).filter(Boolean);return b.forEach(function(v){return v.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),b.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=N.useCallback(function(b,v){if("touches"in b&&b.touches.length===2||b.type==="wheel"&&b.ctrlKey)return!l.current.allowPinchZoom;var j=tH(b),_=n.current,S="deltaX"in b?b.deltaX:_[0]-j[0],A="deltaY"in b?b.deltaY:_[1]-j[1],T,D=b.target,L=Math.abs(S)>Math.abs(A)?"h":"v";if("touches"in b&&L==="h"&&D.type==="range")return!1;var M=tBe(L,D);if(!M)return!0;if(M?T=L:(T=L==="v"?"h":"v",M=tBe(L,D)),!M)return!1;if(!r.current&&"changedTouches"in b&&(S||A)&&(r.current=T),!T)return!0;var F=r.current||T;return EFt(F,v,b,F==="h"?S:A,!0)},[]),c=N.useCallback(function(b){var v=b;if(!(!bI.length||bI[bI.length-1]!==i)){var j="deltaY"in v?sBe(v):tH(v),_=t.current.filter(function(T){return T.name===v.type&&(T.target===v.target||v.target===T.shadowParent)&&AFt(T.delta,j)})[0];if(_&&_.should){v.cancelable&&v.preventDefault();return}if(!_){var S=(l.current.shards||[]).map(nBe).filter(Boolean).filter(function(T){return T.contains(v.target)}),A=S.length>0?o(v,S[0]):!l.current.noIsolation;A&&v.cancelable&&v.preventDefault()}}},[]),d=N.useCallback(function(b,v,j,_){var S={name:b,delta:v,target:j,should:_,shadowParent:LFt(j)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(A){return A!==S})},1)},[]),u=N.useCallback(function(b){n.current=tH(b),r.current=void 0},[]),h=N.useCallback(function(b){d(b.type,sBe(b),b.target,o(b,s.lockRef.current))},[]),p=N.useCallback(function(b){d(b.type,tH(b),b.target,o(b,s.lockRef.current))},[]);N.useEffect(function(){return bI.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:p}),document.addEventListener("wheel",c,vI),document.addEventListener("touchmove",c,vI),document.addEventListener("touchstart",u,vI),function(){bI=bI.filter(function(b){return b!==i}),document.removeEventListener("wheel",c,vI),document.removeEventListener("touchmove",c,vI),document.removeEventListener("touchstart",u,vI)}},[]);var f=s.removeScrollBar,g=s.inert;return N.createElement(N.Fragment,null,g?N.createElement(i,{styles:MFt(a)}):null,f?N.createElement(wFt,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function LFt(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const DFt=cFt(Vit,PFt);var Q$=N.forwardRef(function(s,t){return N.createElement(eye,ew({},s,{ref:t,sideCar:DFt}))});Q$.classNames=eye.classNames;var E4e=["Enter"," "],RFt=["ArrowDown","PageUp","Home"],Yit=["ArrowUp","PageDown","End"],OFt=[...RFt,...Yit],FFt={ltr:[...E4e,"ArrowRight"],rtl:[...E4e,"ArrowLeft"]},zFt={ltr:["ArrowLeft"],rtl:["ArrowRight"]},X$="Menu",[cB,BFt,$Ft]=MD(X$),[HM,Zit]=gu(X$,[$Ft,Ww,K4]),tye=Ww(),Qit=K4(),[UFt,GM]=HM(X$),[qFt,J$]=HM(X$),Xit=s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=tye(t),[c,d]=N.useState(null),u=N.useRef(!1),h=dh(i),p=kN(a);return N.useEffect(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),e.jsx(V$,{...o,children:e.jsx(UFt,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(qFt,{scope:t,onClose:N.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:p,modal:l,children:r})})})};Xit.displayName=X$;var VFt="MenuAnchor",zAe=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=tye(n);return e.jsx(RD,{...a,...r,ref:t})});zAe.displayName=VFt;var BAe="MenuPortal",[HFt,Jit]=HM(BAe,{forceMount:void 0}),eot=s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=GM(BAe,t);return e.jsx(HFt,{scope:t,forceMount:n,children:e.jsx(Bh,{present:n||i.open,children:e.jsx(ID,{asChild:!0,container:a,children:r})})})};eot.displayName=BAe;var $v="MenuContent",[GFt,$Ae]=HM($v),tot=N.forwardRef((s,t)=>{const n=Jit($v,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=GM($v,s.__scopeMenu),l=J$($v,s.__scopeMenu);return e.jsx(cB.Provider,{scope:s.__scopeMenu,children:e.jsx(Bh,{present:r||i.open,children:e.jsx(cB.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(WFt,{...a,ref:t}):e.jsx(KFt,{...a,ref:t})})})})}),WFt=N.forwardRef((s,t)=>{const n=GM($v,s.__scopeMenu),r=N.useRef(null),a=Ti(t,r);return N.useEffect(()=>{const i=r.current;if(i)return J0e(i)},[]),e.jsx(UAe,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:wr(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),KFt=N.forwardRef((s,t)=>{const n=GM($v,s.__scopeMenu);return e.jsx(UAe,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),YFt=C4("MenuContent.ScrollLock"),UAe=N.forwardRef((s,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:p,onDismiss:f,disableOutsideScroll:g,...b}=s,v=GM($v,n),j=J$($v,n),_=tye(n),S=Qit(n),A=BFt(n),[T,D]=N.useState(null),L=N.useRef(null),M=Ti(t,L,v.onContentChange),F=N.useRef(0),z=N.useRef(""),V=N.useRef(0),W=N.useRef(null),K=N.useRef("right"),Y=N.useRef(0),ee=g?Q$:N.Fragment,ne=g?{as:YFt,allowPinchZoom:!0}:void 0,oe=ce=>{var Ee,De;const de=z.current+ce,ie=A().filter(Ie=>!Ie.disabled),ye=document.activeElement,_e=(Ee=ie.find(Ie=>Ie.ref.current===ye))==null?void 0:Ee.textValue,Me=ie.map(Ie=>Ie.textValue),Te=o7t(Me,de,_e),Ce=(De=ie.find(Ie=>Ie.textValue===Te))==null?void 0:De.ref.current;(function Ie(Fe){z.current=Fe,window.clearTimeout(F.current),Fe!==""&&(F.current=window.setTimeout(()=>Ie(""),1e3))})(de),Ce&&setTimeout(()=>Ce.focus())};N.useEffect(()=>()=>window.clearTimeout(F.current),[]),Z0e();const pe=N.useCallback(ce=>{var ie,ye;return K.current===((ie=W.current)==null?void 0:ie.side)&&c7t(ce,(ye=W.current)==null?void 0:ye.area)},[]);return e.jsx(GFt,{scope:n,searchRef:z,onItemEnter:N.useCallback(ce=>{pe(ce)&&ce.preventDefault()},[pe]),onItemLeave:N.useCallback(ce=>{var de;pe(ce)||((de=L.current)==null||de.focus(),D(null))},[pe]),onTriggerLeave:N.useCallback(ce=>{pe(ce)&&ce.preventDefault()},[pe]),pointerGraceTimerRef:V,onPointerGraceIntentChange:N.useCallback(ce=>{W.current=ce},[]),children:e.jsx(ee,{...ne,children:e.jsx(Y$,{asChild:!0,trapped:a,onMountAutoFocus:wr(i,ce=>{var de;ce.preventDefault(),(de=L.current)==null||de.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(G4,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:p,onDismiss:f,children:e.jsx(Q0e,{asChild:!0,...S,dir:j.dir,orientation:"vertical",loop:r,currentTabStopId:T,onCurrentTabStopIdChange:D,onEntryFocus:wr(c,ce=>{j.isUsingKeyboardRef.current||ce.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(H$,{role:"menu","aria-orientation":"vertical","data-state":got(v.open),"data-radix-menu-content":"",dir:j.dir,..._,...b,ref:M,style:{outline:"none",...b.style},onKeyDown:wr(b.onKeyDown,ce=>{const ie=ce.target.closest("[data-radix-menu-content]")===ce.currentTarget,ye=ce.ctrlKey||ce.altKey||ce.metaKey,_e=ce.key.length===1;ie&&(ce.key==="Tab"&&ce.preventDefault(),!ye&&_e&&oe(ce.key));const Me=L.current;if(ce.target!==Me||!OFt.includes(ce.key))return;ce.preventDefault();const Ce=A().filter(Ee=>!Ee.disabled).map(Ee=>Ee.ref.current);Yit.includes(ce.key)&&Ce.reverse(),a7t(Ce)}),onBlur:wr(s.onBlur,ce=>{ce.currentTarget.contains(ce.target)||(window.clearTimeout(F.current),z.current="")}),onPointerMove:wr(s.onPointerMove,dB(ce=>{const de=ce.target,ie=Y.current!==ce.clientX;if(ce.currentTarget.contains(de)&&ie){const ye=ce.clientX>Y.current?"right":"left";K.current=ye,Y.current=ce.clientX}}))})})})})})})});tot.displayName=$v;var ZFt="MenuGroup",qAe=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(sa.div,{role:"group",...r,ref:t})});qAe.displayName=ZFt;var QFt="MenuLabel",sot=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(sa.div,{...r,ref:t})});sot.displayName=QFt;var afe="MenuItem",rBe="menu.itemSelect",sye=N.forwardRef((s,t)=>{const{disabled:n=!1,onSelect:r,...a}=s,i=N.useRef(null),l=J$(afe,s.__scopeMenu),o=$Ae(afe,s.__scopeMenu),c=Ti(t,i),d=N.useRef(!1),u=()=>{const h=i.current;if(!n&&h){const p=new CustomEvent(rBe,{bubbles:!0,cancelable:!0});h.addEventListener(rBe,f=>r==null?void 0:r(f),{once:!0}),hAe(h,p),p.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(not,{...a,ref:c,disabled:n,onClick:wr(s.onClick,u),onPointerDown:h=>{var p;(p=s.onPointerDown)==null||p.call(s,h),d.current=!0},onPointerUp:wr(s.onPointerUp,h=>{var p;d.current||(p=h.currentTarget)==null||p.click()}),onKeyDown:wr(s.onKeyDown,h=>{const p=o.searchRef.current!=="";n||p&&h.key===" "||E4e.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});sye.displayName=afe;var not=N.forwardRef((s,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=s,l=$Ae(afe,n),o=Qit(n),c=N.useRef(null),d=Ti(t,c),[u,h]=N.useState(!1),[p,f]=N.useState("");return N.useEffect(()=>{const g=c.current;g&&f((g.textContent??"").trim())},[i.children]),e.jsx(cB.ItemSlot,{scope:n,disabled:r,textValue:a??p,children:e.jsx(X0e,{asChild:!0,...o,focusable:!r,children:e.jsx(sa.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:wr(s.onPointerMove,dB(g=>{r?l.onItemLeave(g):(l.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:wr(s.onPointerLeave,dB(g=>l.onItemLeave(g))),onFocus:wr(s.onFocus,()=>h(!0)),onBlur:wr(s.onBlur,()=>h(!1))})})})}),XFt="MenuCheckboxItem",rot=N.forwardRef((s,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=s;return e.jsx(cot,{scope:s.__scopeMenu,checked:n,children:e.jsx(sye,{role:"menuitemcheckbox","aria-checked":ife(n)?"mixed":n,...a,ref:t,"data-state":HAe(n),onSelect:wr(a.onSelect,()=>r==null?void 0:r(ife(n)?!0:!n),{checkForDefaultPrevented:!1})})})});rot.displayName=XFt;var aot="MenuRadioGroup",[JFt,e7t]=HM(aot,{value:void 0,onValueChange:()=>{}}),iot=N.forwardRef((s,t)=>{const{value:n,onValueChange:r,...a}=s,i=dh(r);return e.jsx(JFt,{scope:s.__scopeMenu,value:n,onValueChange:i,children:e.jsx(qAe,{...a,ref:t})})});iot.displayName=aot;var oot="MenuRadioItem",lot=N.forwardRef((s,t)=>{const{value:n,...r}=s,a=e7t(oot,s.__scopeMenu),i=n===a.value;return e.jsx(cot,{scope:s.__scopeMenu,checked:i,children:e.jsx(sye,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":HAe(i),onSelect:wr(r.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,n)},{checkForDefaultPrevented:!1})})})});lot.displayName=oot;var VAe="MenuItemIndicator",[cot,t7t]=HM(VAe,{checked:!1}),dot=N.forwardRef((s,t)=>{const{__scopeMenu:n,forceMount:r,...a}=s,i=t7t(VAe,n);return e.jsx(Bh,{present:r||ife(i.checked)||i.checked===!0,children:e.jsx(sa.span,{...a,ref:t,"data-state":HAe(i.checked)})})});dot.displayName=VAe;var s7t="MenuSeparator",uot=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(sa.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});uot.displayName=s7t;var n7t="MenuArrow",hot=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=tye(n);return e.jsx(G$,{...a,...r,ref:t})});hot.displayName=n7t;var r7t="MenuSub",[Fxn,mot]=HM(r7t),m7="MenuSubTrigger",pot=N.forwardRef((s,t)=>{const n=GM(m7,s.__scopeMenu),r=J$(m7,s.__scopeMenu),a=mot(m7,s.__scopeMenu),i=$Ae(m7,s.__scopeMenu),l=N.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},u=N.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return N.useEffect(()=>u,[u]),N.useEffect(()=>{const h=o.current;return()=>{window.clearTimeout(h),c(null)}},[o,c]),e.jsx(zAe,{asChild:!0,...d,children:e.jsx(not,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":got(n.open),...s,ref:hN(t,a.onTriggerChange),onClick:h=>{var p;(p=s.onClick)==null||p.call(s,h),!(s.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:wr(s.onPointerMove,dB(h=>{i.onItemEnter(h),!h.defaultPrevented&&!s.disabled&&!n.open&&!l.current&&(i.onPointerGraceIntentChange(null),l.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:wr(s.onPointerLeave,dB(h=>{var f,g;u();const p=(f=n.content)==null?void 0:f.getBoundingClientRect();if(p){const b=(g=n.content)==null?void 0:g.dataset.side,v=b==="right",j=v?-5:5,_=p[v?"left":"right"],S=p[v?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+j,y:h.clientY},{x:_,y:p.top},{x:S,y:p.top},{x:S,y:p.bottom},{x:_,y:p.bottom}],side:b}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:wr(s.onKeyDown,h=>{var f;const p=i.searchRef.current!=="";s.disabled||p&&h.key===" "||FFt[r.dir].includes(h.key)&&(n.onOpenChange(!0),(f=n.content)==null||f.focus(),h.preventDefault())})})})});pot.displayName=m7;var fot="MenuSubContent",xot=N.forwardRef((s,t)=>{const n=Jit($v,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=GM($v,s.__scopeMenu),l=J$($v,s.__scopeMenu),o=mot(fot,s.__scopeMenu),c=N.useRef(null),d=Ti(t,c);return e.jsx(cB.Provider,{scope:s.__scopeMenu,children:e.jsx(Bh,{present:r||i.open,children:e.jsx(cB.Slot,{scope:s.__scopeMenu,children:e.jsx(UAe,{id:o.contentId,"aria-labelledby":o.triggerId,...a,ref:d,align:"start",side:l.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{var h;l.isUsingKeyboardRef.current&&((h=c.current)==null||h.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:wr(s.onFocusOutside,u=>{u.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:wr(s.onEscapeKeyDown,u=>{l.onClose(),u.preventDefault()}),onKeyDown:wr(s.onKeyDown,u=>{var f;const h=u.currentTarget.contains(u.target),p=zFt[l.dir].includes(u.key);h&&p&&(i.onOpenChange(!1),(f=o.trigger)==null||f.focus(),u.preventDefault())})})})})})});xot.displayName=fot;function got(s){return s?"open":"closed"}function ife(s){return s==="indeterminate"}function HAe(s){return ife(s)?"indeterminate":s?"checked":"unchecked"}function a7t(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}function i7t(s,t){return s.map((n,r)=>s[(t+r)%s.length])}function o7t(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=i7t(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==n));const c=l.find(d=>d.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}function l7t(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=p>r&&n<(h-d)*(r-u)/(p-u)+d&&(a=!a)}return a}function c7t(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return l7t(n,t)}function dB(s){return t=>t.pointerType==="mouse"?s(t):void 0}var d7t=Xit,u7t=zAe,h7t=eot,m7t=tot,p7t=qAe,f7t=sot,x7t=sye,g7t=rot,y7t=iot,v7t=lot,b7t=dot,_7t=uot,w7t=hot,j7t=pot,N7t=xot,nye="DropdownMenu",[k7t,zxn]=gu(nye,[Zit]),dg=Zit(),[S7t,yot]=k7t(nye),vot=s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=dg(t),d=N.useRef(null),[u,h]=mm({prop:a,defaultProp:i??!1,onChange:l,caller:nye});return e.jsx(S7t,{scope:t,triggerId:um(),triggerRef:d,contentId:um(),open:u,onOpenChange:h,onOpenToggle:N.useCallback(()=>h(p=>!p),[h]),modal:o,children:e.jsx(d7t,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})};vot.displayName=nye;var bot="DropdownMenuTrigger",_ot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=s,i=yot(bot,n),l=dg(n);return e.jsx(u7t,{asChild:!0,...l,children:e.jsx(sa.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:hN(t,i.triggerRef),onPointerDown:wr(s.onPointerDown,o=>{!r&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:wr(s.onKeyDown,o=>{r||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});_ot.displayName=bot;var C7t="DropdownMenuPortal",wot=s=>{const{__scopeDropdownMenu:t,...n}=s,r=dg(t);return e.jsx(h7t,{...r,...n})};wot.displayName=C7t;var jot="DropdownMenuContent",Not=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=yot(jot,n),i=dg(n),l=N.useRef(!1);return e.jsx(m7t,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:wr(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:wr(s.onInteractOutside,o=>{const c=o.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,u=c.button===2||d;(!a.modal||u)&&(l.current=!0)}),style:{...s.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Not.displayName=jot;var T7t="DropdownMenuGroup",E7t=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(p7t,{...a,...r,ref:t})});E7t.displayName=T7t;var A7t="DropdownMenuLabel",kot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(f7t,{...a,...r,ref:t})});kot.displayName=A7t;var M7t="DropdownMenuItem",Sot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(x7t,{...a,...r,ref:t})});Sot.displayName=M7t;var I7t="DropdownMenuCheckboxItem",Cot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(g7t,{...a,...r,ref:t})});Cot.displayName=I7t;var P7t="DropdownMenuRadioGroup",L7t=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(y7t,{...a,...r,ref:t})});L7t.displayName=P7t;var D7t="DropdownMenuRadioItem",Tot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(v7t,{...a,...r,ref:t})});Tot.displayName=D7t;var R7t="DropdownMenuItemIndicator",Eot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(b7t,{...a,...r,ref:t})});Eot.displayName=R7t;var O7t="DropdownMenuSeparator",Aot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(_7t,{...a,...r,ref:t})});Aot.displayName=O7t;var F7t="DropdownMenuArrow",z7t=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(w7t,{...a,...r,ref:t})});z7t.displayName=F7t;var B7t="DropdownMenuSubTrigger",Mot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(j7t,{...a,...r,ref:t})});Mot.displayName=B7t;var $7t="DropdownMenuSubContent",Iot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=dg(n);return e.jsx(N7t,{...a,...r,ref:t,style:{...s.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Iot.displayName=$7t;var U7t=vot,q7t=_ot,V7t=wot,Pot=Not,Lot=kot,Dot=Sot,Rot=Cot,Oot=Tot,Fot=Eot,zot=Aot,Bot=Mot,$ot=Iot;const jc=U7t,Nc=q7t,H7t=N.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(Bot,{ref:a,className:Et("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",t&&"pl-8",s),...r,children:[n,e.jsx(ga,{className:"ml-auto h-4 w-4"})]}));H7t.displayName=Bot.displayName;const G7t=N.forwardRef(({className:s,...t},n)=>e.jsx($ot,{ref:n,className:Et("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}));G7t.displayName=$ot.displayName;const cc=N.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(V7t,{children:e.jsx(Pot,{ref:r,sideOffset:t,className:Et("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})}));cc.displayName=Pot.displayName;const Xr=N.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(Dot,{ref:r,className:Et("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}));Xr.displayName=Dot.displayName;const W7t=N.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(Rot,{ref:a,className:Et("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(Fot,{children:e.jsx(Lr,{className:"h-4 w-4"})})}),t]}));W7t.displayName=Rot.displayName;const K7t=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Oot,{ref:r,className:Et("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(Fot,{children:e.jsx(dm,{className:"h-2 w-2 fill-current"})})}),t]}));K7t.displayName=Oot.displayName;const I4=N.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(Lot,{ref:r,className:Et("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));I4.displayName=Lot.displayName;const Qg=N.forwardRef(({className:s,...t},n)=>e.jsx(zot,{ref:n,className:Et("-mx-1 my-1 h-px bg-muted",s),...t}));Qg.displayName=zot.displayName;const Y7t=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=Y0e();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(Xi,{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(_n,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{variant:"secondary",size:"sm",className:"gap-2 bg-primary-foreground/20 hover:bg-primary-foreground/30 text-primary-foreground border-0",children:[a?e.jsxs(e.Fragment,{children:[e.jsx(Xi,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(aa,{className:"h-5 w-5",children:[e.jsx(ri,{src:t.avatar_url||void 0}),e.jsx(ia,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(io,{className:"h-3 w-3"})]})}),e.jsxs(cc,{align:"start",className:"z-[2147483647]",children:[e.jsxs(Xr,{onClick:i,className:"gap-2",children:[e.jsx(Xi,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(ze,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(Qg,{}),n.map(o=>e.jsxs(Xr,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(aa,{className:"h-6 w-6",children:[e.jsx(ri,{src:o.avatar_url||void 0}),e.jsx(ia,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(ze,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(ze,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})},rn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=gs(),c=Jl();if(a||(t||n)&&i)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!r){const d=c.pathname+c.search+c.hash;return d&&d!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",d),e.jsx(f4,{to:"/auth",replace:!0})}return t&&!l?e.jsx(f4,{to:"/dashboard",replace:!0}):n&&!o&&!l?e.jsx(f4,{to:"/dashboard",replace:!0}):e.jsx(e.Fragment,{children:s})};var GAe={};(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 de=new OffscreenCanvas(1,1),ie=de.getContext("2d");ie.fillRect(0,0,1,1);var ye=de.transferToImageBitmap();ie.createPattern(ye,"no-repeat")}catch{return!1}return!0}();function c(){}function d(de){var ie=n.exports.Promise,ye=ie!==void 0?ie:t.Promise;return typeof ye=="function"?new ye(de):(de(c,c),null)}var u=function(de,ie){return{transform:function(ye){if(de)return ye;if(ie.has(ye))return ie.get(ye);var _e=new OffscreenCanvas(ye.width,ye.height),Me=_e.getContext("2d");return Me.drawImage(ye,0,0),ie.set(ye,_e),_e},clear:function(){ie.clear()}}}(o,new Map),h=function(){var de=Math.floor(16.666666666666668),ie,ye,_e={},Me=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(ie=function(Te){var Ce=Math.random();return _e[Ce]=requestAnimationFrame(function Ee(De){Me===De||Me+de-1{const{data:t,error:n}=await q.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function Q7t(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function X7t(){const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{const{error:r}=await q.from("celebration_queue").insert({user_id:n.user_id,celebration_type:n.celebration_type,title:n.title,message:n.message||null,points_amount:n.points_amount||null,created_by:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}var rye="Dialog",[Uot,qot]=gu(rye),[J7t,Pb]=Uot(rye),Vot=s=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=N.useRef(null),c=N.useRef(null),[d,u]=mm({prop:r,defaultProp:a??!1,onChange:i,caller:rye});return e.jsx(J7t,{scope:t,triggerRef:o,contentRef:c,contentId:um(),titleId:um(),descriptionId:um(),open:d,onOpenChange:u,onOpenToggle:N.useCallback(()=>u(h=>!h),[u]),modal:l,children:n})};Vot.displayName=rye;var Hot="DialogTrigger",Got=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Pb(Hot,n),i=Ti(t,a.triggerRef);return e.jsx(sa.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":YAe(a.open),...r,ref:i,onClick:wr(s.onClick,a.onOpenToggle)})});Got.displayName=Hot;var WAe="DialogPortal",[e9t,Wot]=Uot(WAe,{forceMount:void 0}),Kot=s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=Pb(WAe,t);return e.jsx(e9t,{scope:t,forceMount:n,children:N.Children.map(r,l=>e.jsx(Bh,{present:n||i.open,children:e.jsx(ID,{asChild:!0,container:a,children:l})}))})};Kot.displayName=WAe;var ofe="DialogOverlay",Yot=N.forwardRef((s,t)=>{const n=Wot(ofe,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=Pb(ofe,s.__scopeDialog);return i.modal?e.jsx(Bh,{present:r||i.open,children:e.jsx(s9t,{...a,ref:t})}):null});Yot.displayName=ofe;var t9t=C4("DialogOverlay.RemoveScroll"),s9t=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Pb(ofe,n);return e.jsx(Q$,{as:t9t,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(sa.div,{"data-state":YAe(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),xM="DialogContent",Zot=N.forwardRef((s,t)=>{const n=Wot(xM,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=Pb(xM,s.__scopeDialog);return e.jsx(Bh,{present:r||i.open,children:i.modal?e.jsx(n9t,{...a,ref:t}):e.jsx(r9t,{...a,ref:t})})});Zot.displayName=xM;var n9t=N.forwardRef((s,t)=>{const n=Pb(xM,s.__scopeDialog),r=N.useRef(null),a=Ti(t,n.contentRef,r);return N.useEffect(()=>{const i=r.current;if(i)return J0e(i)},[]),e.jsx(Qot,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:wr(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:wr(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:wr(s.onFocusOutside,i=>i.preventDefault())})}),r9t=N.forwardRef((s,t)=>{const n=Pb(xM,s.__scopeDialog),r=N.useRef(!1),a=N.useRef(!1);return e.jsx(Qot,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(r.current||(o=n.triggerRef.current)==null||o.focus(),i.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=n.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),Qot=N.forwardRef((s,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=Pb(xM,n),c=N.useRef(null),d=Ti(t,c);return Z0e(),e.jsxs(e.Fragment,{children:[e.jsx(Y$,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(G4,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":YAe(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(i9t,{titleId:o.titleId}),e.jsx(l9t,{contentRef:c,descriptionId:o.descriptionId})]})]})}),KAe="DialogTitle",Xot=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Pb(KAe,n);return e.jsx(sa.h2,{id:a.titleId,...r,ref:t})});Xot.displayName=KAe;var Jot="DialogDescription",elt=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Pb(Jot,n);return e.jsx(sa.p,{id:a.descriptionId,...r,ref:t})});elt.displayName=Jot;var tlt="DialogClose",slt=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Pb(tlt,n);return e.jsx(sa.button,{type:"button",...r,ref:t,onClick:wr(s.onClick,()=>a.onOpenChange(!1))})});slt.displayName=tlt;function YAe(s){return s?"open":"closed"}var nlt="DialogTitleWarning",[a9t,rlt]=lMt(nlt,{contentName:xM,titleName:KAe,docsSlug:"dialog"}),i9t=({titleId:s})=>{const t=rlt(nlt),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return N.useEffect(()=>{s&&(document.getElementById(s)||console.error(n))},[n,s]),null},o9t="DialogDescriptionWarning",l9t=({contentRef:s,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${rlt(o9t).contentName}}.`;return N.useEffect(()=>{var i;const a=(i=s.current)==null?void 0:i.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(r))},[r,s,t]),null},aye=Vot,ZAe=Got,iye=Kot,UD=Yot,qD=Zot,eU=Xot,tU=elt,sU=slt;const bs=aye,Di=ZAe,c9t=iye,Bxn=sU,alt=N.forwardRef(({className:s,...t},n)=>e.jsx(UD,{ref:n,className:Et("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}));alt.displayName=UD.displayName;const vs=N.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(c9t,{children:[e.jsx(alt,{className:n}),e.jsxs(qD,{ref:a,className:Et("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(sU,{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(Fn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));vs.displayName=qD.displayName;const ws=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});ws.displayName="DialogHeader";const Xn=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Xn.displayName="DialogFooter";const _s=N.forwardRef(({className:s,...t},n)=>e.jsx(eU,{ref:n,className:Et("text-lg font-semibold leading-none tracking-tight",s),...t}));_s.displayName=eU.displayName;const Qn=N.forwardRef(({className:s,...t},n)=>e.jsx(tU,{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));Qn.displayName=tU.displayName;const d9t={points_earned:vo,listing_created:zr,deal_closed:Zl,custom:ua},iBe={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"},oBe=()=>{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 u9t(){const{user:s}=gs(),t=Gt(),{data:n}=Z7t(),r=Q7t(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=N.useCallback(()=>{const f=Date.now()+3e3,g={startVelocity:30,spread:360,ticks:60,zIndex:9999},b=(j,_)=>Math.random()*(_-j)+j,v=setInterval(()=>{const j=f-Date.now();if(j<=0){clearInterval(v);return}const _=50*(j/3e3);aBe({...g,particleCount:_,origin:{x:b(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),aBe({...g,particleCount:_,origin:{x:b(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);N.useEffect(()=>{oBe()||n&&n.length>0&&!a&&(i(n[0]),o(!0),setTimeout(c,100))},[n,a,c]);const d=async()=>{if(a){const p=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],f=>(f==null?void 0:f.filter(g=>g.id!==p))??[]),await r.mutateAsync(p)}};if(oBe()||!a)return null;const u=d9t[a.celebration_type]||ua,h=iBe[a.celebration_type]||iBe.custom;return e.jsx(bs,{open:l,onOpenChange:p=>!p&&d(),children:e.jsxs(vs,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${h} opacity-10`}),e.jsxs("div",{className:"relative z-10 py-6",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${h} flex items-center justify-center animate-bounce`,children:e.jsx(u,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(un,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(un,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(un,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),e.jsxs("h2",{className:"text-2xl font-bold mb-2 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent",children:["🎉 ",a.title]}),a.points_amount&&a.points_amount>0&&e.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",a.points_amount," points!"]}),a.message&&e.jsx("p",{className:"text-muted-foreground mb-6",children:a.message}),e.jsx(B,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),n&&n.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",n.length-1," more celebration",n.length>2?"s":""," waiting"]})]})]})})}function Ws({className:s,...t}){return e.jsx("div",{className:Et("animate-pulse rounded-md bg-muted",s),...t})}const ge=N.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:Et("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}));ge.displayName="Input";var h9t="Label",ilt=N.forwardRef((s,t)=>e.jsx(sa.label,{...s,ref:t,onMouseDown:n=>{var a;n.target.closest("button, input, select, textarea")||((a=s.onMouseDown)==null||a.call(s,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));ilt.displayName=h9t;var olt=ilt;const m9t=qM("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),se=N.forwardRef(({className:s,...t},n)=>e.jsx(olt,{ref:n,className:Et(m9t(),s),...t}));se.displayName=olt.displayName;const Ts=N.forwardRef(({className:s,...t},n)=>e.jsx("textarea",{className:Et("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}));Ts.displayName="Textarea";var oye="Tabs",[p9t,$xn]=gu(oye,[K4]),llt=K4(),[f9t,QAe]=p9t(oye),clt=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,u=kN(o),[h,p]=mm({prop:r,onChange:a,defaultProp:i??"",caller:oye});return e.jsx(f9t,{scope:n,baseId:um(),value:h,onValueChange:p,orientation:l,dir:u,activationMode:c,children:e.jsx(sa.div,{dir:u,"data-orientation":l,...d,ref:t})})});clt.displayName=oye;var dlt="TabsList",ult=N.forwardRef((s,t)=>{const{__scopeTabs:n,loop:r=!0,...a}=s,i=QAe(dlt,n),l=llt(n);return e.jsx(Q0e,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:r,children:e.jsx(sa.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});ult.displayName=dlt;var hlt="TabsTrigger",mlt=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,disabled:a=!1,...i}=s,l=QAe(hlt,n),o=llt(n),c=xlt(l.baseId,r),d=glt(l.baseId,r),u=r===l.value;return e.jsx(X0e,{asChild:!0,...o,focusable:!a,active:u,children:e.jsx(sa.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":d,"data-state":u?"active":"inactive","data-disabled":a?"":void 0,disabled:a,id:c,...i,ref:t,onMouseDown:wr(s.onMouseDown,h=>{!a&&h.button===0&&h.ctrlKey===!1?l.onValueChange(r):h.preventDefault()}),onKeyDown:wr(s.onKeyDown,h=>{[" ","Enter"].includes(h.key)&&l.onValueChange(r)}),onFocus:wr(s.onFocus,()=>{const h=l.activationMode!=="manual";!u&&!a&&h&&l.onValueChange(r)})})})});mlt.displayName=hlt;var plt="TabsContent",flt=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,forceMount:a,children:i,...l}=s,o=QAe(plt,n),c=xlt(o.baseId,r),d=glt(o.baseId,r),u=r===o.value,h=N.useRef(u);return N.useEffect(()=>{const p=requestAnimationFrame(()=>h.current=!1);return()=>cancelAnimationFrame(p)},[]),e.jsx(Bh,{present:a||u,children:({present:p})=>e.jsx(sa.div,{"data-state":u?"active":"inactive","data-orientation":o.orientation,role:"tabpanel","aria-labelledby":c,hidden:!p,id:d,tabIndex:0,...l,ref:t,style:{...s.style,animationDuration:h.current?"0s":void 0},children:p&&i})})});flt.displayName=plt;function xlt(s,t){return`${s}-trigger-${t}`}function glt(s,t){return`${s}-content-${t}`}var x9t=clt,ylt=ult,vlt=mlt,blt=flt;const $r=x9t,Ur=N.forwardRef(({className:s,...t},n)=>e.jsx(ylt,{ref:n,className:Et("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));Ur.displayName=ylt.displayName;const Zt=N.forwardRef(({className:s,...t},n)=>e.jsx(vlt,{ref:n,className:Et("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",s),...t}));Zt.displayName=vlt.displayName;const ls=N.forwardRef(({className:s,...t},n)=>e.jsx(blt,{ref:n,className:Et("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));ls.displayName=blt.displayName;const uB="#0d0d0d",lfe="#1a1a1a",cf="#c9a84c",nU="#f0d78c",Iw={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function lye(s){const t={...s,source_page:typeof window<"u"?window.location.pathname:null,user_agent:typeof navigator<"u"?navigator.userAgent:null,referrer:typeof document<"u"?document.referrer:null},{data:n,error:r}=await q.functions.invoke("public-site-lead",{body:t});if(r)throw r;try{localStorage.setItem(Iw.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function XAe(){try{return!!localStorage.getItem(Iw.captured)}catch{return!1}}function g9t(){try{const s=localStorage.getItem(Iw.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function JAe({open:s,onClose:t,children:n}){return N.useEffect(()=>{if(!s)return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[s]),s?Gx.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, ${lfe} 0%, ${uB} 100%)`,border:`1px solid ${cf}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${cf}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(Fn,{className:"h-4 w-4"})}),n]})}),document.body):null}function eMe(){const[s,t]=N.useState({first_name:"",email:"",phone:"",area:""}),[n,r]=N.useState(!1),[a,i]=N.useState("");return{values:s,setValues:t,loading:n,setLoading:r,honeypot:a,setHoneypot:i}}function tMe({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(Xi,{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(Hs,{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(Pr,{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(Ca,{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 sMe({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, ${nU} 0%, ${cf} 100%)`,color:uB,boxShadow:`0 8px 24px ${cf}55`},children:s})}function lBe({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=eMe(),[d,u]=N.useState(!1),h=async p=>{if(p.preventDefault(),!!r.email){l(!0);try{await lye({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(Iw.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{ae.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(JAe,{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(lm,{className:"h-4 w-4",style:{color:cf}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:nU},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:`${cf}22`,border:`1px solid ${cf}55`},children:e.jsx(un,{className:"h-5 w-5",style:{color:cf}})}),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(tMe,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(sMe,{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 y9t(){const[s,t]=N.useState(!0),[n,r]=N.useState(!1);N.useEffect(()=>{try{const i=!!localStorage.getItem(Iw.stickyDismissed)||XAe();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(Iw.stickyDismissed,"1")}catch{}};return s?e.jsx(lBe,{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, ${lfe} 0%, ${uB} 100%)`,borderTop:`1px solid ${cf}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:`${cf}22`,border:`1px solid ${cf}55`},children:e.jsx(lm,{className:"h-4 w-4",style:{color:cf}})}),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, ${nU} 0%, ${cf} 100%)`,color:uB},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(Fn,{className:"h-4 w-4"})})]})}),e.jsx(lBe,{open:n,onClose:()=>r(!1)})]})}function v9t(){const[s,t]=N.useState(!1),n=N.useRef(!1);N.useEffect(()=>{try{if(sessionStorage.getItem(Iw.exitShown)||XAe())return}catch{}const p=setTimeout(()=>{n.current=!0},8e3),f=g=>{if(n.current&&!(g.clientY>0)){t(!0);try{sessionStorage.setItem(Iw.exitShown,"1")}catch{}window.removeEventListener("mouseleave",f),document.removeEventListener("mouseleave",f)}};return document.addEventListener("mouseleave",f),()=>{clearTimeout(p),document.removeEventListener("mouseleave",f)}},[]);const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=eMe(),[d,u]=N.useState(!1),h=async p=>{if(p.preventDefault(),!!r.email){l(!0);try{await lye({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(JAe,{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, ${uB} 0%, ${lfe} 60%, ${cf} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:nU},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:lfe,border:`1px solid ${cf}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(un,{className:"h-6 w-6",style:{color:cf}})}),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(tMe,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(sMe,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function b9t(){const[s,t]=N.useState([]);N.useEffect(()=>{try{const o=localStorage.getItem(Iw.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(Iw.savedListings,JSON.stringify(o))}catch{}},r=N.useCallback(o=>s.includes(o),[s]),a=o=>{s.includes(o)||n([...s,o])},i=o=>n(s.filter(c=>c!==o));return{ids:s,has:r,add:a,remove:i,toggle:o=>s.includes(o)?i(o):a(o)}}function _9t({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=b9t(),l=r(s),[o,c]=N.useState(!1),d=()=>{if(l){i(s);return}if(XAe()){a(s),ae.success("Saved to your favorites"),lye({lead_type:"saved_listing",email:g9t()||"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(yi,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(w9t,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function w9t({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=eMe(),h=async p=>{if(p.preventDefault(),!!i.email){c(!0);try{await lye({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(JAe,{open:s,onClose:t,children:e.jsxs("div",{className:"p-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(yi,{className:"h-4 w-4",style:{color:cf}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:nU},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(tMe,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(sMe,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}function hB(s,[t,n]){return Math.min(n,Math.max(t,s))}function rU(s){const t=N.useRef({value:s,previous:s});return N.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}var _lt=["PageUp","PageDown"],wlt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],jlt={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},VD="Slider",[A4e,j9t,N9t]=MD(VD),[Nlt,Uxn]=gu(VD,[N9t]),[k9t,cye]=Nlt(VD),klt=N.forwardRef((s,t)=>{const{name:n,min:r=0,max:a=100,step:i=1,orientation:l="horizontal",disabled:o=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[r],value:u,onValueChange:h=()=>{},onValueCommit:p=()=>{},inverted:f=!1,form:g,...b}=s,v=N.useRef(new Set),j=N.useRef(0),S=l==="horizontal"?S9t:C9t,[A=[],T]=mm({prop:u,defaultProp:d,onChange:V=>{var K;(K=[...v.current][j.current])==null||K.focus(),h(V)}}),D=N.useRef(A);function L(V){const W=I9t(A,V);z(V,W)}function M(V){z(V,j.current)}function F(){const V=D.current[j.current];A[j.current]!==V&&p(A)}function z(V,W,{commit:K}={commit:!1}){const Y=R9t(i),ee=O9t(Math.round((V-r)/i)*i+r,Y),ne=hB(ee,[r,a]);T((oe=[])=>{const pe=A9t(oe,ne,W);if(D9t(pe,c*i)){j.current=pe.indexOf(ne);const ce=String(pe)!==String(oe);return ce&&K&&p(pe),ce?pe:oe}else return oe})}return e.jsx(k9t,{scope:s.__scopeSlider,name:n,disabled:o,min:r,max:a,valueIndexToChangeRef:j,thumbs:v.current,values:A,orientation:l,form:g,children:e.jsx(A4e.Provider,{scope:s.__scopeSlider,children:e.jsx(A4e.Slot,{scope:s.__scopeSlider,children:e.jsx(S,{"aria-disabled":o,"data-disabled":o?"":void 0,...b,ref:t,onPointerDown:wr(b.onPointerDown,()=>{o||(D.current=A)}),min:r,max:a,inverted:f,onSlideStart:o?void 0:L,onSlideMove:o?void 0:M,onSlideEnd:o?void 0:F,onHomeKeyDown:()=>!o&&z(r,0,{commit:!0}),onEndKeyDown:()=>!o&&z(a,A.length-1,{commit:!0}),onStepKeyDown:({event:V,direction:W})=>{if(!o){const ee=_lt.includes(V.key)||V.shiftKey&&wlt.includes(V.key)?10:1,ne=j.current,oe=A[ne],pe=i*ee*W;z(oe+pe,ne,{commit:!0})}}})})})})});klt.displayName=VD;var[Slt,Clt]=Nlt(VD,{startEdge:"left",endEdge:"right",size:"width",direction:1}),S9t=N.forwardRef((s,t)=>{const{min:n,max:r,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=s,[h,p]=N.useState(null),f=Ti(t,S=>p(S)),g=N.useRef(void 0),b=kN(a),v=b==="ltr",j=v&&!i||!v&&i;function _(S){const A=g.current||h.getBoundingClientRect(),T=[0,A.width],L=nMe(T,j?[n,r]:[r,n]);return g.current=A,L(S-A.left)}return e.jsx(Slt,{scope:s.__scopeSlider,startEdge:j?"left":"right",endEdge:j?"right":"left",direction:j?1:-1,size:"width",children:e.jsx(Tlt,{dir:b,"data-orientation":"horizontal",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:S=>{const A=_(S.clientX);l==null||l(A)},onSlideMove:S=>{const A=_(S.clientX);o==null||o(A)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:S=>{const T=jlt[j?"from-left":"from-right"].includes(S.key);d==null||d({event:S,direction:T?-1:1})}})})}),C9t=N.forwardRef((s,t)=>{const{min:n,max:r,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,u=N.useRef(null),h=Ti(t,u),p=N.useRef(void 0),f=!a;function g(b){const v=p.current||u.current.getBoundingClientRect(),j=[0,v.height],S=nMe(j,f?[r,n]:[n,r]);return p.current=v,S(b-v.top)}return e.jsx(Slt,{scope:s.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:e.jsx(Tlt,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const v=g(b.clientY);i==null||i(v)},onSlideMove:b=>{const v=g(b.clientY);l==null||l(v)},onSlideEnd:()=>{p.current=void 0,o==null||o()},onStepKeyDown:b=>{const j=jlt[f?"from-bottom":"from-top"].includes(b.key);c==null||c({event:b,direction:j?-1:1})}})})}),Tlt=N.forwardRef((s,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,u=cye(VD,n);return e.jsx(sa.span,{...d,ref:t,onKeyDown:wr(s.onKeyDown,h=>{h.key==="Home"?(l(h),h.preventDefault()):h.key==="End"?(o(h),h.preventDefault()):_lt.concat(wlt).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:wr(s.onPointerDown,h=>{const p=h.target;p.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(p)?p.focus():r(h)}),onPointerMove:wr(s.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&a(h)}),onPointerUp:wr(s.onPointerUp,h=>{const p=h.target;p.hasPointerCapture(h.pointerId)&&(p.releasePointerCapture(h.pointerId),i(h))})})}),Elt="SliderTrack",Alt=N.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=cye(Elt,n);return e.jsx(sa.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...r,ref:t})});Alt.displayName=Elt;var M4e="SliderRange",Mlt=N.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=cye(M4e,n),i=Clt(M4e,n),l=N.useRef(null),o=Ti(t,l),c=a.values.length,d=a.values.map(p=>Llt(p,a.min,a.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return e.jsx(sa.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...r,ref:o,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:h+"%"}})});Mlt.displayName=M4e;var I4e="SliderThumb",Ilt=N.forwardRef((s,t)=>{const n=j9t(s.__scopeSlider),[r,a]=N.useState(null),i=Ti(t,o=>a(o)),l=N.useMemo(()=>r?n().findIndex(o=>o.ref.current===r):-1,[n,r]);return e.jsx(T9t,{...s,ref:i,index:l})}),T9t=N.forwardRef((s,t)=>{const{__scopeSlider:n,index:r,name:a,...i}=s,l=cye(I4e,n),o=Clt(I4e,n),[c,d]=N.useState(null),u=Ti(t,_=>d(_)),h=c?l.form||!!c.closest("form"):!0,p=q$(c),f=l.values[r],g=f===void 0?0:Llt(f,l.min,l.max),b=M9t(r,l.values.length),v=p==null?void 0:p[o.size],j=v?P9t(v,g,o.direction):0;return N.useEffect(()=>{if(c)return l.thumbs.add(c),()=>{l.thumbs.delete(c)}},[c,l.thumbs]),e.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${g}% + ${j}px)`},children:[e.jsx(A4e.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(sa.span,{role:"slider","aria-label":s["aria-label"]||b,"aria-valuemin":l.min,"aria-valuenow":f,"aria-valuemax":l.max,"aria-orientation":l.orientation,"data-orientation":l.orientation,"data-disabled":l.disabled?"":void 0,tabIndex:l.disabled?void 0:0,...i,ref:u,style:f===void 0?{display:"none"}:s.style,onFocus:wr(s.onFocus,()=>{l.valueIndexToChangeRef.current=r})})}),h&&e.jsx(Plt,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:f},r)]})});Ilt.displayName=I4e;var E9t="RadioBubbleInput",Plt=N.forwardRef(({__scopeSlider:s,value:t,...n},r)=>{const a=N.useRef(null),i=Ti(a,r),l=rU(t);return N.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const h=new Event("input",{bubbles:!0});u.call(o,t),o.dispatchEvent(h)}},[l,t]),e.jsx(sa.input,{style:{display:"none"},...n,ref:i,defaultValue:t})});Plt.displayName=E9t;function A9t(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}function Llt(s,t,n){const i=100/(n-t)*(s-t);return hB(i,[0,100])}function M9t(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function I9t(s,t){if(s.length===1)return 0;const n=s.map(a=>Math.abs(a-t)),r=Math.min(...n);return n.indexOf(r)}function P9t(s,t,n){const r=s/2,i=nMe([0,50],[0,r]);return(r-i(t)*n)*n}function L9t(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}function D9t(s,t){if(t>0){const n=L9t(s);return Math.min(...n)>=t}return!0}function nMe(s,t){return n=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(s[1]-s[0]);return t[0]+r*(n-s[0])}}function R9t(s){return(String(s).split(".")[1]||"").length}function O9t(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}var Dlt=klt,F9t=Alt,z9t=Mlt,B9t=Ilt;const $m=N.forwardRef(({className:s,...t},n)=>e.jsxs(Dlt,{ref:n,className:Et("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(F9t,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(z9t,{className:"absolute h-full bg-primary"})}),e.jsx(B9t,{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"})]}));$m.displayName=Dlt.displayName;var $9t=[" ","Enter","ArrowUp","ArrowDown"],U9t=[" ","Enter"],gM="Select",[dye,uye,q9t]=MD(gM),[HD,qxn]=gu(gM,[q9t,Ww]),hye=Ww(),[V9t,Y4]=HD(gM),[H9t,G9t]=HD(gM),Rlt=s=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:p,required:f,form:g}=s,b=hye(t),[v,j]=N.useState(null),[_,S]=N.useState(null),[A,T]=N.useState(!1),D=kN(d),[L,M]=mm({prop:r,defaultProp:a??!1,onChange:i,caller:gM}),[F,z]=mm({prop:l,defaultProp:o,onChange:c,caller:gM}),V=N.useRef(null),W=v?g||!!v.closest("form"):!0,[K,Y]=N.useState(new Set),ee=Array.from(K).map(ne=>ne.props.value).join(";");return e.jsx(V$,{...b,children:e.jsxs(V9t,{required:f,scope:t,trigger:v,onTriggerChange:j,valueNode:_,onValueNodeChange:S,valueNodeHasChildren:A,onValueNodeHasChildrenChange:T,contentId:um(),value:F,onValueChange:z,open:L,onOpenChange:M,dir:D,triggerPointerDownPosRef:V,disabled:p,children:[e.jsx(dye.Provider,{scope:t,children:e.jsx(H9t,{scope:s.__scopeSelect,onNativeOptionAdd:N.useCallback(ne=>{Y(oe=>new Set(oe).add(ne))},[]),onNativeOptionRemove:N.useCallback(ne=>{Y(oe=>{const pe=new Set(oe);return pe.delete(ne),pe})},[]),children:n})}),W?e.jsxs(ict,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:h,value:F,onChange:ne=>z(ne.target.value),disabled:p,form:g,children:[F===void 0?e.jsx("option",{value:""}):null,Array.from(K)]},ee):null]})})};Rlt.displayName=gM;var Olt="SelectTrigger",Flt=N.forwardRef((s,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=s,i=hye(n),l=Y4(Olt,n),o=l.disabled||r,c=Ti(t,l.onTriggerChange),d=uye(n),u=N.useRef("touch"),[h,p,f]=lct(b=>{const v=d().filter(S=>!S.disabled),j=v.find(S=>S.value===l.value),_=cct(v,b,j);_!==void 0&&l.onValueChange(_.value)}),g=b=>{o||(l.onOpenChange(!0),f()),b&&(l.triggerPointerDownPosRef.current={x:Math.round(b.pageX),y:Math.round(b.pageY)})};return e.jsx(RD,{asChild:!0,...i,children:e.jsx(sa.button,{type:"button",role:"combobox","aria-controls":l.contentId,"aria-expanded":l.open,"aria-required":l.required,"aria-autocomplete":"none",dir:l.dir,"data-state":l.open?"open":"closed",disabled:o,"data-disabled":o?"":void 0,"data-placeholder":oct(l.value)?"":void 0,...a,ref:c,onClick:wr(a.onClick,b=>{b.currentTarget.focus(),u.current!=="mouse"&&g(b)}),onPointerDown:wr(a.onPointerDown,b=>{u.current=b.pointerType;const v=b.target;v.hasPointerCapture(b.pointerId)&&v.releasePointerCapture(b.pointerId),b.button===0&&b.ctrlKey===!1&&b.pointerType==="mouse"&&(g(b),b.preventDefault())}),onKeyDown:wr(a.onKeyDown,b=>{const v=h.current!=="";!(b.ctrlKey||b.altKey||b.metaKey)&&b.key.length===1&&p(b.key),!(v&&b.key===" ")&&$9t.includes(b.key)&&(g(),b.preventDefault())})})})});Flt.displayName=Olt;var zlt="SelectValue",Blt=N.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:l="",...o}=s,c=Y4(zlt,n),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,h=Ti(t,c.onValueNodeChange);return fh(()=>{d(u)},[d,u]),e.jsx(sa.span,{...o,ref:h,style:{pointerEvents:"none"},children:oct(c.value)?e.jsx(e.Fragment,{children:l}):i})});Blt.displayName=zlt;var W9t="SelectIcon",$lt=N.forwardRef((s,t)=>{const{__scopeSelect:n,children:r,...a}=s;return e.jsx(sa.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});$lt.displayName=W9t;var K9t="SelectPortal",Ult=s=>e.jsx(ID,{asChild:!0,...s});Ult.displayName=K9t;var yM="SelectContent",qlt=N.forwardRef((s,t)=>{const n=Y4(yM,s.__scopeSelect),[r,a]=N.useState();if(fh(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?Gx.createPortal(e.jsx(Vlt,{scope:s.__scopeSelect,children:e.jsx(dye.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(Hlt,{...s,ref:t})});qlt.displayName=yM;var q1=10,[Vlt,Z4]=HD(yM),Y9t="SelectContentImpl",Z9t=C4("SelectContent.RemoveScroll"),Hlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:l,side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:p,collisionPadding:f,sticky:g,hideWhenDetached:b,avoidCollisions:v,...j}=s,_=Y4(yM,n),[S,A]=N.useState(null),[T,D]=N.useState(null),L=Ti(t,Ee=>A(Ee)),[M,F]=N.useState(null),[z,V]=N.useState(null),W=uye(n),[K,Y]=N.useState(!1),ee=N.useRef(!1);N.useEffect(()=>{if(S)return J0e(S)},[S]),Z0e();const ne=N.useCallback(Ee=>{const[De,...Ie]=W().map(ve=>ve.ref.current),[Fe]=Ie.slice(-1),qe=document.activeElement;for(const ve of Ee)if(ve===qe||(ve==null||ve.scrollIntoView({block:"nearest"}),ve===De&&T&&(T.scrollTop=0),ve===Fe&&T&&(T.scrollTop=T.scrollHeight),ve==null||ve.focus(),document.activeElement!==qe))return},[W,T]),oe=N.useCallback(()=>ne([M,S]),[ne,M,S]);N.useEffect(()=>{K&&oe()},[K,oe]);const{onOpenChange:pe,triggerPointerDownPosRef:ce}=_;N.useEffect(()=>{if(S){let Ee={x:0,y:0};const De=Fe=>{var qe,ve;Ee={x:Math.abs(Math.round(Fe.pageX)-(((qe=ce.current)==null?void 0:qe.x)??0)),y:Math.abs(Math.round(Fe.pageY)-(((ve=ce.current)==null?void 0:ve.y)??0))}},Ie=Fe=>{Ee.x<=10&&Ee.y<=10?Fe.preventDefault():S.contains(Fe.target)||pe(!1),document.removeEventListener("pointermove",De),ce.current=null};return ce.current!==null&&(document.addEventListener("pointermove",De),document.addEventListener("pointerup",Ie,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",De),document.removeEventListener("pointerup",Ie,{capture:!0})}}},[S,pe,ce]),N.useEffect(()=>{const Ee=()=>pe(!1);return window.addEventListener("blur",Ee),window.addEventListener("resize",Ee),()=>{window.removeEventListener("blur",Ee),window.removeEventListener("resize",Ee)}},[pe]);const[de,ie]=lct(Ee=>{const De=W().filter(qe=>!qe.disabled),Ie=De.find(qe=>qe.ref.current===document.activeElement),Fe=cct(De,Ee,Ie);Fe&&setTimeout(()=>Fe.ref.current.focus())}),ye=N.useCallback((Ee,De,Ie)=>{const Fe=!ee.current&&!Ie;(_.value!==void 0&&_.value===De||Fe)&&(F(Ee),Fe&&(ee.current=!0))},[_.value]),_e=N.useCallback(()=>S==null?void 0:S.focus(),[S]),Me=N.useCallback((Ee,De,Ie)=>{const Fe=!ee.current&&!Ie;(_.value!==void 0&&_.value===De||Fe)&&V(Ee)},[_.value]),Te=r==="popper"?P4e:Glt,Ce=Te===P4e?{side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:p,collisionPadding:f,sticky:g,hideWhenDetached:b,avoidCollisions:v}:{};return e.jsx(Vlt,{scope:n,content:S,viewport:T,onViewportChange:D,itemRefCallback:ye,selectedItem:M,onItemLeave:_e,itemTextRefCallback:Me,focusSelectedItem:oe,selectedItemText:z,position:r,isPositioned:K,searchRef:de,children:e.jsx(Q$,{as:Z9t,allowPinchZoom:!0,children:e.jsx(Y$,{asChild:!0,trapped:_.open,onMountAutoFocus:Ee=>{Ee.preventDefault()},onUnmountAutoFocus:wr(a,Ee=>{var De;(De=_.trigger)==null||De.focus({preventScroll:!0}),Ee.preventDefault()}),children:e.jsx(G4,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:Ee=>Ee.preventDefault(),onDismiss:()=>_.onOpenChange(!1),children:e.jsx(Te,{role:"listbox",id:_.contentId,"data-state":_.open?"open":"closed",dir:_.dir,onContextMenu:Ee=>Ee.preventDefault(),...j,...Ce,onPlaced:()=>Y(!0),ref:L,style:{display:"flex",flexDirection:"column",outline:"none",...j.style},onKeyDown:wr(j.onKeyDown,Ee=>{const De=Ee.ctrlKey||Ee.altKey||Ee.metaKey;if(Ee.key==="Tab"&&Ee.preventDefault(),!De&&Ee.key.length===1&&ie(Ee.key),["ArrowUp","ArrowDown","Home","End"].includes(Ee.key)){let Fe=W().filter(qe=>!qe.disabled).map(qe=>qe.ref.current);if(["ArrowUp","End"].includes(Ee.key)&&(Fe=Fe.slice().reverse()),["ArrowUp","ArrowDown"].includes(Ee.key)){const qe=Ee.target,ve=Fe.indexOf(qe);Fe=Fe.slice(ve+1)}setTimeout(()=>ne(Fe)),Ee.preventDefault()}})})})})})})});Hlt.displayName=Y9t;var Q9t="SelectItemAlignedPosition",Glt=N.forwardRef((s,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=s,i=Y4(yM,n),l=Z4(yM,n),[o,c]=N.useState(null),[d,u]=N.useState(null),h=Ti(t,L=>u(L)),p=uye(n),f=N.useRef(!1),g=N.useRef(!0),{viewport:b,selectedItem:v,selectedItemText:j,focusSelectedItem:_}=l,S=N.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&b&&v&&j){const L=i.trigger.getBoundingClientRect(),M=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),z=j.getBoundingClientRect();if(i.dir!=="rtl"){const qe=z.left-M.left,ve=F.left-qe,Je=L.left-ve,we=L.width+Je,it=Math.max(we,M.width),Ne=window.innerWidth-q1,He=hB(ve,[q1,Math.max(q1,Ne-it)]);o.style.minWidth=we+"px",o.style.left=He+"px"}else{const qe=M.right-z.right,ve=window.innerWidth-F.right-qe,Je=window.innerWidth-L.right-ve,we=L.width+Je,it=Math.max(we,M.width),Ne=window.innerWidth-q1,He=hB(ve,[q1,Math.max(q1,Ne-it)]);o.style.minWidth=we+"px",o.style.right=He+"px"}const V=p(),W=window.innerHeight-q1*2,K=b.scrollHeight,Y=window.getComputedStyle(d),ee=parseInt(Y.borderTopWidth,10),ne=parseInt(Y.paddingTop,10),oe=parseInt(Y.borderBottomWidth,10),pe=parseInt(Y.paddingBottom,10),ce=ee+ne+K+pe+oe,de=Math.min(v.offsetHeight*5,ce),ie=window.getComputedStyle(b),ye=parseInt(ie.paddingTop,10),_e=parseInt(ie.paddingBottom,10),Me=L.top+L.height/2-q1,Te=W-Me,Ce=v.offsetHeight/2,Ee=v.offsetTop+Ce,De=ee+ne+Ee,Ie=ce-De;if(De<=Me){const qe=V.length>0&&v===V[V.length-1].ref.current;o.style.bottom="0px";const ve=d.clientHeight-b.offsetTop-b.offsetHeight,Je=Math.max(Te,Ce+(qe?_e:0)+ve+oe),we=De+Je;o.style.height=we+"px"}else{const qe=V.length>0&&v===V[0].ref.current;o.style.top="0px";const Je=Math.max(Me,ee+b.offsetTop+(qe?ye:0)+Ce)+Ie;o.style.height=Je+"px",b.scrollTop=De-Me+b.offsetTop}o.style.margin=`${q1}px 0`,o.style.minHeight=de+"px",o.style.maxHeight=W+"px",r==null||r(),requestAnimationFrame(()=>f.current=!0)}},[p,i.trigger,i.valueNode,o,d,b,v,j,i.dir,r]);fh(()=>S(),[S]);const[A,T]=N.useState();fh(()=>{d&&T(window.getComputedStyle(d).zIndex)},[d]);const D=N.useCallback(L=>{L&&g.current===!0&&(S(),_==null||_(),g.current=!1)},[S,_]);return e.jsx(J9t,{scope:n,contentWrapper:o,shouldExpandOnScrollRef:f,onScrollButtonChange:D,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:A},children:e.jsx(sa.div,{...a,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});Glt.displayName=Q9t;var X9t="SelectPopperPosition",P4e=N.forwardRef((s,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=q1,...i}=s,l=hye(n);return e.jsx(H$,{...l,...i,ref:t,align:r,collisionPadding:a,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});P4e.displayName=X9t;var[J9t,rMe]=HD(yM,{}),L4e="SelectViewport",Wlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,nonce:r,...a}=s,i=Z4(L4e,n),l=rMe(L4e,n),o=Ti(t,i.onViewportChange),c=N.useRef(0);return e.jsxs(e.Fragment,{children:[e.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),e.jsx(dye.Slot,{scope:n,children:e.jsx(sa.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:wr(a.onScroll,d=>{const u=d.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:p}=l;if(p!=null&&p.current&&h){const f=Math.abs(c.current-u.scrollTop);if(f>0){const g=window.innerHeight-q1*2,b=parseFloat(h.style.minHeight),v=parseFloat(h.style.height),j=Math.max(b,v);if(j0?A:0,h.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});Wlt.displayName=L4e;var Klt="SelectGroup",[ezt,tzt]=HD(Klt),szt=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=um();return e.jsx(ezt,{scope:n,id:a,children:e.jsx(sa.div,{role:"group","aria-labelledby":a,...r,ref:t})})});szt.displayName=Klt;var Ylt="SelectLabel",Zlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=tzt(Ylt,n);return e.jsx(sa.div,{id:a.id,...r,ref:t})});Zlt.displayName=Ylt;var cfe="SelectItem",[nzt,Qlt]=HD(cfe),Xlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...l}=s,o=Y4(cfe,n),c=Z4(cfe,n),d=o.value===r,[u,h]=N.useState(i??""),[p,f]=N.useState(!1),g=Ti(t,_=>{var S;return(S=c.itemRefCallback)==null?void 0:S.call(c,_,r,a)}),b=um(),v=N.useRef("touch"),j=()=>{a||(o.onValueChange(r),o.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return e.jsx(nzt,{scope:n,value:r,disabled:a,textId:b,isSelected:d,onItemTextChange:N.useCallback(_=>{h(S=>S||((_==null?void 0:_.textContent)??"").trim())},[]),children:e.jsx(dye.ItemSlot,{scope:n,value:r,disabled:a,textValue:u,children:e.jsx(sa.div,{role:"option","aria-labelledby":b,"data-highlighted":p?"":void 0,"aria-selected":d&&p,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...l,ref:g,onFocus:wr(l.onFocus,()=>f(!0)),onBlur:wr(l.onBlur,()=>f(!1)),onClick:wr(l.onClick,()=>{v.current!=="mouse"&&j()}),onPointerUp:wr(l.onPointerUp,()=>{v.current==="mouse"&&j()}),onPointerDown:wr(l.onPointerDown,_=>{v.current=_.pointerType}),onPointerMove:wr(l.onPointerMove,_=>{var S;v.current=_.pointerType,a?(S=c.onItemLeave)==null||S.call(c):v.current==="mouse"&&_.currentTarget.focus({preventScroll:!0})}),onPointerLeave:wr(l.onPointerLeave,_=>{var S;_.currentTarget===document.activeElement&&((S=c.onItemLeave)==null||S.call(c))}),onKeyDown:wr(l.onKeyDown,_=>{var A;((A=c.searchRef)==null?void 0:A.current)!==""&&_.key===" "||(U9t.includes(_.key)&&j(),_.key===" "&&_.preventDefault())})})})})});Xlt.displayName=cfe;var p7="SelectItemText",Jlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=s,l=Y4(p7,n),o=Z4(p7,n),c=Qlt(p7,n),d=G9t(p7,n),[u,h]=N.useState(null),p=Ti(t,j=>h(j),c.onItemTextChange,j=>{var _;return(_=o.itemTextRefCallback)==null?void 0:_.call(o,j,c.value,c.disabled)}),f=u==null?void 0:u.textContent,g=N.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:f},c.value),[c.disabled,c.value,f]),{onNativeOptionAdd:b,onNativeOptionRemove:v}=d;return fh(()=>(b(g),()=>v(g)),[b,v,g]),e.jsxs(e.Fragment,{children:[e.jsx(sa.span,{id:c.textId,...i,ref:p}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?Gx.createPortal(i.children,l.valueNode):null]})});Jlt.displayName=p7;var ect="SelectItemIndicator",tct=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return Qlt(ect,n).isSelected?e.jsx(sa.span,{"aria-hidden":!0,...r,ref:t}):null});tct.displayName=ect;var D4e="SelectScrollUpButton",sct=N.forwardRef((s,t)=>{const n=Z4(D4e,s.__scopeSelect),r=rMe(D4e,s.__scopeSelect),[a,i]=N.useState(!1),l=Ti(t,r.onScrollButtonChange);return fh(()=>{if(n.viewport&&n.isPositioned){let o=function(){const d=c.scrollTop>0;i(d)};const c=n.viewport;return o(),c.addEventListener("scroll",o),()=>c.removeEventListener("scroll",o)}},[n.viewport,n.isPositioned]),a?e.jsx(rct,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});sct.displayName=D4e;var R4e="SelectScrollDownButton",nct=N.forwardRef((s,t)=>{const n=Z4(R4e,s.__scopeSelect),r=rMe(R4e,s.__scopeSelect),[a,i]=N.useState(!1),l=Ti(t,r.onScrollButtonChange);return fh(()=>{if(n.viewport&&n.isPositioned){let o=function(){const d=c.scrollHeight-c.clientHeight,u=Math.ceil(c.scrollTop)c.removeEventListener("scroll",o)}},[n.viewport,n.isPositioned]),a?e.jsx(rct,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});nct.displayName=R4e;var rct=N.forwardRef((s,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=s,i=Z4("SelectScrollButton",n),l=N.useRef(null),o=uye(n),c=N.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return N.useEffect(()=>()=>c(),[c]),fh(()=>{var u;const d=o().find(h=>h.ref.current===document.activeElement);(u=d==null?void 0:d.ref.current)==null||u.scrollIntoView({block:"nearest"})},[o]),e.jsx(sa.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:wr(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(r,50))}),onPointerMove:wr(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(r,50))}),onPointerLeave:wr(a.onPointerLeave,()=>{c()})})}),rzt="SelectSeparator",act=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return e.jsx(sa.div,{"aria-hidden":!0,...r,ref:t})});act.displayName=rzt;var O4e="SelectArrow",azt=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=hye(n),i=Y4(O4e,n),l=Z4(O4e,n);return i.open&&l.position==="popper"?e.jsx(G$,{...a,...r,ref:t}):null});azt.displayName=O4e;var izt="SelectBubbleInput",ict=N.forwardRef(({__scopeSelect:s,value:t,...n},r)=>{const a=N.useRef(null),i=Ti(r,a),l=rU(t);return N.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const h=new Event("change",{bubbles:!0});u.call(o,t),o.dispatchEvent(h)}},[l,t]),e.jsx(sa.select,{...n,style:{...drt,...n.style},ref:i,defaultValue:t})});ict.displayName=izt;function oct(s){return s===""||s===void 0}function lct(s){const t=dh(s),n=N.useRef(""),r=N.useRef(0),a=N.useCallback(l=>{const o=n.current+l;t(o),function c(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(o)},[t]),i=N.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return N.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}function cct(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=ozt(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==n));const c=l.find(d=>d.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}function ozt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var lzt=Rlt,dct=Flt,czt=Blt,dzt=$lt,uzt=Ult,uct=qlt,hzt=Wlt,hct=Zlt,mct=Xlt,mzt=Jlt,pzt=tct,pct=sct,fct=nct,xct=act;const us=lzt,hs=czt,cs=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(dct,{ref:r,className:Et("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(dzt,{asChild:!0,children:e.jsx(io,{className:"h-4 w-4 opacity-50"})})]}));cs.displayName=dct.displayName;const gct=N.forwardRef(({className:s,...t},n)=>e.jsx(pct,{ref:n,className:Et("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(sx,{className:"h-4 w-4"})}));gct.displayName=pct.displayName;const yct=N.forwardRef(({className:s,...t},n)=>e.jsx(fct,{ref:n,className:Et("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(io,{className:"h-4 w-4"})}));yct.displayName=fct.displayName;const ds=N.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(uzt,{children:e.jsxs(uct,{ref:a,className:Et("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(gct,{}),e.jsx(hzt,{className:Et("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(yct,{})]})}));ds.displayName=uct.displayName;const fzt=N.forwardRef(({className:s,...t},n)=>e.jsx(hct,{ref:n,className:Et("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));fzt.displayName=hct.displayName;const Ze=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(mct,{ref:r,className:Et("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(pzt,{children:e.jsx(Lr,{className:"h-4 w-4"})})}),e.jsx(mzt,{children:t})]}));Ze.displayName=mct.displayName;const xzt=N.forwardRef(({className:s,...t},n)=>e.jsx(xct,{ref:n,className:Et("-mx-1 my-1 h-px bg-muted",s),...t}));xzt.displayName=xct.displayName;const gzt=s=>lt({queryKey:["public-listings",s],queryFn:async()=>{let t=q.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).order("created_at",{ascending:!1});if(s!=null&&s.status&&(t=t.eq("status",s.status)),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city){const a=s.city.replace(/[%,()]/g," ").trim();if(a){const i=`%${a}%`;t=t.or(`city.ilike.${i},neighborhood.ilike.${i},property_address.ilike.${i}`)}}s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:n,error:r}=await t;if(r)throw r;return n}}),yzt=()=>lt({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await q.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(t)throw t;const n=new Map,r=new Map,a=new Map;return(s||[]).forEach(i=>{if(i.city){const l=`${i.city}|${i.state||""}`.toLowerCase(),o=i.state?`${i.city}, ${i.state}`:i.city,c=n.get(l);c?c.count++:n.set(l,{label:o,city:i.city,state:i.state,count:1})}if(i.neighborhood){const l=`${i.neighborhood}|${i.city||""}`.toLowerCase(),o=i.city?`${i.neighborhood} — ${i.city}`:i.neighborhood,c=r.get(l);c?c.count++:r.set(l,{label:o,city:i.city||"",neighborhood:i.neighborhood,count:1})}if(i.property_address){const l=String(i.property_address).match(/\b(\d{5})(?:-\d{4})?\b/);if(l){const o=l[1],c=a.get(o);c?c.count++:a.set(o,{label:o,zip:o,count:1})}}}),{cities:Array.from(n.values()).sort((i,l)=>l.count-i.count),neighborhoods:Array.from(r.values()).sort((i,l)=>l.count-i.count),zips:Array.from(a.values()).sort((i,l)=>l.count-i.count)}}}),vzt=s=>lt({queryKey:["public-listing",s],queryFn:async()=>{const t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);let n=q.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);t?n=n.eq("id",s):n=n.eq("slug",s);const{data:r,error:a}=await n.single();if(a)throw a;return r},enabled:!!s}),bzt=()=>gt({mutationFn:async({listingId:s,agentId:t,firstName:n,lastName:r,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:u,message:h})=>{let p=null,f=null;if(l){const{data:j}=await q.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();j&&(p=j.id,f=j.sharing_agent_id)}const{data:g,error:b}=await q.from("listing_leads").insert({listing_id:s,agent_id:f||t,first_name:n,last_name:r,email:a,phone:i,share_id:p,referred_by_agent_id:f,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:h||null}).select().single();if(b)throw b;const{error:v}=await q.functions.invoke("process-listing-lead",{body:{leadId:g.id}});return v&&console.error("Error processing lead:",v),g}}),_zt=()=>gt({mutationFn:async s=>{const{error:t}=await q.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),cBe="/assets/levelup-logo-color-BeKd2k_g.png",wzt={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"},jzt={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"},dBe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},sH=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),oF=s=>new Intl.NumberFormat("en-US").format(s);function vct({slugOverride:s}={}){var Qt,ns,$s,Ds,Dt;const t=_i(),n=s||t.slugOrId,[r]=yl(),{data:a,isLoading:i}=vzt(n||""),l=bzt(),o=_zt(),c=r.get("ref"),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(""),[b,v]=N.useState(""),[j,_]=N.useState(""),[S,A]=N.useState(""),[T,D]=N.useState(""),[L,M]=N.useState("in_person"),[F,z]=N.useState("info"),[V,W]=N.useState(!1),[K,Y]=N.useState(!1),[ee,ne]=N.useState(null),[oe,pe]=N.useState(!1);N.useState(!1);const[ce,de]=N.useState(!1),[ie,ye]=N.useState(20),[_e,Me]=N.useState(6.5),[Te,Ce]=N.useState(30),Ee=N.useRef(null),[De,Ie]=N.useState(!1);N.useEffect(()=>{const St=()=>Ie(window.scrollY>300);return window.addEventListener("scroll",St,{passive:!0}),()=>window.removeEventListener("scroll",St)},[]),N.useEffect(()=>{c&&o.mutate(c)},[c]),N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const Fe=(a==null?void 0:a.photos)||[],qe=Fe.find(St=>St.is_primary)||Fe[0],ve=N.useMemo(()=>{if(!(a!=null&&a.price))return 0;const St=a.price*(1-ie/100),$t=_e/100/12,ht=Te*12;return $t===0?St/ht:St*$t/(1-Math.pow(1+$t,-ht))},[a==null?void 0:a.price,ie,_e,Te]),Je=async()=>{const St=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:St})}catch{}else await navigator.clipboard.writeText(St),ae.success("Link copied to clipboard")},we=async St=>{if(St.preventDefault(),!d.trim()||!f.trim()||!a)return;const $t=F==="showing";if($t&&!S){ae.error("Please pick a preferred date for your showing");return}W(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:f.trim(),phone:b.trim(),shareToken:c,leadType:$t?"showing_request":"info_request",preferredDate:$t?S:null,preferredTime:$t&&T||null,showingMode:$t?L:null,message:j.trim()||null}),Y(!0),ae.success($t?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(ht){console.error("Lead submission error:",ht),ae.error(`Failed to submit: ${ht.message||"Please try again"}`)}finally{W(!1)}},it=()=>{ee!==null&&ne(ee===0?Fe.length-1:ee-1)},Ne=()=>{ee!==null&&ne(ee===Fe.length-1?0:ee+1)};if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(Ws,{className:"h-[100svh] w-full rounded-none bg-neutral-900"})});if(!a)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(Ln,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:cBe,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(zr,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"This listing may no longer be available."}),e.jsx(B,{asChild:!0,children:e.jsx(Ln,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const He=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,$e=((ns=(Qt=a.agent)==null?void 0:Qt.brokerage)==null?void 0:ns.name)||(($s=a.agent)==null?void 0:$s.brokerage_name),Ye=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,Ke=a.description||"",rt=Ke.length>420,tt=ce||!rt?Ke:Ke.slice(0,420).trimEnd()+"…",at=a.page_config||{},Ge=St=>{var $t;return((($t=at.sections)==null?void 0:$t[St])??!0)!==!1},dt=Array.isArray(at.addons)?at.addons:[],Bt=at.custom_note||"",kt=at.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsxs("title",{children:[He," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${sH(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${dBe[a.property_type]} in ${a.city}, ${a.state}. ${Ke.slice(0,140)}`}),e.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${a.slug||a.id}`}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400;9..144,500;9..144,600&display=swap",rel:"stylesheet"}),e.jsx("meta",{property:"og:title",content:He}),e.jsx("meta",{property:"og:description",content:`${sH(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}`}),qe&&e.jsx("meta",{property:"og:image",content:qe.photo_url}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:He}),e.jsx("meta",{name:"twitter:description",content:`${sH(a.price)} · ${a.city}, ${a.state}`}),qe&&e.jsx("meta",{name:"twitter:image",content:qe.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:Ke,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:Fe.map(St=>St.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 ${De?"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(Ln,{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(Wr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),De&&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(([St,$t])=>e.jsx("a",{href:`#${St}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:$t},St))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_9t,{listingId:a.id,listingAddress:a.property_address?`${a.property_address}, ${a.city}, ${a.state}`:`${a.city}, ${a.state}`,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition text-white"}),e.jsx("button",{onClick:Je,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition","aria-label":"Share",children:e.jsx(Hl,{className:"h-4 w-4 text-white"})}),e.jsx(B,{size:"sm",onClick:()=>pe(!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:Ee,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[qe?e.jsx("img",{src:qe.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(ze,{className:`${wzt[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:jzt[a.status]}),Fe.length>0&&e.jsxs("button",{onClick:()=>ne(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[e.jsx(pf,{className:"h-3.5 w-3.5"}),Fe.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:sH(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:oF(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(Xi,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{className:"pr-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Listing Agent"}),e.jsx("p",{className:"text-white font-medium leading-tight",children:a.agent.name}),$e&&e.jsx("p",{className:"text-xs text-white/60",children:$e})]}),e.jsx(B,{size:"sm",onClick:()=>pe(!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"]})]})})]}),Ge("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:ny,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:Tp,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:cy,label:"Interior",value:`${oF(a.square_footage)} sqft`},a.lot_size&&{icon:eN,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:yr,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:xw,label:"Price / sqft",value:`$${oF(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((St,$t)=>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(St.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:St.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:St.value})]})]},$t))})}),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:[Ge("story")&&Ke&&e.jsxs("section",{id:"story",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-3",children:"The Story"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light mb-6 text-white",children:"A closer look at this home"}),e.jsx("div",{className:"prose prose-invert prose-lg max-w-none",children:e.jsx("p",{className:"text-white/75 leading-relaxed whitespace-pre-wrap",children:tt})}),rt&&e.jsx("button",{onClick:()=>de(!ce),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:ce?"Show less":"Read more"}),e.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[e.jsxs(ze,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(Ga,{className:"h-3 w-3 mr-1.5"}),dBe[a.property_type]]}),a.has_hoa&&e.jsx(ze,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),a.mls_link&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"ml-2 border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:a.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(Bt||a.agent_notes&&a.agent_notes_public)&&e.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(un,{className:"h-4 w-4 text-amber-300"}),e.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),e.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',Bt||a.agent_notes,'"']})]})]}),Ge("gallery")&&Fe.length>1&&e.jsxs("section",{id:"gallery",children:[e.jsxs("div",{className:"flex items-end justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),e.jsxs("button",{onClick:()=>ne(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Fe.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Fe.slice(0,7).map((St,$t)=>{const ht=["col-span-4 sm:col-span-2 sm:row-span-2 aspect-square sm:aspect-auto","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square"],Ut=$t===6&&Fe.length>7;return e.jsxs("button",{onClick:()=>ne($t),className:`${ht[$t]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:St.photo_url,alt:`Photo ${$t+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),Ut&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(pf,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",Fe.length-7," more"]})]})]},St.id)})})]}),Ge("video")&&((Ds=a.video)==null?void 0:Ds.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"})})]}),Ge("map")&&Ye&&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:Ye,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(Ca,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),Ge("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:["$",oF(Math.round(ve))]}),e.jsx("p",{className:"text-white/60",children:"/ month"})]}),e.jsxs("div",{className:"grid sm:grid-cols-3 gap-8",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[ie,"%"]})]}),e.jsx($m,{value:[ie],onValueChange:St=>ye(St[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",oF(Math.round(a.price*ie/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[_e.toFixed(2),"%"]})]}),e.jsx($m,{value:[_e],onValueChange:St=>Me(St[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(se,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[Te," yr"]})]}),e.jsx($m,{value:[Te],onValueChange:St=>Ce(St[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."})]})]}),dt.map(St=>{const $t=St.type,ht=St.data||{};if($t==="extra_video"&&ht.url){const Ut=String(ht.url).includes("youtu")?`https://www.youtube.com/embed/${String(ht.url).split(/[/=]/).pop()}`:ht.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:ht.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:ht.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:Ut,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:ht.title||"Video"})})]},St.id)}return $t==="3d_tour"&&ht.url?e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"3D Tour"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:ht.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:ht.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},St.id):$t==="floor_plan"&&ht.image_url?e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Floor Plan"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:ht.title||"Layout"}),e.jsx("img",{src:ht.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},St.id):$t==="testimonial"&&ht.quote?e.jsxs("section",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-8",children:[e.jsxs("p",{className:"font-display italic text-2xl text-white/90 leading-relaxed",children:['"',ht.quote,'"']}),ht.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",ht.author]})]},St.id):$t==="custom_cta"&&ht.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:kt?`${kt}22`:"rgba(255,255,255,0.05)",border:`1px solid ${kt||"rgba(255,255,255,0.1)"}`},children:[ht.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:ht.title}),e.jsx(B,{asChild:!0,size:"lg",style:kt?{background:kt}:void 0,children:e.jsx("a",{href:ht.url||"#agent",children:ht.label})})]},St.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(Xi,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.agent.name}),$e&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:$e})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.agent.phone&&e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.agent.phone}`,children:[e.jsx(Pr,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.agent.email&&e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.agent.email}`,children:[e.jsx(Hs,{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(uBe,{submitted:K,activeTab:F,setActiveTab:z,firstName:d,setFirstName:u,lastName:h,setLastName:p,email:f,setEmail:g,phone:b,setPhone:v,message:j,setMessage:_,preferredDate:S,setPreferredDate:A,preferredTime:T,setPreferredTime:D,showingMode:L,setShowingMode:M,isSubmitting:V,onSubmit:we})})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-neutral-950/95 backdrop-blur-xl border-t border-white/10 px-4 py-3 flex items-center gap-2 safe-area-inset-bottom",children:[((Dt=a.agent)==null?void 0:Dt.phone)&&e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15 flex-1",children:e.jsxs("a",{href:`tel:${a.agent.phone}`,children:[e.jsx(Pr,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs(B,{onClick:()=>pe(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(cm,{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:cBe,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(bs,{open:ee!==null,onOpenChange:()=>ne(null),children:e.jsxs(vs,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(ws,{className:"sr-only",children:e.jsx(_s,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>ne(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:e.jsx(Fn,{className:"h-5 w-5"})}),ee!==null&&Fe[ee]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Fe[ee].photo_url,alt:`Photo ${ee+1}`,className:"w-full max-h-[85vh] object-contain"}),Fe.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:it,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(fl,{className:"h-6 w-6"})}),e.jsx("button",{onClick:Ne,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(ga,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/60 px-3 py-1 rounded-full text-sm",children:[ee+1," / ",Fe.length]})]})]})]})}),e.jsx(bs,{open:oe,onOpenChange:pe,children:e.jsxs(vs,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(ws,{className:"sr-only",children:e.jsx(_s,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(uBe,{submitted:K,activeTab:F,setActiveTab:z,firstName:d,setFirstName:u,lastName:h,setLastName:p,email:f,setEmail:g,phone:b,setPhone:v,message:j,setMessage:_,preferredDate:S,setPreferredDate:A,preferredTime:T,setPreferredTime:D,showingMode:L,setShowingMode:M,isSubmitting:V,onSubmit:we})})]})})]})]})}function uBe(s){const{submitted:t,activeTab:n,setActiveTab:r,firstName:a,setFirstName:i,lastName:l,setLastName:o,email:c,setEmail:d,phone:u,setPhone:h,message:p,setMessage:f,preferredDate:g,setPreferredDate:b,preferredTime:v,setPreferredTime:j,showingMode:_,setShowingMode:S,isSubmitting:A,onSubmit:T}=s;return t?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(Lr,{className:"h-7 w-7 text-emerald-600"})}),e.jsx("p",{className:"font-display text-2xl font-medium mb-1",children:n==="showing"?"Showing request sent!":"Thanks — you're all set!"}),e.jsx("p",{className:"text-sm text-neutral-600",children:n==="showing"?"The listing agent will reach out to confirm your showing time.":"The listing agent will contact you shortly with more details."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-[0.25em] text-neutral-500 mb-1",children:"Interested?"}),e.jsx("h3",{className:"font-display text-2xl font-medium",children:"Talk to the listing agent"})]}),e.jsxs($r,{value:n,onValueChange:D=>r(D),children:[e.jsxs(Ur,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Zt,{value:"info",className:"gap-1.5",children:[e.jsx(Ci,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(Zt,{value:"showing",className:"gap-1.5",children:[e.jsx(cm,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:T,className:"space-y-3",children:[e.jsxs(ls,{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(se,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(ge,{id:"preferredDate",type:"date",value:g,onChange:D=>b(D.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(us,{value:v,onValueChange:j,children:[e.jsx(cs,{id:"preferredTime",children:e.jsx(hs,{placeholder:"Any time"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(Ze,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(Ze,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(us,{value:_,onValueChange:D=>S(D),children:[e.jsx(cs,{id:"showingMode",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(Ze,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(Ze,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"firstName",children:"First Name *"}),e.jsx(ge,{id:"firstName",value:a,onChange:D=>i(D.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lastName",children:"Last Name"}),e.jsx(ge,{id:"lastName",value:l,onChange:D=>o(D.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email *"}),e.jsx(ge,{id:"email",type:"email",value:c,onChange:D=>d(D.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(ge,{id:"phone",type:"tel",value:u,onChange:D=>h(D.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Ts,{id:"message",value:p,onChange:D=>f(D.target.value),rows:2})]}),e.jsx(B,{type:"submit",disabled:A,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:A?"Sending…":n==="showing"?"Request Showing":"Get More Info"}),e.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const dfe="/assets/levelup-logo-white-C2RAgAoG.png",Nzt="/assets/listings-hero-noir-BHCJrhvU.jpg";var bct={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(Ih,function(){let n,r,a;function i(o,c){if(!n)n=c;else if(!r)r=c;else{const d={};n(d),a=c(d);const u="self.onerror = function() { console.error('An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling'); }; var sharedChunk = {}; ("+n+")(sharedChunk); ("+r+")(undefined, sharedChunk); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(a.workerUrl=window.URL.createObjectURL(new Blob([u],{type:"text/javascript"})))}}i(["exports"],function(o){var c=1e-6,d=typeof Float32Array<"u"?Float32Array:Array;function u(w,m){var x=m[0],k=m[1],E=m[2],P=m[3],O=x*P-E*k;return O?(w[0]=P*(O=1/O),w[1]=-k*O,w[2]=-E*O,w[3]=x*O,w):null}function h(){var w=new d(9);return d!=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 p(w,m){var x=m[0],k=m[1],E=m[2],P=m[3],O=m[4],U=m[5],H=m[6],X=m[7],le=m[8];return w[0]=O*le-U*X,w[1]=E*X-k*le,w[2]=k*U-E*O,w[3]=U*H-P*le,w[4]=x*le-E*H,w[5]=E*P-x*U,w[6]=P*X-O*H,w[7]=k*H-x*X,w[8]=x*O-k*P,w}function f(w,m,x){var k=m[0],E=m[1],P=m[2],O=m[3],U=m[4],H=m[5],X=m[6],le=m[7],he=m[8],me=x[0],be=x[1],Se=x[2],Pe=x[3],Be=x[4],We=x[5],ot=x[6],nt=x[7],ft=x[8];return w[0]=me*k+be*O+Se*X,w[1]=me*E+be*U+Se*le,w[2]=me*P+be*H+Se*he,w[3]=Pe*k+Be*O+We*X,w[4]=Pe*E+Be*U+We*le,w[5]=Pe*P+Be*H+We*he,w[6]=ot*k+nt*O+ft*X,w[7]=ot*E+nt*U+ft*le,w[8]=ot*P+nt*H+ft*he,w}function g(){var w=new d(16);return d!=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 b(w){var m=new d(16);return m[0]=w[0],m[1]=w[1],m[2]=w[2],m[3]=w[3],m[4]=w[4],m[5]=w[5],m[6]=w[6],m[7]=w[7],m[8]=w[8],m[9]=w[9],m[10]=w[10],m[11]=w[11],m[12]=w[12],m[13]=w[13],m[14]=w[14],m[15]=w[15],m}function v(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 j(w,m){var x=m[0],k=m[1],E=m[2],P=m[3],O=m[4],U=m[5],H=m[6],X=m[7],le=m[8],he=m[9],me=m[10],be=m[11],Se=m[12],Pe=m[13],Be=m[14],We=m[15],ot=x*U-k*O,nt=x*H-E*O,ft=x*X-P*O,bt=k*H-E*U,wt=k*X-P*U,Yt=E*X-P*H,zt=le*Pe-he*Se,Kt=le*Be-me*Se,Vt=le*We-be*Se,Ht=he*Be-me*Pe,Os=he*We-be*Pe,Vs=me*We-be*Be,Js=ot*Vs-nt*Os+ft*Ht+bt*Vt-wt*Kt+Yt*zt;return Js?(w[0]=(U*Vs-H*Os+X*Ht)*(Js=1/Js),w[1]=(E*Os-k*Vs-P*Ht)*Js,w[2]=(Pe*Yt-Be*wt+We*bt)*Js,w[3]=(me*wt-he*Yt-be*bt)*Js,w[4]=(H*Vt-O*Vs-X*Kt)*Js,w[5]=(x*Vs-E*Vt+P*Kt)*Js,w[6]=(Be*ft-Se*Yt-We*nt)*Js,w[7]=(le*Yt-me*ft+be*nt)*Js,w[8]=(O*Os-U*Vt+X*zt)*Js,w[9]=(k*Vt-x*Os-P*zt)*Js,w[10]=(Se*wt-Pe*ft+We*ot)*Js,w[11]=(he*ft-le*wt-be*ot)*Js,w[12]=(U*Kt-O*Ht-H*zt)*Js,w[13]=(x*Ht-k*Kt+E*zt)*Js,w[14]=(Pe*nt-Se*bt-Be*ot)*Js,w[15]=(le*bt-he*nt+me*ot)*Js,w):null}function _(w,m,x){var k=m[0],E=m[1],P=m[2],O=m[3],U=m[4],H=m[5],X=m[6],le=m[7],he=m[8],me=m[9],be=m[10],Se=m[11],Pe=m[12],Be=m[13],We=m[14],ot=m[15],nt=x[0],ft=x[1],bt=x[2],wt=x[3];return w[0]=nt*k+ft*U+bt*he+wt*Pe,w[1]=nt*E+ft*H+bt*me+wt*Be,w[2]=nt*P+ft*X+bt*be+wt*We,w[3]=nt*O+ft*le+bt*Se+wt*ot,w[4]=(nt=x[4])*k+(ft=x[5])*U+(bt=x[6])*he+(wt=x[7])*Pe,w[5]=nt*E+ft*H+bt*me+wt*Be,w[6]=nt*P+ft*X+bt*be+wt*We,w[7]=nt*O+ft*le+bt*Se+wt*ot,w[8]=(nt=x[8])*k+(ft=x[9])*U+(bt=x[10])*he+(wt=x[11])*Pe,w[9]=nt*E+ft*H+bt*me+wt*Be,w[10]=nt*P+ft*X+bt*be+wt*We,w[11]=nt*O+ft*le+bt*Se+wt*ot,w[12]=(nt=x[12])*k+(ft=x[13])*U+(bt=x[14])*he+(wt=x[15])*Pe,w[13]=nt*E+ft*H+bt*me+wt*Be,w[14]=nt*P+ft*X+bt*be+wt*We,w[15]=nt*O+ft*le+bt*Se+wt*ot,w}function S(w,m,x){var k,E,P,O,U,H,X,le,he,me,be,Se,Pe=x[0],Be=x[1],We=x[2];return m===w?(w[12]=m[0]*Pe+m[4]*Be+m[8]*We+m[12],w[13]=m[1]*Pe+m[5]*Be+m[9]*We+m[13],w[14]=m[2]*Pe+m[6]*Be+m[10]*We+m[14],w[15]=m[3]*Pe+m[7]*Be+m[11]*We+m[15]):(E=m[1],P=m[2],O=m[3],U=m[4],H=m[5],X=m[6],le=m[7],he=m[8],me=m[9],be=m[10],Se=m[11],w[0]=k=m[0],w[1]=E,w[2]=P,w[3]=O,w[4]=U,w[5]=H,w[6]=X,w[7]=le,w[8]=he,w[9]=me,w[10]=be,w[11]=Se,w[12]=k*Pe+U*Be+he*We+m[12],w[13]=E*Pe+H*Be+me*We+m[13],w[14]=P*Pe+X*Be+be*We+m[14],w[15]=O*Pe+le*Be+Se*We+m[15]),w}function A(w,m,x){var k=x[0],E=x[1],P=x[2];return w[0]=m[0]*k,w[1]=m[1]*k,w[2]=m[2]*k,w[3]=m[3]*k,w[4]=m[4]*E,w[5]=m[5]*E,w[6]=m[6]*E,w[7]=m[7]*E,w[8]=m[8]*P,w[9]=m[9]*P,w[10]=m[10]*P,w[11]=m[11]*P,w[12]=m[12],w[13]=m[13],w[14]=m[14],w[15]=m[15],w}function T(w,m,x){var k=Math.sin(x),E=Math.cos(x),P=m[4],O=m[5],U=m[6],H=m[7],X=m[8],le=m[9],he=m[10],me=m[11];return m!==w&&(w[0]=m[0],w[1]=m[1],w[2]=m[2],w[3]=m[3],w[12]=m[12],w[13]=m[13],w[14]=m[14],w[15]=m[15]),w[4]=P*E+X*k,w[5]=O*E+le*k,w[6]=U*E+he*k,w[7]=H*E+me*k,w[8]=X*E-P*k,w[9]=le*E-O*k,w[10]=he*E-U*k,w[11]=me*E-H*k,w}function D(w,m,x){var k=Math.sin(x),E=Math.cos(x),P=m[0],O=m[1],U=m[2],H=m[3],X=m[8],le=m[9],he=m[10],me=m[11];return m!==w&&(w[4]=m[4],w[5]=m[5],w[6]=m[6],w[7]=m[7],w[12]=m[12],w[13]=m[13],w[14]=m[14],w[15]=m[15]),w[0]=P*E-X*k,w[1]=O*E-le*k,w[2]=U*E-he*k,w[3]=H*E-me*k,w[8]=P*k+X*E,w[9]=O*k+le*E,w[10]=U*k+he*E,w[11]=H*k+me*E,w}function L(w,m,x){var k=Math.sin(x),E=Math.cos(x),P=m[0],O=m[1],U=m[2],H=m[3],X=m[4],le=m[5],he=m[6],me=m[7];return m!==w&&(w[8]=m[8],w[9]=m[9],w[10]=m[10],w[11]=m[11],w[12]=m[12],w[13]=m[13],w[14]=m[14],w[15]=m[15]),w[0]=P*E+X*k,w[1]=O*E+le*k,w[2]=U*E+he*k,w[3]=H*E+me*k,w[4]=X*E-P*k,w[5]=le*E-O*k,w[6]=he*E-U*k,w[7]=me*E-H*k,w}function M(w,m){return w[0]=m[0],w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[5]=m[1],w[6]=0,w[7]=0,w[8]=0,w[9]=0,w[10]=m[2],w[11]=0,w[12]=0,w[13]=0,w[14]=0,w[15]=1,w}function F(w,m,x){var k,E,P,O=x[0],U=x[1],H=x[2],X=Math.sqrt(O*O+U*U+H*H);return X0&&(P=1/Math.sqrt(P)),w[0]=m[0]*P,w[1]=m[1]*P,w[2]=m[2]*P,w}function Fe(w,m){return w[0]*m[0]+w[1]*m[1]+w[2]*m[2]}function qe(w,m,x){var k=m[0],E=m[1],P=m[2],O=x[0],U=x[1],H=x[2];return w[0]=E*H-P*U,w[1]=P*O-k*H,w[2]=k*U-E*O,w}function ve(w,m,x,k){var E=m[0],P=m[1],O=m[2];return w[0]=E+k*(x[0]-E),w[1]=P+k*(x[1]-P),w[2]=O+k*(x[2]-O),w}function Je(w,m,x){var k=m[0],E=m[1],P=m[2],O=x[3]*k+x[7]*E+x[11]*P+x[15];return w[0]=(x[0]*k+x[4]*E+x[8]*P+x[12])/(O=O||1),w[1]=(x[1]*k+x[5]*E+x[9]*P+x[13])/O,w[2]=(x[2]*k+x[6]*E+x[10]*P+x[14])/O,w}function we(w,m,x){var k=m[0],E=m[1],P=m[2];return w[0]=k*x[0]+E*x[3]+P*x[6],w[1]=k*x[1]+E*x[4]+P*x[7],w[2]=k*x[2]+E*x[5]+P*x[8],w}function it(w,m,x){var k=x[0],E=x[1],P=x[2],O=x[3],U=m[0],H=m[1],X=m[2],le=E*X-P*H,he=P*U-k*X,me=k*H-E*U;return w[0]=U+O*(le+=le)+E*(me+=me)-P*(he+=he),w[1]=H+O*he+P*le-k*me,w[2]=X+O*me+k*he-E*le,w}function Ne(w){return w[0]=0,w[1]=0,w[2]=0,w}function He(w,m){return w[0]===m[0]&&w[1]===m[1]&&w[2]===m[2]}var $e=ce,Ye=de,Ke=ee;function rt(){var w=new d(4);return d!=Float32Array&&(w[0]=0,w[1]=0,w[2]=0,w[3]=0),w}function tt(w,m,x){return w[0]=m[0]*x,w[1]=m[1]*x,w[2]=m[2]*x,w[3]=m[3]*x,w}function at(w,m){var x=m[0],k=m[1],E=m[2],P=m[3],O=x*x+k*k+E*E+P*P;return O>0&&(O=1/Math.sqrt(O)),w[0]=x*O,w[1]=k*O,w[2]=E*O,w[3]=P*O,w}function Ge(w,m){return w[0]*m[0]+w[1]*m[1]+w[2]*m[2]+w[3]*m[3]}function dt(w,m,x){var k=m[0],E=m[1],P=m[2],O=m[3];return w[0]=x[0]*k+x[4]*E+x[8]*P+x[12]*O,w[1]=x[1]*k+x[5]*E+x[9]*P+x[13]*O,w[2]=x[2]*k+x[6]*E+x[10]*P+x[14]*O,w[3]=x[3]*k+x[7]*E+x[11]*P+x[15]*O,w}function Bt(){var w=new d(4);return d!=Float32Array&&(w[0]=0,w[1]=0,w[2]=0),w[3]=1,w}function kt(w){return w[0]=0,w[1]=0,w[2]=0,w[3]=1,w}function Qt(w,m,x){x*=.5;var k=m[0],E=m[1],P=m[2],O=m[3],U=Math.sin(x),H=Math.cos(x);return w[0]=k*H+O*U,w[1]=E*H+P*U,w[2]=P*H-E*U,w[3]=O*H-k*U,w}function ns(w,m,x){x*=.5;var k=m[0],E=m[1],P=m[2],O=m[3],U=Math.sin(x),H=Math.cos(x);return w[0]=k*H-P*U,w[1]=E*H+O*U,w[2]=P*H+k*U,w[3]=O*H-E*U,w}K(),rt();var $s,Ds,Dt,St=at,$t=($s=K(),Ds=ne(1,0,0),Dt=ne(0,1,0),function(w,m,x){var k=Fe(m,x);return k<-.999999?(qe($s,Ds,m),Ke($s)<1e-6&&qe($s,Dt,m),Ie($s,$s),function(E,P,O){O*=.5;var U=Math.sin(O);E[0]=U*P[0],E[1]=U*P[1],E[2]=U*P[2],E[3]=Math.cos(O)}(w,$s,Math.PI),w):k>.999999?(w[0]=0,w[1]=0,w[2]=0,w[3]=1,w):(qe($s,m,x),w[0]=$s[0],w[1]=$s[1],w[2]=$s[2],w[3]=1+k,St(w,w))});function ht(){var w=new d(2);return d!=Float32Array&&(w[0]=0,w[1]=0),w}function Ut(w,m){var x=new d(2);return x[0]=w,x[1]=m,x}function Es(w,m,x){return w[0]=m,w[1]=x,w}function Xt(w,m,x){return w[0]=m[0]+x[0],w[1]=m[1]+x[1],w}function Ys(w,m,x){return w[0]=m[0]-x[0],w[1]=m[1]-x[1],w}function Ss(w,m,x){return w[0]=m[0]*x,w[1]=m[1]*x,w}function Bs(w){var m=w[0],x=w[1];return Math.sqrt(m*m+x*x)}function Us(w,m){var x=m[0],k=m[1],E=x*x+k*k;return E>0&&(E=1/Math.sqrt(E)),w[0]=m[0]*E,w[1]=m[1]*E,w}function sn(w,m){return w[0]*m[0]+w[1]*m[1]}Bt(),Bt(),h();var Jn,fn,Sn=Ys;function Gn(w){return w&&w.__esModule&&Object.prototype.hasOwnProperty.call(w,"default")?w.default:w}ht();var Hr=function(){if(fn)return Jn;function w(m,x,k,E){this.cx=3*m,this.bx=3*(k-m)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*x,this.by=3*(E-x)-this.cy,this.ay=1-this.cy-this.by,this.p1x=m,this.p1y=x,this.p2x=k,this.p2y=E}return fn=1,Jn=w,w.prototype={sampleCurveX:function(m){return((this.ax*m+this.bx)*m+this.cx)*m},sampleCurveY:function(m){return((this.ay*m+this.by)*m+this.cy)*m},sampleCurveDerivativeX:function(m){return(3*this.ax*m+2*this.bx)*m+this.cx},solveCurveX:function(m,x){if(x===void 0&&(x=1e-6),m<0)return 0;if(m>1)return 1;for(var k=m,E=0;E<8;E++){var P=this.sampleCurveX(k)-m;if(Math.abs(P)P?U=k:H=k,k=.5*(H-U)+U;return k},solve:function(m,x){return this.sampleCurveY(this.solveCurveX(m,x))}},Jn}(),pi=Gn(Hr);function Ms(w,m){this.x=w,this.y=m}function bi(w,m){if(Array.isArray(w)){if(!Array.isArray(m)||w.length!==m.length)return!1;for(let x=0;x=1)return 1;const m=w*w,x=m*w;return 4*(w<.5?x:3*(w-m)+x-.75)}function ts(w,m,x,k){const E=new pi(w,m,x,k);return function(P){return E.solve(P)}}const Oe=ts(.25,.1,.25,1);function Qe(w,m,x){return Math.min(x,Math.max(m,w))}function ct(w,m,x){return(x=Qe((x-w)/(m-w),0,1))*x*(3-2*x)}function vt(w,m,x){const k=x-m,E=((w-m)%k+k)%k+m;return E===m?x:E}function It(w,m,x){if(!w.length)return x(null,[]);let k=w.length;const E=new Array(w.length);let P=null;w.forEach((O,U)=>{m(O,(H,X)=>{H&&(P=H),E[U]=X,--k===0&&x(P,E)})})}let qt=1;function xs(){return qt++}function as(w){return w<=1?1:Math.pow(2,Math.ceil(Math.log2(w)))}function Ns(w,m){w.forEach(x=>{m[x]&&(m[x]=m[x].bind(m))})}function ln(w,m,x){const k={};for(const E in w)k[E]=m.call(this,w[E],E,w);return k}function Ks(w,m,x){const k={};for(const E in w)m.call(this,w[E],E,w)&&(k[E]=w[E]);return k}function Un(w){return Array.isArray(w)?w.map(Un):typeof w=="object"&&w?ln(w,Un):w}function br(w,m){for(let x=0;x=0)return!0;return!1}const Ar={};function sr(w){Ar[w]||(typeof console<"u"&&console.warn(w),Ar[w]=!0)}function Tr(w,m,x){return(x.y-w.y)*(m.x-w.x)>(m.y-w.y)*(x.x-w.x)}function Ot(w){let m=0;for(let x,k,E=0,P=w.length,O=P-1;E@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(x,k,E,P)=>{const O=E||P;return m[k]=!O||O.toLowerCase(),""}),m["max-age"]){const x=parseInt(m["max-age"],10);isNaN(x)?delete m["max-age"]:m["max-age"]=x}return m}let Jr,jr=null;function qn(w,m){return[w[4*m],w[4*m+1],w[4*m+2],w[4*m+3]]}function wi(w,m,x,k){for(;m>1;w[E]>1;w[E]<=k?m=E+1:x=E}return m}function ea(w){return w>0?1/(1.001-w):1+w}function ya(w){return w>0?1-1/(1.001-w):-w}function Mi(w,m,x){return(w-m.min)*(x.max-x.min)/(m.max-m.min)+x.min}const da={API_URL:"https://api.mapbox.com",get API_URL_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i},get API_TILEJSON_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/v[0-9]*\/.*\.json.*$)/i},get API_SPRITE_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*\/sprite.*\..*$)/i},get API_FONTS_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/fonts\/v[0-9]*\/)(.*\.pbf.*$)/i},get API_STYLE_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*$)/i},get API_CDN_URL_REGEX(){return/^((https?:)?\/\/)?api\.mapbox\.c(n|om)(\/mapbox-gl-js\/)(.*$)/i},get EVENTS_URL(){if(!da.API_URL)return null;try{const w=new URL(da.API_URL);return w.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":w.hostname==="api.mapbox.com"?"https://events.mapbox.com/events/v2":null}catch{return null}},SESSION_PATH:"/map-sessions/v1",FEEDBACK_URL:"https://apps.mapbox.com/feedback",TILE_URL_VERSION:"v4",RASTER_URL_PREFIX:"raster/v1",RASTERARRAYS_URL_PREFIX:"rasterarrays/v1",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,DEFAULT_STYLE:"mapbox://styles/mapbox/standard",MAX_PARALLEL_IMAGE_REQUESTS:16,DRACO_URL:"/mapbox-gl-js/draco_decoder_gltf_v1.5.6.wasm",MESHOPT_URL:"/mapbox-gl-js/meshopt_base_v0.20.wasm",MESHOPT_SIMD_URL:"/mapbox-gl-js/meshopt_simd_v0.20.wasm",BUILDING_GEN_URL:"/mapbox-gl-js/building-gen/building_gen_v1.2.4.wasm",GLYPHS_URL:"mapbox://fonts/mapbox/{fontstack}/{range}.pbf",TILES3D_URL_PREFIX:"3dtiles/v1",TILE_PROVIDER_URLS:Object.assign(Object.create(null),{pmtiles:"/mapbox-gl-js/mapbox-gl-pmtiles-provider-v0.0.1.js"})};function jn(){return new URL(da.DRACO_URL,da.API_URL).href}function Aa(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(Jr===void 0){if(typeof WebAssembly!="object")return!1;const w=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]);Jr=WebAssembly.validate(w)}return Jr}()?da.MESHOPT_SIMD_URL:da.MESHOPT_URL,da.API_URL).href}function Yi(){return new URL(da.BUILDING_GEN_URL,da.API_URL).href}function Bo(w){return da.API_URL_REGEX.test(w)}function rl(w){return da.API_SPRITE_REGEX.test(w)}let po,zc,Sd,fm,Cd,Hd;function uc(){return po==null&&(po=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),po}const Gd={now:()=>fm!==void 0?fm:performance.now(),setNow(w){fm=w},restoreNow(){fm=void 0},frame(w){const m=requestAnimationFrame(w);return{cancel:()=>cancelAnimationFrame(m)}},getImageData(w,m=0){const{width:x,height:k}=w;Cd||(Cd=document.createElement("canvas"));const E=Cd.getContext("2d",{willReadFrequently:!0});if(!E)throw new Error("failed to create canvas 2d context");return(x>Cd.width||k>Cd.height)&&(Cd.width=x,Cd.height=k),E.clearRect(-m,-m,x+2*m,k+2*m),E.drawImage(w,0,0,x,k),E.getImageData(-m,-m,x+2*m,k+2*m)},resolveURL:w=>(zc||(zc=document.createElement("a")),zc.href=w,zc.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(Sd==null&&(Sd=window.matchMedia("(prefers-reduced-motion: reduce)")),Sd.matches)},hasCanvasFingerprintNoise(){if(Hd!==void 0)return Hd;if(!uc())return Hd=!1,!1;const w=new OffscreenCanvas(85,1),m=w.getContext("2d",{willReadFrequently:!0});let x=0;for(let E=0;E0?`?${P}`:""}`}const xm="mapbox-tiles";let Iy=500,Py=50;const Ef=["language","worldview","jobid"];let _h;function px(){try{return caches}catch{}}function fo(){const w=px();w&&_h==null&&(_h=w.open(xm))}let Vb=1/0;const gm={supported:!1,testSupport:function(w){!Yu&&fx&&(al?vu(w):$h=w)}};let $h,fx,Yu=!1,al=!1;const u0=typeof self<"u"?self:{};function vu(w){const m=w.createTexture();w.bindTexture(w.TEXTURE_2D,m);try{if(w.texImage2D(w.TEXTURE_2D,0,w.RGBA,w.RGBA,w.UNSIGNED_BYTE,fx),w.isContextLost())return;gm.supported=!0}catch{}w.deleteTexture(m),Yu=!0}u0.document&&(fx=u0.document.createElement("img"),fx.onload=function(){$h&&vu($h),$h=null,al=!0},fx.onerror=function(){Yu=!0,$h=null},fx.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const h0={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(h0);class cj extends Error{constructor(m,x,k){x===401&&Bo(k)&&(m+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(m),this.status=x,this.url=k}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function Af(w){return typeof w=="object"&&w!==null&&"status"in w&&w.status===404}const Xa=kr()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Ly=function(w,m){return/^file:/.test(x=w.url)||/^file:/.test(Xa())&&!/^\w+:/.test(x)?function(k,E){const P=new XMLHttpRequest;P.open(k.method||"GET",k.url,!0),k.type==="arrayBuffer"&&(P.responseType="arraybuffer");for(const O in k.headers)P.setRequestHeader(O,k.headers[O]);return k.type==="json"&&(P.responseType="text",P.setRequestHeader("Accept","application/json")),P.withCredentials=k.credentials==="include",P.onerror=()=>{E(new Error(P.statusText))},P.onload=()=>{if((P.status>=200&&P.status<300||P.status===0)&&P.response!==null){let O=P.response;if(k.type==="json")try{O=JSON.parse(P.response)}catch(H){return E(H)}const U=new Headers;P.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(H=>{const X=H.split(": "),le=X.shift(),he=X.join(": ");U.append(le,he)}),E(null,O,U)}else E(new cj(P.statusText,P.status,k.url))},P.send(k.body),{cancel:()=>P.abort()}}(w,m):function(k,E){const P=new AbortController,O=new Request(k.url,{method:k.method||"GET",body:k.body,credentials:k.credentials,headers:k.headers,referrer:Xa(),referrerPolicy:k.referrerPolicy,signal:P.signal});let U=!1,H=!1;const X=(le=O.url).indexOf("sku=")>0&&Bo(le);var le;k.type==="json"&&O.headers.set("Accept","application/json");const he=(be,Se,Pe)=>{if(H)return;if(be&&be.message!=="SecurityError"&&sr(be.toString()),Se&&Pe)return me(Se);const Be=Date.now();fetch(O).then(We=>{if(We.ok){const ot=X?We.clone():null;return me(We,ot,Be)}return E(new cj(We.statusText,We.status,k.url))}).catch(We=>{We.name!=="AbortError"&&E(new Error(`${We.message} ${k.url}`))})},me=(be,Se,Pe)=>{(k.type==="arrayBuffer"?be.arrayBuffer():k.type==="json"?be.json():be.text()).then(Be=>{H||(Se&&Pe&&function(We,ot,nt){if(fo(),_h==null)return;const ft=dr(ot.headers.get("cache-control")||"");if(ft["no-store"])return;const bt={status:ot.status,statusText:ot.statusText,headers:new Headers};ot.headers.forEach((Vt,Ht)=>bt.headers.set(Ht,Vt)),ft["max-age"]&&bt.headers.set("Expires",new Date(nt+1e3*ft["max-age"]).toUTCString());const wt=bt.headers.get("expires");if(!wt||new Date(wt).getTime()-nt<42e4)return;let Yt=lj(We.url,{persistentParams:Ef});if(ot.status===206){const Vt=We.headers.get("Range");if(!Vt)return;bt.status=200,Yt=i1(Yt,{range:Vt})}const zt=new Response((Kt=ot.status)!==200&&Kt!==404&&[101,103,204,205,304].includes(Kt)?null:ot.body,bt);var Kt;fo(),_h!=null&&_h.then(Vt=>Vt.put(Yt,zt)).catch(Vt=>sr(Vt.message))}(O,Se,Pe),U=!0,E(null,Be,be.headers))}).catch(Be=>{H||E(new Error(Be.message))})};return X?function(be,Se){if(fo(),_h==null)return Se(null);_h.then(Pe=>{let Be=lj(be.url,{persistentParams:Ef});const We=be.headers.get("Range");We&&(Be=i1(Be,{range:We})),Pe.match(Be).then(ot=>{const nt=function(ft){if(!ft)return!1;const bt=new Date(ft.headers.get("expires")||0),wt=dr(ft.headers.get("cache-control")||"");return Number(bt)>Date.now()&&!wt["no-cache"]}(ot);Pe.delete(Be).catch(Se),nt&&Pe.put(Be,ot.clone()).catch(Se),Se(null,ot,nt)}).catch(Se)}).catch(Se)}(O,he):he(null,null),{cancel:()=>{H=!0,U||P.abort()}}}(w,m);var x},Dy=function(w,m){return Ly(Object.assign(w,{type:"arrayBuffer"}),m)};function Jm(w){const m=document.createElement("a");return m.href=w,m.protocol===location.protocol&&m.host===location.host}let ep,Dp;ep=[],Dp=0;const xx=function(w,m){if(gm.supported&&(w.headers||(w.headers={}),w.headers.accept="image/webp,*/*"),Dp>=da.MAX_PARALLEL_IMAGE_REQUESTS){const P={requestParameters:w,callback:m,cancelled:!1,cancel(){this.cancelled=!0}};return ep.push(P),P}Dp++;let x=!1;const k=()=>{if(!x)for(x=!0,Dp--;ep.length&&Dp{k(),P?m(P):O&&function(H,X){const le=new Blob([new Uint8Array(H)],{type:"image/png"});createImageBitmap(le).then(he=>{X(null,he)}).catch(he=>{X(new Error(`Could not load image because of ${he.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(O,(H,X)=>m(H,X,U))});return{cancel:()=>{E.cancel(),k()}}};var hg,Hb,Rp,tp={exports:{}},Mf={exports:{}},Ry={exports:{}},Gb=function(){if(Rp)return tp.exports;Rp=1;var w=(hg||(hg=1,Mf.exports=function(x,k){var E,P,O,U,H,X,le,he;for(P=x.length-(E=3&x.length),O=k,H=3432918353,X=461845907,he=0;he>>16)*H&65535)<<16)&4294967295)<<15|le>>>17))*X+(((le>>>16)*X&65535)<<16)&4294967295)<<13|O>>>19))+((5*(O>>>16)&65535)<<16)&4294967295))+(((U>>>16)+58964&65535)<<16);switch(le=0,E){case 3:le^=(255&x.charCodeAt(he+2))<<16;case 2:le^=(255&x.charCodeAt(he+1))<<8;case 1:O^=le=(65535&(le=(le=(65535&(le^=255&x.charCodeAt(he)))*H+(((le>>>16)*H&65535)<<16)&4294967295)<<15|le>>>17))*X+(((le>>>16)*X&65535)<<16)&4294967295}return O^=x.length,O=2246822507*(65535&(O^=O>>>16))+((2246822507*(O>>>16)&65535)<<16)&4294967295,O=3266489909*(65535&(O^=O>>>13))+((3266489909*(O>>>16)&65535)<<16)&4294967295,(O^=O>>>16)>>>0}),Mf.exports),m=(Hb||(Hb=1,Ry.exports=function(x,k){for(var E,P=x.length,O=k^P,U=0;P>=4;)E=1540483477*(65535&(E=255&x.charCodeAt(U)|(255&x.charCodeAt(++U))<<8|(255&x.charCodeAt(++U))<<16|(255&x.charCodeAt(++U))<<24))+((1540483477*(E>>>16)&65535)<<16),O=1540483477*(65535&O)+((1540483477*(O>>>16)&65535)<<16)^(E=1540483477*(65535&(E^=E>>>24))+((1540483477*(E>>>16)&65535)<<16)),P-=4,++U;switch(P){case 3:O^=(255&x.charCodeAt(U+2))<<16;case 2:O^=(255&x.charCodeAt(U+1))<<8;case 1:O=1540483477*(65535&(O^=255&x.charCodeAt(U)))+((1540483477*(O>>>16)&65535)<<16)}return O=1540483477*(65535&(O^=O>>>13))+((1540483477*(O>>>16)&65535)<<16),(O^=O>>>15)>>>0}),Ry.exports);return tp.exports=w,tp.exports.murmur3=w,tp.exports.murmur2=m,tp.exports}(),Td=Gn(Gb);class Bc{constructor(m,...x){Object.assign(this,x[0]||{}),this.type=m}}class sp extends Bc{constructor(m,x={}){super("error",Object.assign({error:m},x))}}function Zc(w,m,x){x[w]&&x[w].indexOf(m)!==-1||(x[w]=x[w]||[],x[w].push(m))}function np(w,m,x){if(x&&x[w]){const k=x[w].indexOf(m);k!==-1&&x[w].splice(k,1)}}class Op{on(m,x){return this._listeners=this._listeners||{},Zc(m,x,this._listeners),this}off(m,x){return np(m,x,this._listeners),np(m,x,this._oneTimeListeners),this}once(m,x){return x?(this._oneTimeListeners=this._oneTimeListeners||{},Zc(m,x,this._oneTimeListeners),this):new Promise(k=>{this.once(m,k)})}fire(m,x){const k=typeof m=="string"?new Bc(m,x):m,E=k.type;if(this.listens(E)){k.target=this;const P=this._listeners&&this._listeners[E]?this._listeners[E].slice():[];for(const H of P)H.call(this,k);const O=this._oneTimeListeners&&this._oneTimeListeners[E]?this._oneTimeListeners[E].slice():[];for(const H of O)np(E,H,this._oneTimeListeners),H.call(this,k);const U=this._eventedParent;if(U){const H=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(k,H),U.fire(k)}}else k instanceof sp&&console.error(k.error);return this}listens(m){return!!(this._listeners&&this._listeners[m]&&this._listeners[m].length>0||this._oneTimeListeners&&this._oneTimeListeners[m]&&this._oneTimeListeners[m].length>0||this._eventedParent&&this._eventedParent.listens(m))}setEventedParent(m,x){return this._eventedParent=m,this._eventedParentData=x,this}}class Lt{constructor(m){typeof m=="string"?this.name=m:(this.name=m.name,this.iconsetId=m.iconsetId)}static from(m){return new Lt(m)}static toString(m){return m.iconsetId?`${m.name}${m.iconsetId}`:m.name}static parse(m){const[x,k]=m.split("");return new Lt({name:x,iconsetId:k})}static isEqual(m,x){return m.name===x.name&&m.iconsetId===x.iconsetId}toString(){return Lt.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var hn,zn={},Or=function(){if(hn)return zn;hn=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 m(P){return(P=Math.round(P))<0?0:P>255?255:P}function x(P){return m(P[P.length-1]==="%"?parseFloat(P)/100*255:parseInt(P))}function k(P){return(O=P[P.length-1]==="%"?parseFloat(P)/100:parseFloat(P))<0?0:O>1?1:O;var O}function E(P,O,U){return U<0?U+=1:U>1&&(U-=1),6*U<1?P+(O-P)*U*6:2*U<1?O:3*U<2?P+(O-P)*(2/3-U)*6:P}try{zn.parseCSSColor=function(P){var O,U=P.replace(/ /g,"").toLowerCase();if(U in w)return w[U].slice();if(U[0]==="#")return U.length===4?(O=parseInt(U.substr(1),16))>=0&&O<=4095?[(3840&O)>>4|(3840&O)>>8,240&O|(240&O)>>4,15&O|(15&O)<<4,1]:null:U.length===7&&(O=parseInt(U.substr(1),16))>=0&&O<=16777215?[(16711680&O)>>16,(65280&O)>>8,255&O,1]:null;var H=U.indexOf("("),X=U.indexOf(")");if(H!==-1&&X+1===U.length){var le=U.substr(0,H),he=U.substr(H+1,X-(H+1)).split(","),me=1;switch(le){case"rgba":if(he.length!==4)return null;me=k(he.pop());case"rgb":return he.length!==3?null:[x(he[0]),x(he[1]),x(he[2]),me];case"hsla":if(he.length!==4)return null;me=k(he.pop());case"hsl":if(he.length!==3)return null;var be=(parseFloat(he[0])%360+360)%360/360,Se=k(he[1]),Pe=k(he[2]),Be=Pe<=.5?Pe*(Se+1):Pe+Se-Pe*Se,We=2*Pe-Be;return[m(255*E(We,Be,be+1/3)),m(255*E(We,Be,be)),m(255*E(We,Be,be-1/3)),me];default:return null}}return null}}catch{}return zn}();class Wn{constructor(m,x,k,E=1){this.r=m,this.g=x,this.b=k,this.a=E}static parse(m){if(!m)return;if(m instanceof Wn)return m;if(typeof m!="string")return;const x=Or.parseCSSColor(m);return x?new Wn(x[0]/255,x[1]/255,x[2]/255,x[3]):void 0}toString(){const[m,x,k,E]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*m)},${Math.round(255*x)},${Math.round(255*k)},${E})`}toNonPremultipliedRenderColor(m){const{r:x,g:k,b:E,a:P}=this;return new Ja(m,x,k,E,P)}toPremultipliedRenderColor(m){const{r:x,g:k,b:E,a:P}=this;return new oi(m,x*P,k*P,E*P,P)}clone(){return new Wn(this.r,this.g,this.b,this.a)}}class va{constructor(m,x,k,E,P,O=!1){if(this.premultiplied=!1,this.premultiplied=O,m){const U=m.image.height,H=U*U;this.premultiplied?(x=P===0?0:x/P*(U-1),k=P===0?0:k/P*(U-1),E=P===0?0:E/P*(U-1)):(x*=U-1,k*=U-1,E*=U-1),x=Math.max(0,Math.min(U-1,x)),k=Math.max(0,Math.min(U-1,k)),E=Math.max(0,Math.min(U-1,E));const X=Math.floor(x),le=Math.floor(k),he=Math.floor(E),me=Math.ceil(x),be=Math.ceil(k),Se=Math.ceil(E),Pe=x-X,Be=k-le,We=E-he,ot=m.image.data,nt=4*(X+le*H+he*U),ft=4*(X+le*H+Se*U),bt=4*(X+be*H+he*U),wt=4*(X+be*H+Se*U),Yt=4*(me+le*H+he*U),zt=4*(me+le*H+Se*U),Kt=4*(me+be*H+he*U),Vt=4*(me+be*H+Se*U);this.r=Br(Br(Br(ot[nt],ot[ft],We),Br(ot[bt],ot[wt],We),Be),Br(Br(ot[Yt],ot[zt],We),Br(ot[Kt],ot[Vt],We),Be),Pe)/255*(this.premultiplied?P:1),this.g=Br(Br(Br(ot[nt+1],ot[ft+1],We),Br(ot[bt+1],ot[wt+1],We),Be),Br(Br(ot[Yt+1],ot[zt+1],We),Br(ot[Kt+1],ot[Vt+1],We),Be),Pe)/255*(this.premultiplied?P:1),this.b=Br(Br(Br(ot[nt+2],ot[ft+2],We),Br(ot[bt+2],ot[wt+2],We),Be),Br(Br(ot[Yt+2],ot[zt+2],We),Br(ot[Kt+2],ot[Vt+2],We),Be),Pe)/255*(this.premultiplied?P:1),this.a=P}else this.r=x,this.g=k,this.b=E,this.a=P}toArray(){const{r:m,g:x,b:k,a:E}=this;return[255*m,255*x,255*k,E]}toHslaArray(){let{r:m,g:x,b:k,a:E}=this;if(this.premultiplied){if(E===0)return[0,0,0,0];const Se=1/E;m*=Se,x*=Se,k*=Se}const P=Math.min(Math.max(m,0),1),O=Math.min(Math.max(x,0),1),U=Math.min(Math.max(k,0),1),H=Math.min(P,O,U),X=Math.max(P,O,U),le=X-H,he=.5*(H+X);if(le===0)return[0,0,100*he,E];const me=he>.5?le/(2-X-H):le/(X+H);let be;switch(X){case P:be=60*((O-U)/le+(OBr(k,m[E],x))}Wn.black=new Wn(0,0,0,1),Wn.white=new Wn(1,1,1,1),Wn.transparent=new Wn(0,0,0,0),Wn.red=new Wn(1,0,0,1),Wn.blue=new Wn(0,0,1,1);var ym=Object.freeze({__proto__:null,array:Ed,color:function(w,m,x){return new Wn(Br(w.r,m.r,x),Br(w.g,m.g,x),Br(w.b,m.b,x),Br(w.a,m.a,x))},number:Br});class Zu extends Error{constructor(m,x){super(x),this.message=x,this.key=m}}class mg{constructor(m,x=[]){this.parent=m,this.bindings={};for(const[k,E]of x)this.bindings[k]=E}concat(m){return new mg(this,m)}get(m){if(this.bindings[m])return this.bindings[m];if(this.parent)return this.parent.get(m);throw new Error(`${m} not found in scope.`)}has(m){return!!this.bindings[m]||!!this.parent&&this.parent.has(m)}}const If={kind:"null"},Mr={kind:"number"},Ii={kind:"string"},Zi={kind:"boolean"},Uh={kind:"color"},gx={kind:"object"},to={kind:"value"},yx={kind:"collator"},Oy={kind:"formatted"},Wb={kind:"resolvedImage"};function Qu(w,m){return{kind:"array",itemType:w,N:m}}function Ol(w){if(w.kind==="array"){const m=Ol(w.itemType);return typeof w.N=="number"?`array<${m}, ${w.N}>`:w.itemType.kind==="value"?"array":`array<${m}>`}return w.kind}const x6=[If,Mr,Ii,Zi,Uh,Oy,gx,Qu(to),Wb];function Fy(w,m){if(m.kind==="error")return null;if(w.kind==="array"){if(m.kind==="array"&&(m.N===0&&m.itemType.kind==="value"||!Fy(w.itemType,m.itemType))&&(typeof w.N!="number"||w.N===m.N))return null}else{if(w.kind===m.kind)return null;if(w.kind==="value"){for(const x of x6)if(!Fy(x,m))return null}}return`Expected ${Ol(w)} but found ${Ol(m)} instead.`}function Kb(w,m){return m.some(x=>x.kind===w.kind)}function vx(w,m){return m.some(x=>x==="null"?w===null:x==="array"?Array.isArray(w):x==="object"?w&&!Array.isArray(w)&&typeof w=="object":x===typeof w)}function bx(w,m){return w.kind==="array"&&m.kind==="array"?w.N===m.N&&bx(w.itemType,m.itemType):w.kind===m.kind}class dj{constructor(m,x,k){this.sensitivity=m?x?"variant":"case":x?"accent":"base",this.locale=k,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(m,x){return this.collator.compare(m,x)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class Yb{constructor(m,x,k,E,P){this.text=m.normalize?m.normalize():m,this.image=x,this.scale=k,this.fontStack=E,this.textColor=P}}class Wd{constructor(m){this.sections=m}static fromString(m){return new Wd([new Yb(m,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(m=>m.text.length!==0||!!m.image&&m.image.hasPrimary())}static factory(m){return m instanceof Wd?m:Wd.fromString(m)}toString(){return this.sections.length===0?"":this.sections.map(m=>m.text).join("")}serialize(){const m=["format"];for(const x of this.sections){if(x.image){const E=x.image.getPrimary().id.toString();m.push(["image",E]);continue}m.push(x.text);const k={};x.fontStack&&(k["text-font"]=["literal",x.fontStack.split(",")]),x.scale&&(k["font-scale"]=x.scale),x.textColor&&(k["text-color"]=["rgba"].concat(x.textColor.toNonPremultipliedRenderColor(null).toArray())),m.push(k)}return m}}class rp{constructor(m,x={}){this.id=Lt.from(m),this.params=x.params,this.sx=x.sx||1,this.sy=x.sy||1}toString(){return JSON.stringify(this)}static parse(m){let x,k,E,P;try{({id:x,params:k,sx:E,sy:P}=JSON.parse(m)||{})}catch{return null}return x?new rp(x,{params:k,sx:E,sy:P}):null}scaleSelf(m,x=m){return this.sx*=m,this.sy*=x,this}}class Kd{constructor(m,x,k,E,P=!1){this.primaryId=Lt.from(m),this.primaryOptions=x,k&&(this.secondaryId=Lt.from(k)),this.secondaryOptions=E,this.available=P}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new rp(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new rp(this.secondaryId,this.secondaryOptions):null}static from(m){return typeof m=="string"?Kd.build({name:m}):m}static build(m,x,k,E){return!m||typeof m=="object"&&!("name"in m)?null:new Kd(m,k,x,E)}}function Fp(w,m,x,k){return typeof w=="number"&&w>=0&&w<=255&&typeof m=="number"&&m>=0&&m<=255&&typeof x=="number"&&x>=0&&x<=255?k===void 0||typeof k=="number"&&k>=0&&k<=1?null:`Invalid rgba value [${[w,m,x,k].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof k=="number"?[w,m,x,k]:[w,m,x]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Pf(w){if(w===null||typeof w=="string"||typeof w=="boolean"||typeof w=="number"||w instanceof Wn||w instanceof dj||w instanceof Wd||w instanceof Kd)return!0;if(Array.isArray(w)){for(const m of w)if(!Pf(m))return!1;return!0}if(typeof w=="object"){for(const m in w)if(!Pf(w[m]))return!1;return!0}return!1}function Ml(w){if(w===null)return If;if(typeof w=="string")return Ii;if(typeof w=="boolean")return Zi;if(typeof w=="number")return Mr;if(w instanceof Wn)return Uh;if(w instanceof dj)return yx;if(w instanceof Wd)return Oy;if(w instanceof Kd)return Wb;if(Array.isArray(w)){const m=w.length;let x;for(const k of w){const E=Ml(k);if(x){if(x===E)continue;x=to;break}x=E}return Qu(x||to,m)}return gx}function na(w){const m=typeof w;return w===null?"":m==="string"||m==="number"||m==="boolean"?String(w):w instanceof Wd||w instanceof Kd||w instanceof Wn?w.toString():JSON.stringify(w)}class rr{constructor(m,x){this.type=m,this.value=x}static parse(m,x){if(m.length!==2)return x.error(`'literal' expression requires exactly one argument, but found ${m.length-1} instead.`);if(!Pf(m[1]))return x.error("invalid value");const k=m[1];let E=Ml(k);const P=x.expectedType;return E.kind!=="array"||E.N!==0||!P||P.kind!=="array"||typeof P.N=="number"&&P.N!==0||(E=P),new rr(E,k)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Wn?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Wd?this.value.serialize():this.value}}class vl{constructor(m){this.name="ExpressionEvaluationError",this.message=m}toJSON(){return this.message}}const la={string:Ii,number:Mr,boolean:Zi,object:gx};class ap{constructor(m,x){this.type=m,this.args=x}static parse(m,x){if(m.length<2)return x.error("Expected at least one argument.");let k,E=1;const P=m[0];if(P==="array"){let U,H;if(m.length>2){const X=m[1];if(typeof X!="string"||!(X in la)||X==="object")return x.error('The item type argument of "array" must be one of string, number, boolean',1);U=la[X],E++}else U=to;if(m.length>3){if(m[2]!==null&&(typeof m[2]!="number"||m[2]<0||m[2]!==Math.floor(m[2])))return x.error('The length argument to "array" must be a positive integer literal',2);H=m[2],E++}k=Qu(U,H)}else k=la[P];const O=[];for(;Em.outputDefined())}serialize(){const m=this.type,x=[m.kind];if(m.kind==="array"){const k=m.itemType;if(k.kind==="string"||k.kind==="number"||k.kind==="boolean"){x.push(k.kind);const E=m.N;(typeof E=="number"||this.args.length>1)&&x.push(E)}}return x.concat(this.args.map(k=>k.serialize()))}}class vm{constructor(m){this.type=Oy,this.sections=m}static parse(m,x){if(m.length<2)return x.error("Expected at least one argument.");const k=m[1];if(!Array.isArray(k)&&typeof k=="object")return x.error("First argument must be an image or text section.");const E=[];let P=!1;for(let O=1;O<=m.length-1;++O){const U=m[O];if(P&&typeof U=="object"&&!Array.isArray(U)){P=!1;let H=null;if(U["font-scale"]&&(H=x.parseObjectValue(U["font-scale"],O,"font-scale",Mr),!H))return null;let X=null;if(U["text-font"]&&(X=x.parseObjectValue(U["text-font"],O,"text-font",Qu(Ii)),!X))return null;let le=null;if(U["text-color"]&&(le=x.parseObjectValue(U["text-color"],O,"text-color",Uh),!le))return null;const he=E[E.length-1];he.scale=H,he.font=X,he.textColor=le}else{const H=x.parse(m[O],O,to);if(!H)return null;const X=H.type.kind;if(X!=="string"&&X!=="value"&&X!=="null"&&X!=="resolvedImage")return x.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");P=!0,E.push({content:H,scale:null,font:null,textColor:null})}}return new vm(E)}evaluate(m){return new Wd(this.sections.map(x=>{const k=x.content.evaluate(m);return bx(Ml(k),Wb)?new Yb("",k,null,null,null):new Yb(na(k),null,x.scale?x.scale.evaluate(m):null,x.font?x.font.evaluate(m).join(","):null,x.textColor?x.textColor.evaluate(m):null)}))}eachChild(m){for(const x of this.sections)m(x.content),x.scale&&m(x.scale),x.font&&m(x.font),x.textColor&&m(x.textColor)}outputDefined(){return!1}serialize(){const m=["format"];for(const x of this.sections){m.push(x.content.serialize());const k={};x.scale&&(k["font-scale"]=x.scale.serialize()),x.font&&(k["text-font"]=x.font.serialize()),x.textColor&&(k["text-color"]=x.textColor.serialize()),m.push(k)}return m}}class Fr{constructor(m,x,k,E){this._imageWarnHistory={},this.type=Wb,this.namePrimary=m,this.nameSecondary=x,k&&(this.paramsPrimary=k.params,this.iconsetIdPrimary=k.iconset?k.iconset.id:void 0),E&&(this.paramsSecondary=E.params,this.iconsetIdSecondary=E.iconset?E.iconset.id:void 0)}static parse(m,x){if(m.length<2)return x.error("Expected two or more arguments.");let k=1;const E=[];function P(){if(kLt.isEqual(O,P)),E.available){const O=E.getSecondary()?E.getSecondary().id:null;O&&(E.available=m.availableImages.some(U=>Lt.isEqual(U,O)))}}return E}eachChild(m){if(m(this.namePrimary),this.paramsPrimary)for(const x in this.paramsPrimary)this.paramsPrimary[x]&&m(this.paramsPrimary[x]);if(this.nameSecondary&&(m(this.nameSecondary),this.paramsSecondary))for(const x in this.paramsSecondary)this.paramsSecondary[x]&&m(this.paramsSecondary[x])}outputDefined(){return!1}serializeOptions(m,x){const k={};if(x&&(k.iconset={id:x}),m){k.params={};for(const E in m)m[E]&&(k.params[E]=m[E].serialize())}return Object.keys(k).length>0?k:void 0}serialize(){const m=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const x=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);x&&m.push(x)}if(this.nameSecondary&&(m.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const x=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);x&&m.push(x)}return m}}function zy(w){return o1(w)?"string":Zb(w)?"number":m0(w)?"boolean":Array.isArray(w)?"array":w===null?"null":uj(w)?"object":typeof w}function uj(w){return w!=null&&!Array.isArray(w)&&typeof w!="function"&&!(w instanceof String||w instanceof Number||w instanceof Boolean)&&typeof w=="object"}function o1(w){return typeof w=="string"||w instanceof String}function Zb(w){return typeof w=="number"||w instanceof Number}function m0(w){return typeof w=="boolean"||w instanceof Boolean}const Lf={"to-boolean":Zi,"to-color":Uh,"to-number":Mr,"to-string":Ii};class bm{constructor(m,x){this.type=m,this.args=x}static parse(m,x){if(m.length<2)return x.error("Expected at least one argument.");const k=m[0],E=[];let P=If;if(k==="to-array"){if(!Array.isArray(m[1]))return null;const O=m[1].length;if(x.expectedType){if(x.expectedType.kind!=="array")return x.error(`Expected ${x.expectedType.kind} but found array.`);P=Qu(x.expectedType.itemType,O)}else{if(!(O>0&&Pf(m[1][0])))return null;P=Qu(Ml(m[1][0]),O)}for(let U=0;U4?`Invalid rbga value ${JSON.stringify(x)}: expected an array containing either three or four numeric values.`:Fp(x[0],x[1],x[2],x[3]),!k))return new Wn(x[0]/255,x[1]/255,x[2]/255,x[3])}throw new vl(k||`Could not parse color from value '${typeof x=="string"?x:String(JSON.stringify(x))}'`)}if(this.type.kind==="number"){let x=null;for(const k of this.args){if(x=k.evaluate(m),x===null)return 0;const E=Number(x);if(!isNaN(E))return E}throw new vl(`Could not convert ${JSON.stringify(x)} to number.`)}return this.type.kind==="formatted"?Wd.fromString(na(this.args[0].evaluate(m))):this.type.kind==="resolvedImage"?Kd.build(na(this.args[0].evaluate(m))):this.type.kind==="array"?this.args.map(x=>x.evaluate(m)):na(this.args[0].evaluate(m))}eachChild(m){this.args.forEach(m)}outputDefined(){return this.args.every(m=>m.outputDefined())}serialize(){if(this.type.kind==="formatted")return new vm([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new Fr(this.args[0]).serialize();const m=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(x=>{m.push(x.serialize())}),m}}const Df=["Unknown","Point","LineString","Polygon"];class ip{constructor(m,x,k){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=m,this.options=x,this.iconImageUseTheme=k}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?Df[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}measureLight(m){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const m=this.featureDistanceData.center,x=this.featureDistanceData.scale,{x:k,y:E}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(k*x-m[0])+this.featureDistanceData.bearing[1]*(E*x-m[1])}return 0}parseColor(m){let x=this._parseColorCache[m];return x||(x=this._parseColorCache[m]=Wn.parse(m)),x}getConfig(m){return this.options?this.options.get(m):null}}class $c{constructor(m,x,k,E,P){this.name=m,this.type=x,this._evaluate=k,this.args=E,this._overloadIndex=P}evaluate(m){if(!this._evaluate){const x=$c.definitions[this.name];this._evaluate=Array.isArray(x)?x[2]:x.overloads[this._overloadIndex][1]}return this._evaluate(m,this.args)}eachChild(m){this.args.forEach(m)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(m=>m.serialize()))}static parse(m,x){const k=m[0],E=$c.definitions[k];if(!E)return x.error(`Unknown expression "${k}". If you wanted a literal array, use ["literal", [...]].`,0);const P=Array.isArray(E)?E[0]:E.type,O=Array.isArray(E)?[[E[1],E[2]]]:E.overloads,U=[];let H=null,X=-1;for(const[le,he]of O){if(Array.isArray(le)&&le.length!==m.length-1)continue;U.push(le),X++,H=new jj(x.registry,x.path,null,x.scope,void 0,x._scope,x.options,x.iconImageUseTheme);const me=[];let be=!1;for(let Se=1;Seme)).map(zp).join(" | "),he=[];for(let me=1;mex;){if(k-x>600){const H=k-x+1,X=m-x+1,le=Math.log(H),he=.5*Math.exp(2*le/3),me=.5*Math.sqrt(le*he*(H-he)/H)*(X-H/2<0?-1:1);LN(w,m,Math.max(x,Math.floor(m-X*he/H+me)),Math.min(k,Math.floor(m+(H-X)*he/H+me)),E)}const P=w[m];let O=x,U=k;for(ec(w,x,m),E(w[k],P)>0&&ec(w,x,k);O0;)U--}E(w[x],P)===0?ec(w,x,U):(U++,ec(w,U,k)),U<=m&&(x=U+1),m<=U&&(k=U-1)}}function ec(w,m,x){const k=w[m];w[m]=w[x],w[x]=k}function l1(w,m){return wm?1:0}function DN(w){let m=0;for(let x,k,E=0,P=w.length,O=P-1;E=m[2]||w[1]<=m[1]||w[3]>=m[3])}function gC(w,m,x){const k=w[0]-m[0],E=w[1]-m[1],P=w[0]-x[0],O=w[1]-x[1];return k*O-P*E===0&&k*P<=0&&E*O<=0}function p0(w,m,x){return m[1]>w[1]!=x[1]>w[1]&&w[0]<(x[0]-m[0])*(w[1]-m[1])/(x[1]-m[1])+m[0]}function Wl(w,m,x=!1){let k=!1;for(let E=0,P=m.length;E0&&U<0||O<0&&U>0}function ld(w,m,x,k){return(E=[k[0]-x[0],k[1]-x[1]])[0]*(P=[m[0]-w[0],m[1]-w[1]])[1]-E[1]*P[0]!==0&&!(!Yd(w,m,x,k)||!Yd(x,k,w,m));var E,P}function Qb(w){const m=new Ms(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),x=new Ms(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const k of w[0])m.x>k.x&&(m.x=k.x),m.y>k.y&&(m.y=k.y),x.xx[2]){const E=.5*k;let P=w[0]-x[0]>E?-k:x[0]-w[0]>E?k:0;P===0&&(P=w[0]-x[2]>E?-k:x[2]-w[0]>E?k:0),w[0]+=P}Bp(m,w)}function d1(w,m,x,k){const E=Math.pow(2,k.z)*Rf,P=[k.x*Rf,k.y*Rf],O=[];if(!w)return O;for(const U of w)for(const H of U){const X=[H.x+P[0],H.y+P[1]];Qc(X,m,x,E),O.push(X)}return O}function fj(w,m,x,k){const E=Math.pow(2,k.z)*Rf,P=[k.x*Rf,k.y*Rf],O=[];if(!w)return O;for(const H of w){const X=[];for(const le of H){const he=[le.x+P[0],le.y+P[1]];Bp(m,he),X.push(he)}O.push(X)}if(m[2]-m[0]<=E/2){(U=m)[0]=U[1]=1/0,U[2]=U[3]=-1/0;for(const H of O)for(const X of H)Qc(X,m,x,E)}var U;return O}class pg{constructor(m,x){this.type=Zi,this.geojson=m,this.geometries=x}static parse(m,x){if(m.length!==2)return x.error(`'within' expression requires exactly one argument, but found ${m.length-1} instead.`);if(Pf(m[1])){const k=m[1];if(k.type==="FeatureCollection")for(let E=0;Ex)return xj(P,O,(x-(k-U))/U)}return m[m.length-1]}pointToSegmentDistance(m,x,k){let[E,P]=x,O=op(k[0]-E)*this.kx,U=(k[1]-P)*this.ky;if(O!==0||U!==0){const H=(op(m[0]-E)*this.kx*O+(m[1]-P)*this.ky*U)/(O*O+U*U);H>1?(E=k[0],P=k[1]):H>0&&(E+=O/this.kx*H,P+=U/this.ky*H)}return O=op(m[0]-E)*this.kx,U=(m[1]-P)*this.ky,Math.sqrt(O*O+U*U)}pointOnLine(m,x){let k=1/0,E=m[0][0],P=m[0][1],O=0,U=0;for(let H=0;H1?(X=m[H+1][0],le=m[H+1][1]):be>0&&(X+=he/this.kx*be,le+=me/this.ky*be)),he=op(x[0]-X)*this.kx,me=(x[1]-le)*this.ky;const Se=he*he+me*me;SeP.index||E.index===P.index&&E.t>P.t){const X=E;E=P,P=X}const O=[E.point],U=E.index+1,H=P.index;!zN(k[U],O[0])&&U<=H&&O.push(k[U]);for(let X=U+1;X<=H;X++)O.push(k[X]);return zN(k[H],P.point)||O.push(P.point),O}lineSliceAlong(m,x,k){let E=0;const P=[];for(let O=0;Om&&P.length===0&&P.push(xj(U,H,(m-(E-X))/X)),E>=x)return P.push(xj(U,H,(x-(E-X))/X)),P;E>m&&P.push(H)}return P}bufferPoint(m,x){const k=x/this.ky,E=x/this.kx;return[m[0]-E,m[1]-k,m[0]+E,m[1]+k]}bufferBBox(m,x){const k=x/this.ky,E=x/this.kx;return[m[0]-E,m[1]-k,m[2]+E,m[3]+k]}insideBBox(m,x){return op(m[0]-x[0])>=0&&op(m[0]-x[2])<=0&&m[1]>=x[1]&&m[1]<=x[3]}}function zN(w,m){return w[0]===m[0]&&w[1]===m[1]}function xj(w,m,x){const k=op(m[0]-w[0]);return[w[0]+k*x,w[1]+(m[1]-w[1])*x]}function op(w){for(;w<-180;)w+=360;for(;w>180;)w-=360;return w}class f0{constructor(m=[],x=(k,E)=>kE?1:0){if(this.data=m,this.length=this.data.length,this.compare=x,this.length>0)for(let k=(this.length>>1)-1;k>=0;k--)this._down(k)}push(m){this.data.push(m),this._up(this.length++)}pop(){if(this.length===0)return;const m=this.data[0],x=this.data.pop();return--this.length>0&&(this.data[0]=x,this._down(0)),m}peek(){return this.data[0]}_up(m){const{data:x,compare:k}=this,E=x[m];for(;m>0;){const P=m-1>>1,O=x[P];if(k(E,O)>=0)break;x[m]=O,m=P}x[m]=E}_down(m){const{data:x,compare:k}=this,E=this.length>>1,P=x[m];for(;m=0)break;x[m]=x[O],m=O}x[m]=P}}var Bn=8192;function gj(w,m){return m.dist-w.dist}function yj(w){const m=[1/0,1/0,-1/0,-1/0];if(m.length!==w.length)return!1;for(let x=0;x=w[0]&&w[1]w[1])return[null,null];const x=$y(w);if(m){if(x===2)return[w,null];const k=Math.floor(x/2);return[[w[0],w[0]+k],[w[0]+k,w[1]]]}{if(x===1)return[w,null];const k=Math.floor(x/2)-1;return[[w[0],w[0]+k],[w[0]+k+1,w[1]]]}}function x0(w,m){const x=[1/0,1/0,-1/0,-1/0];if(!$p(m,w.length))return x;for(let k=m[0];k<=m[1];++k)Bp(x,w[k]);return x}function e_(w){const m=[1/0,1/0,-1/0,-1/0];for(let x=0;xm[2]&&(k=w[0]-m[2]),w[1]>m[3]&&(E=w[1]-m[3]),w[3]=k)return k;if(By(E,P)){if(vj(w,m))return 0}else if(vj(m,w))return 0;let O=k;for(const U of w)for(let H=0,X=U.length,le=X-1;H=P)continue;const le=X.range1;if($y(le)<=U){if(!$p(le,w.length))return NaN;if(m){const he=dl(w,le,x,k);if((P=Math.min(P,he))===0)return P}else for(let he=le[0];he<=le[1];++he){const me=g6(w[he],x,k);if((P=Math.min(P,me))===0)return P}}else{const he=m1(le,m);if(he[0]!==null){const me=p1(x0(w,he[0]),H,k);me=O)continue;const he=le.range1,me=le.range2;if($y(he)<=H&&$y(me)<=X){if(!$p(he,w.length)||!$p(me,x.length))return NaN;if(m&&k?O=Math.min(O,UR(w,he,x,me,E)):m||k?m&&!k?O=Math.min(O,_C(x,me,w,he,E)):!m&&k&&(O=Math.min(O,_C(w,he,x,me,E))):O=Math.min(O,jC(w,he,x,me,E)),O===0)return O}else{const be=m1(he,m),Se=m1(me,k);BN(U,O,E,w,x,be[0],Se[0]),BN(U,O,E,w,x,be[0],Se[1]),BN(U,O,E,w,x,be[1],Se[0]),BN(U,O,E,w,x,be[1],Se[1])}}return O}function bj(w,m,x,k,E=1/0){let P=E;const O=x0(w,[0,w.length-1]);for(const U of x)if(!(P!==1/0&&p1(O,x0(U,[0,U.length-1]),k)>=P)&&(P=Math.min(P,Ff(w,m,U,!0,k,P)),P===0))return P;return P}function f1(w,m,x,k,E=1/0){let P=E;const O=x0(w,[0,w.length-1]);for(const U of x){if(P!==1/0&&p1(O,e_(U),k)>=P)continue;const H=VR(w,m,U,k,P);if(isNaN(H))return H;if((P=Math.min(P,H))===0)return P}return P}function $N(w){return w==="Point"||w==="MultiPoint"||w==="LineString"||w==="MultiLineString"||w==="Polygon"||w==="MultiPolygon"}class Uy{constructor(m,x){this.type=Mr,this.geojson=m,this.geometries=x}static parse(m,x){if(m.length!==2)return x.error(`'distance' expression requires either one argument, but found ' ${m.length-1} instead.`);if(Pf(m[1])){const k=m[1];if(k.type==="FeatureCollection"){for(let E=0;E{m&&!qy(x)&&(m=!1)}),m}function Vy(w){if(w instanceof $c&&w.name==="feature-state")return!1;let m=!0;return w.eachChild(x=>{m&&!Vy(x)&&(m=!1)}),m}function _m(w,m){if(w instanceof $c&&m.indexOf(w.name)>=0)return!1;let x=!0;return w.eachChild(k=>{x&&!_m(k,m)&&(x=!1)}),x}function UN(w,m,x){return[w,m,x].filter(Boolean).join("")}function _j(w,m){switch(w){case"string":return na(m);case"number":return+m;case"boolean":return!!m;case"color":return Wn.parse(m);case"formatted":return Wd.fromString(na(m));case"resolvedImage":return Kd.build(na(m))}return m}function y6(w,m,x,k){return k!==void 0&&(w=k*Math.round(w/k)),m!==void 0&&wx&&(w=x),w}class x1{constructor(m,x,k,E=!1){this.type=m,this.key=x,this.scope=k,this.featureConstant=E}static parse(m,x){let k=x.expectedType;if(k==null&&(k=to),m.length<2||m.length>3)return x.error("Invalid number of arguments for 'config' expression.");const E=x.parse(m[1],1);if(!(E instanceof rr))return x.error("Key name of 'config' expression must be a string literal.");let P,O=!0;const U=na(E.value);if(m.length>=3){const H=x.parse(m[2],2);if(!(H instanceof rr))return x.error("Scope of 'config' expression must be a string literal.");P=na(H.value)}if(x.options){const H=UN(U,P,x._scope),X=x.options.get(H);X&&(O=qy(X.value||X.default))}return new x1(k,U,P,O)}evaluate(m){const x=UN(this.key,this.scope,m.scope),k=m.getConfig(x);if(!k)return null;const{type:E,value:P,values:O,minValue:U,maxValue:H,stepValue:X}=k,le=k.default.evaluate(m);let he=le;if(P){const me=m.scope;m.scope=(me||"").split("").slice(1).join(""),he=P.evaluate(m),m.scope=me}return E&&(he=_j(E,he)),he===void 0||U===void 0&&H===void 0&&X===void 0||(typeof he=="number"?he=y6(he,U,H,X):Array.isArray(he)&&(he=he.map(me=>typeof me=="number"?y6(me,U,H,X):me))),P!==void 0&&he!==void 0&&O&&!O.includes(he)&&(he=le,E&&(he=_j(E,he))),(E&&E!==this.type||he!==void 0&&!bx(Ml(he),this.type))&&(he=_j(this.type.kind,he)),he}eachChild(){}outputDefined(){return!1}serialize(){const m=["config",this.key];return this.scope&&m.concat(this.scope),m}}class wj{constructor(m,x){this.type=x.type,this.name=m,this.boundExpression=x}static parse(m,x){if(m.length!==2||typeof m[1]!="string")return x.error("'var' expression requires exactly one string literal argument.");const k=m[1];return x.scope.has(k)?new wj(k,x.scope.get(k)):x.error(`Unknown variable "${k}". Make sure "${k}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(m){return this.boundExpression.evaluate(m)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class jj{constructor(m,x=[],k,E=new mg,P=[],O,U,H){this.registry=m,this.path=x,this.key=x.map(X=>typeof X=="string"?`['${X}']`:`[${X}]`).join(""),this.scope=E,this.errors=P,this.expectedType=k,this._scope=O,this.options=U,this.iconImageUseTheme=H}parse(m,x,k,E,P={}){return x||k?this.concat(x,null,k,E)._parse(m,P):this._parse(m,P)}parseObjectValue(m,x,k,E,P,O={}){return this.concat(x,k,E,P)._parse(m,O)}_parse(m,x){function k(E,P,O){return O==="assert"?new ap(P,[E]):O==="coerce"?new bm(P,[E]):E}if(m!==null&&typeof m!="string"&&typeof m!="boolean"&&typeof m!="number"||(m=["literal",m]),Array.isArray(m)){if(m.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const E=typeof m[0]=="string"?this.registry[m[0]]:void 0;if(E){let P=E.parse(m,this);if(!P)return null;if(this.expectedType){const O=this.expectedType,U=P.type;if(O.kind!=="string"&&O.kind!=="number"&&O.kind!=="boolean"&&O.kind!=="object"&&O.kind!=="array"||U.kind!=="value")if(O.kind!=="color"&&O.kind!=="formatted"&&O.kind!=="resolvedImage"||U.kind!=="value"&&U.kind!=="string"){if(this.checkSubtype(O,U))return null}else P=k(P,O,x.typeAnnotation||"coerce");else P=k(P,O,x.typeAnnotation||"assert")}if(!(P instanceof rr)&&P.type.kind!=="resolvedImage"&&qN(P)){const O=new ip(this._scope,this.options,this.iconImageUseTheme);try{P=new rr(P.type,P.evaluate(O))}catch(U){return this.error(U.message),null}}return P}return bm.parse(["to-array",m],this)}return this.error(m===void 0?"'undefined' value invalid. Use null instead.":typeof m=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof m} instead.`)}concat(m,x,k,E){let P=typeof m=="number"?this.path.concat(m):this.path;P=typeof x=="string"?P.concat(x):P;const O=E?this.scope.concat(E):this.scope;return new jj(this.registry,P,k||null,O,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(m,...x){const k=`${this.key}${x.map(E=>`[${E}]`).join("")}`;this.errors.push(new Zu(k,m))}checkSubtype(m,x){const k=Fy(m,x);return k&&this.error(k),k}}function qN(w){if(w instanceof wj)return qN(w.boundExpression);if(w instanceof $c&&w.name==="error"||w instanceof hj||w instanceof pg||w instanceof Uy||w instanceof x1)return!1;const m=w instanceof bm||w instanceof ap;let x=!0;return w.eachChild(k=>{x=m?x&&qN(k):x&&k instanceof rr}),!!x&&qy(w)&&_m(w,["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 Nj(w,m){const x=w.length-1;let k,E,P=0,O=x,U=0;for(;P<=O;)if(U=Math.floor((P+O)/2),k=w[U],E=w[U+1],k<=m){if(U===x||mm))throw new vl("Input is not a number.");O=U-1}return 0}class kj{constructor(m,x,k){this.type=m,this.input=x,this.labels=[],this.outputs=[];for(const[E,P]of k)this.labels.push(E),this.outputs.push(P)}static parse(m,x){if(m.length-1<4)return x.error(`Expected at least 4 arguments, but found only ${m.length-1}.`);if((m.length-1)%2!=0)return x.error("Expected an even number of arguments.");const k=x.parse(m[1],1,Mr);if(!k)return null;const E=[];let P=null;x.expectedType&&x.expectedType.kind!=="value"&&(P=x.expectedType);for(let O=1;O=U)return x.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',X);const he=x.parse(H,le,P);if(!he)return null;P=P||he.type,E.push([U,he])}return new kj(P,k,E)}evaluate(m){const x=this.labels,k=this.outputs;if(x.length===1)return k[0].evaluate(m);const E=this.input.evaluate(m);if(E<=x[0])return k[0].evaluate(m);const P=x.length;return E>=x[P-1]?k[P-1].evaluate(m):k[Nj(x,E)].evaluate(m)}eachChild(m){m(this.input);for(const x of this.outputs)m(x)}outputDefined(){return this.outputs.every(m=>m.outputDefined())}serialize(){const m=["step",this.input.serialize()];for(let x=0;x0&&m.push(this.labels[x]),m.push(this.outputs[x].serialize());return m}}const wm=.95047,Vh=1.08883,NC=4/29,g1=6/29,kC=3*g1*g1,v6=g1*g1*g1,b6=Math.PI/180,SC=180/Math.PI;function VN(w){return w>v6?Math.pow(w,1/3):w/kC+NC}function Sj(w){return w>g1?w*w*w:kC*(w-NC)}function t_(w){return 255*(w<=.0031308?12.92*w:1.055*Math.pow(w,1/2.4)-.055)}function y1(w){return(w/=255)<=.04045?w/12.92:Math.pow((w+.055)/1.055,2.4)}function Cj(w){const m=y1(w.r),x=y1(w.g),k=y1(w.b),E=VN((.4124564*m+.3575761*x+.1804375*k)/wm),P=VN((.2126729*m+.7151522*x+.072175*k)/1);return{l:116*P-16,a:500*(E-P),b:200*(P-VN((.0193339*m+.119192*x+.9503041*k)/Vh)),alpha:w.a}}function HN(w){let m=(w.l+16)/116,x=isNaN(w.a)?m:m+w.a/500,k=isNaN(w.b)?m:m-w.b/200;return m=1*Sj(m),x=wm*Sj(x),k=Vh*Sj(k),new Wn(t_(3.2404542*x-1.5371385*m-.4985314*k),t_(-.969266*x+1.8760108*m+.041556*k),t_(.0556434*x-.2040259*m+1.0572252*k),w.alpha)}function _6(w,m,x){const k=m-w;return w+x*(k>180||k<-180?k-360*Math.round(k/360):k)}const v1={forward:Cj,reverse:HN,interpolate:function(w,m,x){return{l:Br(w.l,m.l,x),a:Br(w.a,m.a,x),b:Br(w.b,m.b,x),alpha:Br(w.alpha,m.alpha,x)}}},g0={forward:function(w){const{l:m,a:x,b:k}=Cj(w),E=Math.atan2(k,x)*SC;return{h:E<0?E+360:E,c:Math.sqrt(x*x+k*k),l:m,alpha:w.a}},reverse:function(w){const m=w.h*b6,x=w.c;return HN({l:w.l,a:Math.cos(m)*x,b:Math.sin(m)*x,alpha:w.alpha})},interpolate:function(w,m,x){return{h:_6(w.h,m.h,x),c:Br(w.c,m.c,x),l:Br(w.l,m.l,x),alpha:Br(w.alpha,m.alpha,x)}}};var CC=Object.freeze({__proto__:null,hcl:g0,lab:v1});class bu{constructor(m,x,k,E,P){this.type=m,this.operator=x,this.interpolation=k,this.input=E,this.labels=[],this.outputs=[];for(const[O,U]of P)this.labels.push(O),this.outputs.push(U)}static interpolationFactor(m,x,k,E){let P=0;if(m.name==="exponential")P=s_(x,m.base,k,E);else if(m.name==="linear")P=s_(x,1,k,E);else if(m.name==="cubic-bezier"){const O=m.controlPoints;P=new pi(O[0],O[1],O[2],O[3]).solve(s_(x,1,k,E))}return P}static parse(m,x){let[k,E,P,...O]=m;if(!Array.isArray(E)||E.length===0)return x.error("Expected an interpolation type expression.",1);if(E[0]==="linear")E={name:"linear"};else if(E[0]==="exponential"){const X=E[1];if(typeof X!="number")return x.error("Exponential interpolation requires a numeric base.",1,1);E={name:"exponential",base:X}}else{if(E[0]!=="cubic-bezier")return x.error(`Unknown interpolation type ${String(E[0])}`,1,0);{const X=E.slice(1);if(X.length!==4||X.some(le=>typeof le!="number"||le<0||le>1))return x.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);E={name:"cubic-bezier",controlPoints:X}}}if(m.length-1<4)return x.error(`Expected at least 4 arguments, but found only ${m.length-1}.`);if(m.length-1>3&&(m.length-1)%2!=0)return x.error("Expected an even number of arguments.");if(P=x.parse(P,2,Mr),!P)return null;const U=[];let H=null;k==="interpolate-hcl"||k==="interpolate-lab"?H=Uh:x.expectedType&&x.expectedType.kind!=="value"&&(H=x.expectedType);for(let X=0;X=le)return x.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',me);const Se=x.parse(he,be,H);if(!Se)return null;H=H||Se.type,U.push([le,Se])}return H.kind==="number"||H.kind==="color"||H.kind==="array"&&H.itemType.kind==="number"&&typeof H.N=="number"?new bu(H,k,E,P,U):x.error(`Type ${Ol(H)} is not interpolatable.`)}evaluate(m){const x=this.labels,k=this.outputs;if(x.length===1)return k[0].evaluate(m);const E=this.input.evaluate(m);if(E<=x[0])return k[0].evaluate(m);const P=x.length;if(E>=x[P-1])return k[P-1].evaluate(m);const O=Nj(x,E),U=bu.interpolationFactor(this.interpolation,E,x[O],x[O+1]),H=k[O].evaluate(m),X=k[O+1].evaluate(m);return this.operator==="interpolate"?ym[this.type.kind.toLowerCase()](H,X,U):this.operator==="interpolate-hcl"?g0.reverse(g0.interpolate(g0.forward(H),g0.forward(X),U)):v1.reverse(v1.interpolate(v1.forward(H),v1.forward(X),U))}eachChild(m){m(this.input);for(const x of this.outputs)m(x)}outputDefined(){return this.outputs.every(m=>m.outputDefined())}serialize(){let m;m=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const x=[this.operator,m,this.input.serialize()];for(let k=0;kFy(E,U.type));return new n_(O?to:k,P)}evaluate(m){let x,k=null,E=0;for(const P of this.args){if(E++,k=P.evaluate(m),k&&k instanceof Kd&&!k.available&&(x||(x=k),k=null,E===this.args.length))return x;if(k!==null)break}return k}eachChild(m){this.args.forEach(m)}outputDefined(){return this.args.every(m=>m.outputDefined())}serialize(){const m=["coalesce"];return this.eachChild(x=>{m.push(x.serialize())}),m}}class b1{constructor(m,x){this.type=x.type,this.bindings=[].concat(m),this.result=x}evaluate(m){return this.result.evaluate(m)}eachChild(m){for(const x of this.bindings)m(x[1]);m(this.result)}static parse(m,x){if(m.length<4)return x.error(`Expected at least 3 arguments, but found ${m.length-1} instead.`);const k=[];for(let P=1;P=k.length)throw new vl("Array index out of bounds: index exceeds array size");if(x!==Math.floor(x))throw new vl("Array index must be an integer. Use at-interpolated for fractional indices");return k[x]}eachChild(m){m(this.index),m(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class Tj{constructor(m,x,k){this.type=m,this.index=x,this.input=k}static parse(m,x){if(m.length!==3)return x.error(`Expected 2 arguments, but found ${m.length-1} instead.`);const k=x.parse(m[1],1,Mr),E=x.parse(m[2],2,Qu(x.expectedType||to));return k&&E?new Tj(E.type.itemType,k,E):null}evaluate(m){const x=this.index.evaluate(m),k=this.input.evaluate(m);if(x<0)throw new vl(`Array index out of bounds: ${x} < 0.`);if(x>k.length-1)throw new vl(`Array index out of bounds: ${x} > ${k.length-1}.`);if(x===Math.floor(x))return k[x];const E=Math.floor(x),P=Math.ceil(x),O=k[E],U=k[P];if(typeof O!="number"||typeof U!="number")throw new vl(`Cannot interpolate between non-number values at index ${x}.`);const H=x-E;return O*(1-H)+U*H}eachChild(m){m(this.index),m(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class lp{constructor(m,x){this.type=Zi,this.needle=m,this.haystack=x}static parse(m,x){if(m.length!==3)return x.error(`Expected 2 arguments, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1,to),E=x.parse(m[2],2,to);return k&&E?Kb(k.type,[Zi,Ii,Mr,If,to])?new lp(k,E):(x.error(`Expected first argument to be of type boolean, string, number or null, but found ${Ol(k.type)} instead`),null):null}evaluate(m){const x=this.needle.evaluate(m),k=this.haystack.evaluate(m);if(k==null)return!1;if(!vx(x,["boolean","string","number","null"]))throw new vl(`Expected first argument to be of type boolean, string, number or null, but found ${Ol(Ml(x))} instead.`);if(!vx(k,["string","array"]))throw new vl(`Expected second argument to be of type array or string, but found ${Ol(Ml(k))} instead.`);return k.indexOf(x)>=0}eachChild(m){m(this.needle),m(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Ej{constructor(m,x,k){this.type=Mr,this.needle=m,this.haystack=x,this.fromIndex=k}static parse(m,x){if(m.length<=2||m.length>=5)return x.error(`Expected 3 or 4 arguments, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1,to),E=x.parse(m[2],2,to);if(!k||!E)return null;if(!Kb(k.type,[Zi,Ii,Mr,If,to]))return x.error(`Expected first argument to be of type boolean, string, number or null, but found ${Ol(k.type)} instead`),null;if(m.length===4){const P=x.parse(m[3],3,Mr);return P?new Ej(k,E,P):null}return new Ej(k,E)}evaluate(m){const x=this.needle.evaluate(m),k=this.haystack.evaluate(m);if(!vx(x,["boolean","string","number","null"]))throw new vl(`Expected first argument to be of type boolean, string, number or null, but found ${Ol(Ml(x))} instead.`);if(!vx(k,["string","array"]))throw new vl(`Expected second argument to be of type array or string, but found ${Ol(Ml(k))} instead.`);if(this.fromIndex){const E=this.fromIndex.evaluate(m);return k.indexOf(x,E)}return k.indexOf(x)}eachChild(m){m(this.needle),m(this.haystack),this.fromIndex&&m(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const m=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),m]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class _1{constructor(m,x,k,E,P,O){this.inputType=m,this.type=x,this.input=k,this.cases=E,this.outputs=P,this.otherwise=O}static parse(m,x){if(m.length<5)return x.error(`Expected at least 4 arguments, but found only ${m.length-1}.`);if(m.length%2!=1)return x.error("Expected an even number of arguments.");let k,E;x.expectedType&&x.expectedType.kind!=="value"&&(E=x.expectedType);const P={},O=[];for(let X=2;XNumber.MAX_SAFE_INTEGER)return me.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof Se=="number"&&Math.floor(Se)!==Se)return me.error("Numeric branch labels must be integer values.");if(k){if(me.checkSubtype(k,Ml(Se)))return null}else k=Ml(Se);if(P[String(Se)]!==void 0)return me.error("Branch labels must be unique.");P[String(Se)]=O.length}const be=x.parse(he,X,E);if(!be)return null;E=E||be.type,O.push(be)}const U=x.parse(m[1],1,to);if(!U)return null;const H=x.parse(m[m.length-1],m.length-1,E);return H?U.type.kind!=="value"&&x.concat(1).checkSubtype(k,U.type)?null:new _1(k,E,U,P,O,H):null}evaluate(m){const x=this.input.evaluate(m);return(bx(Ml(x),this.inputType)&&this.outputs[this.cases[x]]||this.otherwise).evaluate(m)}eachChild(m){m(this.input),this.outputs.forEach(m),m(this.otherwise)}outputDefined(){return this.outputs.every(m=>m.outputDefined())&&this.otherwise.outputDefined()}serialize(){const m=["match",this.input.serialize()],x=Object.keys(this.cases).sort(),k=[],E={};for(const O of x){const U=E[this.cases[O]];U===void 0?(E[this.cases[O]]=k.length,k.push([this.cases[O],[O]])):k[U][1].push(O)}const P=O=>this.inputType.kind==="number"?Number(O):O;for(const[O,U]of k)m.push(U.length===1?P(U[0]):U.map(P)),m.push(this.outputs[O].serialize());return m.push(this.otherwise.serialize()),m}}class Hy{constructor(m,x,k){this.type=m,this.branches=x,this.otherwise=k}static parse(m,x){if(m.length<4)return x.error(`Expected at least 3 arguments, but found only ${m.length-1}.`),null;if(m.length%2!=0)return x.error("Expected an odd number of arguments."),null;let k;x.expectedType&&x.expectedType.kind!=="value"&&(k=x.expectedType);const E=[];for(let O=1;Ox.outputDefined())&&this.otherwise.outputDefined()}serialize(){const m=["case"];return this.eachChild(x=>{m.push(x.serialize())}),m}}class Gy{constructor(m,x,k,E){this.type=m,this.input=x,this.beginIndex=k,this.endIndex=E}static parse(m,x){if(m.length<=2||m.length>=5)return x.error(`Expected 3 or 4 arguments, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1,to),E=x.parse(m[2],2,Mr);if(!k||!E)return null;if(!Kb(k.type,[Qu(to),Ii,to]))return x.error(`Expected first argument to be of type array or string, but found ${Ol(k.type)} instead`),null;if(m.length===4){const P=x.parse(m[3],3,Mr);return P?new Gy(k.type,k,E,P):null}return new Gy(k.type,k,E)}evaluate(m){const x=this.input.evaluate(m),k=this.beginIndex.evaluate(m);if(!vx(x,["string","array"]))throw new vl(`Expected first argument to be of type array or string, but found ${Ol(Ml(x))} instead.`);if(this.endIndex){const E=this.endIndex.evaluate(m);return x.slice(k,E)}return x.slice(k)}eachChild(m){m(this.input),m(this.beginIndex),this.endIndex&&m(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const m=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),m]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class r_{constructor(m,x){this.type=Qu(Ii),this.str=m,this.delimiter=x}static parse(m,x){if(m.length!==3)return x.error(`Expected 2 arguments, but found ${m.length-1} instead.`);const k=x.parse(m[1],1,Ii),E=x.parse(m[2],2,Ii);return k&&E?new r_(k,E):void 0}evaluate(m){const x=this.str.evaluate(m),k=this.delimiter.evaluate(m);return x.split(k)}eachChild(m){m(this.str),m(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function TC(w,m){return w==="=="||w==="!="?m.kind==="boolean"||m.kind==="string"||m.kind==="number"||m.kind==="null"||m.kind==="value":m.kind==="string"||m.kind==="number"||m.kind==="value"}function a_(w,m,x,k){return k.compare(m,x)===0}function cd(w,m,x){const k=w!=="=="&&w!=="!=";return class _ct{constructor(P,O,U){this.type=Zi,this.lhs=P,this.rhs=O,this.collator=U,this.hasUntypedArgument=P.type.kind==="value"||O.type.kind==="value"}static parse(P,O){if(P.length!==3&&P.length!==4)return O.error("Expected two or three arguments.");const U=P[0];let H=O.parse(P[1],1,to);if(!H)return null;if(!TC(U,H.type))return O.concat(1).error(`"${U}" comparisons are not supported for type '${Ol(H.type)}'.`);let X=O.parse(P[2],2,to);if(!X)return null;if(!TC(U,X.type))return O.concat(2).error(`"${U}" comparisons are not supported for type '${Ol(X.type)}'.`);if(H.type.kind!==X.type.kind&&H.type.kind!=="value"&&X.type.kind!=="value")return O.error(`Cannot compare types '${Ol(H.type)}' and '${Ol(X.type)}'.`);k&&(H.type.kind==="value"&&X.type.kind!=="value"?H=new ap(X.type,[H]):H.type.kind!=="value"&&X.type.kind==="value"&&(X=new ap(H.type,[X])));let le=null;if(P.length===4){if(H.type.kind!=="string"&&X.type.kind!=="string"&&H.type.kind!=="value"&&X.type.kind!=="value")return O.error("Cannot use collator to compare non-string types.");if(le=O.parse(P[3],3,yx),!le)return null}return new _ct(H,X,le)}evaluate(P){const O=this.lhs.evaluate(P),U=this.rhs.evaluate(P);if(k&&this.hasUntypedArgument){const H=Ml(O),X=Ml(U);if(H.kind!==X.kind||H.kind!=="string"&&H.kind!=="number")throw new vl(`Expected arguments for "${w}" to be (string, string) or (number, number), but found (${H.kind}, ${X.kind}) instead.`)}if(this.collator&&!k&&this.hasUntypedArgument){const H=Ml(O),X=Ml(U);if(H.kind!=="string"||X.kind!=="string")return m(P,O,U)}return this.collator?x(P,O,U,this.collator.evaluate(P)):m(P,O,U)}eachChild(P){P(this.lhs),P(this.rhs),this.collator&&P(this.collator)}outputDefined(){return!0}serialize(){const P=[w];return this.eachChild(O=>{P.push(O.serialize())}),P}}}const w6=cd("==",function(w,m,x){return m===x},a_),GN=cd("!=",function(w,m,x){return m!==x},function(w,m,x,k){return!a_(0,m,x,k)}),WN=cd("<",function(w,m,x){return m",function(w,m,x){return m>x},function(w,m,x,k){return k.compare(m,x)>0}),HR=cd("<=",function(w,m,x){return m<=x},function(w,m,x,k){return k.compare(m,x)<=0}),qa=cd(">=",function(w,m,x){return m>=x},function(w,m,x,k){return k.compare(m,x)>=0});class y0{constructor(m,x,k,E,P,O){this.type=Ii,this.number=m,this.locale=x,this.currency=k,this.unit=E,this.minFractionDigits=P,this.maxFractionDigits=O}static parse(m,x){if(m.length!==3)return x.error("Expected two arguments.");const k=x.parse(m[1],1,Mr);if(!k)return null;const E=m[2];if(typeof E!="object"||Array.isArray(E))return x.error("NumberFormat options argument must be an object.");let P=null;if(E.locale&&(P=x.parseObjectValue(E.locale,2,"locale",Ii),!P))return null;let O=null;if(E.currency&&(O=x.parseObjectValue(E.currency,2,"currency",Ii),!O))return null;let U=null;if(E.unit&&(U=x.parseObjectValue(E.unit,2,"unit",Ii),!U))return null;let H=null;if(E["min-fraction-digits"]&&(H=x.parseObjectValue(E["min-fraction-digits"],2,"min-fraction-digits",Mr),!H))return null;let X=null;return E["max-fraction-digits"]&&(X=x.parseObjectValue(E["max-fraction-digits"],2,"max-fraction-digits",Mr),!X)?null:new y0(k,P,O,U,H,X)}evaluate(m){return new Intl.NumberFormat(this.locale?this.locale.evaluate(m):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(m):void 0,unit:this.unit?this.unit.evaluate(m):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(m):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(m):void 0}).format(this.number.evaluate(m))}eachChild(m){m(this.number),this.locale&&m(this.locale),this.currency&&m(this.currency),this.unit&&m(this.unit),this.minFractionDigits&&m(this.minFractionDigits),this.maxFractionDigits&&m(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const m={};return this.locale&&(m.locale=this.locale.serialize()),this.currency&&(m.currency=this.currency.serialize()),this.unit&&(m.unit=this.unit.serialize()),this.minFractionDigits&&(m["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(m["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),m]}}class i_{constructor(m){this.type=Mr,this.input=m}static parse(m,x){if(m.length!==2)return x.error(`Expected 1 argument, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1);return k?k.type.kind!=="array"&&k.type.kind!=="string"&&k.type.kind!=="value"?(x.error(`Expected argument of type string or array, but found ${Ol(k.type)} instead.`),null):new i_(k):null}evaluate(m){const x=this.input.evaluate(m);if(typeof x=="string"||Array.isArray(x))return x.length;throw new vl(`Expected value to be of type string or array, but found ${Ol(Ml(x))} instead.`)}eachChild(m){m(this.input)}outputDefined(){return!1}serialize(){const m=["length"];return this.eachChild(x=>{m.push(x.serialize())}),m}}function EC(w){return function(){w=1831565813+(w|=0)|0;let m=Math.imul(w^w>>>15,1|w);return m=m+Math.imul(m^m>>>7,61|m)^m,((m^m>>>14)>>>0)/4294967296}}const o_={"==":w6,"!=":GN,">":wh,"<":WN,">=":qa,"<=":HR,array:ap,at:Up,"at-interpolated":Tj,boolean:ap,case:Hy,coalesce:n_,collator:hj,format:vm,image:Fr,in:lp,"index-of":Ej,interpolate:bu,"interpolate-hcl":bu,"interpolate-lab":bu,length:i_,let:b1,literal:rr,match:_1,number:ap,"number-format":y0,object:ap,slice:Gy,step:kj,string:ap,"to-boolean":bm,"to-color":bm,"to-number":bm,"to-string":bm,var:wj,within:pg,distance:Uy,config:x1,split:r_};function l_(w,[m,x,k,E]){m=m.evaluate(w),x=x.evaluate(w),k=k.evaluate(w);const P=E?E.evaluate(w):1,O=Fp(m,x,k,P);if(O)throw new vl(O);return new Wn(m/255,x/255,k/255,P)}function Aj(w,[m,x,k,E]){m=m.evaluate(w),x=x.evaluate(w),k=k.evaluate(w);const P=E?E.evaluate(w):1,O=function(X,le,he,me){return typeof X=="number"&&X>=0&&X<=360?typeof le=="number"&&le>=0&&le<=100&&typeof he=="number"&&he>=0&&he<=100?me===void 0||typeof me=="number"&&me>=0&&me<=1?null:`Invalid hsla value [${[X,le,he,me].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof me=="number"?[X,le,he,me]:[X,le,he]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof me=="number"?[X,le,he,me]:[X,le,he]).join(", ")}]: 'h' must be between 0 and 360.`}(m,x,k,P);if(O)throw new vl(O);const U=`hsla(${m}, ${x}%, ${k}%, ${P})`,H=Wn.parse(U);if(!H)throw new vl(`Failed to parse HSLA color: ${U}`);return H}function w1(w,m){return w in m}function Mj(w,m){const x=m[w];return x===void 0?null:x}function v0(w){return{type:w}}function Ij(w){if(w instanceof x1)return new Set([w.key]);let m=new Set;return w.eachChild(x=>{m=new Set([...m,...Ij(x)])}),m}function c_(w){if(w instanceof $c&&w.name==="is-active-floor")return!0;let m=!1;return w.eachChild(x=>{!m&&c_(x)&&(m=!0)}),m}function KN(w){return{result:"success",value:w}}function Uc(w){return{result:"error",value:w}}function jm(w,m){return!!w&&!!w.parameters&&w.parameters.indexOf(m)>-1}function qp(w){return w["property-type"]==="data-driven"}function YN(w){return jm(w.expression,"measure-light")}function ZN(w){return jm(w.expression,"zoom")}function cp(w){return!!w.expression&&w.expression.interpolated}function QN(w){return typeof w=="object"&&w!==null&&!Array.isArray(w)}function _x(w){return w}function j6(w,m){const x=m.type==="color",k=w.stops&&typeof w.stops[0][0]=="object",E=k||!(k||w.property!==void 0),P=w.type||(cp(m)?"exponential":"interval");if(x&&((w=Object.assign({},w)).stops&&(w.stops=w.stops.map(X=>[X[0],Wn.parse(X[1])])),w.default=Wn.parse(w.default?w.default:m.default)),w.colorSpace&&w.colorSpace!=="rgb"&&!CC[w.colorSpace])throw new Error(`Unknown color space: ${w.colorSpace}`);let O,U,H;if(P==="exponential")O=AC;else if(P==="interval")O=k6;else if(P==="categorical"){O=N6,U=Object.create(null);for(const X of w.stops)U[X[0]]=X[1];H=typeof w.stops[0][0]}else{if(P!=="identity")throw new Error(`Unknown function type "${P}"`);O=Pj}if(k){const X={},le=[];for(let be=0;bebe[0]),evaluate:({zoom:be},Se)=>AC({stops:he,base:w.base},m,be).evaluate(be,Se)}}if(E){const X=P==="exponential"?{name:"exponential",base:w.base!==void 0?w.base:1}:null;return{kind:"camera",interpolationType:X,interpolationFactor:bu.interpolationFactor.bind(void 0,X),zoomStops:w.stops.map(le=>le[0]),evaluate:({zoom:le})=>O(w,m,le,U,H)}}return{kind:"source",evaluate(X,le){const he=le&&le.properties?le.properties[w.property]:void 0;return he===void 0?wx(w.default,m.default):O(w,m,he,U,H)}}}function wx(w,m,x){return w!==void 0?w:m!==void 0?m:x!==void 0?x:void 0}function N6(w,m,x,k,E){return wx(typeof x===E?k[x]:void 0,w.default,m.default)}function k6(w,m,x){if(!Zb(x))return wx(w.default,m.default);const k=w.stops.length;if(k===1||x<=w.stops[0][0])return w.stops[0][1];if(x>=w.stops[k-1][0])return w.stops[k-1][1];const E=Nj(w.stops.map(P=>P[0]),x);return w.stops[E][1]}function AC(w,m,x){const k=w.base!==void 0?w.base:1;if(!Zb(x))return wx(w.default,m.default);const E=w.stops.length;if(E===1||x<=w.stops[0][0])return w.stops[0][1];if(x>=w.stops[E-1][0])return w.stops[E-1][1];const P=Nj(w.stops.map(le=>le[0]),x),O=function(le,he,me,be){const Se=be-me,Pe=le-me;return Se===0?0:he===1?Pe/Se:(Math.pow(he,Pe)-1)/(Math.pow(he,Se)-1)}(x,k,w.stops[P][0],w.stops[P+1][0]),U=w.stops[P][1],H=w.stops[P+1][1];let X=ym[m.type]||_x;if(w.colorSpace&&w.colorSpace!=="rgb"){const le=CC[w.colorSpace];X=(he,me)=>le.reverse(le.interpolate(le.forward(he),le.forward(me),O))}return typeof U.evaluate=="function"?{evaluate(...le){const he=U.evaluate.apply(void 0,le),me=H.evaluate.apply(void 0,le);if(he!==void 0&&me!==void 0)return X(he,me,O)}}:X(U,H,O)}function Pj(w,m,x){return m.type==="color"?x=Wn.parse(x):m.type==="formatted"?x=Wd.fromString(x.toString()):m.type==="resolvedImage"?x=Kd.build(x.toString()):zy(x)===m.type||m.type==="enum"&&m.values[x]||(x=void 0),wx(x,w.default,m.default)}$c.register(o_,{error:[{kind:"error"},[Ii],(w,[m])=>{throw new vl(m.evaluate(w))}],typeof:[Ii,[to],(w,[m])=>Ol(Ml(m.evaluate(w)))],"to-rgba":[Qu(Mr,4),[Uh],(w,[m])=>m.evaluate(w).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Qu(Mr,4),[Uh],(w,[m])=>m.evaluate(w).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[Uh,[Mr,Mr,Mr],l_],rgba:[Uh,[Mr,Mr,Mr,Mr],l_],hsl:[Uh,[Mr,Mr,Mr],Aj],hsla:[Uh,[Mr,Mr,Mr,Mr],Aj],has:{type:Zi,overloads:[[[Ii],(w,[m])=>w1(m.evaluate(w),w.properties())],[[Ii,gx],(w,[m,x])=>w1(m.evaluate(w),x.evaluate(w))]]},get:{type:to,overloads:[[[Ii],(w,[m])=>Mj(m.evaluate(w),w.properties())],[[Ii,gx],(w,[m,x])=>Mj(m.evaluate(w),x.evaluate(w))]]},"feature-state":[to,[Ii],(w,[m])=>Mj(m.evaluate(w),w.featureState||{})],properties:[gx,[],w=>w.properties()],"geometry-type":[Ii,[],w=>w.geometryType()],worldview:[Ii,[],w=>w.globals.worldview||""],"is-active-floor":[Zi,v0(Ii),(w,m)=>{if(!(w.globals&&w.globals.activeFloors&&w.globals.activeFloors.size>0))return!1;if(m.length===0)return!0;const x=w.globals.activeFloors;return m.some(k=>{const E=k.evaluate(w);return x.has(E)})}],id:[to,[],w=>w.id()],zoom:[Mr,[],w=>w.globals.zoom],pitch:[Mr,[],w=>w.globals.pitch||0],"distance-from-center":[Mr,[],w=>w.distanceFromCenter()],"measure-light":[Mr,[Ii],(w,[m])=>w.measureLight(m.evaluate(w))],"heatmap-density":[Mr,[],w=>w.globals.heatmapDensity||0],"line-progress":[Mr,[],w=>w.globals.lineProgress||0],"raster-value":[Mr,[],w=>w.globals.rasterValue||0],"raster-particle-speed":[Mr,[],w=>w.globals.rasterParticleSpeed||0],"sky-radial-progress":[Mr,[],w=>w.globals.skyRadialProgress||0],accumulated:[to,[],w=>w.globals.accumulated===void 0?null:w.globals.accumulated],"+":[Mr,v0(Mr),(w,m)=>{let x=0;for(const k of m)x+=k.evaluate(w);return x}],"*":[Mr,v0(Mr),(w,m)=>{let x=1;for(const k of m)x*=k.evaluate(w);return x}],"-":{type:Mr,overloads:[[[Mr,Mr],(w,[m,x])=>m.evaluate(w)-x.evaluate(w)],[[Mr],(w,[m])=>-m.evaluate(w)]]},"/":[Mr,[Mr,Mr],(w,[m,x])=>m.evaluate(w)/x.evaluate(w)],"%":[Mr,[Mr,Mr],(w,[m,x])=>m.evaluate(w)%x.evaluate(w)],ln2:[Mr,[],()=>Math.LN2],pi:[Mr,[],()=>Math.PI],e:[Mr,[],()=>Math.E],"^":[Mr,[Mr,Mr],(w,[m,x])=>Math.pow(m.evaluate(w),x.evaluate(w))],sqrt:[Mr,[Mr],(w,[m])=>Math.sqrt(m.evaluate(w))],log10:[Mr,[Mr],(w,[m])=>Math.log(m.evaluate(w))/Math.LN10],ln:[Mr,[Mr],(w,[m])=>Math.log(m.evaluate(w))],log2:[Mr,[Mr],(w,[m])=>Math.log2(m.evaluate(w))],sin:[Mr,[Mr],(w,[m])=>Math.sin(m.evaluate(w))],cos:[Mr,[Mr],(w,[m])=>Math.cos(m.evaluate(w))],tan:[Mr,[Mr],(w,[m])=>Math.tan(m.evaluate(w))],asin:[Mr,[Mr],(w,[m])=>Math.asin(m.evaluate(w))],acos:[Mr,[Mr],(w,[m])=>Math.acos(m.evaluate(w))],atan:[Mr,[Mr],(w,[m])=>Math.atan(m.evaluate(w))],min:[Mr,v0(Mr),(w,m)=>Math.min(...m.map(x=>x.evaluate(w)))],max:[Mr,v0(Mr),(w,m)=>Math.max(...m.map(x=>x.evaluate(w)))],abs:[Mr,[Mr],(w,[m])=>Math.abs(m.evaluate(w))],round:[Mr,[Mr],(w,[m])=>{const x=m.evaluate(w);return x<0?-Math.round(-x):Math.round(x)}],floor:[Mr,[Mr],(w,[m])=>Math.floor(m.evaluate(w))],ceil:[Mr,[Mr],(w,[m])=>Math.ceil(m.evaluate(w))],"filter-==":[Zi,[Ii,to],(w,[m,x])=>w.properties()[m.value]===x.value],"filter-id-==":[Zi,[to],(w,[m])=>w.id()===m.value],"filter-type-==":[Zi,[Ii],(w,[m])=>w.geometryType()===m.value],"filter-<":[Zi,[Ii,to],(w,[m,x])=>{const k=w.properties()[m.value],E=x.value;return typeof k==typeof E&&k{const x=w.id(),k=m.value;return typeof x==typeof k&&x":[Zi,[Ii,to],(w,[m,x])=>{const k=w.properties()[m.value],E=x.value;return typeof k==typeof E&&k>E}],"filter-id->":[Zi,[to],(w,[m])=>{const x=w.id(),k=m.value;return typeof x==typeof k&&x>k}],"filter-<=":[Zi,[Ii,to],(w,[m,x])=>{const k=w.properties()[m.value],E=x.value;return typeof k==typeof E&&k<=E}],"filter-id-<=":[Zi,[to],(w,[m])=>{const x=w.id(),k=m.value;return typeof x==typeof k&&x<=k}],"filter->=":[Zi,[Ii,to],(w,[m,x])=>{const k=w.properties()[m.value],E=x.value;return typeof k==typeof E&&k>=E}],"filter-id->=":[Zi,[to],(w,[m])=>{const x=w.id(),k=m.value;return typeof x==typeof k&&x>=k}],"filter-has":[Zi,[to],(w,[m])=>m.value in w.properties()],"filter-has-id":[Zi,[],w=>w.id()!==null&&w.id()!==void 0],"filter-type-in":[Zi,[Qu(Ii)],(w,[m])=>m.value.indexOf(w.geometryType())>=0],"filter-id-in":[Zi,[Qu(to)],(w,[m])=>m.value.indexOf(w.id())>=0],"filter-in-small":[Zi,[Ii,Qu(to)],(w,[m,x])=>x.value.indexOf(w.properties()[m.value])>=0],"filter-in-large":[Zi,[Ii,Qu(to)],(w,[m,x])=>function(k,E,P,O){for(;P<=O;){const U=P+O>>1;if(E[U]===k)return!0;E[U]>k?O=U-1:P=U+1}return!1}(w.properties()[m.value],x.value,0,x.value.length-1)],all:{type:Zi,overloads:[[[Zi,Zi],(w,[m,x])=>m.evaluate(w)&&x.evaluate(w)],[v0(Zi),(w,m)=>{for(const x of m)if(!x.evaluate(w))return!1;return!0}]]},any:{type:Zi,overloads:[[[Zi,Zi],(w,[m,x])=>m.evaluate(w)||x.evaluate(w)],[v0(Zi),(w,m)=>{for(const x of m)if(x.evaluate(w))return!0;return!1}]]},"!":[Zi,[Zi],(w,[m])=>!m.evaluate(w)],"is-supported-script":[Zi,[Ii],(w,[m])=>{const x=w.globals&&w.globals.isSupportedScript;return!x||x(m.evaluate(w))}],upcase:[Ii,[Ii],(w,[m])=>m.evaluate(w).toUpperCase()],downcase:[Ii,[Ii],(w,[m])=>m.evaluate(w).toLowerCase()],concat:[Ii,v0(to),(w,m)=>m.map(x=>na(x.evaluate(w))).join("")],"resolved-locale":[Ii,[yx],(w,[m])=>m.evaluate(w).resolvedLocale()],random:[Mr,[Mr,Mr,to],(w,m)=>{const[x,k,E]=m.map(O=>O.evaluate(w));if(x>k||x===k)return x;let P;if(typeof E=="string")P=function(O){let U=0;if(O.length===0)return U;for(let H=0;HJSON.stringify(he)).join(", ")}, but found ${JSON.stringify(le)} instead.`);return le}catch(le){const he=le;return this._warningHistory[he.message]||(this._warningHistory[he.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${he.message}`)),this._defaultValue}}}function Wy(w){return Array.isArray(w)&&w.length>0&&typeof w[0]=="string"&&w[0]in o_}function jx(w,m,x,k,E){const P=new jj(o_,[],m?function(U){const H={color:Uh,string:Ii,number:Mr,enum:Ii,boolean:Zi,formatted:Oy,resolvedImage:Wb};return U.type==="array"?Qu(H[U.value]||to,U.length):H[U.type]}(m):void 0,void 0,void 0,x,k,E),O=P.parse(w,void 0,void 0,void 0,m&&m.type==="string"?{typeAnnotation:"coerce"}:void 0);return O?KN(new j1(O,m,x,k,E)):Uc(P.errors)}class b0{constructor(m,x,k,E){this.kind=m,this._styleExpression=x,this.isLightConstant=k,this.isLineProgressConstant=E,this.isStateDependent=m!=="constant"&&!Vy(x.expression),this.configDependencies=Ij(x.expression),this.isIndoorDependent=c_(x.expression)}evaluateWithoutErrorHandling(m,x,k,E,P,O){return this._styleExpression.evaluateWithoutErrorHandling(m,x,k,E,P,O)}evaluate(m,x,k,E,P,O,U){return this._styleExpression.evaluate(m,x,k,E,P,O,void 0,void 0,U)}}class Nx{constructor(m,x,k,E,P,O){this.kind=m,this.zoomStops=k,this._styleExpression=x,this.isStateDependent=m!=="camera"&&!Vy(x.expression),this.isIndoorDependent=c_(x.expression),this.isLightConstant=P,this.isLineProgressConstant=O,this.configDependencies=Ij(x.expression),this.interpolationType=E}evaluateWithoutErrorHandling(m,x,k,E,P,O){return this._styleExpression.evaluateWithoutErrorHandling(m,x,k,E,P,O)}evaluate(m,x,k,E,P,O){return this._styleExpression.evaluate(m,x,k,E,P,O)}interpolationFactor(m,x,k){return this.interpolationType?bu.interpolationFactor(this.interpolationType,m,x,k):0}}function Lj(w,m,x,k,E){if((w=jx(w,m,x,k,E)).result==="error")return w;const P=w.value.expression,O=qy(P);if(!O&&!qp(m))return Uc([new Zu("","data expressions not supported")]);const U=_m(P,["zoom","pitch","distance-from-center"]);if(!U&&!ZN(m))return Uc([new Zu("","zoom expressions not supported")]);const H=_m(P,["measure-light"]);if(!H&&!YN(m))return Uc([new Zu("","measure-light expression not supported")]);const X=_m(P,["line-progress"]);if(!X&&!function(me){return jm(me.expression,"line-progress")}(m))return Uc([new Zu("","line-progress expression not supported")]);const le=m.expression&&m.expression.relaxZoomRestriction,he=Vp(P);return he||U||le?he instanceof Zu?Uc([he]):he instanceof bu&&!cp(m)?Uc([new Zu("",'"interpolate" expressions cannot be used with this property')]):KN(he?new Nx(O&&X?"camera":"composite",w.value,he.labels,he instanceof bu?he.interpolation:void 0,H,X):new b0(O&&X?"constant":"source",w.value,H,X)):Uc([new Zu("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class d_{constructor(m,x){this._parameters=m,this._specification=x,Object.assign(this,j6(this._parameters,this._specification))}static deserialize(m){return new d_(m._parameters,m._specification)}static serialize(m){return{_parameters:m._parameters,_specification:m._specification}}}function Vp(w){let m=null;if(w instanceof b1)m=Vp(w.result);else if(w instanceof n_){for(const x of w.args)if(m=Vp(x),m)break}else(w instanceof kj||w instanceof bu)&&w.input instanceof $c&&w.input.name==="zoom"&&(m=w);return m instanceof Zu||w.eachChild(x=>{const k=Vp(x);k instanceof Zu?m=k:m&&k&&m!==k&&(m=new Zu("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),m}var XN,JN,Dj=function(){if(JN)return XN;JN=1,XN=m;var w=3;function m(x,k,E){var P=this.cells=[];if(x instanceof ArrayBuffer){this.arrayBuffer=x;var O=new Int32Array(this.arrayBuffer);x=O[0],this.d=(k=O[1])+2*(E=O[2]);for(var U=0;U=me[Pe+0]&&P>=me[Pe+1])?(H[Se]=!0,U.push(he[Se])):H[Se]=!1}}},m.prototype._forEachCell=function(x,k,E,P,O,U,H,X){for(var le=this._convertToCellCoord(x),he=this._convertToCellCoord(k),me=this._convertToCellCoord(E),be=this._convertToCellCoord(P),Se=le;Se<=me;Se++)for(var Pe=he;Pe<=be;Pe++){var Be=this.d*Pe+Se;if((!X||X(this._convertFromCellCoord(Se),this._convertFromCellCoord(Pe),this._convertFromCellCoord(Se+1),this._convertFromCellCoord(Pe+1)))&&O.call(this,x,k,E,P,Be,U,H,X))return}},m.prototype._convertFromCellCoord=function(x){return(x-this.padding)/this.scale},m.prototype._convertToCellCoord=function(x){return Math.max(0,Math.min(this.d-1,Math.floor(x*this.scale)+this.padding))},m.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var x=this.cells,k=w+this.cells.length+1+1,E=0,P=0;P=0||(E[P]=hc(w[P],m)));w instanceof Error&&(E.message=w.message)}if(E.$name)throw new Error("$name property is reserved for worker serialization logic.");return k!=="Object"&&(E.$name=k),E}throw new Error("can't serialize object of type "+typeof w)}function tc(w){if(w==null||typeof w=="boolean"||typeof w=="number"||typeof w=="string"||w instanceof Boolean||w instanceof Number||w instanceof String||w instanceof Date||w instanceof RegExp||xo(w)||w instanceof ImageBitmap||ArrayBuffer.isView(w)||w instanceof ImageData)return w;if(Array.isArray(w))return w.map(tc);if(typeof w=="object"){const m=w.$name||"Object";if(m==="Map"){const E=w.entries||[],P=new Map;for(let O=0;Ow>=1536&&w<=1791,Hh=w=>w>=1872&&w<=1919,j0=w=>w>=2208&&w<=2303,dd=w=>w>=11904&&w<=12031,Hp=w=>w>=12032&&w<=12255,N0=w=>w>=12272&&w<=12287,Ky=w=>w>=12288&&w<=12351,N1=w=>w>=12352&&w<=12447,kx=w=>w>=12448&&w<=12543,Gh=w=>w>=12544&&w<=12591,u_=w=>w>=12704&&w<=12735,zf=w=>w>=12736&&w<=12783,xg=w=>w>=12784&&w<=12799,k1=w=>w>=12800&&w<=13055,Rj=w=>w>=13056&&w<=13311,Oj=w=>w>=13312&&w<=19903,Sx=w=>w>=19968&&w<=40959,Yy=w=>w>=40960&&w<=42127,gg=w=>w>=42128&&w<=42191,h_=w=>w>=44032&&w<=55215,Zy=w=>w>=63744&&w<=64255,Fj=w=>w>=64336&&w<=65023,zj=w=>w>=65040&&w<=65055,m_=w=>w>=65072&&w<=65103,jh=w=>w>=65104&&w<=65135,yg=w=>w>=65136&&w<=65279,dp=w=>w>=65280&&w<=65519;function Wh(w){for(const m of w)if(PC(m.charCodeAt(0)))return!0;return!1}function S6(w){for(const m of w)if(!MC(m.charCodeAt(0)))return!1;return!0}function MC(w){return!(Xu(w)||Hh(w)||j0(w)||Fj(w)||yg(w))}function IC(w){return!(w<11904||!(u_(w)||Gh(w)||m_(w)||Zy(w)||Rj(w)||dd(w)||zf(w)||Ky(w)||Oj(w)||Sx(w)||k1(w)||dp(w)||N1(w)||N0(w)||Hp(w)||xg(w)||kx(w)||zj(w)||gg(w)||Yy(w)))}function PC(w){return!(w!==746&&w!==747&&(w<4352||!(u_(w)||Gh(w)||m_(w)&&!(w>=65097&&w<=65103)||Zy(w)||Rj(w)||dd(w)||zf(w)||!(!Ky(w)||w>=12296&&w<=12305||w>=12308&&w<=12319||w===12336)||Oj(w)||Sx(w)||k1(w)||(m=>m>=12592&&m<=12687)(w)||(m=>m>=43360&&m<=43391)(w)||(m=>m>=55216&&m<=55295)(w)||(m=>m>=4352&&m<=4607)(w)||h_(w)||N1(w)||N0(w)||(m=>m>=12688&&m<=12703)(w)||Hp(w)||xg(w)||kx(w)&&w!==12540||!(!dp(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)||!(!jh(w)||w>=65112&&w<=65118||w>=65123&&w<=65126)||(m=>m>=5120&&m<=5759)(w)||(m=>m>=6320&&m<=6399)(w)||zj(w)||(m=>m>=19904&&m<=19967)(w)||Yy(w)||gg(w))))}function k0(w){return w===12312||w===12313||w===12316||w===12540||w===12448}function Qy(w){return!(PC(w)||function(m){return!!((x=>x>=128&&x<=255)(m)&&(m===167||m===169||m===174||m===177||m===188||m===189||m===190||m===215||m===247)||(x=>x>=8192&&x<=8303)(m)&&(m===8214||m===8224||m===8225||m===8240||m===8241||m===8251||m===8252||m===8258||m===8263||m===8264||m===8265||m===8273)||(x=>x>=8448&&x<=8527)(m)||(x=>x>=8528&&x<=8591)(m)||(x=>x>=8960&&x<=9215)(m)&&(m>=8960&&m<=8967||m>=8972&&m<=8991||m>=8996&&m<=9e3||m===9003||m>=9085&&m<=9114||m>=9150&&m<=9165||m===9167||m>=9169&&m<=9179||m>=9186&&m<=9215)||(x=>x>=9216&&x<=9279)(m)&&m!==9251||(x=>x>=9280&&x<=9311)(m)||(x=>x>=9312&&x<=9471)(m)||(x=>x>=9632&&x<=9727)(m)||(x=>x>=9728&&x<=9983)(m)&&!(m>=9754&&m<=9759)||(x=>x>=11008&&x<=11263)(m)&&(m>=11026&&m<=11055||m>=11088&&m<=11097||m>=11192&&m<=11243)||Ky(m)||kx(m)||(x=>x>=57344&&x<=63743)(m)||m_(m)||jh(m)||dp(m)||m===8734||m===8756||m===8757||m>=9984&&m<=10087||m>=10102&&m<=10131||m===65532||m===65533)}(w))}function LC(w){return Xu(w)||Hh(w)||j0(w)||Fj(w)||yg(w)}function Bj(w){return w>=1424&&w<=2303||Fj(w)||yg(w)}function vg(w,m){return!(!m&&Bj(w)||w>=2304&&w<=3583||w>=3840&&w<=4255||(x=>x>=6016&&x<=6143)(w))}function C6(w){for(const m of w)if(Bj(m.charCodeAt(0)))return!0;return!1}const Nm={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let Bf=null,Zd=Nm.unavailable,Gp=null;const T6=function(w){w&&typeof w=="string"&&w.indexOf("NetworkError")>-1&&(Zd=Nm.error),Bf&&Bf(w)};function ek(){tk.fire(new Bc("pluginStateChange",{pluginStatus:Zd,pluginURL:Gp}))}const tk=new Op,S0=function(){return Zd},E6=function(){if(Zd!==Nm.deferred||!Gp)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Zd=Nm.loading,ek(),Gp&&Dy({url:Gp},w=>{w?T6(w):(Zd=Nm.loaded,ek())})},km={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Zd===Nm.loaded||km.applyArabicShaping!=null,isLoading:()=>Zd===Nm.loading,setState(w){Zd=w.pluginStatus,Gp=w.pluginURL},isParsing:()=>Zd===Nm.parsing,isParsed:()=>Zd===Nm.parsed,getPluginURL:()=>Gp},DC=function(){km.isLoading()||km.isLoaded()||S0()!=="deferred"||E6()};class Ra{constructor(m,x){this.zoom=m,x?(this.now=x.now,this.fadeDuration=x.fadeDuration,this.transition=x.transition,this.pitch=x.pitch,this.brightness=x.brightness,this.worldview=x.worldview,this.activeFloors=x.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(m){return function(x,k){for(const E of x)if(!vg(E.charCodeAt(0),k))return!1;return!0}(m,km.isLoaded())}}class p_{constructor(m,x,k,E,P){this.property=m,this.value=x,this.expression=function(O,U,H,X,le){if(QN(O))return new d_(O,U);if(Wy(O)||Array.isArray(O)&&O.length>0){const he=Lj(O,U,H,X,le);if(he.result==="error")throw new Error(he.value.map(me=>`${me.key}: ${me.message}`).join(", "));return he.value}{let he=O;return typeof O=="string"&&U.type==="color"&&(he=Wn.parse(O)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>he}}}(x===void 0?m.specification.default:x,m.specification,k,E,P)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(m,x,k,E){return this.property.possiblyEvaluate(this,m,x,k,E)}}class $j{constructor(m,x,k,E){this.property=m,this.value=new p_(m,void 0,x,k,E)}transitioned(m,x){return new f_(this.property,this.value,x,Object.assign({},m.transition,this.transition),m.now)}untransitioned(){return new f_(this.property,this.value,null,{},0)}}class sk{constructor(m,x,k,E){this._properties=m,this._values=Object.create(m.defaultTransitionablePropertyValues),this._scope=x,this._options=k,this._iconImageUseTheme=E,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(m){return Un(this._values[m].value.value)}setValue(m,x){this._values.hasOwnProperty(m)||(this._values[m]=new $j(this._values[m].property,this._scope,this._options,this._iconImageUseTheme)),this._values[m].value=new p_(this._values[m].property,x===null?void 0:Un(x),this._scope,this._options,this._iconImageUseTheme),this._values[m].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[m].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[m].value.isIndoorDependent())}setTransitionOrValue(m,x){x&&(this._options=x);const k=this._properties.properties;if(m)for(const E in m){const P=m[E];if(E.endsWith("-transition")){const O=E.slice(0,-11);k[O]&&this.setTransition(O,P)}else k.hasOwnProperty(E)&&this.setValue(E,P)}}getTransition(m){return Un(this._values[m].transition)}setTransition(m,x){this._values.hasOwnProperty(m)||(this._values[m]=new $j(this._values[m].property)),this._values[m].transition=Un(x)||void 0}serialize(){const m={};for(const x of Object.keys(this._values)){const k=this.getValue(x);k!==void 0&&(m[x]=k);const E=this.getTransition(x);E!==void 0&&(m[`${x}-transition`]=E)}return m}transitioned(m,x){const k=new nk(this._properties);for(const E of Object.keys(this._values))k._values[E]=this._values[E].transitioned(m,x._values[E]);return k}untransitioned(){const m=new nk(this._properties);for(const x of Object.keys(this._values))m._values[x]=this._values[x].untransitioned();return m}isIndoorDependent(){return this._isIndoorDependent}}class f_{constructor(m,x,k,E,P){const O=E.delay||0,U=E.duration||0;P=P||0,this.property=m,this.value=x,this.begin=P+O,this.end=this.begin+U,m.specification.transition&&(E.delay||E.duration)&&(this.prior=k)}possiblyEvaluate(m,x,k){const E=m.now||0,P=this.value.possiblyEvaluate(m,x,k),O=this.prior;if(O){if(E>this.end)return this.prior=null,P;if(this.value.isDataDriven())return this.prior=null,P;if(E":1,">=":1,"<":1,"<=":1,"in":1,"!in":1,"all":1,"any":1,"none":1,"has":1,"!has":1}},"geometry_type":{"type":"enum","values":{"Point":1,"LineString":1,"Polygon":1}},"function":{"expression":{"type":"expression"},"stops":{"type":"array","value":"function_stop"},"base":{"type":"number","default":1,"minimum":0},"property":{"type":"string","default":"$zoom"},"type":{"type":"enum","values":{"identity":1,"exponential":1,"interval":1,"categorical":1},"default":"exponential"},"colorSpace":{"type":"enum","values":{"rgb":1,"lab":1,"hcl":1},"default":"rgb"},"default":{"type":"*"}},"function_stop":{"type":"array","minimum":0,"maximum":24,"value":["number","color"],"length":2},"expression":{"type":"array","value":"*","minimum":1},"fog":{"range":{"type":"array","default":[0.5,10],"minimum":-20,"maximum":20,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"high-color":{"type":"color","default":"#245cdf","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"space-color":{"type":"color","default":["interpolate",["linear"],["zoom"],4,"#010b19",7,"#367ab9"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"horizon-blend":{"type":"number","default":["interpolate",["linear"],["zoom"],4,0.2,7,0.1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"star-intensity":{"type":"number","default":["interpolate",["linear"],["zoom"],5,0.35,6,0],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vertical-range":{"type":"array","default":[0,0],"minimum":0,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}}},"snow":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.85],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.3],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.4,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,50],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"flake-size":{"type":"number","default":0.71,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"rain":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.5],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#03113d",0.3,"#a8adbc"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":["interpolate",["linear"],["measure-light","brightness"],0,0.88,1,0.7],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#001736",0.3,"#464646"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.57,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,80],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"droplet-size":{"type":"array","default":[2.6,18.2],"minimum":0,"maximum":50,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"distortion-strength":{"type":"number","default":0.7,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"camera":{"camera-projection":{"type":"enum","values":{"perspective":1,"orthographic":1},"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"default":"perspective"}},"colorTheme":{"data":{"type":"string","expression":{}}},"indoor_source":{"sourceId":{"type":"string"},"sourceLayers":{"type":"array","value":"string"}},"indoor":{"*":{"type":"indoor_source"}},"light":{"anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"position":{"type":"array","default":[1.15,210,30],"length":3,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"use-theme":true,"transition":true},"intensity":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"projection":{"name":{"type":"enum","values":{"albers":1,"equalEarth":1,"equirectangular":1,"lambertConformalConic":1,"mercator":1,"naturalEarth":1,"winkelTripel":1,"globe":1},"default":"mercator"},"center":{"type":"array","length":2,"value":"number","minimum":[-180,-90],"maximum":[180,90]},"parallels":{"type":"array","length":2,"value":"number","minimum":[-90,-90],"maximum":[90,90]}},"terrain":{"source":{"type":"string"},"exaggeration":{"type":"number","default":1,"minimum":0,"maximum":1000,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"paint":["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_building","paint_symbol","paint_raster","paint_raster-particle","paint_hillshade","paint_background","paint_sky","paint_model"],"paint_fill":{"fill-antialias":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-outline-color":{"type":"color","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-bridge-guard-rail-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"},"fill-tunnel-structure-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-extrusion-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-extrusion-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-height":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-height-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"flat"},"fill-extrusion-base-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"terrain"},"fill-extrusion-vertical-gradient":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-wall-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-wall-radius":{"property-type":"data-driven","type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-radius":{"property-type":"data-driven","type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-rounded-roof":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"fill-extrusion-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"fill-extrusion-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"property-type":"data-driven"},"fill-extrusion-line-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-cast-shadows":{"type":"boolean","default":true}},"paint_building":{"building-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"parameters":[]},"transition":true},"building-ambient-occlusion-ground-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-cast-shadows":{"type":"boolean","default":true},"building-color":{"type":"color","default":"rgba(193, 154, 127, 1)","use-theme":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-facade-emissive-chance":{"type":"number","default":0.35,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["measure-light","zoom"]}},"building-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"building-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"building-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_line":{"line-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"line-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"line-width":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light","line-progress"]},"property-type":"data-driven"},"line-gap-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-offset":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-dasharray":{"type":"array","value":"number","minimum":0,"expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-gradient":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["line-progress"]}},"line-trim-offset":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1]},"line-trim-fade-range":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1],"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-trim-color":{"type":"color","default":"transparent","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-driven"},"line-border-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-border-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"line-blend-mode":{"type":"enum","values":{"default":1,"multiply":1,"additive":1},"default":"default","expression":{"parameters":["zoom"]}}},"paint_circle":{"circle-radius":{"type":"number","default":5,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-blur":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"circle-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"circle-pitch-scale":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"circle-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]}},"circle-stroke-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_heatmap":{"heatmap-radius":{"type":"number","default":30,"minimum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-weight":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-intensity":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"heatmap-color":{"type":"color","default":["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",0.1,"royalblue",0.3,"cyan",0.5,"lime",0.7,"yellow",1,"red"],"use-theme":true,"expression":{"interpolated":true,"parameters":["heatmap-density"]}},"heatmap-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_symbol":{"icon-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"appearance":true,"property-type":"data-driven"},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"appearance":true,"property-type":"data-driven"},"icon-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"icon-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"icon-image-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"text-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"overridable":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"text-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"icon-color-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{}},"icon-color-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{}},"icon-color-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"icon-color-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{}},"symbol-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"}},"paint_raster":{"raster-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["raster-value"]}},"raster-color-mix":{"type":"array","default":[0.2126,0.7152,0.0722,0],"length":4,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color-range":{"type":"array","length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-hue-rotate":{"type":"number","default":0,"period":360,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-resampling":{"type":"enum","values":{"linear":1,"nearest":1},"default":"linear","expression":{"parameters":["zoom"]}},"raster-fade-duration":{"type":"number","default":300,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"raster-array-band":{"type":"string"},"raster-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1},"default":"sea","expression":{}}},"paint_raster-particle":{"raster-particle-array-band":{"type":"string"},"raster-particle-count":{"type":"number","default":512,"minimum":1},"raster-particle-color":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["raster-particle-speed"]}},"raster-particle-max-speed":{"type":"number","default":1,"minimum":1},"raster-particle-speed-factor":{"type":"number","default":0.2,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-particle-fade-opacity-factor":{"type":"number","default":0.98,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-particle-reset-rate-factor":{"type":"number","default":0.8,"minimum":0,"maximum":1},"raster-particle-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_hillshade":{"hillshade-illumination-direction":{"type":"number","default":335,"minimum":0,"maximum":359,"expression":{"interpolated":true,"parameters":["zoom"]}},"hillshade-illumination-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]}},"hillshade-exaggeration":{"type":"number","default":0.5,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"hillshade-shadow-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-highlight-color":{"type":"color","default":"#FFFFFF","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-accent-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_background":{"background-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":[]}},"background-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"background-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom"]}},"background-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"background-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_sky":{"sky-type":{"type":"enum","values":{"gradient":1,"atmosphere":1},"default":"atmosphere","expression":{"parameters":["zoom"]}},"sky-atmosphere-sun":{"type":"array","value":"number","length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]}},"sky-atmosphere-sun-intensity":{"type":"number","default":10,"minimum":0,"maximum":100},"sky-gradient-center":{"type":"array","value":"number","default":[0,0],"length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]}},"sky-gradient-radius":{"type":"number","default":90,"minimum":0,"maximum":180,"expression":{"parameters":["zoom"]}},"sky-gradient":{"type":"color","default":["interpolate",["linear"],["sky-radial-progress"],0.8,"#87ceeb",1,"white"],"use-theme":true,"expression":{"interpolated":true,"parameters":["sky-radial-progress"]}},"sky-atmosphere-halo-color":{"type":"color","default":"white","use-theme":true},"sky-atmosphere-color":{"type":"color","default":"white","use-theme":true},"sky-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_model":{"model-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"property-type":"data-driven"},"model-rotation":{"type":"array","value":"number","length":3,"default":[0,0,0],"period":360,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-scale":{"type":"array","value":"number","length":3,"default":[1,1,1],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-translation":{"type":"array","value":"number","length":3,"default":[0,0,0],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-color":{"type":"color","default":"#ffffff","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light","zoom"]},"use-theme":true,"transition":true},"model-color-mix-intensity":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-type":{"type":"enum","values":{"common-3d":1,"location-indicator":1},"default":"common-3d"},"model-cast-shadows":{"type":"boolean","default":true},"model-receive-shadows":{"type":"boolean","default":true},"model-ambient-occlusion-intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"model-emissive-strength":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-roughness":{"type":"number","default":1,"minimum":0,"maximum":1,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state"]},"transition":true},"model-height-based-emissive-strength-multiplier":{"type":"array","default":[1,1,1,1,0],"length":5,"value":"number","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"model-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"model-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1,"hd-road-markup":1},"default":"ground","expression":{}},"model-ignore-line-cutout":{"type":"boolean","default":false,"expression":{}}},"transition":{"duration":{"type":"number","default":300,"minimum":0},"delay":{"type":"number","default":0,"minimum":0}},"promoteId":{"*":{"type":"*"}}}');function Uj(w){return w instanceof Number||w instanceof String||w instanceof Boolean?w.valueOf():w}function x_(w){if(Array.isArray(w))return w.map(x_);if(w instanceof Object&&!(w instanceof Number||w instanceof String||w instanceof Boolean)){const m={};for(const x in w)m[x]=x_(w[x]);return m}return Uj(w)}function qj(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 m of w.slice(1))if(!qj(m)&&typeof m!="boolean")return!1;return!0;default:return!0}}function ak(w,m="",x=null,k="fill"){if(w==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};qj(w)||(w=ok(w));const E=w;let P=!0;try{P=function(le){if(!C1(le))return le;let he=x_(le);return OC(he),he=RC(he),he}(E)}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(E,null,2)} `)}let O=null,U=null;if(k!=="background"&&k!=="sky"&&k!=="slot"){U=fs[`filter_${k}`];const le=jx(P,U,m,x);if(le.result==="error")throw new Error(le.value.map(he=>`${he.key}: ${he.message}`).join(", "));O=(he,me,be)=>le.value.evaluate(he,me,{},be)}let H=null,X=null;if(P!==E){const le=jx(E,U,m,x);if(le.result==="error")throw new Error(le.value.map(he=>`${he.key}: ${he.message}`).join(", "));H=(he,me,be,Se,Pe)=>le.value.evaluate(he,me,{},be,void 0,void 0,Se,Pe),X=!qy(le.value.expression)}return{filter:O,dynamicFilter:H||void 0,needGeometry:A6(P),needFeature:!!X}}function RC(w){if(!Array.isArray(w))return w;const m=function(x){if(FC.has(x[0])){for(let k=1;kRC(x))}function OC(w){let m=!1;const x=[];if(w[0]==="case"){for(let k=1;k",">=","<","<=","to-boolean"]);function ik(w,m){return wm?1:0}function A6(w){if(!Array.isArray(w))return!1;if(w[0]==="within"||w[0]==="distance")return!0;for(let m=1;m"||m==="<="||m===">="?Q(w[1],w[2],m):m==="any"?(x=w.slice(1),["any"].concat(x.map(ok))):m==="all"?["all"].concat(w.slice(1).map(ok)):m==="none"?["all"].concat(w.slice(1).map(ok).map(Ve)):m==="in"?J(w[1],w.slice(2)):m==="!in"?Ve(J(w[1],w.slice(2))):m==="has"?ke(w[1]):m!=="!has"||Ve(ke(w[1]));var x}function Q(w,m,x){switch(w){case"$type":return[`filter-type-${x}`,m];case"$id":return[`filter-id-${x}`,m];default:return[`filter-${x}`,w,m]}}function J(w,m){if(m.length===0)return!1;switch(w){case"$type":return["filter-type-in",["literal",m]];case"$id":return["filter-id-in",["literal",m]];default:return m.length>200&&!m.some(x=>typeof x!=typeof m[0])?["filter-in-large",w,["literal",m.sort(ik)]]:["filter-in-small",w,["literal",m]]}}function ke(w){switch(w){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",w]}}function Ve(w){return["!",w]}const et="";function yt(w,m){return m?`${w}${et}${m}`:w}function ps(w){const m=w.indexOf(et);return m>=0?w.slice(m+1):""}let pn;const Kn=()=>pn||(pn=new Zo({"icon-size":new Nn(fs.layout_symbol["icon-size"]),"icon-image":new Nn(fs.layout_symbol["icon-image"]),"icon-rotate":new Nn(fs.layout_symbol["icon-rotate"]),"icon-offset":new Nn(fs.layout_symbol["icon-offset"]),"text-size":new Nn(fs.layout_symbol["text-size"]),"text-rotate":new Nn(fs.layout_symbol["text-rotate"]),"text-offset":new Nn(fs.layout_symbol["text-offset"])}));let qr;const Va=()=>qr||(qr=new Zo({"icon-opacity":new Nn(fs.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Nn(fs.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Nn(fs.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Nn(fs.paint_symbol["text-emissive-strength"]),"icon-color":new Nn(fs.paint_symbol["icon-color"]),"icon-halo-color":new Nn(fs.paint_symbol["icon-halo-color"]),"icon-halo-width":new Nn(fs.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Nn(fs.paint_symbol["icon-halo-blur"]),"icon-translate":new Nn(fs.paint_symbol["icon-translate"]),"text-opacity":new Nn(fs.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Nn(fs.paint_symbol["text-occlusion-opacity"]),"text-color":new Nn(fs.paint_symbol["text-color"],{runtimeType:Uh,getOverride:w=>w.textColor,hasOverride:w=>!!w.textColor}),"text-halo-color":new Nn(fs.paint_symbol["text-halo-color"]),"text-halo-width":new Nn(fs.paint_symbol["text-halo-width"]),"text-halo-blur":new Nn(fs.paint_symbol["text-halo-blur"]),"text-translate":new Nn(fs.paint_symbol["text-translate"]),"symbol-z-offset":new Nn(fs.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"})}));class oo{constructor(m,x,k,E,P,O){this._conditionSpec=m,this._propertiesSpec=k;const U=jx(m,fs.appearance.condition);if(U.result==="success"&&(this.condition=U.value),this.name=x,k){this.layoutProperties=new Qd(Kn()),this.unevaluatedLayout=new rk(Kn(),E,P,O),this.paintProperties=new Qd(Va()),this.unevaluatedPaint=new rk(Va(),E,P,"");for(const H in k)H in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(H,k[H]):H in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(H,k[H])}}isActive(m){return!(this.condition||!m.isHidden||this.name!=="hidden")||this.condition.evaluate(m.globals,m.feature,m.featureState,m.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(m){return this.layoutProperties.get(m)}getPaintProperty(m){return this.paintProperties.get(m)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(m){return this.unevaluatedLayout._values[m]}getUnevaluatedPaintProperty(m){return this.unevaluatedPaint._values[m]}recalculate(m,x,k){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(m,void 0,x,k)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(m,void 0,x,""))}serialize(){const m={};m.condition=this.condition.expression.serialize(),this.name&&(m.name=this.name);const x=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},k=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},E=Object.assign({},x,k);return Object.keys(E).length>0&&(m.properties=E),m}hasIconLayoutProperties(){const m=this.hasLayoutProperty("icon-image"),x=this.hasLayoutProperty("icon-size"),k=this.hasLayoutProperty("icon-offset"),E=this.hasLayoutProperty("icon-rotate");return m||x||k||E}hasTextLayoutProperties(){const m=this.hasLayoutProperty("text-size"),x=this.hasLayoutProperty("text-offset"),k=this.hasLayoutProperty("text-rotate");return m||x||k}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(m=>!m.endsWith("-use-theme")).some(m=>(m.startsWith("icon-")||m==="symbol-z-offset")&&this.hasPaintProperty(m))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(m=>!m.endsWith("-use-theme")).some(m=>(m.startsWith("text-")||m==="symbol-z-offset")&&this.hasPaintProperty(m))}hasLayoutProperty(m){return this.unevaluatedLayout&&this.unevaluatedLayout._values[m].value!==void 0}hasPaintProperty(m){return this.unevaluatedPaint&&this.unevaluatedPaint._values[m].value!==void 0}}const Ta="-transition",kc=new Set(["fill","line","background","hillshade","raster"]);class lo extends Op{constructor(m,x,k,E,P,O){if(super(),this.id=m.id,this.fqid=yt(this.id,k),this.type=m.type,this.scope=k,this.lut=E,this.options=P,this.iconImageUseTheme=O,this.appearances=new Array,this.appearancesVersion=0,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,this.expressionDependencies={isIndoorDependent:!1,configDependencies:new Set},m.type!=="custom"){if(this.metadata=m.metadata,this.minzoom=m.minzoom,this.maxzoom=m.maxzoom,m.type&&m.type!=="background"&&m.type!=="sky"&&m.type!=="slot"){this.source=m.source,this.sourceLayer=m["source-layer"],this.filter=m.filter;const U=jx(this.filter,fs[`filter_${m.type}`]);U.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...U.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||U.value.isIndoorDependent)}if(m.slot&&(this.slot=m.slot),m.appearances&&this.setAppearances(m.appearances),x.layout&&(this._unevaluatedLayout=new rk(x.layout,this.scope,P,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),x.paint){this._transitionablePaint=new sk(x.paint,this.scope,P);for(const U in m.paint)this.setPaintProperty(U,m.paint[U]);for(const U in m.layout)this.setLayoutProperty(U,m.layout[U]);this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._transitionablePaint.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._transitionablePaint.isIndoorDependent(),this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Qd(x.paint)}}}onAdd(m){}onRemove(m){}isDraped(m){return!this.is3D(!0)&&kc.has(this.type)}getLayoutProperty(m){return m==="visibility"?this.visibility:this._unevaluatedLayout.getValue(m)}setLayoutProperty(m,x){if(this.type==="custom"&&m==="visibility")return void(this.visibility=x);const k=this._unevaluatedLayout;k._properties.properties[m]&&(k.setValue(m,x),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...k.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||k.isIndoorDependent(),m==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(m){this.appearances=[],m.forEach(x=>{this.appearances.push(new oo(x.condition,x.name,x.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(m){return m.endsWith(Ta)?this._transitionablePaint.getTransition(m.slice(0,-11)):this._transitionablePaint.getValue(m)}isPaintProperty(m){return!!this._transitionablePaint._properties.properties[m]}setPaintProperty(m,x){const k=this._transitionablePaint,E=k._properties.properties;if(m.endsWith(Ta)){const he=m.slice(0,-11);return E[he]&&k.setTransition(he,x||void 0),!1}if(!E[m])return!1;const P=k._values[m],O=P.value.isDataDriven(),U=P.value;k.setValue(m,x),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...k.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||k.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(m);const H=k._values[m].value,X=H.isDataDriven(),le=m.endsWith("pattern")||m==="line-dasharray";return X||O||le||this._handleOverridablePaintPropertyUpdate(m,U,H)}_handleSpecialPaintPropertyUpdate(m){}getProgramIds(){return null}getDefaultProgramParams(m,x,k){return null}_handleOverridablePaintPropertyUpdate(m,x,k){return!1}isHidden(m){return!!(this.minzoom&&m=this.maxzoom)||this.visibility==="none"}updateTransitions(m){this._transitioningPaint=this._transitionablePaint.transitioned(m,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(m,x){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(m,void 0,x,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(m,void 0,x)}serialize(){const m={id:this.id,type:this.type,slot:this.slot,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.appearances.length!==0&&(m.appearances=this.appearances.map(x=>x.serialize())),Ks(m,(x,k)=>!(x===void 0||k==="layout"&&!Object.keys(x).length||k==="paint"&&!Object.keys(x).length))}is3D(m){return!1}hasElevation(){return!1}isSky(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}hasShadowPass(){return!1}canCastShadows(){return!1}hasLightBeamPass(){return!1}cutoffRange(){return 0}tileCoverLift(){return 0}resize(){}_clear(){}isStateDependent(){for(const m in this.paint._values){const x=this.paint.get(m);if(x instanceof S1&&qp(x.property.specification)&&(x.value.kind==="source"||x.value.kind==="composite")&&x.value.isStateDependent)return!0}for(const m of this.appearances)if(!Vy(m.condition.expression))return!0;return!1}compileFilter(m){this._filterCompiled||(this._featureFilter=ak(this.filter,this.scope,m),this._filterCompiled=!0)}invalidateCompiledFilter(){this._filterCompiled=!1}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}dynamicFilterNeedsGeometry(){return this._featureFilter.needGeometry}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(m){this._stats&&(m.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(m,x,k){return{}}queryRadius(m){}queryIntersectsFeature(m,x,k,E,P,O,U,H,X,le){}}const Nh={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Kp{constructor(m,x){this._structArray=m,this._pos1=x*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const Vn=new ArrayBuffer(0);class Zs{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(m,x){return m._trim(),x&&m.arrayBuffer&&x.add(m.arrayBuffer),{length:m.length,arrayBuffer:m.arrayBuffer}}static deserialize(m){const x=Object.create(this.prototype);return x.arrayBuffer=m.arrayBuffer,x.length=m.length,m.arrayBuffer?x.capacity=m.arrayBuffer.byteLength/x.bytesPerElement:(x.capacity=0,x.arrayBuffer=Vn),x._refreshViews(),x}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(m){this.reserve(m),this.length=m}reserve(m){if(m>this.capacity){this._reallocCount++,this.capacity=Math.max(m,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const x=this.uint8;this._refreshViews(),x&&this.uint8.set(x)}}reserveForAdditional(m){this.reserve(this.length+m)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...m){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...m){throw new Error("StructArray#emplaceBack() must be implemented by each concrete StructArray layout")}destroy(){this.int8=this.uint8=this.int16=this.uint16=this.int32=this.uint32=this.float32=null,this.arrayBuffer=null}}function cn(w,m=1){let x=0,k=0;return{members:w.map(E=>{const P=Nh[E.type].BYTES_PER_ELEMENT,O=x=Oa(x,Math.max(m,P)),U=E.components||1;return k=Math.max(k,P),x+=P*U,{name:E.name,type:E.type,components:U,offset:O}}),size:Oa(x,Math.max(k,m)),alignment:m}}function Oa(w,m){return Math.ceil(w/m)*m}class Wa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x){const k=this.length;return this.resize(k+1),this.emplace(k,m,x)}emplace(m,x,k){const E=2*m;return this.int16[E+0]=x,this.int16[E+1]=k,m}}Wa.prototype.bytesPerElement=4,Yn(Wa,"StructArrayLayout2i4");class Ui extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k){const E=this.length;return this.resize(E+1),this.emplace(E,m,x,k)}emplace(m,x,k,E){const P=3*m;return this.int16[P+0]=x,this.int16[P+1]=k,this.int16[P+2]=E,m}}Ui.prototype.bytesPerElement=6,Yn(Ui,"StructArrayLayout3i6");class ai extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,E){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,E)}emplace(m,x,k,E,P){const O=4*m;return this.int16[O+0]=x,this.int16[O+1]=k,this.uint16[O+2]=E,this.uint16[O+3]=P,m}}ai.prototype.bytesPerElement=8,Yn(ai,"StructArrayLayout2i2ui8");class ro extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.float32[1*m+0]=x,m}}ro.prototype.bytesPerElement=4,Yn(ro,"StructArrayLayout1f4");class Xd extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k){const E=this.length;return this.resize(E+1),this.emplace(E,m,x,k)}emplace(m,x,k,E){const P=4*m,O=2*m;return this.int16[P+0]=x,this.int16[P+1]=k,this.float32[O+1]=E,m}}Xd.prototype.bytesPerElement=8,Yn(Xd,"StructArrayLayout2i1f8");class il extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k){const E=this.length;return this.resize(E+1),this.emplace(E,m,x,k)}emplace(m,x,k,E){const P=4*m;return this.int16[P+0]=x,this.int16[P+1]=k,this.int16[P+2]=E,m}}il.prototype.bytesPerElement=8,Yn(il,"StructArrayLayout3i8");class bg extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,E){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,E)}emplace(m,x,k,E,P){const O=4*m;return this.int16[O+0]=x,this.int16[O+1]=k,this.int16[O+2]=E,this.int16[O+3]=P,m}}bg.prototype.bytesPerElement=8,Yn(bg,"StructArrayLayout4i8");class zC extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P){const O=this.length;return this.resize(O+1),this.emplace(O,m,x,k,E,P)}emplace(m,x,k,E,P,O){const U=5*m;return this.int16[U+0]=x,this.int16[U+1]=k,this.int16[U+2]=E,this.int16[U+3]=P,this.int16[U+4]=O,m}}zC.prototype.bytesPerElement=10,Yn(zC,"StructArrayLayout5i10");class BC extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U){const H=this.length;return this.resize(H+1),this.emplace(H,m,x,k,E,P,O,U)}emplace(m,x,k,E,P,O,U,H){const X=6*m,le=12*m,he=3*m;return this.int16[X+0]=x,this.int16[X+1]=k,this.uint8[le+4]=E,this.uint8[le+5]=P,this.uint8[le+6]=O,this.uint8[le+7]=U,this.float32[he+2]=H,m}}BC.prototype.bytesPerElement=12,Yn(BC,"StructArrayLayout2i4ub1f12");class _g extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k){const E=this.length;return this.resize(E+1),this.emplace(E,m,x,k)}emplace(m,x,k,E){const P=3*m;return this.float32[P+0]=x,this.float32[P+1]=k,this.float32[P+2]=E,m}}_g.prototype.bytesPerElement=12,Yn(_g,"StructArrayLayout3f12");class Xy extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P){const O=this.length;return this.resize(O+1),this.emplace(O,m,x,k,E,P)}emplace(m,x,k,E,P,O){const U=6*m,H=3*m;return this.uint16[U+0]=x,this.uint16[U+1]=k,this.uint16[U+2]=E,this.uint16[U+3]=P,this.float32[H+2]=O,m}}Xy.prototype.bytesPerElement=12,Yn(Xy,"StructArrayLayout4ui1f12");class lk extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,E){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,E)}emplace(m,x,k,E,P){const O=4*m;return this.uint16[O+0]=x,this.uint16[O+1]=k,this.uint16[O+2]=E,this.uint16[O+3]=P,m}}lk.prototype.bytesPerElement=8,Yn(lk,"StructArrayLayout4ui8");class M6 extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,E,P,O)}emplace(m,x,k,E,P,O,U){const H=6*m;return this.int16[H+0]=x,this.int16[H+1]=k,this.int16[H+2]=E,this.int16[H+3]=P,this.int16[H+4]=O,this.int16[H+5]=U,m}}M6.prototype.bytesPerElement=12,Yn(M6,"StructArrayLayout6i12");class GR extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X,le,he,me){const be=this.length;return this.resize(be+1),this.emplace(be,m,x,k,E,P,O,U,H,X,le,he,me)}emplace(m,x,k,E,P,O,U,H,X,le,he,me,be){const Se=12*m;return this.int16[Se+0]=x,this.int16[Se+1]=k,this.int16[Se+2]=E,this.int16[Se+3]=P,this.uint16[Se+4]=O,this.uint16[Se+5]=U,this.uint16[Se+6]=H,this.uint16[Se+7]=X,this.int16[Se+8]=le,this.int16[Se+9]=he,this.int16[Se+10]=me,this.int16[Se+11]=be,m}}GR.prototype.bytesPerElement=24,Yn(GR,"StructArrayLayout4i4ui4i24");class WR extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,E,P,O)}emplace(m,x,k,E,P,O,U){const H=10*m,X=5*m;return this.int16[H+0]=x,this.int16[H+1]=k,this.int16[H+2]=E,this.float32[X+2]=P,this.float32[X+3]=O,this.float32[X+4]=U,m}}WR.prototype.bytesPerElement=20,Yn(WR,"StructArrayLayout3i3f20");class T1 extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,E)}emplace(m,x,k,E,P){const O=4*m;return this.float32[O+0]=x,this.float32[O+1]=k,this.float32[O+2]=E,this.float32[O+3]=P,m}}T1.prototype.bytesPerElement=16,Yn(T1,"StructArrayLayout4f16");class $C extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.uint32[1*m+0]=x,m}}$C.prototype.bytesPerElement=4,Yn($C,"StructArrayLayout1ul4");class wg extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x){const k=this.length;return this.resize(k+1),this.emplace(k,m,x)}emplace(m,x,k){const E=2*m;return this.uint16[E+0]=x,this.uint16[E+1]=k,m}}wg.prototype.bytesPerElement=4,Yn(wg,"StructArrayLayout2ui4");class I6 extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X,le,he,me,be){const Se=this.length;return this.resize(Se+1),this.emplace(Se,m,x,k,E,P,O,U,H,X,le,he,me,be)}emplace(m,x,k,E,P,O,U,H,X,le,he,me,be,Se){const Pe=20*m,Be=10*m;return this.int16[Pe+0]=x,this.int16[Pe+1]=k,this.int16[Pe+2]=E,this.int16[Pe+3]=P,this.int16[Pe+4]=O,this.float32[Be+3]=U,this.float32[Be+4]=H,this.float32[Be+5]=X,this.float32[Be+6]=le,this.int16[Pe+14]=he,this.uint32[Be+8]=me,this.uint16[Pe+18]=be,this.uint16[Pe+19]=Se,m}}I6.prototype.bytesPerElement=40,Yn(I6,"StructArrayLayout5i4f1i1ul2ui40");class UC extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U){const H=this.length;return this.resize(H+1),this.emplace(H,m,x,k,E,P,O,U)}emplace(m,x,k,E,P,O,U,H){const X=8*m;return this.int16[X+0]=x,this.int16[X+1]=k,this.int16[X+2]=E,this.int16[X+4]=P,this.int16[X+5]=O,this.int16[X+6]=U,this.int16[X+7]=H,m}}UC.prototype.bytesPerElement=16,Yn(UC,"StructArrayLayout3i2i2i16");class KR extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P){const O=this.length;return this.resize(O+1),this.emplace(O,m,x,k,E,P)}emplace(m,x,k,E,P,O){const U=4*m,H=8*m;return this.float32[U+0]=x,this.float32[U+1]=k,this.float32[U+2]=E,this.int16[H+6]=P,this.int16[H+7]=O,m}}KR.prototype.bytesPerElement=16,Yn(KR,"StructArrayLayout2f1f2i16");class qC extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,E,P,O)}emplace(m,x,k,E,P,O,U){const H=20*m,X=5*m;return this.uint8[H+0]=x,this.uint8[H+1]=k,this.float32[X+1]=E,this.float32[X+2]=P,this.float32[X+3]=O,this.float32[X+4]=U,m}}qC.prototype.bytesPerElement=20,Yn(qC,"StructArrayLayout2ub4f20");class sc extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k){const E=this.length;return this.resize(E+1),this.emplace(E,m,x,k)}emplace(m,x,k,E){const P=3*m;return this.uint16[P+0]=x,this.uint16[P+1]=k,this.uint16[P+2]=E,m}}sc.prototype.bytesPerElement=6,Yn(sc,"StructArrayLayout3ui6");class P6 extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be,We,ot,nt,ft,bt){const wt=this.length;return this.resize(wt+1),this.emplace(wt,m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be,We,ot,nt,ft,bt)}emplace(m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be,We,ot,nt,ft,bt,wt){const Yt=30*m,zt=15*m,Kt=60*m;return this.int16[Yt+0]=x,this.int16[Yt+1]=k,this.int16[Yt+2]=E,this.float32[zt+2]=P,this.float32[zt+3]=O,this.uint16[Yt+8]=U,this.uint16[Yt+9]=H,this.uint32[zt+5]=X,this.uint32[zt+6]=le,this.uint32[zt+7]=he,this.uint16[Yt+16]=me,this.uint16[Yt+17]=be,this.uint16[Yt+18]=Se,this.float32[zt+10]=Pe,this.float32[zt+11]=Be,this.uint8[Kt+48]=We,this.uint8[Kt+49]=ot,this.uint8[Kt+50]=nt,this.uint32[zt+13]=ft,this.int16[Yt+28]=bt,this.uint8[Kt+58]=wt,m}}P6.prototype.bytesPerElement=60,Yn(P6,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class YR extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be,We,ot,nt,ft,bt,wt,Yt,zt,Kt,Vt,Ht,Os,Vs,Js,nn,en,xn){const Ls=this.length;return this.resize(Ls+1),this.emplace(Ls,m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be,We,ot,nt,ft,bt,wt,Yt,zt,Kt,Vt,Ht,Os,Vs,Js,nn,en,xn)}emplace(m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be,We,ot,nt,ft,bt,wt,Yt,zt,Kt,Vt,Ht,Os,Vs,Js,nn,en,xn,Ls){const tn=20*m,on=40*m,gn=80*m;return this.float32[tn+0]=x,this.float32[tn+1]=k,this.int16[on+4]=E,this.int16[on+5]=P,this.int16[on+6]=O,this.int16[on+7]=U,this.int16[on+8]=H,this.int16[on+9]=X,this.int16[on+10]=le,this.int16[on+11]=he,this.int16[on+12]=me,this.uint16[on+13]=be,this.uint16[on+14]=Se,this.uint16[on+15]=Pe,this.uint16[on+16]=Be,this.uint16[on+17]=We,this.uint16[on+18]=ot,this.uint16[on+19]=nt,this.uint16[on+20]=ft,this.uint16[on+21]=bt,this.uint16[on+22]=wt,this.uint16[on+23]=Yt,this.uint16[on+24]=zt,this.uint16[on+25]=Kt,this.uint16[on+26]=Vt,this.uint16[on+27]=Ht,this.uint32[tn+14]=Os,this.float32[tn+15]=Vs,this.float32[tn+16]=Js,this.float32[tn+17]=nn,this.float32[tn+18]=en,this.uint8[gn+76]=xn,this.uint16[on+39]=Ls,m}}YR.prototype.bytesPerElement=80,Yn(YR,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class L6 extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,E,P,O)}emplace(m,x,k,E,P,O,U){const H=6*m;return this.float32[H+0]=x,this.float32[H+1]=k,this.float32[H+2]=E,this.float32[H+3]=P,this.float32[H+4]=O,this.float32[H+5]=U,m}}L6.prototype.bytesPerElement=24,Yn(L6,"StructArrayLayout6f24");class Vj extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P){const O=this.length;return this.resize(O+1),this.emplace(O,m,x,k,E,P)}emplace(m,x,k,E,P,O){const U=5*m;return this.float32[U+0]=x,this.float32[U+1]=k,this.float32[U+2]=E,this.float32[U+3]=P,this.float32[U+4]=O,m}}Vj.prototype.bytesPerElement=20,Yn(Vj,"StructArrayLayout5f20");class VC extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U){const H=this.length;return this.resize(H+1),this.emplace(H,m,x,k,E,P,O,U)}emplace(m,x,k,E,P,O,U,H){const X=7*m;return this.float32[X+0]=x,this.float32[X+1]=k,this.float32[X+2]=E,this.float32[X+3]=P,this.float32[X+4]=O,this.float32[X+5]=U,this.float32[X+6]=H,m}}VC.prototype.bytesPerElement=28,Yn(VC,"StructArrayLayout7f28");class ZR extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X,le,he){const me=this.length;return this.resize(me+1),this.emplace(me,m,x,k,E,P,O,U,H,X,le,he)}emplace(m,x,k,E,P,O,U,H,X,le,he,me){const be=11*m;return this.float32[be+0]=x,this.float32[be+1]=k,this.float32[be+2]=E,this.float32[be+3]=P,this.float32[be+4]=O,this.float32[be+5]=U,this.float32[be+6]=H,this.float32[be+7]=X,this.float32[be+8]=le,this.float32[be+9]=he,this.float32[be+10]=me,m}}ZR.prototype.bytesPerElement=44,Yn(ZR,"StructArrayLayout11f44");class QR extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X){const le=this.length;return this.resize(le+1),this.emplace(le,m,x,k,E,P,O,U,H,X)}emplace(m,x,k,E,P,O,U,H,X,le){const he=9*m;return this.float32[he+0]=x,this.float32[he+1]=k,this.float32[he+2]=E,this.float32[he+3]=P,this.float32[he+4]=O,this.float32[he+5]=U,this.float32[he+6]=H,this.float32[he+7]=X,this.float32[he+8]=le,m}}QR.prototype.bytesPerElement=36,Yn(QR,"StructArrayLayout9f36");class Hj extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x){const k=this.length;return this.resize(k+1),this.emplace(k,m,x)}emplace(m,x,k){const E=2*m;return this.float32[E+0]=x,this.float32[E+1]=k,m}}Hj.prototype.bytesPerElement=8,Yn(Hj,"StructArrayLayout2f8");class XR extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,E){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,E)}emplace(m,x,k,E,P){const O=6*m;return this.uint32[3*m+0]=x,this.uint16[O+2]=k,this.uint16[O+3]=E,this.uint16[O+4]=P,m}}XR.prototype.bytesPerElement=12,Yn(XR,"StructArrayLayout1ul3ui12");class Gj extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.uint16[1*m+0]=x,m}}Gj.prototype.bytesPerElement=2,Yn(Gj,"StructArrayLayout1ui2");class JR extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be){const We=this.length;return this.resize(We+1),this.emplace(We,m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be)}emplace(m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be,We){const ot=16*m;return this.float32[ot+0]=x,this.float32[ot+1]=k,this.float32[ot+2]=E,this.float32[ot+3]=P,this.float32[ot+4]=O,this.float32[ot+5]=U,this.float32[ot+6]=H,this.float32[ot+7]=X,this.float32[ot+8]=le,this.float32[ot+9]=he,this.float32[ot+10]=me,this.float32[ot+11]=be,this.float32[ot+12]=Se,this.float32[ot+13]=Pe,this.float32[ot+14]=Be,this.float32[ot+15]=We,m}}JR.prototype.bytesPerElement=64,Yn(JR,"StructArrayLayout16f64");class D6 extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U){const H=this.length;return this.resize(H+1),this.emplace(H,m,x,k,E,P,O,U)}emplace(m,x,k,E,P,O,U,H){const X=10*m,le=5*m;return this.uint16[X+0]=x,this.uint16[X+1]=k,this.uint16[X+2]=E,this.uint16[X+3]=P,this.float32[le+2]=O,this.float32[le+3]=U,this.float32[le+4]=H,m}}D6.prototype.bytesPerElement=20,Yn(D6,"StructArrayLayout4ui3f20");class R6 extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.int16[1*m+0]=x,m}}R6.prototype.bytesPerElement=2,Yn(R6,"StructArrayLayout1i2");class O6 extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.uint8[1*m+0]=x,m}}O6.prototype.bytesPerElement=1,Yn(O6,"StructArrayLayout1ub1");class aq extends Kp{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]}}aq.prototype.size=40;class eO extends I6{get(m){return new aq(this,m)}}Yn(eO,"CollisionBoxArray");class iq extends Kp{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.float32[this._pos4+2]}get tileAnchorY(){return this._structArray.float32[this._pos4+3]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+8]}get numGlyphs(){return this._structArray.uint16[this._pos2+9]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+5]}get lineStartIndex(){return this._structArray.uint32[this._pos4+6]}get lineLength(){return this._structArray.uint32[this._pos4+7]}get segment(){return this._structArray.uint16[this._pos2+16]}get lowerSize(){return this._structArray.uint16[this._pos2+17]}get upperSize(){return this._structArray.uint16[this._pos2+18]}get lineOffsetX(){return this._structArray.float32[this._pos4+10]}get lineOffsetY(){return this._structArray.float32[this._pos4+11]}get writingMode(){return this._structArray.uint8[this._pos1+48]}get placedOrientation(){return this._structArray.uint8[this._pos1+49]}set placedOrientation(m){this._structArray.uint8[this._pos1+49]=m}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(m){this._structArray.uint8[this._pos1+50]=m}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(m){this._structArray.uint32[this._pos4+13]=m}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(m){this._structArray.uint8[this._pos1+58]=m}}iq.prototype.size=60;class oq extends P6{get(m){return new iq(this,m)}}Yn(oq,"PlacedSymbolArray");class HC extends Kp{get tileAnchorX(){return this._structArray.float32[this._pos4+0]}get tileAnchorY(){return this._structArray.float32[this._pos4+1]}get projectedAnchorX(){return this._structArray.int16[this._pos2+4]}get projectedAnchorY(){return this._structArray.int16[this._pos2+5]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+6]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+7]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+8]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+9]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+10]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+11]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+12]}get key(){return this._structArray.uint16[this._pos2+13]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+14]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+15]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+16]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+17]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+18]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+19]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+20]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+21]}get featureIndex(){return this._structArray.uint16[this._pos2+22]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+23]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+24]}get numIconVertices(){return this._structArray.uint16[this._pos2+25]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+26]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+27]}get crossTileID(){return this._structArray.uint32[this._pos4+14]}set crossTileID(m){this._structArray.uint32[this._pos4+14]=m}get textOffset0(){return this._structArray.float32[this._pos4+15]}get textOffset1(){return this._structArray.float32[this._pos4+16]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+17]}get zOffset(){return this._structArray.float32[this._pos4+18]}set zOffset(m){this._structArray.float32[this._pos4+18]=m}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}HC.prototype.size=80;class lq extends YR{get(m){return new HC(this,m)}}Yn(lq,"SymbolInstanceArray");class cq extends ro{getoffsetX(m){return this.float32[1*m+0]}}Yn(cq,"GlyphOffsetArray");class GC extends Wa{getx(m){return this.int16[2*m+0]}gety(m){return this.int16[2*m+1]}}Yn(GC,"SymbolLineVertexArray");class dq extends Kp{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]}}dq.prototype.size=12;class tO extends XR{get(m){return new dq(this,m)}}Yn(tO,"FeatureIndexArray");class uq extends wg{geta_centroid_pos0(m){return this.uint16[2*m+0]}geta_centroid_pos1(m){return this.uint16[2*m+1]}}Yn(uq,"FillExtrusionCentroidArray");class sO extends Kp{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]}}sO.prototype.size=6;class nO extends Ui{get(m){return new sO(this,m)}}Yn(nO,"FillExtrusionWallArray");const hq=cn([{name:"a_pos",components:2,type:"Int16"}],4),Sbe=cn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),Cbe=cn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Po{constructor(m=[]){this.segments=m}_prepareSegment(m,x,k,E,P){let O=this.segments[this.segments.length-1];return m>Po.MAX_VERTEX_ARRAY_LENGTH&&sr(`Max vertices per segment is ${Po.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${m}`),(!O||O.vertexLength+m>Po.MAX_VERTEX_ARRAY_LENGTH||O.sortKey!==E||P!==void 0&&O&&O.batchIndex!==void 0&&O.batchIndex!==P)&&(O={vertexOffset:x,primitiveOffset:k,vertexLength:0,primitiveLength:0},E!==void 0&&(O.sortKey=E),P!==void 0&&(O.batchIndex=P),this.segments.push(O)),O}prepareSegment(m,x,k,E,P){return this._prepareSegment(m,x.length,k.length,E,P)}get(){return this.segments}destroy(){for(const m of this.segments)for(const x in m.vaos)m.vaos[x].destroy()}static simpleSegment(m,x,k,E){return new Po([{vertexOffset:m,primitiveOffset:x,vertexLength:k,primitiveLength:E,vaos:{},sortKey:0}])}}function F6(w,m){return 256*(w=Qe(Math.floor(w),0,255))+Qe(Math.floor(m),0,255)}Po.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Yn(Po,"SegmentVector");const Tbe=cn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),Ebe=cn([{name:"a_pattern_b",components:4,type:"Uint16"}]),Abe=cn([{name:"a_dash",components:4,type:"Uint16"}]);class WC{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(m,x,k,E){this.ids.push(rO(m)),this.positions.push(x,k,E)}eachPosition(m,x){const k=rO(m);let E=0,P=this.ids.length-1;for(;E>1;this.ids[O]>=k?P=O:E=O+1}for(;this.ids[E]===k;)x(this.positions[3*E],this.positions[3*E+1],this.positions[3*E+2]),E++}static serialize(m,x){const k=new Float64Array(m.ids),E=new Uint32Array(m.positions);return KC(k,E,0,k.length-1),x&&(x.add(k.buffer),x.add(E.buffer)),{ids:k,positions:E}}static deserialize(m){const x=new WC;let k;x.ids=m.ids,x.positions=m.positions;for(const E of x.ids)E!==k&&x.uniqueIds.push(E),k=E;return x.indexed=!0,x}}function rO(w){const m=+w;return Number.isSafeInteger(m)?m:Td(String(w))}function KC(w,m,x,k){for(;x>1];let P=x-1,O=k+1;for(;;){do P++;while(w[P]E);if(P>=O)break;Cx(w,P,O),Cx(m,3*P,3*O),Cx(m,3*P+1,3*O+1),Cx(m,3*P+2,3*O+2)}O-x`u_${P}`),this.type=k,this.context=E}setUniform(m,x,k,E,P){const O=E.constantOr(this.value);x.set(m,P,O instanceof Wn?O.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):O)}getBinding(m,x){return this.type==="color"?new Ibe(m):new ud(m)}}class ue{constructor(m,x){this.uniformNames=x.map(k=>`u_${k}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(m,x){this.pixelRatio=m.pixelRatio||1,this.pattern=m.tl.concat(m.br),this.patternTransition=x?x.tl.concat(x.br):this.pattern}setUniform(m,x,k,E,P){let O=null;P!=="u_pattern"&&P!=="u_dash"||(O=this.pattern),P==="u_pattern_b"&&(O=this.patternTransition),P==="u_pixel_ratio"&&(O=this.pixelRatio),O&&x.set(m,P,O)}getBinding(m,x){return x==="u_pattern"||x==="u_pattern_b"||x==="u_dash"?new Mbe(m):new ud(m)}}class xe{constructor(m,x,k,E){this.expression=m,this.type=k,this.maxValue=0,this.paintVertexAttributes=x.map(P=>({name:`a_${P}`,type:"Float32",components:k==="color"?2:1,offset:0})),this.paintVertexArray=new E}populatePaintArray(m,x,k,E,P,O,U,H){const X=this.paintVertexArray.length,le=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new Ra(0,{brightness:O,worldview:H}),x,{},P,E,U):this.expression.kind==="constant"&&this.expression.value,he=Z(this.lutExpression,x,{},E,P,O,U,H);this.paintVertexArray.resize(m),this._setPaintValue(X,m,le,he?null:this.context.lut)}updatePaintArray(m,x,k,E,P,O,U,H){const X=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:U,worldview:H},k,E,void 0,P):this.expression.kind==="constant"&&this.expression.value,le=Z(this.lutExpression,k,E,P,void 0,U,void 0,H);this._setPaintValue(m,x,X,le?null:this.context.lut)}_setPaintValue(m,x,k,E){if(this.type==="color"){const P=G(k.toPremultipliedRenderColor(E));for(let O=m;O`u_${U}_t`),this.type=k,this.useIntegerZoom=E,this.context=P,this.maxValue=0,this.paintVertexAttributes=x.map(U=>({name:`a_${U}`,type:"Float32",components:k==="color"?4:2,offset:0})),this.paintVertexArray=new O}populatePaintArray(m,x,k,E,P,O,U,H){const X=this.expression.evaluate(new Ra(this.context.zoom,{brightness:O,worldview:H}),x,{},P,E,U),le=this.expression.evaluate(new Ra(this.context.zoom+1,{brightness:O,worldview:H}),x,{},P,E,U),he=Z(this.lutExpression,x,{},E,P,O,U,H),me=this.paintVertexArray.length;this.paintVertexArray.resize(m),this._setPaintValue(me,m,X,le,he?null:this.context.lut)}updatePaintArray(m,x,k,E,P,O,U,H){const X=this.expression.evaluate({zoom:this.context.zoom,brightness:U,worldview:H},k,E,void 0,P),le=this.expression.evaluate({zoom:this.context.zoom+1,brightness:U,worldview:H},k,E,void 0,P),he=Z(this.lutExpression,k,E,P,void 0,U,void 0,H);this._setPaintValue(m,x,X,le,he?null:this.context.lut)}_setPaintValue(m,x,k,E,P){if(this.type==="color"){const O=G(k.toPremultipliedRenderColor(P)),U=G(E.toPremultipliedRenderColor(P));for(let H=m;H!0){this.binders={},this._buffers=[],this.context=x;const E=[],P=m;for(const O in m.paint._values){const U=P.paint.get(O);if(O.endsWith("-use-theme")||!k(O)||!(U instanceof S1&&qp(U.property.specification)))continue;const H=Xe(O,m.type),X=U.value,le=U.property.specification.type,he=!!U.property.useIntegerZoom,me=O==="line-dasharray"||O.endsWith("pattern"),be=P.paint.get(`${O}-use-theme`),Se=O==="line-dasharray"&&P.layout.get("line-cap").value.kind!=="constant"||be&&be.value.kind!=="constant";if(X.kind!=="constant"||Se)if(X.kind==="source"||Se||me){const Pe=jt(O,le,"source");this.binders[O]=me?new Re(X,H,le,Pe,m.id):new xe(X,H,le,Pe),E.push(`/a_${O}`)}else{const Pe=jt(O,le,"composite");this.binders[O]=new je(X,H,le,he,x,Pe),E.push(`/z_${O}`)}else this.binders[O]=me?new ue(X.value,H):new te(X.value,H,le,x),E.push(`/u_${O}`);be&&(this.binders[O].lutExpression=be.value)}this.cacheKey=E.sort().join("")}getMaxValue(m){const x=this.binders[m];return x instanceof xe||x instanceof je?x.maxValue:0}populatePaintArrays(m,x,k,E,P,O,U,H){for(const X in this.binders){const le=this.binders[X];le.context=this.context,(le instanceof xe||le instanceof je||le instanceof Re)&&le.populatePaintArray(m,x,k,E,P,O,U,H)}}setConstantPatternPositions(m,x){for(const k in this.binders){const E=this.binders[k];E instanceof ue&&E.setConstantPatternPositions(m,x)}}getPatternTransitionVertexBuffer(m){const x=this.binders[m];return x instanceof Re?x.paintTransitionVertexBuffer:null}updatePaintArrays(m,x,k,E,P,O,U,H,X,le){let he=!1;const me=Object.keys(m),be=me.length!==0&&!H,Se=be?me:x.uniqueIds;this.context.lut=P.lut;for(const Pe in this.binders){const Be=this.binders[Pe];if(Be.context=this.context,(Be instanceof xe||Be instanceof je||Be instanceof Re)&&Be.expression&&Be.expression.kind&&Be.expression.kind!=="constant"&&(Be.expression.isStateDependent===!0||Be.expression.isLightConstant===!1)){const We=P.paint.get(Pe);Be.expression=We.value;for(const ot of Se){const nt=m[ot.toString()];x.eachPosition(ot,(ft,bt,wt)=>{const Yt=E.feature(ft);Be.updatePaintArray(bt,wt,Yt,nt,O,U,X,le)})}if(!be)for(const ot of k.uniqueIds){const nt=m[ot.toString()];k.eachPosition(ot,(ft,bt,wt)=>{const Yt=E.feature(ft);Be.updatePaintArray(bt,wt,Yt,nt,O,U,X,le)})}he=!0}}return he}defines(){const m=[];for(const x in this.binders){const k=this.binders[x];(k instanceof te||k instanceof ue)&&m.push(...k.uniformNames.map(E=>`#define HAS_UNIFORM_${E}`))}return m}getPaintVertexBuffers(){return this._buffers}getUniforms(m){const x=[];for(const k in this.binders){const E=this.binders[k];if(E instanceof te||E instanceof ue||E instanceof je)for(const P of E.uniformNames)x.push({name:P,property:k,binding:E.getBinding(m,P)})}return x}setUniforms(m,x,k,E,P){for(const{name:O,property:U,binding:H}of k)this.binders[U].setUniform(m,H,P,E.get(U),O)}updatePaintBuffers(){this._buffers=[];for(const m in this.binders){const x=this.binders[m];(x instanceof xe||x instanceof je||x instanceof Re)&&x.paintVertexBuffer&&this._buffers.push(x.paintVertexBuffer),x instanceof Re&&x.paintTransitionVertexBuffer&&this._buffers.push(x.paintTransitionVertexBuffer)}}upload(m){for(const x in this.binders){const k=this.binders[x];(k instanceof xe||k instanceof je||k instanceof Re)&&k.upload(m)}this.updatePaintBuffers()}destroy(){for(const m in this.binders){const x=this.binders[m];(x instanceof xe||x instanceof je||x instanceof Re)&&x.destroy()}}}class Ue{constructor(m,x,k=()=>!0){this.programConfigurations={};for(const E of m)this.programConfigurations[E.id]=new Le(E,x,k);this.needsUpload=!1,this._featureMap=new WC,this._featureMapWithoutIds=new WC,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(m,x,k,E,P,O,U,H,X){for(const le in this.programConfigurations)this.programConfigurations[le].populatePaintArrays(m,x,E,P,O,U,H,X);x.id!==void 0?this._featureMap.add(x.id,k,this._bufferOffset,m):(this._featureMapWithoutIds.add(this._idlessCounter,k,this._bufferOffset,m),this._idlessCounter+=1),this._bufferOffset=m,this.needsUpload=!0}updatePaintArrays(m,x,k,E,P,O,U,H){for(const X of k)this.needsUpload=this.programConfigurations[X.id].updatePaintArrays(m,this._featureMap,this._featureMapWithoutIds,x,X,E,P,O,U||0,H)||this.needsUpload}get(m){return this.programConfigurations[m]}upload(m){if(this.needsUpload){for(const x in this.programConfigurations)this.programConfigurations[x].upload(m);this.needsUpload=!1}}destroy(){for(const m in this.programConfigurations)this.programConfigurations[m].destroy()}}const st={"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-occlusion-opacity":["occlusion_opacity"],"icon-occlusion-opacity":["occlusion_opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-emissive-strength":["emissive_strength"],"icon-emissive-strength":["emissive_strength"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"symbol-z-offset":["z_offset"],"line-gap-width":["gapwidth"],"line-pattern":["pattern","pixel_ratio","pattern_b"],"fill-pattern":["pattern","pixel_ratio","pattern_b"],"fill-extrusion-pattern":["pattern","pixel_ratio","pattern_b"],"line-dasharray":["dash"],"fill-bridge-guard-rail-color":["structure_color"],"fill-tunnel-structure-color":["structure_color"]};function Xe(w,m){return st[w]||[w.replace(`${m}-`,"").replace(/-/g,"_")]}const pt={"line-pattern":{source:Xy,composite:Xy},"fill-pattern":{source:Xy,composite:Xy},"fill-extrusion-pattern":{source:Xy,composite:Xy},"line-dasharray":{source:lk,composite:lk}},mt={color:{source:Hj,composite:T1},number:{source:ro,composite:Hj}};function jt(w,m,x){const k=pt[w];return k&&k[x]||mt[m][x]}Yn(te,"ConstantBinder"),Yn(ue,"PatternConstantBinder"),Yn(xe,"SourceExpressionBinder"),Yn(Re,"PatternCompositeBinder"),Yn(je,"CompositeExpressionBinder"),Yn(Le,"ProgramConfiguration",{omit:["_buffers"]}),Yn(Ue,"ProgramConfigurationSet");const Tt=Bn/Math.PI/2,xt=64,es=[xt,32,16],Ft=-Tt,Jt=Tt;function At(w,m,x,k=Tt){return x=lr(x),[w*Math.sin(x)*k,-m*k,w*Math.cos(x)*k]}function Rt(w,m,x){return At(Math.cos(lr(w)),Math.sin(lr(w)),m,x)}const Wt=63710088e-1,ys=2*Math.PI*Wt;class rs{constructor(m,x){if(isNaN(m)||isNaN(x))throw new Error(`Invalid LngLat object: (${m}, ${x})`);if(this.lng=+m,this.lat=+x,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new rs(vt(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(m){const x=Math.PI/180,k=this.lat*x,E=m.lat*x,P=Math.sin(k)*Math.sin(E)+Math.cos(k)*Math.cos(E)*Math.cos((m.lng-this.lng)*x);return Wt*Math.acos(Math.min(P,1))}toBounds(m=0){const x=360*m/40075017,k=x/Math.cos(Math.PI/180*this.lat);return new zs({lng:this.lng-k,lat:this.lat-x},{lng:this.lng+k,lat:this.lat+x})}toEcef(m){return Rt(this.lat,this.lng,Tt+m*Tt/Wt)}static convert(m){if(m instanceof rs)return m;if(Array.isArray(m)&&(m.length===2||m.length===3))return new rs(Number(m[0]),Number(m[1]));if(!Array.isArray(m)&&typeof m=="object"&&m!==null)return new rs(Number("lng"in m?m.lng:m.lon),Number(m.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}class zs{constructor(m,x){m&&(x?this.setSouthWest(m).setNorthEast(x):Array.isArray(m)&&m.length===4?this.setSouthWest([m[0],m[1]]).setNorthEast([m[2],m[3]]):this.setSouthWest(m[0]).setNorthEast(m[1]))}setNorthEast(m){return this._ne=m instanceof rs?new rs(m.lng,m.lat):rs.convert(m),this}setSouthWest(m){return this._sw=m instanceof rs?new rs(m.lng,m.lat):rs.convert(m),this}extend(m){const x=this._sw,k=this._ne;let E,P;if(m instanceof rs)E=m,P=m;else{if(!(m instanceof zs))return Array.isArray(m)?m.length===4||m.every(Array.isArray)?this.extend(zs.convert(m)):this.extend(rs.convert(m)):typeof m=="object"&&m!==null&&m.hasOwnProperty("lat")&&(m.hasOwnProperty("lon")||m.hasOwnProperty("lng"))?this.extend(rs.convert(m)):this;if(E=m._sw,P=m._ne,!E||!P)return this}return x||k?(x.lng=Math.min(E.lng,x.lng),x.lat=Math.min(E.lat,x.lat),k.lng=Math.max(P.lng,k.lng),k.lat=Math.max(P.lat,k.lat)):(this._sw=new rs(E.lng,E.lat),this._ne=new rs(P.lng,P.lat)),this}getCenter(){return new rs((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 rs(this.getWest(),this.getNorth())}getSouthEast(){return new rs(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(m){const{lng:x,lat:k}=rs.convert(m);let E=this._sw.lng<=x&&x<=this._ne.lng;return this._sw.lng>this._ne.lng&&(E=this._sw.lng>=x&&x>=this._ne.lng),this._sw.lat<=k&&k<=this._ne.lat&&E}static convert(m){if(m)return m instanceof zs?m:new zs(m)}}function Is(w){return ys*Math.cos(w*Math.PI/180)}function an(w){return(180+w)/360}function mn(w){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+w*Math.PI/360)))/360}function js(w,m){return w/Is(m)}function ms(w){return 360*w-180}function Rs(w){return 360/Math.PI*Math.atan(Math.exp((180-360*w)*Math.PI/180))-90}function qs(w,m){return w*Is(Rs(m))}const Qs=85.051129;function Dn(w){return Math.cos(lr(Qe(w,-85.051129,Qs)))}function Cn(w,m){const x=Qe(m,0,25.5),k=Math.pow(2,x);return Dn(w)*ys/(512*k)}function Tn(w){return 1/Math.cos(w*Math.PI/180)}function dn(w,m=0){const x=Math.exp(Math.PI*(1-(w.y+m/Bn)/(1<=H?(Er(w,m,x,X,le,P,he,U,H),Er(w,X,le,k,E,he,O,U,H)):w.push(O)}function ar(w,m,x){let k=w[0],E=k.x,P=k.y;m(k);const O=[k];for(let U=1;Uw.x+1||kw.y+1)&&sr("Geometry exceeds allowed extent, reduce your vector tile buffer size"),w}function Kr(w,m,x){const k=w.loadGeometry(),E=w.extent,P=Bn/E;if(m&&x&&x.projection.isReprojectedInTileSpace){const O=1<{const be=ms((m.x+me.x/E)/O),Se=Rs((m.y+me.y/E)/O),Pe=le.project(be,Se);me.x=(Pe.x*U-H)*E,me.y=(Pe.y*U-X)*E};for(let me=0;me=E||Se.y<0||Se.y>=E||(he(Se),be.push(Se));k[me]=be}}for(const O of k)for(const U of O)Ka(U,P);return k}function Ya(w,m){return{type:w.type,id:w.id,properties:w.properties,geometry:m?Kr(w):[]}}class _a{constructor(m,x,k,E,P){this.properties={},this.extent=k,this.type=0,this.id=void 0,this._pbf=m,this._geometry=-1,this._keys=E,this._values=P,m.readFields(Pi,this,x)}loadGeometry(){const m=this._pbf;m.pos=this._geometry;const x=m.readVarint()+m.pos,k=[];let E,P=1,O=0,U=0,H=0;for(;m.pos>3}if(O--,P===1||P===2)U+=m.readSVarint(),H+=m.readSVarint(),P===1&&(E&&k.push(E),E=[]),E&&E.push(new Ms(U,H));else{if(P!==7)throw new Error(`unknown command ${P}`);E&&E.push(E[0].clone())}}return E&&k.push(E),k}bbox(){const m=this._pbf;m.pos=this._geometry;const x=m.readVarint()+m.pos;let k=1,E=0,P=0,O=0,U=1/0,H=-1/0,X=1/0,le=-1/0;for(;m.pos>3}if(E--,k===1||k===2)P+=m.readSVarint(),O+=m.readSVarint(),PH&&(H=P),Ole&&(le=O);else if(k!==7)throw new Error(`unknown command ${k}`)}return[U,X,H,le]}toGeoJSON(m,x,k){const E=this.extent*Math.pow(2,k),P=this.extent*m,O=this.extent*x,U=this.loadGeometry();function H(me){return[360*(me.x+P)/E-180,360/Math.PI*Math.atan(Math.exp((1-2*(me.y+O)/E)*Math.PI))-90]}function X(me){return me.map(H)}let le;if(this.type===1){const me=[];for(const Se of U)me.push(Se[0]);const be=X(me);le=me.length===1?{type:"Point",coordinates:be[0]}:{type:"MultiPoint",coordinates:be}}else if(this.type===2){const me=U.map(X);le=me.length===1?{type:"LineString",coordinates:me[0]}:{type:"MultiLineString",coordinates:me}}else{if(this.type!==3)throw new Error("unknown feature type");{const me=function(Se){const Pe=Se.length;if(Pe<=1)return[Se];const Be=[];let We,ot;for(let nt=0;nt=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[m];const x=this._pbf.readVarint()+this._pbf.pos;return new _a(this._pbf,x,this.extent,this._keys,this._values)}}function Lo(w,m,x){w===15?m.version=x.readVarint():w===1?m.name=x.readString():w===5?m.extent=x.readVarint():w===2?m._features.push(x.pos):w===3?m._keys.push(x.readString()):w===4&&m._values.push(function(k){let E=null;const P=k.readVarint()+k.pos;for(;k.pos>3;E=O===1?k.readString():O===2?k.readFloat():O===3?k.readDouble():O===4?k.readVarint64():O===5?k.readVarint():O===6?k.readSVarint():O===7?k.readBoolean():null}if(E==null)throw new Error("unknown feature value");return E}(x))}class Vi{constructor(m,x){this.layers=m.readFields(Ba,{},x)}}function Ba(w,m,x){if(w===3){const k=new bl(x,x.readVarint()+x.pos);k.length&&(m[k.name]=k)}}const $a="3d_elevation_id",Do="level";class kl{constructor(){this._valid=!1}reset(m){return this.feature=m,this._valid=!0,this._geometry=m.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(m,x){return this._valid&&m(x(this._geometry)),this}require(m,x,k){return this.get(m,!0,x,k)}optional(m,x,k){return this.get(m,!1,x,k)}success(){return this._valid}get(m,x,k,E){const P=this.feature.properties.hasOwnProperty(m)?+this.feature.properties[m]:void 0;return this._valid&&P!==void 0&&!Number.isNaN(P)?k(E?E(P):P):x&&(this._valid=!1),this}}class Hi{constructor(m,x){this.featureFunc=m,this.vertexFunc=x}parseFeature(m,x,k){return this.featureFunc(m,x,k)}parseVertex(m,x,k){return this.vertexFunc(m,x,k)}}const Ea=new Hi((w,m,x)=>w.reset(m).require($a,k=>{x.id=k}).optional("fixed_height_relative",k=>{x.constantHeight=k},_o.decodeRelativeHeight).geometry(k=>{x.bounds=k},Qb).success(),(w,m,x)=>w.reset(m).require($a,k=>{x.id=k}).require("elevation_idx",k=>{x.idx=k}).require("extent",k=>{x.extent=k}).require("height_relative",k=>{x.height=k},_o.decodeRelativeHeight).geometry(k=>{x.position=k},_o.getPoint).success()),ul=new Hi((w,m,x)=>w.reset(m).require($a,k=>{x.id=k}).optional("fixed_height",k=>{x.constantHeight=k},_o.decodeMetricHeight).geometry(k=>{x.bounds=k},Qb).success(),(w,m,x)=>w.reset(m).require($a,k=>{x.id=k}).require("elevation_idx",k=>{x.idx=k}).require("extent",k=>{x.extent=k}).require("height",k=>{x.height=k},_o.decodeMetricHeight).geometry(k=>{x.position=k},_o.getPoint).success());class _o{static getPoint(m){return Ut(m[0][0].x,m[0][0].y)}static decodeRelativeHeight(m){return 1e-4*m*5}static decodeMetricHeight(m){return 1e-4*m}static getVersionSchema(m){return m?m==="1.0.1"?ul:void 0:Ea}static parse(m){const x=[],k=[],E=m.length,P=new kl;for(let O=0;O=0);if(P===0)return 0;P!==m.length&&(x=!1)}return x?2:1}function hd(w,m){for(const x of w.projections){const k=Xc(m,w.points[0],x.axis);if(x.projection[1]k[1])return 0}return 1}function _u(w,m){let x=0;const k=[0,0,0,0];for(let E=0;E=0&&x++;return x}class $f{constructor(m,x){this.points=m||new Array(8).fill([0,0,0]),this.planes=x||new Array(6).fill([0,0,0,0]),this.bounds=so.fromPoints(this.points),this.projections=[],this.frustumEdges=[$e([],this.points[2],this.points[3]),$e([],this.points[0],this.points[3]),$e([],this.points[4],this.points[0]),$e([],this.points[5],this.points[1]),$e([],this.points[6],this.points[2]),$e([],this.points[7],this.points[3])];for(const k of this.frustumEdges){const E=[0,-k[2],k[1]],P=[k[2],0,-k[0]];this.projections.push({axis:E,projection:Xc(this.points,this.points[0],E)}),this.projections.push({axis:P,projection:Xc(this.points,this.points[0],P)})}}static fromInvProjectionMatrix(m,x,k,E){const P=Math.pow(2,k),O=[[-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 le=dt([],X,m),he=1/le[3]/x*P;return(me=le)[0]=(be=le)[0]*(Se=[he,he,E?1/le[3]:he,he])[0],me[1]=be[1]*Se[1],me[2]=be[2]*Se[2],me[3]=be[3]*Se[3],me;var me,be,Se}),U=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(X=>{const le=Ie([],qe([],$e([],O[X[0]],O[X[1]]),$e([],O[X[2]],O[X[1]]))),he=-Fe(le,O[X[1]]);return le.concat(he)}),H=[];for(let X=0;XX[1]||X[0]>H[1])return 0}return 1}containsPoint(m){for(const x of this.planes){const k=x[3];if(Fe([x[0],x[1],x[2]],m)+k<0)return!1}return!0}}class so{static fromPoints(m){const x=[1/0,1/0,1/0],k=[-1/0,-1/0,-1/0];for(const E of m)ie(x,x,E),ye(k,k,E);return new so(x,k)}static fromTileIdAndHeight(m,x,k){const E=1<m.max[x]||m.min[x]>this.max[x])return!1;return!0}intersectsAabbXY(m){return!(this.min[0]>m.max[0]||m.min[0]>this.max[0]||this.min[1]>m.max[1]||m.min[1]>this.max[1])}encapsulate(m){for(let x=0;x<3;x++)this.min[x]=Math.min(this.min[x],m.min[x]),this.max[x]=Math.max(this.max[x],m.max[x])}encapsulatePoint(m){for(let x=0;x<3;x++)this.min[x]=Math.min(this.min[x],m[x]),this.max[x]=Math.max(this.max[x],m[x])}closestPoint(m){return[Math.max(Math.min(this.max[0],m[0]),this.min[0]),Math.max(Math.min(this.max[1],m[1]),this.min[1]),Math.max(Math.min(this.max[2],m[2]),this.min[2])]}}Yn(so,"Aabb");class Tx{constructor(m,x){this.feature=m,this.metersToTile=x,this.index=0}get(){const m=this.feature.vertices[this.index],x=this.feature.vertexProps[this.index].dir,k=x[1],E=-x[0],P=(m.extent+1)*this.metersToTile;return[new Ms(Math.trunc(m.position[0]+k*P),Math.trunc(m.position[1]+E*P)),new Ms(Math.trunc(m.position[0]-k*P),Math.trunc(m.position[1]-E*P))]}next(){this.index++}valid(){return this.index{return U.a0?_e(H,H,1/X):oe(H,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(m){if(this.edges.length===0)return;let x=0,k=Number.POSITIVE_INFINITY,E=0;const[P,O,U,H,X,le,he]=this._tmpVec2;Es(he,m.x,m.y);const me=new Sc(he,null);for(let be=0;be0?sn(H,U)/ft:0,wt=Qe(bt,0,1),Yt=Math.abs((bt-wt)*this.edgeProps[be].len);Ys(X,he,Be),Es(le,Pe[1],-Pe[0]);const zt=Yt+Math.abs(sn(X,le));zt=0;--O){const U=this.edges[O].a,H=this.edges[O].b,{position:X,height:le,extent:he}=this.vertices[U],{position:me,height:be,extent:Se}=this.vertices[H],Pe=this.vertexProps[U].dir,Be=this.vertexProps[H].dir;if(oe(x,X[0]/m,X[1]/m,le),oe(k,me[0]/m,me[1]/m,be),oe(E,Pe[1],-Pe[0],0),_e(E,E,he),oe(P,Be[1],-Be[0],0),_e(P,P,Se),this.distSqLines(ne(x[0]+.5*E[0],x[1]+.5*E[1],x[2]+.5*E[2]),ne(k[0]-.5*P[0],k[1]-.5*P[1],k[2]-.5*P[2]),ne(x[0]-.5*E[0],x[1]-.5*E[1],x[2]-.5*E[2]),ne(k[0]+.5*P[0],k[1]+.5*P[1],k[2]+.5*P[2]))<=.0025000000000000005)continue;const We=this.vertices.length,ot=Xt(ht(),X,me);this.vertices.push({position:Ss(ot,ot,.5),height:.5*(le+be),extent:.5*(he+Se)});const nt=Xt(ht(),Pe,Be);this.vertexProps.push({dir:Us(nt,nt)}),this.edges.splice(O,1),this.edgeProps.splice(O,1),this.edges.push({a:U,b:We}),this.edges.push({a:We,b:H});const ft=Ys(ht(),this.vertices[We].position,X),bt=Bs(ft),wt={vec:ft,dir:Ss(ht(),ft,1/bt),len:bt};this.edgeProps.push(wt),this.edgeProps.push(wt)}}distSqLines(m,x,k,E){const P=ce(K(),x,m),O=ce(K(),E,k),U=ce(K(),m,k),H=Fe(P,P),X=Fe(P,O),le=Fe(P,U),he=Fe(O,O),me=Fe(O,U),be=H*he-X*X;if(be===0)return Ce(ve(P,k,E,Fe(U,O)/Fe(O,O)),m);const Se=(H*me-X*le)/be;return Ce(ve(P,m,x,(X*me-le*he)/be),ve(O,k,E,Se))}}class $o{static parseFrom(m,x){const k=_o.parse(m);if(!k)return[];let{vertices:E,features:P}=k;const O=1/dn(x);P.sort((le,he)=>le.id-he.id),E.sort((le,he)=>le.id-he.id||le.idx-he.idx),E=E.filter((le,he,me)=>he===me.findIndex(be=>be.id===le.id&&be.idx===le.idx));const U=new Array;let H=0;const X=E.length;for(const le of P){if(le.constantHeight){U.push(new Ex(le.id,le.bounds,le.constantHeight));continue}for(;H!==X&&E[H].idE.id===k)}}class Qo{constructor(m,x){this.zScale=1,this.xOffset=0,this.yOffset=0,m.equals(x)||(this.zScale=Math.pow(2,x.z-m.z),this.xOffset=(m.x*this.zScale-x.x)*Bn,this.yOffset=(m.y*this.zScale-x.y)*Bn)}constantElevation(m,x){if(m.constantHeight!=null)return this.computeBiasedHeight(m.constantHeight,x)}pointElevation(m,x,k){const E=this.constantElevation(x,k);return E??(m.x=m.x*this.zScale+this.xOffset,m.y=m.y*this.zScale+this.yOffset,this.computeBiasedHeight(x.pointElevation(m),k))}computeBiasedHeight(m,x){return x<=0?m:m+x*ct(0,x,m>=0?m:Math.abs(.5*m))}}Yn(Ex,"ElevationFeature");class co{constructor(m){this.zoom=m.zoom,this.overscaling=m.overscaling,this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.projection=m.projection,this.layoutVertexArray=new Wa,this.indexArray=new sc,this.segments=new Po,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut}),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new ro),this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){const P=this.layers[0],O=[];let U=null;P.type==="circle"&&(U=P.layout.get("circle-sort-key"));for(const{feature:X,id:le,index:he,sourceLayerIndex:me}of m){const be=this.layers[0]._featureFilter.needGeometry,Se=Ya(X,be);if(!this.layers[0]._featureFilter.filter(new Ra(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),Se,k))continue;const Pe=U?U.evaluate(Se,{},k):void 0,Be={id:le,properties:X.properties,type:X.type,sourceLayerIndex:me,index:he,geometry:be?Se.geometry:Kr(X,k,E),patterns:{},sortKey:Pe};O.push(Be)}U&&O.sort((X,le)=>X.sortKey-le.sortKey);let H=null;E.projection.name==="globe"&&(this.globeExtVertexArray=new M6,H=E.projection);for(const X of O){const{geometry:le,index:he,sourceLayerIndex:me}=X,be=m[he].feature;this.addFeature(X,le,he,x.availableImages,k,H,x.brightness,x.elevationFeatures),x.featureIndex.insert(be,le,he,me,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(m,x,k,E,P,O,U){this.programConfigurations.updatePaintArrays(m,x,P,k,E,O,U,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,hq.members),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=m.createVertexBuffer(this.globeExtVertexArray,Cbe.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=m.createVertexBuffer(this.elevatedLayoutVertexArray,Sbe.members))),this.programConfigurations.upload(m),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy())}addFeature(m,x,k,E,P,O,U,H){let X;this.elevationMode!=="none"&&(X=$o.getElevationFeature(m,H));for(const le of x)for(const he of le){const me=he.x,be=he.y;if(me<0||me>=Bn||be<0||be>=Bn)continue;if(O){const Be=O.projectTilePoint(me,be,P),We=O.upVector(P,me,be);this.addGlobeExtVertex(Be,We),this.addGlobeExtVertex(Be,We),this.addGlobeExtVertex(Be,We),this.addGlobeExtVertex(Be,We)}const Se=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,m.sortKey),Pe=Se.vertexLength;if(this.addCircleVertex(me,be,-1,-1),this.addCircleVertex(me,be,1,-1),this.addCircleVertex(me,be,1,1),this.addCircleVertex(me,be,-1,1),this.elevationMode!=="none"){const Be=X?X.pointElevation(new Ms(me,be)):0;this.hasElevation=this.hasElevation||Be!==0;for(let We=0;We<4;We++)this.elevatedLayoutVertexArray.emplaceBack(Be)}this.indexArray.emplaceBack(Pe,Pe+1,Pe+2),this.indexArray.emplaceBack(Pe,Pe+2,Pe+3),Se.vertexLength+=4,Se.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,m,k,{},E,P,U,void 0,this.worldview)}addCircleVertex(m,x,k,E){this.layoutVertexArray.emplaceBack(2*m+(k+1)/2,2*x+(E+1)/2)}addGlobeExtVertex(m,x){this.globeExtVertexArray.emplaceBack(m.x,m.y,m.z,x[0]*16384,x[1]*16384,x[2]*16384)}}function mc(w,m){for(let x=0;x1){if(g_(w,m))return!0;for(let k=0;k1?x:x.sub(m)._mult(E)._add(m))}function dk(w,m){let x,k,E,P=!1;for(let O=0;Om.y!=E.y>m.y&&m.x<(E.x-k.x)*(m.y-k.y)/(E.y-k.y)+k.x&&(P=!P)}return P}function Yp(w,m){let x=!1;for(let k=0,E=w.length-1;km.y!=O.y>m.y&&m.x<(O.x-P.x)*(m.y-P.y)/(O.y-P.y)+P.x&&(x=!x)}return x}function y_(w,m,x,k,E){for(const O of w)if(m<=O.x&&x<=O.y&&k>=O.x&&E>=O.y)return!0;const P=[new Ms(m,x),new Ms(m,E),new Ms(k,E),new Ms(k,x)];if(w.length>2){for(const O of P)if(Yp(w,O))return!0}for(let O=0;OE.x&&m.x>E.x||w.yE.y&&m.y>E.y)return!1;const P=Tr(w,m,x[0]);return P!==Tr(w,m,x[1])||P!==Tr(w,m,x[2])||P!==Tr(w,m,x[3])}function b_(w,m,x,k,E,P){let O=m.y-w.y,U=w.x-m.x;if(P=P||0){const H=O*O+U*U;if(H===0)return!0;const X=Math.sqrt(H);O/=X,U/=X}return!((x.x-w.x)*O+(x.y-w.y)*U-P<0||(k.x-w.x)*O+(k.y-w.y)*U-P<0||(E.x-w.x)*O+(E.y-w.y)*U-P<0)}function B6(w,m,x,k,E,P,O){return!(b_(w,m,k,E,P,O)||b_(m,x,k,E,P,O)||b_(x,w,k,E,P,O)||b_(k,E,w,m,x,O)||b_(E,P,w,m,x,O)||b_(P,k,w,m,x,O))}function uk(w,m,x){const k=m.paint.get(w).value;return k.kind==="constant"?k.value:x.programConfigurations.get(m.id).getMaxValue(w)}function mq(w){return Math.sqrt(w[0]*w[0]+w[1]*w[1])}function NDe(w,m,x,k,E){if(!m[0]&&!m[1])return w;const P=Ms.convert(m)._mult(E);x==="viewport"&&P._rotate(-k);const O=[];for(let U=0;U>x&&m.y===this.y>>x}url(m,x){const k=function(P,O,U){const H=2**U,X=2*Math.PI*6378137,le=X*(P/H-.5),he=X*(.5-(O+1)/H);return`${le},${he},${le+X/H},${he+X/H}`}(this.x,this.y,this.z),E=function(P,O,U){let H,X="";for(let le=P;le>0;le--)H=1<this.canonical.z?new up(m,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new up(m,this.wrap,m,this.canonical.x>>x,this.canonical.y>>x)}calculateScaledKey(m,x=!0){if(this.overscaledZ===m&&x)return this.key;if(m>this.canonical.z)return $6(this.wrap*+x,m,this.canonical.z,this.canonical.x,this.canonical.y);{const k=this.canonical.z-m;return $6(this.wrap*+x,m,m,this.canonical.x>>k,this.canonical.y>>k)}}isChildOf(m){if(m.wrap!==this.wrap)return!1;const x=this.canonical.z-m.canonical.z;return m.overscaledZ===0||m.overscaledZ>x&&m.canonical.y===this.canonical.y>>x}children(m){if(this.overscaledZ>=m)return[new up(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const x=this.canonical.z+1,k=2*this.canonical.x,E=2*this.canonical.y;return[new up(x,this.wrap,x,k,E),new up(x,this.wrap,x,k+1,E),new up(x,this.wrap,x,k,E+1),new up(x,this.wrap,x,k+1,E+1)]}isLessThan(m){return this.wrapm.wrap)&&(this.overscaledZm.overscaledZ)&&(this.canonical.xm.canonical.x)&&this.canonical.y{let m=w.canonical.x-1,x=w.wrap;return m<0&&(m=(1<{let m=w.canonical.x+1,x=w.wrap;return m===1<new up(w.overscaledZ,w.wrap,w.canonical.z,w.canonical.x,(w.canonical.y===0?1<new up(w.overscaledZ,w.wrap,w.canonical.z,w.canonical.x,w.canonical.y===(1<1?null:function(k,E,P,O){const U=Math.sin(P);return k*(Math.sin((1-O)*P)/U)+E*(Math.sin(O*P)/U)}(w.a[m],w.b[m],w.angle,Qe(x,0,1))+w.center[m]}function __(w){if(w.z<=1)return M4t[w.z+2*w.y+w.x];const m=Lbe(xq(w));return so.fromPoints(m)}function Yj(w,m,x){return _e(w,w,1-x),Me(w,w,m,x)}function MDe(w,m){const x=Zj(m.zoom);if(x===0)return __(w);const k=xq(w),E=Lbe(k),P=an(k.getWest())*m.worldSize,O=an(k.getEast())*m.worldSize,U=mn(k.getNorth())*m.worldSize,H=mn(k.getSouth())*m.worldSize,X=[P,U,0],le=[O,U,0],he=[P,H,0],me=[O,H,0],be=j([],m.globeMatrix);return Je(X,X,be),Je(le,le,be),Je(he,he,be),Je(me,me,be),E[0]=Yj(E[0],he,x),E[1]=Yj(E[1],me,x),E[2]=Yj(E[2],le,x),E[3]=Yj(E[3],X,x),so.fromPoints(E)}function IDe(w,m,x){for(const k of w)Je(k,k,m),_e(k,k,x)}function PDe(w,m,x,k){const E=m/w.worldSize,P=w.globeMatrix;if(x.z<=1){const Kt=__(x).getCorners();return IDe(Kt,P,E),so.fromPoints(Kt)}const O=xq(x,k),U=Lbe(O,Tt+fq(w._tileCoverLift));IDe(U,P,E);const H=Number.MAX_VALUE,X=[-H,-H,-H],le=[H,H,H];if(O.contains(w.center)){for(const Ht of U)ie(le,le,Ht),ye(X,X,Ht);X[2]=0;const Kt=w.point,Vt=[Kt.x*E,Kt.y*E,0];return ie(le,le,Vt),ye(X,X,Vt),new so(le,X)}if(w._tileCoverLift>0){for(const Kt of U)ie(le,le,Kt),ye(X,X,Kt);return new so(le,X)}const he=[P[12]*E,P[13]*E,P[14]*E],me=O.getCenter(),be=Qe(w.center.lat,-85.051129,Qs),Se=Qe(me.lat,-85.051129,Qs),Pe=an(w.center.lng),Be=mn(be);let We=Pe-an(me.lng);const ot=Be-mn(Se);We>.5?We-=1:We<-.5&&(We+=1);let nt=0;Math.abs(We)>Math.abs(ot)?nt=We>=0?1:3:(nt=ot>=0?0:2,Me(he,he,[P[4]*E,P[5]*E,P[6]*E],-Math.sin(lr(ot>=0?O.getSouth():O.getNorth()))*Tt));const ft=U[nt],bt=U[(nt+1)%4],wt=new I4t(ft,bt,he),Yt=[Pbe(wt,0)||ft[0],Pbe(wt,1)||ft[1],Pbe(wt,2)||ft[2]],zt=Zj(w.zoom);if(zt>0){const Kt=function({x:Ht,y:Os,z:Vs},Js,nn,en,xn){const Ls=1/(1<.5?ir=-1:On<-.5&&(ir=1),tn=((tn+ir)*Js-(en*=Js))*nn+en,on=((on+ir)*Js-en)*nn+en,gn=(gn*Js-(xn*=Js))*nn+xn,En=(En*Js-xn)*nn+xn,[[tn,En,0],[on,En,0],[on,gn,0],[tn,gn,0]]}(x,m,w._pixelsPerMercatorPixel,Pe,Be);for(let Ht=0;HtMath.PI/2*1.01}const FDe=lr(85),P4t=Math.cos(FDe),L4t=Math.sin(FDe),D4t=g(),zDe=w=>{const m=[];return w.paint.get("circle-pitch-alignment")==="map"&&m.push("PITCH_WITH_MAP"),w.paint.get("circle-pitch-scale")==="map"&&m.push("SCALE_WITH_MAP"),m};function BDe(w,m,x,k,E,P,O,U,H){if(P&&w.queryGeometry.isAboveHorizon)return!1;P&&(H*=w.pixelToTileUnitsFactor);const X=w.tileID.canonical,le=x.projection.upVectorScale(X,x.center.lat,x.worldSize).metersToTile;for(const he of m)for(const me of he){const be=me.add(U),Se=E&&x.elevation?x.elevation.exaggeration()*E.getElevationAt(be.x,be.y,!0):0,Pe=x.projection.projectTilePoint(be.x,be.y,X);if(Se>0){const nt=x.projection.upVector(X,be.x,be.y);Pe.x+=nt[0]*le*Se,Pe.y+=nt[1]*le*Se,Pe.z+=nt[2]*le*Se}const Be=P?be:R4t(Pe.x,Pe.y,Pe.z,k),We=P?w.tilespaceRays.map(nt=>F4t(nt,Se)):w.queryGeometry.screenGeometry,ot=dt([],[Pe.x,Pe.y,Pe.z,1],k);if(!O&&P?H*=ot[3]/x.cameraToCenterDistance:O&&!P&&(H*=x.cameraToCenterDistance/ot[3]),P){const nt=Rs((me.y/Bn+X.y)/(1<w.width||E.height>w.height||x.x>w.width-E.width||x.y>w.height-E.height)throw new RangeError("out of range source coordinates for image copy");if(E.width>m.width||E.height>m.height||k.x>m.width-E.width||k.y>m.height-E.height)throw new RangeError("out of range destination coordinates for image copy");const H=w.data,X=m.data,le=P===4&&U;for(let he=0;he{m[w.evaluationKey]=H;const X=w.expression.evaluate(m),le=X?X.toNonPremultipliedRenderColor(null):null;le&&(E.data[O+U+0]=Math.floor(255*le.r),E.data[O+U+1]=Math.floor(255*le.g),E.data[O+U+2]=Math.floor(255*le.b),E.data[O+U+3]=Math.floor(255*le.a))};if(w.clips)for(let O=0,U=0;O80*x){U=w[0],H=w[1];let le=U,he=H;for(let me=x;mele&&(le=be),Se>he&&(he=Se)}X=Math.max(le-U,he-H),X=X!==0?32767/X:0}return cO(P,O,x,U,H,X,0),O}function ZDe(w,m,x,k,E){let P;if(E===function(O,U,H,X){let le=0;for(let he=U,me=H-X;he0)for(let O=m;O=m;O-=k)P=eRe(O/k|0,w[O],w[O+1],P);return P&&q6(P,P.next)&&(hO(P),P=P.next),P}function XC(w,m){if(!w)return w;m||(m=w);let x,k=w;do if(x=!1,k.steiner||!q6(k,k.next)&&wu(k.prev,k,k.next)!==0)k=k.next;else{if(hO(k),k=m=k.prev,k===k.next)break;x=!0}while(x||k!==m);return m}function cO(w,m,x,k,E,P,O){if(!w)return;!O&&P&&function(H,X,le,he){let me=H;do me.z===0&&(me.z=zbe(me.x,me.y,X,le,he)),me.prevZ=me.prev,me.nextZ=me.next,me=me.next;while(me!==H);me.prevZ.nextZ=null,me.prevZ=null,function(be){let Se,Pe=1;do{let Be,We=be;be=null;let ot=null;for(Se=0;We;){Se++;let nt=We,ft=0;for(let wt=0;wt0||bt>0&&nt;)ft!==0&&(bt===0||!nt||We.z<=nt.z)?(Be=We,We=We.nextZ,ft--):(Be=nt,nt=nt.nextZ,bt--),ot?ot.nextZ=Be:be=Be,Be.prevZ=ot,ot=Be;We=nt}ot.nextZ=null,Pe*=2}while(Se>1)}(me)}(w,k,E,P);let U=w;for(;w.prev!==w.next;){const H=w.prev,X=w.next;if(P?V4t(w,k,E,P):q4t(w))m.push(H.i,w.i,X.i),hO(w),w=X.next,U=X.next;else if((w=X)===U){O?O===1?cO(w=H4t(XC(w),m),m,x,k,E,P,2):O===2&&G4t(w,m,x,k,E,P):cO(XC(w),m,x,k,E,P,1);break}}}function q4t(w){const m=w.prev,x=w,k=w.next;if(wu(m,x,k)>=0)return!1;const E=m.x,P=x.x,O=k.x,U=m.y,H=x.y,X=k.y,le=Math.min(E,P,O),he=Math.min(U,H,X),me=Math.max(E,P,O),be=Math.max(U,H,X);let Se=k.next;for(;Se!==m;){if(Se.x>=le&&Se.x<=me&&Se.y>=he&&Se.y<=be&&dO(E,U,P,H,O,X,Se.x,Se.y)&&wu(Se.prev,Se,Se.next)>=0)return!1;Se=Se.next}return!0}function V4t(w,m,x,k){const E=w.prev,P=w,O=w.next;if(wu(E,P,O)>=0)return!1;const U=E.x,H=P.x,X=O.x,le=E.y,he=P.y,me=O.y,be=Math.min(U,H,X),Se=Math.min(le,he,me),Pe=Math.max(U,H,X),Be=Math.max(le,he,me),We=zbe(be,Se,m,x,k),ot=zbe(Pe,Be,m,x,k);let nt=w.prevZ,ft=w.nextZ;for(;nt&&nt.z>=We&&ft&&ft.z<=ot;){if(nt.x>=be&&nt.x<=Pe&&nt.y>=Se&&nt.y<=Be&&nt!==E&&nt!==O&&dO(U,le,H,he,X,me,nt.x,nt.y)&&wu(nt.prev,nt,nt.next)>=0||(nt=nt.prevZ,ft.x>=be&&ft.x<=Pe&&ft.y>=Se&&ft.y<=Be&&ft!==E&&ft!==O&&dO(U,le,H,he,X,me,ft.x,ft.y)&&wu(ft.prev,ft,ft.next)>=0))return!1;ft=ft.nextZ}for(;nt&&nt.z>=We;){if(nt.x>=be&&nt.x<=Pe&&nt.y>=Se&&nt.y<=Be&&nt!==E&&nt!==O&&dO(U,le,H,he,X,me,nt.x,nt.y)&&wu(nt.prev,nt,nt.next)>=0)return!1;nt=nt.prevZ}for(;ft&&ft.z<=ot;){if(ft.x>=be&&ft.x<=Pe&&ft.y>=Se&&ft.y<=Be&&ft!==E&&ft!==O&&dO(U,le,H,he,X,me,ft.x,ft.y)&&wu(ft.prev,ft,ft.next)>=0)return!1;ft=ft.nextZ}return!0}function H4t(w,m){let x=w;do{const k=x.prev,E=x.next.next;!q6(k,E)&&XDe(k,x,x.next,E)&&uO(k,E)&&uO(E,k)&&(m.push(k.i,x.i,E.i),hO(x),hO(x.next),x=w=E),x=x.next}while(x!==w);return XC(x)}function G4t(w,m,x,k,E,P){let O=w;do{let U=O.next.next;for(;U!==O.prev;){if(O.i!==U.i&&Q4t(O,U)){let H=JDe(O,U);return O=XC(O,O.next),H=XC(H,H.next),cO(O,m,x,k,E,P,0),void cO(H,m,x,k,E,P,0)}U=U.next}O=O.next}while(O!==w)}function W4t(w,m){let x=w.x-m.x;return x===0&&(x=w.y-m.y,x===0)&&(x=(w.next.y-w.y)/(w.next.x-w.x)-(m.next.y-m.y)/(m.next.x-m.x)),x}function K4t(w,m){const x=function(E,P){let O=P;const U=E.x,H=E.y;let X,le=-1/0;if(q6(E,O))return O;do{if(q6(E,O.next))return O.next;if(H<=O.y&&H>=O.next.y&&O.next.y!==O.y){const Pe=O.x+(H-O.y)*(O.next.x-O.x)/(O.next.y-O.y);if(Pe<=U&&Pe>le&&(le=Pe,X=O.x=O.x&&O.x>=me&&U!==O.x&&QDe(HX.x||O.x===X.x&&Y4t(X,O)))&&(X=O,Se=Pe)}O=O.next}while(O!==he);return X}(w,m);if(!x)return m;const k=JDe(x,w);return XC(k,k.next),XC(x,x.next)}function Y4t(w,m){return wu(w.prev,w,m.prev)<0&&wu(m.next,w,w.next)<0}function zbe(w,m,x,k,E){return(w=1431655765&((w=858993459&((w=252645135&((w=16711935&((w=(w-x)*E|0)|w<<8))|w<<4))|w<<2))|w<<1))|(m=1431655765&((m=858993459&((m=252645135&((m=16711935&((m=(m-k)*E|0)|m<<8))|m<<4))|m<<2))|m<<1))<<1}function Z4t(w){let m=w,x=w;do(m.x=(w-O)*(P-U)&&(w-O)*(k-U)>=(x-O)*(m-U)&&(x-O)*(P-U)>=(E-O)*(k-U)}function dO(w,m,x,k,E,P,O,U){return!(w===O&&m===U)&&QDe(w,m,x,k,E,P,O,U)}function Q4t(w,m){return w.next.i!==m.i&&w.prev.i!==m.i&&!function(x,k){let E=x;do{if(E.i!==x.i&&E.next.i!==x.i&&E.i!==k.i&&E.next.i!==k.i&&XDe(E,E.next,x,k))return!0;E=E.next}while(E!==x);return!1}(w,m)&&(uO(w,m)&&uO(m,w)&&function(x,k){let E=x,P=!1;const O=(x.x+k.x)/2,U=(x.y+k.y)/2;do E.y>U!=E.next.y>U&&E.next.y!==E.y&&O<(E.next.x-E.x)*(U-E.y)/(E.next.y-E.y)+E.x&&(P=!P),E=E.next;while(E!==x);return P}(w,m)&&(wu(w.prev,w,m.prev)||wu(w,m.prev,m))||q6(w,m)&&wu(w.prev,w,w.next)>0&&wu(m.prev,m,m.next)>0)}function wu(w,m,x){return(m.y-w.y)*(x.x-m.x)-(m.x-w.x)*(x.y-m.y)}function q6(w,m){return w.x===m.x&&w.y===m.y}function XDe(w,m,x,k){const E=vq(wu(w,m,x)),P=vq(wu(w,m,k)),O=vq(wu(x,k,w)),U=vq(wu(x,k,m));return E!==P&&O!==U||!(E!==0||!yq(w,x,m))||!(P!==0||!yq(w,k,m))||!(O!==0||!yq(x,w,k))||!(U!==0||!yq(x,m,k))}function yq(w,m,x){return m.x<=Math.max(w.x,x.x)&&m.x>=Math.min(w.x,x.x)&&m.y<=Math.max(w.y,x.y)&&m.y>=Math.min(w.y,x.y)}function vq(w){return w>0?1:w<0?-1:0}function uO(w,m){return wu(w.prev,w,w.next)<0?wu(w,m,w.next)>=0&&wu(w,w.prev,m)>=0:wu(w,m,w.prev)<0||wu(w,w.next,m)<0}function JDe(w,m){const x=Bbe(w.i,w.x,w.y),k=Bbe(m.i,m.x,m.y),E=w.next,P=m.prev;return w.next=m,m.prev=w,x.next=E,E.prev=x,k.next=x,x.prev=k,P.next=k,k.prev=P,k}function eRe(w,m,x,k){const E=Bbe(w,m,x);return k?(E.next=k.next,E.prev=k,k.next.prev=E,k.next=E):(E.prev=E,E.next=E),E}function hO(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 Bbe(w,m,x){return{i:w,x:m,y:x,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function mO(w,m){const x=w.length;if(x<=1)return[w];const k=[];let E,P;for(let O=0;O1)for(let O=0;O=Bn&&x>=Bn}static evaluate(m){if(m.length===0)return new Qj;let x=[];for(const H of m)x.push(...H.portals);if(x.length===0)return new Qj;for(const H of x){const X=H.va,le=H.vb;(Qj.isOnBorder(X.x,le.x)||Qj.isOnBorder(X.y,le.y))&&(H.type="border")}const k=x.filter(H=>H.type!=="unevaluated"),E=x.filter(H=>H.type==="unevaluated");if(E.length===0)return new Qj;E.sort((H,X)=>H.hash===X.hash?H.isTunnel===X.isTunnel?0:H.isTunnel?-1:1:H.hashH.hashP!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new Ue(x,{zoom:k,lut:E},P=>P!=="fill-bridge-guard-rail-color")}addVertices(m,x){const k=this.unevalVertices.length;for(let E=0;E=P.min.x&&he.x<=P.max.x&&he.y>=P.min.y&&he.y<=P.max.y||me.x>=P.min.x&&me.x<=P.max.x&&me.y>=P.min.y&&me.y<=P.max.y||v_(he,me,U))||this.isOnBorder(he.x,me.x)||this.isOnBorder(he.y,me.y))continue;const be=Ax.computeEdgeHash(this.unevalVertices[X],this.unevalVertices[le]);let Se,Pe=this.vertexHashLookup.get(Ax.computePosHash(he));Pe!=null?Se=Pe.next:(Pe=this.vertexHashLookup.get(Ax.computePosHash(me)),Se=Pe!=null?Pe.prev:be),this.unevalEdges.push({polygonIdx:m,a:X,b:le,hash:be,portalHash:Se,isTunnel:E,type:"unevaluated",featureInfo:O})}}addPortalCandidates(m,x,k,E,P){if(x.length!==0){this.vertexHashLookup.clear();for(const O of x){if(O.length===0)continue;const U=O[0];let H=Ax.computeEdgeHash(U[U.length-2],U[U.length-1]);for(let X=0;X({vertexOffset:0,primitiveOffset:this.indexArray.length}),k=me=>{me.primitiveLength=this.indexArray.length-me.primitiveOffset},E=new J4t(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(m.portals,this.unevalEdges);const P=x(),O=x(),U=x(),H=(me,be)=>{me.sort((Pe,Be)=>Pe.type===be&&Be.type!==be?-1:Pe.type!==be&&Be.type===be?1:0);const Se=me.findIndex(Pe=>Pe.type!==be);return Se>=0?Se:me.length};let X=0;this.unevalEdges.length>0&&(X=H(this.unevalEdges,"none"),this.constructBridgeStructures(E,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:X},this.tileToMeters)),k(U);const le=x(),he=x();if(this.unevalEdges.length>0){const me=this.unevalEdges.splice(X),be=H(me,"tunnel")+X;this.unevalEdges.push(...me),this.constructTunnelStructures(E,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:X},{min:X,max:be})}k(le),E.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),k(he),E.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),k(O),E.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),k(P),this.maskSegments=Po.simpleSegment(0,he.primitiveOffset,0,he.primitiveLength),this.depthSegments=Po.simpleSegment(0,O.primitiveOffset,0,O.primitiveLength),this.renderableBridgeSegments=Po.simpleSegment(0,U.primitiveOffset,0,U.primitiveLength),this.renderableTunnelSegments=Po.simpleSegment(0,le.primitiveOffset,0,le.primitiveLength),this.shadowCasterSegments=Po.simpleSegment(0,P.primitiveOffset,0,P.primitiveLength)}update(m,x,k,E,P,O,U,H){this.bridgeProgramConfigurations.updatePaintArrays(m,x,P,k,E,O,U,H),this.tunnelProgramConfigurations.updatePaintArrays(m,x,P,k,E,O,U,H)}upload(m){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=m.createVertexBuffer(this.vertexPositions,$4t.members),this.vertexBufferNormal=m.createVertexBuffer(this.vertexNormals,U4t.members),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(m),this.tunnelProgramConfigurations.upload(m))}destroy(){this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBufferNormal.destroy(),this.indexBuffer.destroy()),this.maskSegments&&(this.maskSegments.destroy(),this.depthSegments.destroy(),this.renderableBridgeSegments.destroy(),this.renderableTunnelSegments.destroy(),this.shadowCasterSegments.destroy()),this.bridgeProgramConfigurations.destroy(),this.tunnelProgramConfigurations.destroy()}populatePaintArrays(m,x,k,E,P){const O=(U,H)=>{for(let X=0;Xoe(nn,x[en].x,x[en].y,k[en]*H),he=K(),me=K(),be=K(),Se=K(),Pe=K(),Be=(nn,en)=>{const xn=U.get(Ax.computePosHash(x[en])),Ls=xn.from,tn=xn.to;if(!Ls||!tn)return;le(he,Ls),le(me,en),le(be,tn),Ne(Se),He(he,me)||($e(Pe,me,he),Ie(Se,Pe)),He(be,me)||($e(Pe,be,me),pe(Se,Se,Ie(Pe,Pe)));const on=Ke(Se);return on>0?_e(nn,Se,1/on):void 0};let We=Number.POSITIVE_INFINITY;this.sortSubarray(E,P.min,P.max,(nn,en)=>nn.featureInfo.featureIndex-en.featureInfo.featureIndex);const ot=K(),nt=K(),ft=K(),bt=K(),wt=K(),Yt=K(),zt=K(),Kt=K(),Vt=K(),Ht=[K(),K(),K(),K()],Os=[K(),K(),K(),K()],Vs=[{coord:new Ms(0,0),height:0},{coord:new Ms(0,0),height:0}],Js=(nn,en)=>nn>en;for(let nn=P.min;nnWe.featureInfo.featureIndex-ot.featureInfo.featureIndex;this.sortSubarray(E,P.min,P.max,H),this.sortSubarray(E,O.min,O.max,H);const X=We=>Ie(We,We),le=[{coord:new Ms(0,0),height:0},{coord:new Ms(0,0),height:0}],he=(We,ot)=>WeU.hash===H.hash?H.polygonIdx-U.polygonIdx:H.hash>U.hash?1:-1);let k=0,E=0,P=0,O=x[k].polygonIdx;do E++,(E===x.length||x[k].hash!==x[E].hash)&&((E-k===1||x[E-1].polygonIdx!==O)&&(PX.portalHashle.hash?U++:le.hash>X.portalHash?H++:(X.type=le.type,U++)}}}isOnBorder(m,x){return m<=0&&x<=0||m>=Bn&&x>=Bn}addFeatureSection(m,x,k,E){return m!==x&&(x=m,k.push({featureIndex:m,vertexStart:E.getVertexCount()}),E.clearVertexLookup()),x}sortSubarray(m,x,k,E){const P=m.slice(x,k);P.sort(E),m.splice(x,P.length,...P)}static computeEdgeHash(m,x){return(m.y===x.y&&m.x>x.x||m.y>x.y)&&([m,x]=[x,m]),BigInt(Ax.computePosHash(m))<<32n|BigInt(Ax.computePosHash(x))}static computePosHash(m){return((65535&m.x)<<16|65535&m.y)>>>0}}function eCt(w,m){return w>m?1:w0))return x;x=x.left}}return null}contains(m){for(var x=this._root,k=this._compare;x;){var E=k(m,x.key);if(E===0)return!0;x=E<0?x.left:x.right}return!1}remove(m){var x=this.find(m);if(!x)return!1;if(this.splay(x),x.left)if(x.right){var k=this.minNode(x.right);k.parent!==x&&(this.replace(k,k.right),k.right=x.right,k.right.parent=k),this.replace(x,k),k.left=x.left,k.left.parent=k}else this.replace(x,x.left);else this.replace(x,x.right);return this._size--,!0}removeNode(m){if(!m)return!1;if(this.splay(m),m.left)if(m.right){var x=this.minNode(m.right);x.parent!==m&&(this.replace(x,x.right),x.right=m.right,x.right.parent=x),this.replace(m,x),x.left=m.left,x.left.parent=x}else this.replace(m,m.left);else this.replace(m,m.right);return this._size--,!0}erase(m){var x=this.find(m);if(x){this.splay(x);var k=x.left,E=x.right,P=null;k&&(k.parent=null,P=this.maxNode(k),this.splay(P),this._root=P),E&&(k?P.right=E:this._root=E,E.parent=P),this._size--}}pop(){var m=this._root,x=null;if(m){for(;m.left;)m=m.left;x={key:m.key,data:m.data},this.remove(m.key)}return x}next(m){var x=m;if(x)if(x.right)for(x=x.right;x&&x.left;)x=x.left;else for(x=m.parent;x&&x.right===m;)m=x,x=x.parent;return x}prev(m){var x=m;if(x)if(x.left)for(x=x.left;x&&x.right;)x=x.right;else for(x=m.parent;x&&x.left===m;)m=x,x=x.parent;return x}forEach(m){for(var x=this._root,k=[],E=!1,P=0;!E;)x?(k.push(x),x=x.left):k.length>0?(m(x=k.pop(),P++),x=x.right):E=!0;return this}range(m,x,k,E){const P=[],O=this._compare;let U,H=this._root;for(;P.length!==0||H;)if(H)P.push(H),H=H.left;else{if(H=P.pop(),U=O(H.key,x),U>0)break;if(O(H.key,m)>=0&&k.call(E,H))return this;H=H.right}return this}keys(){for(var m=this._root,x=[],k=[],E=!1;!E;)m?(x.push(m),m=m.left):x.length>0?(m=x.pop(),k.push(m.key),m=m.right):E=!0;return k}values(){for(var m=this._root,x=[],k=[],E=!1;!E;)m?(x.push(m),m=m.left):x.length>0?(m=x.pop(),k.push(m.data),m=m.right):E=!0;return k}at(m){for(var x=this._root,k=[],E=!1,P=0;!E;)if(x)k.push(x),x=x.left;else if(k.length>0){if(x=k.pop(),P===m)return x;P++,x=x.right}else E=!0;return null}load(m=[],x=[],k=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const E=m.length;return k&&Hbe(m,x,0,E-1,this._compare),this._root=Vbe(null,m,x,0,E),this._size=E,this}min(){var m=this.minNode(this._root);return m?m.key:null}max(){var m=this.maxNode(this._root);return m?m.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(m,x,k,E,P){return new qbe(k,P).load(m,x,E)}}function Vbe(w,m,x,k,E){const P=E-k;if(P>0){const O=k+Math.floor(P/2),U={key:m[O],data:x[O],parent:w};return U.left=Vbe(U,m,x,k,O),U.right=Vbe(U,m,x,O+1,E),U}return null}function Hbe(w,m,x,k,E){if(x>=k)return;const P=w[x+k>>1];let O=x-1,U=k+1;for(;;){do O++;while(E(w[O],P)<0);do U--;while(E(w[U],P)>0);if(O>=U)break;let H=w[O];w[O]=w[U],w[U]=H,H=m[O],m[O]=m[U],m[U]=H}Hbe(w,m,x,U,E),Hbe(w,m,U+1,k,E)}const sRe=11102230246251565e-32,qf=134217729,tCt=(3+8*sRe)*sRe;function Gbe(w,m,x,k,E){let P,O,U,H,X=m[0],le=k[0],he=0,me=0;le>X==le>-X?(P=X,X=m[++he]):(P=le,le=k[++me]);let be=0;if(heX==le>-X?(O=X+P,U=P-(O-X),X=m[++he]):(O=le+P,U=P-(O-le),le=k[++me]),P=O,U!==0&&(E[be++]=U);heX==le>-X?(O=P+X,H=O-P,U=P-(O-H)+(X-H),X=m[++he]):(O=P+le,H=O-P,U=P-(O-H)+(le-H),le=k[++me]),P=O,U!==0&&(E[be++]=U);for(;he0:(k[0]-m[0])*(x[1]-m[1])-(x[0]-m[0])*(k[1]-m[1])>0}isAbove(m){return!this.isBelow(m)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const m=new H6(this.point,this.left,this.otherEvent,this.isSubject,this.type);return m.contourId=this.contourId,m.resultTransition=this.resultTransition,m.prevInResult=this.prevInResult,m.isExteriorRing=this.isExteriorRing,m.inOut=this.inOut,m.otherInOut=this.otherInOut,m}}function w_(w,m){return w[0]===m[0]&&w[1]===m[1]}function Wbe(w,m,x){const k=function(E,P,O,U,H,X){const le=(P-X)*(O-H),he=(E-H)*(U-X),me=le-he;if(le===0||he===0||le>0!=he>0)return me;const be=Math.abs(le+he);return Math.abs(me)>=33306690738754716e-32*be?me:-function(Se,Pe,Be,We,ot,nt,ft){let bt,wt,Yt,zt,Kt,Vt,Ht,Os,Vs,Js,nn,en,xn,Ls,tn,on,gn,En;const ir=Se-ot,On=Be-ot,Rn=Pe-nt,An=We-nt;Ls=ir*An,Vt=qf*ir,Ht=Vt-(Vt-ir),Os=ir-Ht,Vt=qf*An,Vs=Vt-(Vt-An),Js=An-Vs,tn=Os*Js-(Ls-Ht*Vs-Os*Vs-Ht*Js),on=Rn*On,Vt=qf*Rn,Ht=Vt-(Vt-Rn),Os=Rn-Ht,Vt=qf*On,Vs=Vt-(Vt-On),Js=On-Vs,gn=Os*Js-(on-Ht*Vs-Os*Vs-Ht*Js),nn=tn-gn,Kt=tn-nn,V6[0]=tn-(nn+Kt)+(Kt-gn),en=Ls+nn,Kt=en-Ls,xn=Ls-(en-Kt)+(nn-Kt),nn=xn-on,Kt=xn-nn,V6[1]=xn-(nn+Kt)+(Kt-on),En=en+nn,Kt=En-en,V6[2]=en-(En-Kt)+(nn-Kt),V6[3]=En;let nr=function(ki,Ia){let Ei=Ia[0];for(let Za=1;Za<4;Za++)Ei+=Ia[Za];return Ei}(0,V6),pr=22204460492503146e-32*ft;if(nr>=pr||-nr>=pr||(Kt=Se-ir,bt=Se-(ir+Kt)+(Kt-ot),Kt=Be-On,Yt=Be-(On+Kt)+(Kt-ot),Kt=Pe-Rn,wt=Pe-(Rn+Kt)+(Kt-nt),Kt=We-An,zt=We-(An+Kt)+(Kt-nt),bt===0&&wt===0&&Yt===0&&zt===0)||(pr=11093356479670487e-47*ft+tCt*Math.abs(nr),nr+=ir*zt+An*bt-(Rn*Yt+On*wt),nr>=pr||-nr>=pr))return nr;Ls=bt*An,Vt=qf*bt,Ht=Vt-(Vt-bt),Os=bt-Ht,Vt=qf*An,Vs=Vt-(Vt-An),Js=An-Vs,tn=Os*Js-(Ls-Ht*Vs-Os*Vs-Ht*Js),on=wt*On,Vt=qf*wt,Ht=Vt-(Vt-wt),Os=wt-Ht,Vt=qf*On,Vs=Vt-(Vt-On),Js=On-Vs,gn=Os*Js-(on-Ht*Vs-Os*Vs-Ht*Js),nn=tn-gn,Kt=tn-nn,Mx[0]=tn-(nn+Kt)+(Kt-gn),en=Ls+nn,Kt=en-Ls,xn=Ls-(en-Kt)+(nn-Kt),nn=xn-on,Kt=xn-nn,Mx[1]=xn-(nn+Kt)+(Kt-on),En=en+nn,Kt=En-en,Mx[2]=en-(En-Kt)+(nn-Kt),Mx[3]=En;const Gr=Gbe(4,V6,4,Mx,nRe);Ls=ir*zt,Vt=qf*ir,Ht=Vt-(Vt-ir),Os=ir-Ht,Vt=qf*zt,Vs=Vt-(Vt-zt),Js=zt-Vs,tn=Os*Js-(Ls-Ht*Vs-Os*Vs-Ht*Js),on=Rn*Yt,Vt=qf*Rn,Ht=Vt-(Vt-Rn),Os=Rn-Ht,Vt=qf*Yt,Vs=Vt-(Vt-Yt),Js=Yt-Vs,gn=Os*Js-(on-Ht*Vs-Os*Vs-Ht*Js),nn=tn-gn,Kt=tn-nn,Mx[0]=tn-(nn+Kt)+(Kt-gn),en=Ls+nn,Kt=en-Ls,xn=Ls-(en-Kt)+(nn-Kt),nn=xn-on,Kt=xn-nn,Mx[1]=xn-(nn+Kt)+(Kt-on),En=en+nn,Kt=En-en,Mx[2]=en-(En-Kt)+(nn-Kt),Mx[3]=En;const Sr=Gbe(Gr,nRe,4,Mx,rRe);Ls=bt*zt,Vt=qf*bt,Ht=Vt-(Vt-bt),Os=bt-Ht,Vt=qf*zt,Vs=Vt-(Vt-zt),Js=zt-Vs,tn=Os*Js-(Ls-Ht*Vs-Os*Vs-Ht*Js),on=wt*Yt,Vt=qf*wt,Ht=Vt-(Vt-wt),Os=wt-Ht,Vt=qf*Yt,Vs=Vt-(Vt-Yt),Js=Yt-Vs,gn=Os*Js-(on-Ht*Vs-Os*Vs-Ht*Js),nn=tn-gn,Kt=tn-nn,Mx[0]=tn-(nn+Kt)+(Kt-gn),en=Ls+nn,Kt=en-Ls,xn=Ls-(en-Kt)+(nn-Kt),nn=xn-on,Kt=xn-nn,Mx[1]=xn-(nn+Kt)+(Kt-on),En=en+nn,Kt=En-en,Mx[2]=en-(En-Kt)+(nn-Kt),Mx[3]=En;const Ma=Gbe(Sr,rRe,4,Mx,aRe);return aRe[Ma-1]}(E,P,O,U,H,X,be)}(w[0],w[1],m[0],m[1],x[0],x[1]);return k>0?-1:k<0?1:0}function mk(w,m){const x=w.point,k=m.point;return x[0]>k[0]?1:x[0]k[1]?1:-1:function(E,P,O){return E.left!==P.left?E.left?1:-1:Wbe(O,E.otherEvent.point,P.otherEvent.point)!==0?E.isBelow(P.otherEvent.point)?-1:1:!E.isSubject&&P.isSubject?1:-1}(w,m,x)}function pk(w,m,x){const k=new H6(m,!1,w,w.isSubject),E=new H6(m,!0,w.otherEvent,w.isSubject);return w_(w.point,w.otherEvent.point)&&console.warn("what is that, a collapsed segment?",w),k.contourId=E.contourId=w.contourId,mk(E,w.otherEvent)>0&&(w.otherEvent.left=!0,E.left=!1),w.otherEvent.otherEvent=E,w.otherEvent=k,x.push(E),x.push(k),x}function bq(w,m){return w[0]*m[1]-w[1]*m[0]}function Kbe(w,m){return w[0]*m[0]+w[1]*m[1]}function Ybe(w,m,x){const k=function(H,X,le,he){const me=[X[0]-H[0],X[1]-H[1]],be=[he[0]-le[0],he[1]-le[1]];function Se(Yt,zt,Kt){return[Yt[0]+zt*Kt[0],Yt[1]+zt*Kt[1]]}const Pe=[le[0]-H[0],le[1]-H[1]];let Be=bq(me,be),We=Be*Be;const ot=Kbe(me,me);if(We>0){const Yt=bq(Pe,be)/Be;if(Yt<0||Yt>1)return null;const zt=bq(Pe,me)/Be;return zt<0||zt>1?null:Yt===0||Yt===1?[Se(H,Yt,me)]:zt===0||zt===1?[Se(le,zt,be)]:[Se(H,Yt,me)]}if(Be=bq(Pe,me),We=Be*Be,We>0)return null;const nt=Kbe(me,Pe)/ot,ft=nt+Kbe(me,be)/ot,bt=Math.min(nt,ft),wt=Math.max(nt,ft);return bt<=1&&wt>=0?bt===1?[Se(H,bt>0?bt:0,me)]:wt===0?[Se(H,wt<1?wt:1,me)]:[Se(H,bt>0?bt:0,me),Se(H,wt<1?wt:1,me)]:null}(w.point,w.otherEvent.point,m.point,m.otherEvent.point),E=k?k.length:0;if(E===0||E===1&&(w_(w.point,m.point)||w_(w.otherEvent.point,m.otherEvent.point))||E===2&&w.isSubject===m.isSubject)return 0;if(E===1)return!w_(w.point,k[0])&&!w_(w.otherEvent.point,k[0])&&pk(w,k[0],x),!w_(m.point,k[0])&&!w_(m.otherEvent.point,k[0])&&pk(m,k[0],x),1;const P=[];let O=!1,U=!1;return w_(w.point,m.point)?O=!0:mk(w,m)===1?P.push(m,w):P.push(w,m),w_(w.otherEvent.point,m.otherEvent.point)?U=!0:mk(w.otherEvent,m.otherEvent)===1?P.push(m.otherEvent,w.otherEvent):P.push(w.otherEvent,m.otherEvent),O&&U||O?(m.type=1,w.type=m.inOut===w.inOut?2:3,O&&!U&&pk(P[1].otherEvent,P[0].point,x),2):U?(pk(P[0],P[1].point,x),3):P[0]!==P[3].otherEvent?(pk(P[0],P[1].point,x),pk(P[1],P[2].point,x),3):(pk(P[0],P[1].point,x),pk(P[3].otherEvent,P[2].point,x),3)}function sCt(w,m){if(w===m)return 0;if(Wbe(w.point,w.otherEvent.point,m.point)!==0||Wbe(w.point,w.otherEvent.point,m.otherEvent.point)!==0)return w_(w.point,m.point)?w.isBelow(m.otherEvent.point)?-1:1:w.point[0]===m.point[0]?w.point[1](m.contourId??0)?1:-1}return mk(w,m)===1?1:-1}class nCt{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function rCt(w,m,x,k){let E,P=w+1,O=m[w].point;const U=m.length;for(Pk;)P--;return P}function aCt(w,m,x){const k=new nCt;if(w.prevInResult!=null){const E=w.prevInResult,P=E.outputContourId;if(E.resultTransition>0){const O=m[P];if(O.holeOf!=null){const U=O.holeOf;m[U].holeIds.push(x),k.holeOf=U,k.depth=m[P].depth}else m[P].holeIds.push(x),k.holeOf=P,k.depth=m[P].depth+1}else k.holeOf=null,k.depth=m[P].depth}else k.holeOf=null,k.depth=0;return k}const oRe=Math.max,lRe=Math.min;let _q=0;function cRe(w,m,x,k,E,P){let O,U,H,X,le,he;for(O=0,U=w.length-1;O0?he.left=!0:le.left=!0;const me=H[0],be=H[1];E[0]=lRe(E[0],me),E[1]=lRe(E[1],be),E[2]=oRe(E[2],me),E[3]=oRe(E[3],be),k.push(le),k.push(he)}}const wq=[];function dRe(w,m,x){let k=w,E=m;typeof w[0][0][0]=="number"&&(k=[w]),typeof m[0][0][0]=="number"&&(E=[m]);let P=function(me,be,Se){let Pe=null;return me.length*be.length===0&&(Se===0?Pe=wq:Se===2?Pe=me:(Se===1||Se===3)&&(Pe=me.length===0?be:me)),Pe}(k,E,x);if(P)return P===wq?null:P;const O=[1/0,1/0,-1/0,-1/0],U=[1/0,1/0,-1/0,-1/0],H=function(me,be,Se,Pe,Be){const We=new f0(void 0,mk);let ot,nt,ft,bt,wt,Yt;for(ft=0,bt=me.length;ftPe[2]||Pe[0]>Se[2]||Se[1]>Pe[3]||Pe[1]>Se[3])&&(Be===0?We=wq:Be===2?We=me:(Be===1||Be===3)&&(We=me.concat(be))),We}(k,E,O,U,x),P)return P===wq?null:P;const X=function(me,be,Se,Pe,Be,We){const ot=new qbe(sCt),nt=[],ft=Math.min(Pe[2],Be[2]);let bt,wt,Yt;for(;me.length!==0;){let zt=me.pop();if(nt.push(zt),We===0&&zt.point[0]>ft||We===2&&zt.point[0]>Pe[2])break;if(zt.left){wt=bt=ot.insert(zt),Yt=ot.minNode(),bt=bt!==Yt?ot.prev(bt):null,wt=ot.next(wt);const Kt=bt?bt.key:null;let Vt;if(fO(zt,Kt,We),wt&&Ybe(zt,wt.key,me)===2&&(fO(zt,Kt,We),fO(wt.key,zt,We)),bt&&Ybe(bt.key,zt,me)===2){let Ht=bt;Ht=Ht!==Yt?ot.prev(Ht):null,Vt=Ht?Ht.key:null,fO(Kt,Vt,We),fO(zt,Kt,We)}}else zt=zt.otherEvent,wt=bt=ot.find(zt),bt&&wt&&(bt=bt!==Yt?ot.prev(bt):null,wt=ot.next(wt),ot.remove(zt),wt&&bt&&Ybe(bt.key,wt.key,me))}return nt}(H,0,0,O,U,x),le=function(me){let be,Se;const Pe=function(ot){let nt,ft,bt,wt,Yt;const zt=[];for(ft=0,bt=ot.length;ft{Be[Yt]=!0,Yt=Pe.length)&&Pe[bt];);We.push(nt)}return We}(X),he=[];for(let me=0;me{O.push(new Ms(he,H+(he-U)/(X-U)*(le-H)))}:(O,U,H,X,le,he)=>{O.push(new Ms(U+(he-H)/(le-H)*(X-U),he))};for(const O of w){const U=[];for(const H of O){if(H.length<=2)continue;const X=[];for(let me=0;mem&&P(X,be,Se,Pe,Be,m):We>x?ot=m&&P(X,be,Se,Pe,Be,m),ot>x&&We<=x&&P(X,be,Se,Pe,Be,x)}let le=H[H.length-1];const he=k===0?le.x:le.y;he>=m&&he<=x&&X.push(le),X.length&&(le=X[X.length-1],X[0].x===le.x&&X[0].y===le.y||X.push(X[0]),U.push(X))}U.length&&E.push(U)}return E}function iCt(w,m){const x=dRe(Zbe(w),Zbe([m]),0);return x==null?[]:uRe(x)}function oCt(w,m,x=0){let E=Zbe(w,65536);const P=[];for(;m.valid();m.next()){const[O,U]=m.get();let H=O.x*65536,X=O.y*65536,le=U.x*65536,he=U.y*65536;const me=le-H,be=he-X,Se=Math.hypot(me,be);if(Se===0)continue;H-=me*x,X-=be*x,le+=me*x,he+=be*x;const Pe=Math.trunc(be/Se*3),Be=-Math.trunc(me/Se*3);P.push([[[H,X],[le,he],[le+Pe,he+Be],[H+Pe,X+Be],[H,X]]])}return P.length>0&&(E=dRe(E,P,2)),uRe(E,1/65536,128)}function Zbe(w,m=1){return[w.map(x=>x.map(k=>[k.x*m,k.y*m]))]}function uRe(w,m=1,x){return w.map(k=>k.map((E,P)=>{const O=E.map(U=>{let H=U[0],X=U[1];return x&&(H=Math.round(H/x)*x,X=Math.round(X/x)*x),new Ms(H*m,X*m)._round()});return P>0&&O.reverse(),O}))}class Qbe{constructor(m,x){this.layoutVertexArray=new Wa,this.indexArray=new sc,this.lineIndexArray=new wg,this.triangleSegments=new Po,this.lineSegments=new Po,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut}),this.uploaded=!1,x&&(this.elevatedLayoutVertexArray=new ro)}update(m,x,k,E,P,O,U,H){this.programConfigurations.updatePaintArrays(m,x,P,k,E,O,U,H)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,z4t.members),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.lineIndexBuffer=m.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=m.createVertexBuffer(this.elevatedLayoutVertexArray,B4t.members))),this.programConfigurations.upload(m),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(m,x,k,E,P,O,U){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,m,x,k,E,P,O,void 0,U)}}class Nq{constructor(m){this.zoom=m.zoom,this.pixelRatio=m.pixelRatio,this.overscaling=m.overscaling,this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=m.lut,this.bufferData=new Qbe(m,!1),this.elevationBufferData=new Qbe(m,!0),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.projection=m.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=m.sourceLayerIndex,this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){this.hasPattern=$be("fill",this.layers,this.pixelRatio,x);const P=this.layers[0].layout.get("fill-sort-key"),O=[];for(const{feature:U,id:H,index:X,sourceLayerIndex:le}of m){const he=this.layers[0]._featureFilter.needGeometry,me=Ya(U,he);if(!this.layers[0]._featureFilter.filter(new Ra(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),me,k))continue;const be=P?P.evaluate(me,{},k,x.availableImages):void 0,Se={id:H,properties:U.properties,type:U.type,sourceLayerIndex:le,index:X,geometry:he?me.geometry:Kr(U,k,E),patterns:{},sortKey:be};O.push(Se)}P&&O.sort((U,H)=>U.sortKey-H.sortKey);for(const U of O){const{geometry:H,index:X,sourceLayerIndex:le}=U;if(this.hasPattern){const he=Ube("fill",this.layers,U,this.zoom,this.pixelRatio,x);this.patternFeatures.push(he)}else this.addFeature(U,H,X,k,{},x.availableImages,x.brightness,x.elevationFeatures);x.featureIndex.insert(m[X].feature,H,X,le,this.index)}}update(m,x,k,E,P,O,U){this.bufferData.update(m,x,k,E,P,O,U,this.worldview),this.elevationBufferData.update(m,x,k,E,P,O,U,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(m,x,k,E,P,O,U,this.worldview)}addFeatures(m,x,k,E,P,O){for(const U of this.patternFeatures)this.addFeature(U,U.geometry,U.index,x,k,E,O,m.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(m){this.bufferData.upload(m),this.elevationBufferData.upload(m),this.elevatedStructures&&this.elevatedStructures.upload(m)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(m,x,k,E,P,O=[],U,H){const X=mO(x,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(m,X,E,k,H):this.addGeometry(X,this.bufferData),this.bufferData.populatePaintArrays(m,k,P,O,E,U,this.worldview),this.elevationBufferData.populatePaintArrays(m,k,P,O,E,U,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(m,x,k,E,P){this.elevatedStructures&&(this.elevatedStructures.construct(m),this.elevatedStructures.populatePaintArrays(x,k,E,P,this.worldview))}addElevatedRoadFeature(m,x,k,E,P){const O=new Array,U=$o.getElevationFeature(m,P);if(!U)return void this.addGeometry(x,this.bufferData);{const X=this.clipPolygonsToTile(x,1);X.length>0&&O.push({polygons:X,elevationFeature:U,elevationTileID:k})}const H={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(m,{},k),featureIndex:E};for(const X of O)if(X.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Ax(X.elevationTileID,this.layers,this.zoom,this.lut));const he=X.elevationFeature.isTunnel();let me=0;m.properties.hasOwnProperty(Do)&&(me=+m.properties[Do]),this.elevatedStructures.addPortalCandidates(X.elevationFeature.id,X.polygons,he,X.elevationFeature,me)}X.elevationFeature.constantHeight==null&&(X.polygons=this.prepareElevatedPolygons(X.polygons,X.elevationFeature,X.elevationTileID));const le=new Qo(k,X.elevationTileID);this.addElevatedGeometry(X.polygons,le,X.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,E,H)}}addElevatedGeometry(m,x,k,E,P,O){const U={elevation:k,elevationSampler:x,bias:E,index:P,featureInfo:O},[H,X]=this.addGeometry(m,this.elevationBufferData,U);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:H,max:X}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,H),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,X))}addGeometry(m,x,k){let E=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,O=null;k&&(O=k.elevationSampler.constantElevation(k.elevation,k.bias),O!=null&&(E=O,P=O));const U=(H,X,le)=>{if(k!=null)if(X.push(H),O!=null)x.elevatedLayoutVertexArray.emplaceBack(O),le.push(O);else{const he=k.elevationSampler.pointElevation(H,k.elevation,k.bias);x.elevatedLayoutVertexArray.emplaceBack(he),le.push(he),E=Math.min(E,he),P=Math.max(P,he)}};for(const H of m){let X=0;for(const nt of H)X+=nt.length;const le=x.triangleSegments.prepareSegment(X,x.layoutVertexArray,x.indexArray),he=le.vertexLength,me=[],be=[],Se=[],Pe=[],Be=[],We=x.layoutVertexArray.length;for(const nt of H){if(nt.length===0)continue;nt!==H[0]&&be.push(me.length/2);const ft=x.lineSegments.prepareSegment(nt.length,x.layoutVertexArray,x.lineIndexArray),bt=ft.vertexLength;k&&Be.push(x.layoutVertexArray.length-We),U(nt[0],Se,Pe),x.layoutVertexArray.emplaceBack(nt[0].x,nt[0].y),x.lineIndexArray.emplaceBack(bt+nt.length-1,bt),me.push(nt[0].x),me.push(nt[0].y);for(let wt=1;wt0&&k&&this.elevationMode==="hd-road-base"){const nt=k.elevation.isTunnel(),ft=k.elevation.safeArea,bt=this.elevatedStructures.addVertices(Se,Pe);this.elevatedStructures.addTriangles(ot,bt,nt);const wt=Be.length;if(wt>0){for(let Yt=0;Yt=k&&be.max.x<=P&&be.min.y>=E&&be.max.y<=O?H:X).push(me)}if(H.length===m.length)return m;const le=[new Ms(k,E),new Ms(P,E),new Ms(P,O),new Ms(k,O),new Ms(k,E)],he=H;for(const me of X)he.push(...iCt(me,le));return he}}let hRe,mRe,pRe,fRe;Yn(Nq,"FillBucket",{omit:["layers","patternFeatures"]}),Yn(Qbe,"FillBufferData"),Yn(Ax,"ElevatedStructures");class kq{constructor(m,x,k,E){if(this.triangleCount=x.length/3,this.min=new Ms(0,0),this.max=new Ms(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||m.length===0)return;const[P,O]=[m[0].clone(),m[0].clone()];for(let he=1;hehe.cellIdx-me.cellIdx||he.triIdx-me.triIdx);let le=0;for(;lethis.max.x||this.min.x>m.x||m.y>this.max.y||this.min.y>m.y)return;const k=j_(m.x-this.min.x,this.xScale,this.cellsX),E=j_(m.y-this.min.y,this.yScale,this.cellsY),P=this.cells[E*this.cellsX+k];if(P){this._lazyInitLookup();for(let O=0;Othis.max.x||this.min.x>x.x||m.y>this.max.y||this.min.y>x.y)return;this._lazyInitLookup();const E=j_(m.x-this.min.x,this.xScale,this.cellsX),P=j_(x.x-this.min.x,this.xScale,this.cellsX),O=j_(m.y-this.min.y,this.yScale,this.cellsY),U=j_(x.y-this.min.y,this.yScale,this.cellsY);for(let H=O;H<=U;H++)for(let X=E;X<=P;X++){const le=this.cells[H*this.cellsX+X];if(le)for(let he=0;hex.fqid),this.index=m.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.footprints=[],this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){for(const k of this.footprints)x.push({footprint:k,id:m})}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){const P=[];for(const{feature:O,id:U,index:H,sourceLayerIndex:X}of m){const le=this.layers[0]._featureFilter.needGeometry,he=Ya(O,le);if(!this.layers[0]._featureFilter.filter(new Ra(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),he,k))continue;const me={id:U,properties:O.properties,type:O.type,sourceLayerIndex:X,index:H,geometry:le?he.geometry:Kr(O,k,E),patterns:{}};P.push(me)}for(const O of P){const{geometry:U,index:H,sourceLayerIndex:X}=O;this.addFeature(O,U,H,k,{},x.availableImages,x.brightness),x.featureIndex.insert(m[H].feature,U,H,X,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(m){}update(m,x,k,E,P,O,U){}destroy(){}addFeature(m,x,k,E,P,O=[],U){for(const H of mO(x,2)){const X=[],le=[],he=[],me=new Ms(1/0,1/0),be=new Ms(-1/0,-1/0);for(const Be of H)if(Be.length!==0){Be!==H[0]&&he.push(le.length/2);for(let We=0;Wem.max.x||w.max.xm.max.y||w.max.ynew Ms((H.x+P.x*Bn)*U-O.x*Bn,(H.y+P.y*Bn)*U-O.y*Bn))}return Jbe(x,E,w.indices,0,w.indices.length,0,0)}function _Re(w,m,x,k){const E=Math.pow(2,k.z-x.z);return new Ms((w+x.x*Bn)*E-k.x*Bn,(m+x.y*Bn)*E-k.y*Bn)}function wRe(w,m){const x=[];m.grid.queryPoint(w,x);const k=m.indices,E=m.vertices;for(let P=0;P0&&(k.length>1&&x.push(k),k=[])}return k.length>1&&x.push(k),x}const t_e=_a.types,yCt=["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"],vCt=["fill-extrusion-flood-light-ground-radius"],bCt=Math.pow(2,13),_Ct=Math.pow(2,15)-1,Eq=new Ms(0,1),Xj=2147483648,Aq=1073741824;function gO(w,m,x,k,E,P,O,U){w.emplaceBack((m<<1)+O,(x<<1)+P,(Math.floor(k*bCt)<<1)+E,Math.round(U))}function yO(w,m,x){w.emplaceBack(m.x*Bn,m.y*Bn,x?1:0)}function Mq(w,m,x,k,E,P){w.emplaceBack(m.x,m.y,(x.x<<1)+k,(x.y<<1)+E,P)}function vO(w,m,x){w.emplaceBack(m.x,m.y,m.z,x[0]*16384,x[1]*16384,x[2]*16384)}class NRe{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class s_e{constructor(){this.centroidXY=new Ms(0,0),this.vertexArrayOffset=0,this.vertexCount=0,this.groundVertexArrayOffset=0,this.groundVertexCount=0,this.flags=0,this.footprintSegIdx=-1,this.footprintSegLen=0,this.polygonSegIdx=-1,this.polygonSegLen=0,this.min=new Ms(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Ms(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Ms(0,0)}span(){return new Ms(this.max.x-this.min.x,this.max.y-this.min.y)}}class n_e{constructor(){this.acc=new Ms(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(m,x){m.min.x===Number.MAX_VALUE&&(m.min.x=m.max.x=x.x,m.min.y=m.max.y=x.y)}appendEdge(m,x,k){this.accCount++,this.acc._add(x);let E=!!this.borders;x.xm.max.x&&(m.max.x=x.x,E=!0),x.ym.max.y&&(m.max.y=x.y,E=!0),((x.x===0||x.x===Bn)&&x.x===k.x)!=((x.y===0||x.y===Bn)&&x.y===k.y)&&this.processBorderOverlap(x,k),E&&this.checkBorderIntersection(x,k)}checkBorderIntersection(m,x){x.x<0!=m.x<0&&this.addBorderIntersection(0,Br(x.y,m.y,(0-x.x)/(m.x-x.x))),x.x>Bn!=m.x>Bn&&this.addBorderIntersection(1,Br(x.y,m.y,(Bn-x.x)/(m.x-x.x))),x.y<0!=m.y<0&&this.addBorderIntersection(2,Br(x.x,m.x,(0-x.y)/(m.y-x.y))),x.y>Bn!=m.y>Bn&&this.addBorderIntersection(3,Br(x.x,m.x,(Bn-x.y)/(m.y-x.y)))}addBorderIntersection(m,x){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const k=this.borders[m];xk[1]&&(k[1]=x)}processBorderOverlap(m,x){if(m.x===x.x){if(m.y===x.y)return;const k=m.x===0?0:1;this.addBorderIntersection(k,x.y),this.addBorderIntersection(k,m.y)}else{const k=m.y===0?2:3;this.addBorderIntersection(k,x.x),this.addBorderIntersection(k,m.x)}}centroid(){return this.accCount===0?new Ms(0,0):new Ms(Math.floor(Math.max(0,this.acc.x)/this.accCount),Math.floor(Math.max(0,this.acc.y)/this.accCount))}intersectsCount(){return this.borders?this.borders.reduce((m,x)=>m+ +(x[0]!==Number.MAX_VALUE),0):0}}function kRe(w,m){const x=w.add(m)._unit(),k=Qe(w.x*x.x+w.y*x.y,-1,1);var E,P,O;return O=Math.acos(k),Math.min(4,Math.max(-4,Math.tan(O)))/4*_Ct*((E=w).x*(P=m).y-E.y*P.x<0?-1:1)}const wCt=[w=>w.x<0,w=>w.x>Bn,w=>w.y<0,w=>w.y>Bn];function jCt(w,m,x,k){const E=[4];if(k===0)return E;x._mult(k);const P=w.sub(x),O=m.sub(x),U=[w,m,P,O];for(let H=0;H<4;H++)for(const X of U)if(wCt[H](X)){E.push(H);break}return E}class r_e{constructor(m){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new zC,this.indexArray=new sc,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut},x=>vCt.includes(x)),this._segments=new Po,this.hiddenByLandmarkVertexArray=new O6,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Po}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(m,x,k,E=!1){const P=m.length;if(P>2){let O=Math.max(0,this._segments.get().length-1);const U=this._segments._prepareSegment(4*P,this.vertexArray.length,2*this._segmentToGroundQuads[O].length);let H;O!==this._segments.get().length-1&&(O++,this._segmentToGroundQuads[O]=[],this._segmentToRegionTriCounts[O]=[0,0,0,0,0]);{const X=m[0],le=m[1];H=kRe(X.sub(m[P-1])._perp()._unit(),le.sub(X)._perp()._unit())}for(let X=0;XE.region-P.region);for(let k=0;kH+X,0);let U=0;for(let H=0;H<=4;H++){const X=O[H];if(X!==0){let le=this.regionSegments[H];le||(le=this.regionSegments[H]=new Po);const he={vertexOffset:P.vertexOffset,primitiveOffset:P.primitiveOffset+U,vertexLength:P.vertexLength,primitiveLength:X};le.get().push(he)}U+=X}for(let H=0;H0?this.hiddenByLandmarkVertexBuffer=m.createVertexBuffer(this.hiddenByLandmarkVertexArray,mCt.members,!0):this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.updateData(this.hiddenByLandmarkVertexArray),this._needsHiddenByLandmarkUpdate=!1)}destroy(){if(this.vertexBuffer){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.destroy(),this.groundRadiusBuffer&&this.groundRadiusBuffer.destroy(),this._segments&&this._segments.destroy(),this.programConfigurations.destroy();for(let m=0;m<=4;m++){const x=this.regionSegments[m];x&&x.destroy()}}}}class Iq{constructor(m){this.zoom=m.zoom,this.canonical=m.canonical,this.overscaling=m.overscaling,this.layers=m.layers,this.pixelRatio=m.pixelRatio,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=m.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new sc,this.footprintVertices=new Wa,this.footprintSegments=[],this.layoutVertexArray=new bg,this.centroidVertexArray=new uq,this.wallVertexArray=new nO,this.indexArray=new sc,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut},x=>yCt.includes(x)),this.segments=new Po,this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.groundEffect=new r_e(m),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){this.features=[],this.hasPattern=$be("fill-extrusion",this.layers,this.pixelRatio,x),this.featuresOnBorder=[],this.borderFeatureIndices=[[],[],[],[]],this.borderDoneWithNeighborZ=[-1,-1,-1,-1],this.selfDEMTileTimestamp=Number.MAX_VALUE,this.borderDEMTileTimestamp=[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],this.tileToMeter=dn(k),this.edgeRadius=this.layers[0].layout.get("fill-extrusion-edge-radius")/this.tileToMeter,this.wallMode=this.layers[0].paint.get("fill-extrusion-line-width").constantOr(1)!==0;for(const{feature:P,id:O,index:U,sourceLayerIndex:H}of m){const X=this.layers[0]._featureFilter.needGeometry,le=Ya(P,X);if(!this.layers[0]._featureFilter.filter(new Ra(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),le,k))continue;const he={id:O,sourceLayerIndex:H,index:U,geometry:X?le.geometry:Kr(P,k,E),properties:P.properties,type:P.type,patterns:{}},me=this.layoutVertexArray.length,be=t_e[he.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:P.id,feature:Ube("fill-extrusion",this.layers,he,this.zoom,this.pixelRatio,x)});else if(this.wallMode)for(const Se of he.geometry)for(const Pe of jRe(Se,be))this.addFeature(P.id,he,[Pe],U,k,{},x.availableImages,E,x.brightness);else this.addFeature(P.id,he,he.geometry,U,k,{},x.availableImages,E,x.brightness);x.featureIndex.insert(P,he.geometry,U,H,this.index,me)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(m,x,k,E,P,O){for(const{featureId:U,feature:H}of this.features){const X=t_e[H.type]==="Polygon",{geometry:le}=H;if(this.wallMode)for(const he of le)for(const me of jRe(he,X))this.addFeature(U,H,[me],H.index,x,k,E,P,O);else this.addFeature(U,H,le,H.index,x,k,E,P,O)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(m,x,k,E,P,O,U){this.programConfigurations.updatePaintArrays(m,x,P,k,E,O,U,this.worldview),this.groundEffect.update(m,x,P,k,E,O,U,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,fCt),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.wallVertexBuffer=m.createVertexBuffer(this.wallVertexArray,hCt.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=m.createVertexBuffer(this.layoutVertexExtArray,pCt.members,!0)),this.groundEffect.upload(m)),this.groundEffect.uploadPaintProperties(m),this.programConfigurations.upload(m),this.uploaded=!0}uploadCentroid(m){this.groundEffect.uploadHiddenByLandmark(m),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=m.createVertexBuffer(this.centroidVertexArray,uCt.members,!0):this.centroidVertexBuffer&&this.centroidVertexBuffer.updateData(this.centroidVertexArray),this.needsCentroidUpdate=!1)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.centroidVertexBuffer&&this.centroidVertexBuffer.destroy(),this.layoutVertexExtBuffer&&this.layoutVertexExtBuffer.destroy(),this.groundEffect.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(m,x,k,E,P,O,U,H,X){const le=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(x,{})/this.tileToMeter,he=[new Ms(0,0),new Ms(Bn,Bn)],me=H.projection,be=me.name==="globe",Se=this.wallMode||t_e[x.type]==="Polygon",Pe=new n_e;Pe.centroidDataIndex=this.centroidData.length;const Be=new s_e;Be.buildingId=m,x.properties&&x.properties.hasOwnProperty("building_id")&&(Be.buildingId=Number(x.properties.building_id)),Pe.buildingId=Be.buildingId;const We=this.layers[0].paint.get("fill-extrusion-base").evaluate(x,{},P)<=0,ot=this.layers[0].paint.get("fill-extrusion-height").evaluate(x,{},P);let nt;if(Be.height=ot,Be.vertexArrayOffset=this.layoutVertexArray.length,Be.groundVertexArrayOffset=this.groundEffect.vertexArray.length,be&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new M6),this.wallMode){if(be)return void sr("Non zero fill-extrusion-line-width is not yet supported on globe.");if(k.length!==1)return;nt=function(Vt){const Ht=Vt[0].x===Vt[Vt.length-1].x&&Vt[0].y===Vt[Vt.length-1].y;(function(Rn){let An=0;const nr=Rn.length;for(let pr=0;pr=0})(Vt)||(Vt=Vt.reverse());const Vs={geometry:[],joinNormals:[],indices:[]},Js=[],nn=[],en=[];let xn=Vt.length;for(;xn>=2&&Vt[xn-1].equals(Vt[xn-2]);)xn--;if(xn<(Ht?3:2))return Vs;let Ls,tn,on,gn,En,ir=0;for(;ir0;let Sr="miter";const Ma=2;Sr==="miter"&&pr>Ma&&(Sr="bevel"),Sr==="bevel"&&(pr>100&&(Sr="flipbevel"),pr{const Ji=new Ms(Ia.x,Ia.y),Fi=new Ms(Ia.x,Ia.y);Ji.x+=Ei.x*zl,Ji.y+=Ei.y*zl,Fi.x-=Ei.x*Math.max(Za,1),Fi.y-=Ei.y*Math.max(Za,1),en.push(Ei),Js.push(Ji),nn.push(Fi)};if(Sr==="miter")An._mult(pr),ki(Ls,An,0,0);else if(Sr==="flipbevel")An=En.mult(-1),ki(Ls,An,0,0),ki(Ls,An.mult(-1),0,0);else{const Ia=-Math.sqrt(pr*pr-1),Ei=Gr?Ia:0,Za=Gr?0:Ia;tn&&ki(Ls,gn,Ei,Za),on&&ki(Ls,En,Ei,Za)}}Vs.geometry=[...Js,...nn.reverse(),Js[0]],Vs.joinNormals=[...en,...en.reverse(),en[en.length-1]];const On=Vs.geometry.length-1;for(let Rn=0;RnVt<(Ht.length-1)/2||Vt===Ht.length-1,bt=this.wallMode?[k]:mO(k,500);for(let Vt=bt.length-1;Vt>=0;Vt--){const Ht=bt[Vt];(Ht.length===0||kCt(Ht[0]))&&bt.splice(Vt,1)}let wt;if(be)wt=IRe(bt,he,P);else{wt=[];for(const Vt of bt)wt.push({polygon:Vt,bounds:he})}const Yt=Se?this.edgeRadius:0,zt=Yt>0&&this.zoom<17,Kt=(Vt,Ht)=>{if(Vt.length===0)return!1;const Os=Vt[Vt.length-1];return Ht.x===Os.x&&Ht.y===Os.y};for(const{polygon:Vt,bounds:Ht}of wt){let Os=0,Vs=0;for(const xn of Vt)Se&&!xn[0].equals(xn[xn.length-1])&&xn.push(xn[0]),Vs+=Se?xn.length-1:xn.length;const Js=this.segments.prepareSegment((Se?5:4)*Vs,this.layoutVertexArray,this.indexArray);Be.footprintSegIdx<0&&(Be.footprintSegIdx=this.footprintSegments.length),Be.polygonSegIdx<0&&(Be.polygonSegIdx=this.polygonSegments.length);const nn={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},en=new NRe;if(en.vertexOffset=this.footprintVertices.length,en.indexOffset=3*this.footprintIndices.length,en.ringIndices=[],Se){const xn=[],Ls=[];Os=Js.vertexLength;for(let on=0;on4&&ERe(Ls[Ls.length-2],Ls[0],Ls[1]),on=Yt?NCt(Ls[Ls.length-2],Ls[0],Ls[1],Yt):0;const gn=[];let En,ir,On;ir=Ls[1].sub(Ls[0])._perp()._unit();let Rn=!0;for(let An=1,nr=0;An0?1:0,Ei=pr.dist(Gr);if(nr+Ei>32768&&(nr=0),Yt){On=Sr.sub(Gr)._perp()._unit();let Fi=CRe(pr,Gr,Sr,SRe(ir,On),Yt);isNaN(Fi)&&(Fi=0);const Ro=Gr.sub(pr)._unit();pr=pr.add(Ro.mult(on))._round(),Gr=Gr.add(Ro.mult(-Fi))._round(),on=Fi,ir=On,We&&this.zoom>=17&&(Kt(gn,pr)||gn.push(pr),Kt(gn,Gr)||gn.push(Gr))}const Za=Js.vertexLength,zl=Ls.length>4&&ERe(pr,Gr,Sr);let Ji=ARe(nr,tn,Rn);if(gO(this.layoutVertexArray,pr.x,pr.y,ki,Ia,0,0,Ji),gO(this.layoutVertexArray,pr.x,pr.y,ki,Ia,0,1,Ji),this.wallMode){const Fi=ft(An-1,Ls),Ro=nt.joinNormals[An-1];yO(this.wallVertexArray,Ro,Fi),yO(this.wallVertexArray,Ro,Fi)}if(nr+=Ei,Ji=ARe(nr,zl,!Rn),tn=zl,gO(this.layoutVertexArray,Gr.x,Gr.y,ki,Ia,0,0,Ji),gO(this.layoutVertexArray,Gr.x,Gr.y,ki,Ia,0,1,Ji),this.wallMode){const Fi=ft(An,Ls),Ro=nt.joinNormals[An];yO(this.wallVertexArray,Ro,Fi),yO(this.wallVertexArray,Ro,Fi)}if(Js.vertexLength+=4,this.indexArray.emplaceBack(Za+0,Za+1,Za+2),this.indexArray.emplaceBack(Za+1,Za+3,Za+2),Js.primitiveLength+=2,Yt){const Fi=Os+(An===1?Ls.length-2:An-2),Ro=An===1?Os:Fi+1;if(this.indexArray.emplaceBack(Za+1,Fi,Za+3),this.indexArray.emplaceBack(Fi,Ro,Za+3),Js.primitiveLength+=2,En===void 0&&(En=Za),!a_e(Sr,Ls[An],Ht)){const Il=An===Ls.length-1?En:Js.vertexLength;this.indexArray.emplaceBack(Za+2,Za+3,Il),this.indexArray.emplaceBack(Za+3,Il+1,Il),this.indexArray.emplaceBack(Za+3,Ro,Il+1),Js.primitiveLength+=3}Rn=!Rn}if(be){const Fi=this.layoutVertexExtArray,Ro=me.projectTilePoint(pr.x,pr.y,P),Il=me.projectTilePoint(Gr.x,Gr.y,P),eu=me.upVector(P,pr.x,pr.y),Pl=me.upVector(P,Gr.x,Gr.y);vO(Fi,Ro,eu),vO(Fi,Ro,eu),vO(Fi,Il,Pl),vO(Fi,Il,Pl)}}Se&&(Os+=Ls.length-1),We&&Yt&&this.zoom>=17&&(gn.length!==0&&Kt(gn,gn[0])&&gn.pop(),this.groundEffect.addData(gn,Ht,le,Yt>0))}this.footprintSegments.push(en),nn.triangleCount=this.indexArray.length-nn.triangleArrayOffset,this.polygonSegments.push(nn),++Be.footprintSegLen,++Be.polygonSegLen}if(Be.vertexCount=this.layoutVertexArray.length-Be.vertexArrayOffset,Be.groundVertexCount=this.groundEffect.vertexArray.length-Be.groundVertexArrayOffset,Be.vertexCount!==0){if(Be.centroidXY=Pe.borders?Eq:this.encodeCentroid(Pe,Be),x.properties&&x.properties.hasOwnProperty("building_id")){const Vt=Be.buildingId;let Ht=this.buildingGroups.get(Vt);Ht||(Ht={accX:0,accY:0,accCount:0,mergedMin:new Ms(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Ms(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Vt,Ht)),Ht.accX+=Pe.acc.x,Ht.accY+=Pe.acc.y,Ht.accCount+=Pe.accCount,Ht.mergedMin.x=Math.min(Ht.mergedMin.x,Be.min.x),Ht.mergedMin.y=Math.min(Ht.mergedMin.y,Be.min.y),Ht.mergedMax.x=Math.max(Ht.mergedMax.x,Be.max.x),Ht.mergedMax.y=Math.max(Ht.mergedMax.y,Be.max.y),Ht.partIndices.push(this.centroidData.length)}if(this.centroidData.push(Be),Pe.borders){this.featuresOnBorder.push(Pe);const Vt=this.featuresOnBorder.length-1;for(let Ht=0;Htthis.featuresOnBorder[x].borders[m][0]-this.featuresOnBorder[k].borders[m][0])}splitToSubtiles(){const m=[];for(let U=0;UBn),le=2*X+(+(H.min.x+H.max.x>Bn)^X);for(let he=0;heU.triangleSegmentIdx===H.triangleSegmentIdx?U.subtile-H.subtile:U.triangleSegmentIdx-H.triangleSegmentIdx);let k=0,E=0,P=0;for(const U of m){if(U.triangleSegmentIdx!==k)break;P++}const O=m.length;for(;E!==m.length;){k=m[E].triangleSegmentIdx;let U=0,H=E,X=E;for(let le=H;le0&&this.triangleSubSegments.push({segment:be,min:he,max:me}),H=X;for(let Se=H;Se[Pe[0]*(1-We[0])+Be[0]*We[0],Pe[1]*(1-We[1])+Be[1]*We[1]],be=[],Se=[];for(const Pe of this.triangleSubSegments){be[0]=Pe.min.x/Bn,be[1]=Pe.min.y/Bn,Se[0]=Pe.max.x/Bn,Se[1]=Pe.max.y/Bn;const Be=me(le,he,be),We=me(le,he,Se);if(new so([Be[0],Be[1],P],[We[0],We[1],O]).intersectsPrecise(k)===0){X&&(E.segments.push(X),X=void 0);continue}const ot=Pe.segment;X&&X.vertexOffset!==ot.vertexOffset&&(E.segments.push(X),X=void 0),X?(X.vertexLength+=ot.vertexLength,X.primitiveLength+=ot.primitiveLength):X={vertexOffset:ot.vertexOffset,primitiveLength:ot.primitiveLength,vertexLength:ot.vertexLength,primitiveOffset:ot.primitiveOffset,sortKey:void 0,vaos:{}}}return X&&E.segments.push(X),E}encodeCentroid(m,x){const k=m.centroid(),E=x.span(),P=Math.min(7,Math.round(E.x*this.tileToMeter/10)),O=Math.min(6,Math.round(E.y*this.tileToMeter/10));return new Ms(Qe(k.x,1,8191)<<3|P,Qe(k.y,1,8191)<<3|O)}encodeBorderCentroid(m){if(!m.borders)return new Ms(0,0);const x=m.borders,k=Number.MAX_VALUE;if(x[0][0]!==k||x[1][0]!==k){const E=x[0][0]!==k?0:1;return new Ms(6|(x[0][0]!==k?0:65528),(x[E][0]+x[E][1])/2<<3|6)}{const E=x[2][0]!==k?2:3;return new Ms((x[E][0]+x[E][1])/2<<3|6,6|(x[2][0]!==k?0:65528))}}showCentroid(m){const x=this.centroidData[m.centroidDataIndex];if(x.flags&=Xj,x.groupCentroidPos.x!==0||x.groupCentroidPos.y!==0){const k=x.span(),E=Math.min(7,Math.round(k.x*this.tileToMeter/10)),P=Math.min(6,Math.round(k.y*this.tileToMeter/10));x.centroidXY=new Ms(Qe(x.groupCentroidPos.x,1,8191)<<3|E,Qe(x.groupCentroidPos.y,1,8191)<<3|P)}else x.centroidXY=new Ms(0,0);this.writeCentroidToBuffer(x)}writeCentroidToBuffer(m){this.groundEffect.updateHiddenByLandmark(m);const x=m.vertexArrayOffset,k=m.vertexCount+m.vertexArrayOffset,E=-1073741824&m.flags?Eq:m.centroidXY,P=this.centroidVertexArray.geta_centroid_pos0(x);if(this.centroidVertexArray.geta_centroid_pos1(x)!==E.y||P!==E.x){for(let O=x;OH.max.x||H.min.x>O.max.x||O.min.y>H.max.y||H.min.y>O.max.y||O.footprint.buildingIds.has(H.buildingId)&&(H.flags|=O.clipMask!==Tq.None?-1073741824:Xj);else for(const H of this.centroidData)if(!(H.flags&Xj||H.flags&Aq||O.min.x>H.max.x||H.min.x>O.max.x||O.min.y>H.max.y||H.min.y>O.max.y))for(let X=0;Xx!=be>x&&m<(this.footprintVertices.int16[2*(le+O.vertexOffset)+0]-he)*(x-me)/(be-me)+he&&(E=!E)}U=H}}return E}getHeightAtTileCoord(m,x){let k=Number.NEGATIVE_INFINITY,E=!0;const P=4*(m+Bn)*Bn+(x+Bn);if(this.partLookup.hasOwnProperty(P)){const O=this.partLookup[P];return O?{height:O.height,hidden:!!(O.flags&Xj)}:void 0}for(const O of this.centroidData)m>O.max.x||O.min.x>m||x>O.max.y||O.min.y>x||O.height<=k||this.footprintContainsPoint(m,x,O)&&(k=O.height,this.partLookup[P]=O,E=!!(O.flags&Xj));if(k!==Number.NEGATIVE_INFINITY)return{height:k,hidden:E};this.partLookup[P]=void 0}}function SRe(w,m){const x=w.add(m)._unit();return w.x*x.x+w.y*x.y}function NCt(w,m,x,k){const E=m.sub(w)._perp()._unit(),P=x.sub(m)._perp()._unit();return CRe(w,m,x,SRe(E,P),k)}function CRe(w,m,x,k,E){const P=Math.sqrt(1-k*k);return Math.min(w.dist(m)/3,m.dist(x)/3,E*P/k)}function a_e(w,m,x){return w.xx[1].x&&m.x>x[1].x||w.yx[1].y&&m.y>x[1].y}function TRe(w,m){return w.xm[1].x||w.ym[1].y}function kCt(w){return w.every(m=>m.x<=0)||w.every(m=>m.x>=Bn)||w.every(m=>m.y<=0)||w.every(m=>m.y>=Bn)}function ERe(w,m,x){if(w.x<0||w.x>=Bn||m.x<0||m.x>=Bn||x.x<0||x.x>=Bn)return!1;const k=x.sub(m),E=k.perp(),P=w.sub(m);return(k.x*P.x+k.y*P.y)/Math.sqrt((k.x*k.x+k.y*k.y)*(P.x*P.x+P.y*P.y))>-.866&&E.x*P.x+E.y*P.y<0}function ARe(w,m,x){const k=m?2|w:-3&w;return x?1|k:-2&k}function MRe(){const w=Math.PI/32,m=Math.tan(w),x=Wt;return x*Math.sqrt(1+2*m*m)-x}function IRe(w,m,x){const k=1<{for(const zt of wt)Se.push({polygon:zt,bounds:Yt})},Be=Math.ceil(Math.log2(le)),We=Math.ceil(Math.log2(he)),ot=Be-We,nt=[];for(let wt=0;wt0?0:1);for(let wt=0;wtYt+1?bt.push({polygons:Js,bounds:en,depth:Yt+1}):Pe(Js,en)}if(nn.length){const en=[new Ms(zt===0?Vs:Kt.x,zt===1?Vs:Kt.y),Vt];nt.length>Yt+1?bt.push({polygons:nn,bounds:en,depth:Yt+1}):Pe(nn,en)}}return Se}(w,m,Math.ceil((P-E)/11.25),Math.ceil((O-U)/11.25),1,(H,X,le)=>{if(H===0)return .5*(X+le);{const he=Rs((x.y+X/Bn)/k);return(mn(.5*(Rs((x.y+le/Bn)/k)+he))*k-x.y)*Bn}})}function SCt(w,m,x,k,E,P){const O=Math.pow(2,k.z-E.z);for(let U=0;U=H[O]&&(U=m,H=w),U[O]E&&RRe(U,H,O,E),U[O]P&&RRe(H,U,O,P)}}function Pq(w,m,x,k,E,P){const O=[];for(let U=0;U=k&&Se.x>=k||(be.x>=k?be=new Ms(k,be.y+(k-be.x)/(Se.x-be.x)*(Se.y-be.y))._round():Se.x>=k&&(Se=new Ms(k,be.y+(k-be.x)/(Se.x-be.x)*(Se.y-be.y))._round()),be.y>=E&&Se.y>=E||(be.y>=E?be=new Ms(be.x+(E-be.y)/(Se.y-be.y)*(Se.x-be.x),E)._round():Se.y>=E&&(Se=new Ms(be.x+(E-be.y)/(Se.y-be.y)*(Se.x-be.x),E)._round()),X&&be.equals(X[X.length-1])||(X=[be],O.push(X),P&&P.push({progress:{min:Be+FRe(We,ot,be)*Pe,max:1},parentIndex:U,prevPoint:We,nextPoint:ot})),X.push(Se),P&&(P[P.length-1].progress.max=Be+FRe(We,ot,Se)*Pe,P[P.length-1].nextPoint=ot)))))}if(P&&he>0)for(let me=le;meX.t-le.t);let O=0,U=0,H=[];for(k.push(H);O!==w.length;){if(U===P.length){for(;O!==w.length;)H.length!==0&&H[H.length-1].equals(w[O])||H.push(w[O]),O++;break}P[U].t<=O?(H.length!==0&&H[H.length-1].equals(P[U].point)||H.push(P[U].point),Math.trunc(P[U].t),U++):(H.length!==0&&H[H.length-1].equals(w[O])||H.push(w[O]),O++)}}function FRe(w,m,x){return w.x!==m.x?(x.x-w.x)/(m.x-w.x):w.y!==m.y?(x.y-w.y)/(m.y-w.y):0}function bO(w,m){return w.x*m.x+w.y*m.y}function zRe(w,m){if(w.length===1){let x=0;const k=m[x++];let E;for(;!E||k.equals(E);)if(E=m[x++],!E)return 1/0;for(;x{Vs[0]=Js,Vs[1]=nn,Vs[2]=en,Vs[3]=1},Os=MRe();be>0&&(be+=Os),Se+=Os;for(const Vs of me){const Js=[],nn=[];for(const en of Vs){const xn=en.x+Pe.x,Ls=en.y+Pe.y,tn=he.projection.projectTilePoint(xn,Ls,bt),on=he.projection.upVector(bt,en.x,en.y);let gn=be,En=Se;if(We){const ir=URe(xn,Ls,be,Se,We,ot,nt,ft);gn+=ir.base,En+=ir.top}be!==0?Ht(Kt,tn.x+on[0]*zt*gn,tn.y+on[1]*zt*gn,tn.z+on[2]*zt*gn):Ht(Kt,tn.x,tn.y,tn.z),Ht(Vt,tn.x+on[0]*zt*En,tn.y+on[1]*zt*En,tn.z+on[2]*zt*En),Je(Kt,Kt,Be),Je(Vt,Vt,Be),Js.push(new JC(Kt[0],Kt[1],Kt[2])),nn.push(new JC(Vt[0],Vt[1],Vt[2]))}wt.push(Js),Yt.push(nn)}return[wt,Yt]}(w,m,x,k,E,P,O,U,H,X,le):O?function(he,me,be,Se,Pe,Be,We,ot,nt){const ft=[],bt=[],wt=[0,0,0,1];for(const Yt of he){const zt=[],Kt=[];for(const Vt of Yt){const Ht=Vt.x+Se.x,Os=Vt.y+Se.y,Vs=URe(Ht,Os,me,be,Be,We,ot,nt);wt[0]=Ht,wt[1]=Os,wt[2]=Vs.base,wt[3]=1,dt(wt,wt,Pe),wt[3]=Math.max(wt[3],1e-5);const Js=new JC(wt[0]/wt[3],wt[1]/wt[3],wt[2]/wt[3]);wt[0]=Ht,wt[1]=Os,wt[2]=Vs.top,wt[3]=1,dt(wt,wt,Pe),wt[3]=Math.max(wt[3],1e-5);const nn=new JC(wt[0]/wt[3],wt[1]/wt[3],wt[2]/wt[3]);zt.push(Js),Kt.push(nn)}ft.push(zt),bt.push(Kt)}return[ft,bt]}(m,x,k,E,P,O,U,H,X):function(he,me,be,Se,Pe){const Be=[],We=[],ot=Pe[8]*me,nt=Pe[9]*me,ft=Pe[10]*me,bt=Pe[11]*me,wt=Pe[8]*be,Yt=Pe[9]*be,zt=Pe[10]*be,Kt=Pe[11]*be;for(const Vt of he){const Ht=[],Os=[];for(const Vs of Vt){const Js=Vs.x+Se.x,nn=Vs.y+Se.y,en=Pe[0]*Js+Pe[4]*nn+Pe[12],xn=Pe[1]*Js+Pe[5]*nn+Pe[13],Ls=Pe[2]*Js+Pe[6]*nn+Pe[14],tn=Pe[3]*Js+Pe[7]*nn+Pe[15],on=en+ot,gn=xn+nt,En=Ls+ft,ir=Math.max(tn+bt,1e-5),On=en+wt,Rn=xn+Yt,An=Ls+zt,nr=Math.max(tn+Kt,1e-5);Ht.push(new JC(on/ir,gn/ir,En/ir)),Os.push(new JC(On/nr,Rn/nr,An/nr))}Be.push(Ht),We.push(Os)}return[Be,We]}(m,x,k,E,P)}function URe(w,m,x,k,E,P,O,U){const H=O*E.getElevationAt(w,m,!0,!0),X=P[0]!==0,le=X?P[1]===0?O*(P[0]/7-450):O*function(he,me,be){const Se=Math.floor(me[0]/8),Pe=Math.floor(me[1]/8),Be=10*(me[0]-8*Se),We=10*(me[1]-8*Pe),ot=he.getElevationAt(Se,Pe,!0,!0),nt=he.getMeterToDEM(be),ft=Math.floor(.5*(Be*nt-1)),bt=Math.floor(.5*(We*nt-1)),wt=he.tileCoordToPixel(Se,Pe),Yt=2*ft+1,zt=2*bt+1,Kt=function(nn,en,xn,Ls,tn){return[nn.getElevationAtPixel(en,xn,!0),nn.getElevationAtPixel(en+tn,xn,!0),nn.getElevationAtPixel(en,xn+tn,!0),nn.getElevationAtPixel(en+Ls,xn+tn,!0)]}(he,wt.x-ft,wt.y-bt,Yt,zt),Vt=Math.abs(Kt[0]-Kt[1]),Ht=Math.abs(Kt[2]-Kt[3]),Os=Math.abs(Kt[0]-Kt[2])+Math.abs(Kt[1]-Kt[3]),Vs=Math.min(.25,.5*nt*(Vt+Ht)/Yt),Js=Math.min(.25,.5*nt*Os/zt);return ot+Math.max(Vs*Be,Js*We)}(E,P,U):H;return{base:H+(x===0?-1:x),top:X?Math.max(le+k,H+x+2):H+k}}const i_e=4096;class TCt{constructor(m){this.module=m,this.memoryStack=this.module.malloc(i_e),this.memoryStackNextFree=this.memoryStack}createIntArray(m){const x=this.memoryStackNextFree;return this.memoryStackNextFree+=m.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>i_e?-1:(new Int32Array(this.module.heap32.buffer,x,m.length).set(m),x)}createFloatArray(m){const x=this.memoryStackNextFree;return this.memoryStackNextFree+=m.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>i_e?-1:(new Float32Array(this.module.heapF32.buffer,x,m.length).set(m),x)}readStringBuffer(m){let x="";for(;this.module.heapU8[m]!==0;)x+=String.fromCharCode(this.module.heapU8[m]),++m;return x}setStyle(m){const x=m.normalScale;this.module.setStyle(x[0],x[1],x[2],m.tileToMeters)}setAOOptions(m,x){this.module.setAOOptions(m?1:0,x)}setMetricOptions(m,x){this.module.setMetricOptions(m?1:0,x)}setStructuralOptions(m){this.module.setStructuralOptions(m?1:0)}setFacadeOptions(m,x){this.module.setFacadeOptions(m,x?1:0)}setFauxFacadeOptions(m,x,k){this.module.setFauxFacadeOptions(m?1:0,x?1:0,k)}setFacadeClassifierOptions(m){this.module.setFacadeClassifierOptions(m)}generateMesh(m,x){this.memoryStackNextFree=this.memoryStack;for(const U of m){const H=this.createIntArray(U.ringIndices),X=this.createFloatArray(U.coordinates);if(H===-1||X===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(U.id,U.sourceId,U.minHeight,U.height,U.roofType,X,H,U.ringIndices.length-1)}for(const U of x){let H;H=U.entrances?JSON.parse(U.entrances):[];const X=this.createFloatArray(H),le=this.createFloatArray(U.coordinates);if(X===-1||le===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(U.sourceId,U.crossPerc,U.distanceToRoad,X,H.length,le,U.coordinates.length)}if(!this.module.generateMesh()){const U=this.module.getLastError();return this.readStringBuffer(U)}const k=this.module.getMeshCount(),E=new Array(k);for(let U=0;U>2)-3,Be=be[Se++]>>2;if(Se++,E.json=JSON.parse(XRe.decode(be.subarray(Se,Se+Be))),Se+=Be,Se>>0,Math.ceil(1.2*ft)),wt=Math.ceil((bt-ft)/65536);try{return Pe.grow(wt),Be(),!0}catch{return!1}},b:We}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(be,ot):be.then(nt=>nt.arrayBuffer()).then(nt=>WebAssembly.instantiate(nt,ot))).then(nt=>{const{Rb:ft,Qb:bt,P:wt,T:Yt,X:zt,Ja:Kt,La:Vt,Qa:Ht,Va:Os,Wa:Vs,eb:Js,jb:nn,f:en,e:xn,yb:Ls,zb:tn,Ab:on,Bb:gn,Db:En,Gb:ir}=nt.instance.exports;Pe=xn;const On=(()=>{let Rn=0,An=0,nr=0,pr=0;return Gr=>{nr&&(ft(pr),ft(Rn),An+=nr,nr=Rn=0),Rn||(An+=128,Rn=bt(An));const Sr=Gr.length+7&-8;let Ma=Rn;Sr>=An&&(nr=Sr,Ma=pr=bt(Sr));for(let ki=0;ki{A1=be,_O=void 0}))}()),me&&le.push(function(){if(o_e)return;const be=function(Se){let Pe;const Be=WebAssembly.instantiateStreaming(Se,{}).then(nt=>{Pe=nt.instance,Pe.exports.__wasm_call_ctors()}),We={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},ot={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:Be,supported:!0,decodeGltfBuffer(nt,ft,bt,wt,Yt,zt){(function(Kt,Vt,Ht,Os,Vs,Js,nn){const en=Kt.exports.sbrk,xn=Os+3&-4,Ls=en(xn*Vs),tn=en(Js.length),on=new Uint8Array(Kt.exports.memory.buffer);on.set(Js,tn);const gn=Vt(Ls,Os,Vs,tn,Js.length);if(gn===0&&nn&&nn(Ls,xn,Vs),Ht.set(on.subarray(Ls,Ls+Os*Vs)),en(Ls-en(0)),gn!==0)throw new Error(`Malformed buffer data: ${gn}`)})(Pe,Pe.exports[ot[Yt]],nt,ft,bt,wt,Pe.exports[We[zt]])}}}(fetch(Aa()));return be.ready.then(()=>{o_e=be})}()),O)for(let be=0;be{const U=Ly(k,(H,X)=>{H?O(H):P(X)});E&&E.addEventListener("abort",()=>{U.cancel(),O(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:w,type:"arrayBuffer"},m);return tOe(x,0,w,m)}function c_e(w){switch(w){case WebGL2RenderingContext.RGBA8:case WebGL2RenderingContext.RGBA16F:return WebGL2RenderingContext.RGBA;case WebGL2RenderingContext.DEPTH_COMPONENT16:return WebGL2RenderingContext.DEPTH_COMPONENT;case WebGL2RenderingContext.DEPTH24_STENCIL8:return WebGL2RenderingContext.DEPTH_STENCIL;case WebGL2RenderingContext.R8:case WebGL2RenderingContext.R32F:return WebGL2RenderingContext.RED}}function d_e(w){switch(w){case WebGL2RenderingContext.RGBA8:return WebGL2RenderingContext.UNSIGNED_BYTE;case WebGL2RenderingContext.RGBA16F:return WebGL2RenderingContext.HALF_FLOAT;case WebGL2RenderingContext.DEPTH_COMPONENT16:return WebGL2RenderingContext.UNSIGNED_SHORT;case WebGL2RenderingContext.DEPTH24_STENCIL8:return WebGL2RenderingContext.UNSIGNED_INT_24_8;case WebGL2RenderingContext.R8:return WebGL2RenderingContext.UNSIGNED_BYTE;case WebGL2RenderingContext.R32F:return WebGL2RenderingContext.FLOAT}}class N_{constructor(m,x,k,E){this.context=m,this.format=k,this.useMipmap=E&&E.useMipmap,this.texture=m.gl.createTexture(),this.update(x,{premultiply:E&&E.premultiply})}update(m,x){const k=m&&m instanceof HTMLVideoElement&&m.width===0?m.videoWidth:m.width,E=m&&m instanceof HTMLVideoElement&&m.height===0?m.videoHeight:m.height,{context:P}=this,{gl:O}=P,{x:U,y:H}=x&&x.position?x.position:{x:0,y:0},X=U+k,le=H+E;this.size&&(this.size[0]!==X||this.size[1]!==le)&&(!x||x.recreateWhenResize===void 0||x.recreateWhenResize)&&(O.bindTexture(O.TEXTURE_2D,null),O.deleteTexture(this.texture),this.texture=O.createTexture(),this.size=null),O.bindTexture(O.TEXTURE_2D,this.texture),P.pixelStoreUnpackFlipY.set(!1),P.pixelStoreUnpack.set(1),P.pixelStoreUnpackPremultiplyAlpha.set(this.format===O.RGBA8&&(!x||x.premultiply!==!1));const he=m instanceof HTMLImageElement||m instanceof HTMLCanvasElement||m instanceof HTMLVideoElement||m instanceof ImageData||ImageBitmap&&m instanceof ImageBitmap;if(!this.size&&X>0&&le>0){const me=this.useMipmap?Math.floor(Math.log2(Math.max(X,le)))+1:1;O.texStorage2D(O.TEXTURE_2D,me,this.format,X,le),this.size=[X,le]}this.size&&(he?O.texSubImage2D(O.TEXTURE_2D,0,U,H,c_e(this.format),d_e(this.format),m):"data"in m&&m.data&&O.texSubImage2D(O.TEXTURE_2D,0,U,H,k,E,c_e(this.format),d_e(this.format),m.data)),this.useMipmap&&O.generateMipmap(O.TEXTURE_2D)}bind(m,x,k=!1){const{context:E}=this,{gl:P}=E;P.bindTexture(P.TEXTURE_2D,this.texture),m!==this.minFilter&&(P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MAG_FILTER,m),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MIN_FILTER,this.useMipmap&&!k?m===P.NEAREST?P.NEAREST_MIPMAP_NEAREST:P.LINEAR_MIPMAP_LINEAR:m),this.minFilter=m),x!==this.wrapS&&(P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_S,x),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_T,x),this.wrapS=x)}bindExtraParam(m,x,k,E,P){const{context:O}=this,{gl:U}=O;U.bindTexture(U.TEXTURE_2D,this.texture),x!==this.magFilter&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_MAG_FILTER,x),this.magFilter=x),m!==this.minFilter&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_MIN_FILTER,this.useMipmap?m===U.NEAREST?U.NEAREST_MIPMAP_NEAREST:U.LINEAR_MIPMAP_LINEAR:m),this.minFilter=m),k!==this.wrapS&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_WRAP_S,k),this.wrapS=k),E!==this.wrapT&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_WRAP_T,E),this.wrapT=E),P!==this.compareMode&&(P?(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_COMPARE_MODE,U.COMPARE_REF_TO_TEXTURE),U.texParameteri(U.TEXTURE_2D,U.TEXTURE_COMPARE_FUNC,P)):U.texParameteri(U.TEXTURE_2D,U.TEXTURE_COMPARE_MODE,U.NONE),this.compareMode=P)}destroy(){const{gl:m}=this.context;m.deleteTexture(this.texture),this.texture=null}}class jO{constructor(m,x){this.context=m,this.texture=x}bind(m,x){const{context:k}=this,{gl:E}=k;E.bindTexture(E.TEXTURE_2D,this.texture),m!==this.minFilter&&(E.texParameteri(E.TEXTURE_2D,E.TEXTURE_MAG_FILTER,m),E.texParameteri(E.TEXTURE_2D,E.TEXTURE_MIN_FILTER,m),this.minFilter=m),x!==this.wrapS&&(E.texParameteri(E.TEXTURE_2D,E.TEXTURE_WRAP_S,x),E.texParameteri(E.TEXTURE_2D,E.TEXTURE_WRAP_T,x),this.wrapS=x)}}const DCt=cn([{name:"a_pos_3f",components:3,type:"Float32"}]),RCt=cn([{name:"a_color_3f",components:3,type:"Float32"}]),OCt=cn([{name:"a_color_4f",components:4,type:"Float32"}]),FCt=cn([{name:"a_uv_2f",components:2,type:"Float32"}]),zCt=cn([{name:"a_normal_3f",components:3,type:"Float32"}]),BCt=cn([{name:"a_normal_matrix0",components:4,type:"Float32"},{name:"a_normal_matrix1",components:4,type:"Float32"},{name:"a_normal_matrix2",components:4,type:"Float32"},{name:"a_normal_matrix3",components:4,type:"Float32"}]),$Ct=cn([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function nOe(w,m){const x=Oq(w.projection,w.zoom,w.width,w.height),k=function(P,O,U,H,X){const le=new rs(U.lng-180*fk,U.lat),he=new rs(U.lng+180*fk,U.lat),me=P.project(le.lng,le.lat),be=P.project(he.lng,he.lat),Se=-Math.atan2(be.y-me.y,be.x-me.x),Pe=mr.fromLngLat(U);Pe.y=Qe(Pe.y,-1+fk,1-fk);const Be=Pe.toLngLat(),We=P.project(Be.lng,Be.lat),ot=mr.fromLngLat(Be);ot.x+=fk;const nt=ot.toLngLat(),ft=P.project(nt.lng,nt.lat),bt=aOe(ft.x-We.x,ft.y-We.y,Se),wt=mr.fromLngLat(Be);wt.y+=fk;const Yt=wt.toLngLat(),zt=P.project(Yt.lng,Yt.lat),Kt=aOe(zt.x-We.x,zt.y-We.y,Se),Vt=Math.abs(bt.x)/Math.abs(Kt.y),Ht=v([]);L(Ht,Ht,-Se*(1-(X?0:H)));const Os=v([]);return A(Os,Os,[1,1-(1-Vt)*H,1]),Os[4]=-Kt.x/Kt.y*H,L(Os,Os,Se),_(Os,Ht,Os),Os}(w.projection,0,w.center,x,m),E=rOe(w);return A(k,k,[E,E,1]),k}function rOe(w){const m=w.projection,x=Oq(w.projection,w.zoom,w.width,w.height),k=u_e(m,w.center),E=u_e(m,rs.convert(m.center));return Math.pow(2,k*x+(1-x)*E)}function Oq(w,m,x,k,E=1/0){const P=w.range;if(!P)return 0;const O=Math.min(E,Math.max(x,k)),U=Math.log2(O/1024);return ct(P[0]+U,P[1]+U,m)}const fk=1/4e4;function u_e(w,m){const x=Qe(m.lat,-85.051129,Qs),k=new rs(m.lng-180*fk,x),E=new rs(m.lng+180*fk,x),P=w.project(k.lng,x),O=w.project(E.lng,x),U=mr.fromLngLat(k),H=mr.fromLngLat(E),X=O.x-P.x,le=O.y-P.y,he=H.x-U.x,me=H.y-U.y,be=Math.sqrt((he*he+me*me)/(X*X+le*le));return Math.log2(be)}function aOe(w,m,x){const k=Math.cos(x),E=Math.sin(x);return{x:w*k-m*E,y:w*E+m*k}}function iOe(w,m,x){v(w),L(w,w,lr(m[2])),T(w,w,lr(m[0])),D(w,w,lr(m[1])),A(w,w,x),_(w,w,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function Fq(w,m,x,k,E,P,O,U){const H=[x[0]-m[0],x[1]-m[1],0],X=[k[0]-m[0],k[1]-m[1],0];if(ee(H)<1e-12||ee(X)<1e-12)return kt(w);const le=qe([],H,X);Ie(le,le),ce(X,k,m),H[2]=(P-E)*U,X[2]=(O-E)*U;const he=H;return qe(he,H,X),Ie(he,he),$t(w,le,he)}function zq(w,m,x=!1){const k=Zj(m.zoom),E=function(P,O,U){const H=O.worldSize,X=[P[12],P[13],P[14]],le=Rs(X[1]/H),he=ms(X[0]/H),me=v([]),be=js(1,le)*H,Se=js(1,0)*H*Cn(le,O.zoom),Pe=1/Rbe(H);let Be=Se*Pe;if(U){const ft=Oq(O.projection,O.zoom,O.width,O.height,1024);Be=Pe*O.projection.pixelSpaceConversion(O.center.lat,H,ft)}const We=Rt(le,he);pe(We,We,_e([],Ie([],We),be*Be*X[2]));const ot=function(ft){const bt=[ft[0],ft[1],ft[2]];let wt=[0,1,0];const Yt=qe([],wt,bt);return qe(wt,bt,Yt),Ee(wt)===0&&(wt=[0,1,0],qe(Yt,bt,wt)),Ie(Yt,Yt),Ie(wt,wt),Ie(bt,bt),[Yt[0],Yt[1],Yt[2],0,wt[0],wt[1],wt[2],0,bt[0],bt[1],bt[2],0,ft[0],ft[1],ft[2],1]}(We);A(me,me,[Be,Be,Be*be]),S(me,me,[-X[0],-X[1],-X[2]]);const nt=_([],O.globeMatrix,ot);return _(nt,nt,me),_(nt,nt,P),nt}(w,m,x);if(k>0){const P=function(O,U){const H=U.worldSize,X=js(1,0)*H*Cn(U.center.lat,U.zoom)/Rbe(H),le=js(1,U.center.lat)*H,he=v([]);D(he,he,lr(U.center.lng)),T(he,he,lr(U.center.lat)),S(he,he,[0,0,Tt]),A(he,he,[X,X,X*le]);const me=U.point;return S(he,he,[-me.x,-me.y,0]),_(he,he,O),_(he,U.globeMatrix,he)}(w,m);return function(O,U,H){const X=(Se,Pe,Be)=>{const We=ee(Se),ot=ee(Pe),nt=Yj(Se,Pe,Be);return _e(nt,nt,1/ee(nt)*Br(We,ot,Be))},le=X([O[0],O[1],O[2]],[U[0],U[1],U[2]],H),he=X([O[4],O[5],O[6]],[U[4],U[5],U[6]],H),me=X([O[8],O[9],O[10]],[U[8],U[9],U[10]],H),be=Yj([O[12],O[13],O[14]],[U[12],U[13],U[14]],H);return[le[0],le[1],le[2],0,he[0],he[1],he[2],0,me[0],me[1],me[2],0,be[0],be[1],be[2],1]}(E,P,k)}return E}function h_e(w,m,x,k){const E=so.projectAabbCorners(k,x);let P=Number.MAX_VALUE;for(let U=0;U0||Be===0&&Se[0]*Pe[0]+Se[1]*Pe[1]>=0&&Se[0]*Se[0]+Se[1]*Se[1]>Pe[0]*Pe[0]+Pe[1]*Pe[1])&&(le=be)}he=le}while(he!==X);return H.length>0&&H.push(H[0]),H}(E);if(mc(w,O))return P}const e3=64,W6={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function Bq(w,m,x,k,E,P,O,U,H,X=!1){const le=x.zoom,he=x.project(k),me=Cn(k.lat,le),be=1/me;v(w),S(w,w,[he.x+O[0]*be,he.y+O[1]*be,O[2]]);let Se=1,Pe=1;const Be=x.worldSize;if(X){if(x.projection.name==="mercator"){let ft=0;x.elevation&&(ft=x.elevation.getAtPointOrZero(new mr(he.x/Be,he.y/Be),0));const bt=dt([],[he.x,he.y,ft,1],x.projMatrix)[3]/x.cameraToCenterDistance;Se=bt,Pe=bt*Cn(x.center.lat,le)}else if(x.projection.name==="globe"){const ft=zq(w,x),bt=[0,0,0,1];dt(bt,bt,_([],x.projMatrix,ft));const wt=bt[3]/x.cameraToCenterDistance,Yt=Zj(le),zt=x.projection.pixelsPerMeter(k.lat,Be)*Cn(k.lat,le),Kt=x.projection.pixelsPerMeter(x.center.lat,Be)*Cn(x.center.lat,le);Se=wt/Br(zt,Dn(x.center.lat),Yt),Pe=wt*me/zt,Se*=Kt,Pe*=Kt}}else Se=be;A(w,w,[Se,Se,Pe]);const We=[...w],ot=m.orientation,nt=[];if(iOe(nt,[ot[0]+(E?E[0]:0),ot[1]+(E?E[1]:0),ot[2]+(E?E[2]:0)],P),_(w,We,nt),U&&x.elevation){let ft=0;const bt=[];if(H&&x.elevation){ft=function(Yt,zt,Kt,Vt,Ht){const Os=zt.elevation;if(!Os)return 0;const Vs=so.projectAabbCorners(Kt,Vt),Js=js(1,Ht.lat)*zt.worldSize,nn=function(An,nr){const pr=[0,0,1],Gr=[{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 Sr of Gr){const Ma=An[Sr.corners[0]],ki=An[Sr.corners[1]],Ia=An[Sr.corners[2]],Ei=[ki[0]-Ma[0],ki[1]-Ma[1],nr*(ki[2]-Ma[2])],Za=qe(Ei,Ei,[Ia[0]-Ma[0],Ia[1]-Ma[1],nr*(Ia[2]-Ma[2])]);Ie(Za,Za),Sr.dotProductWithUp=Fe(Za,pr)}return Gr.sort((Sr,Ma)=>Sr.dotProductWithUp-Ma.dotProductWithUp),Gr[0].corners}(Vs,Js),en=Vs[nn[0]],xn=Vs[nn[1]],Ls=Vs[nn[2]],tn=Vs[nn[3]],on=Os.getAtPointOrZero(new mr(en[0]/zt.worldSize,en[1]/zt.worldSize),0),gn=Os.getAtPointOrZero(new mr(xn[0]/zt.worldSize,xn[1]/zt.worldSize),0),En=Os.getAtPointOrZero(new mr(Ls[0]/zt.worldSize,Ls[1]/zt.worldSize),0),ir=Os.getAtPointOrZero(new mr(tn[0]/zt.worldSize,tn[1]/zt.worldSize),0),On=(on+ir)/2,Rn=(gn+En)/2;return On>Rn?gn=m.gl.NEAREST_MIPMAP_NEAREST}),w.uploaded=!0,w.image=null)}function UCt(w,m,x){w.indexBuffer=m.createIndexBuffer(w.indexArray,!1,!0),w.vertexBuffer=m.createVertexBuffer(w.vertexArray,DCt.members,!1,!0),w.normalArray&&(w.normalBuffer=m.createVertexBuffer(w.normalArray,zCt.members,!1,!0)),w.texcoordArray&&(w.texcoordBuffer=m.createVertexBuffer(w.texcoordArray,FCt.members,!1,!0)),w.colorArray&&(w.colorBuffer=m.createVertexBuffer(w.colorArray,(w.colorArray.bytesPerElement===12?RCt:OCt).members,!1,!0)),w.featureArray&&(w.pbrBuffer=m.createVertexBuffer(w.featureArray,$Ct.members,!0)),w.segments=Po.simpleSegment(0,0,w.vertexArray.length,w.indexArray.length);const k=w.material;k.pbrMetallicRoughness.baseColorTexture&&NO(k.pbrMetallicRoughness.baseColorTexture,m),k.pbrMetallicRoughness.metallicRoughnessTexture&&NO(k.pbrMetallicRoughness.metallicRoughnessTexture,m),k.normalTexture&&NO(k.normalTexture,m),k.occlusionTexture&&NO(k.occlusionTexture,m,x),k.emissionTexture&&NO(k.emissionTexture,m)}function m_e(w,m,x){if(w.meshes)for(const k of w.meshes)UCt(k,m,x);if(w.children)for(const k of w.children)m_e(k,m,x)}function $q(w){if(w.meshes)for(const m of w.meshes)m.indexArray.destroy(),m.vertexArray.destroy(),m.colorArray&&m.colorArray.destroy(),m.normalArray&&m.normalArray.destroy(),m.texcoordArray&&m.texcoordArray.destroy(),m.featureArray&&m.featureArray.destroy();if(w.children)for(const m of w.children)$q(m)}function qCt(w){w.pbrMetallicRoughness.baseColorTexture&&w.pbrMetallicRoughness.baseColorTexture.gfxTexture&&w.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),w.pbrMetallicRoughness.metallicRoughnessTexture&&w.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&w.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),w.normalTexture&&w.normalTexture.gfxTexture&&w.normalTexture.gfxTexture.destroy(),w.emissionTexture&&w.emissionTexture.gfxTexture&&w.emissionTexture.gfxTexture.destroy(),w.occlusionTexture&&w.occlusionTexture.gfxTexture&&w.occlusionTexture.gfxTexture.destroy()}function p_e(w){if(w.meshes)for(const m of w.meshes)m.vertexBuffer&&(m.vertexBuffer.destroy(),m.indexBuffer.destroy(),m.normalBuffer&&m.normalBuffer.destroy(),m.texcoordBuffer&&m.texcoordBuffer.destroy(),m.colorBuffer&&m.colorBuffer.destroy(),m.pbrBuffer&&m.pbrBuffer.destroy(),m.segments.destroy(),m.material&&qCt(m.material));if(w.footprintDebugMesh&&(w.footprintDebugMesh.vertexBuffer.destroy(),w.footprintDebugMesh.indexBuffer.destroy(),w.footprintDebugMesh.segments.destroy()),w.children)for(const m of w.children)p_e(m)}function t3(w,m){const x=w.json.bufferViews[m.bufferView],k=Dq[m.componentType];return new k(w.buffers[x.buffer],(m.byteOffset||0)+(x.byteOffset||0),m.count*(x.byteStride&&x.byteStride!==wO[m.type]*k.BYTES_PER_ELEMENT?x.byteStride/k.BYTES_PER_ELEMENT:wO[m.type]))}function f_e(w,m,x,k){const E=Dq[m.componentType],P=function(le){switch(le){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(E),O=w.json.bufferViews[m.bufferView],U=O.byteStride?O.byteStride/E.BYTES_PER_ELEMENT:wO[m.type],H=x.float32,X=H.length/x.capacity;for(let le=0,he=0;le0){for(let Be=0;Be0){P.texcoordArray=new Hj;const me=m.json.accessors[E.TEXCOORD_0];P.texcoordArray.resize(me.count);const be=t3(m,me);f_e(m,me,P.texcoordArray,be)}if(E._FEATURE_ID_RGBA4444!==void 0){const me=m.json.accessors[E._FEATURE_ID_RGBA4444];m.json.extensionsUsed&&m.json.extensionsUsed.includes("EXT_meshopt_compression")&&(P.featureData=t3(m,me))}E._FEATURE_RGBA4444!==void 0&&(P.featureData=new Uint32Array(t3(m,m.json.accessors[E._FEATURE_RGBA4444]).buffer));const he=w.material;return P.material=function(me,be){const{emissiveFactor:Se=[0,0,0],alphaMode:Pe="OPAQUE",alphaCutoff:Be=.5,normalTexture:We,occlusionTexture:ot,emissiveTexture:nt,doubleSided:ft,name:bt}=me,{baseColorFactor:wt=[1,1,1,1],metallicFactor:Yt=1,roughnessFactor:zt=1,baseColorTexture:Kt,metallicRoughnessTexture:Vt}=me.pbrMetallicRoughness||{},Ht=ot?be[ot.index]:void 0;if(ot&&ot.extensions&&ot.extensions.KHR_texture_transform&&Ht){const Os=ot.extensions.KHR_texture_transform;Ht.offsetScale=[Os.offset[0],Os.offset[1],Os.scale[0],Os.scale[1]]}return{name:bt,pbrMetallicRoughness:{baseColorFactor:new Wn(...wt),metallicFactor:Yt,roughnessFactor:zt,baseColorTexture:Kt?be[Kt.index]:void 0,metallicRoughnessTexture:Vt?be[Vt.index]:void 0},doubleSided:ft,emissiveFactor:new Wn(...Se),alphaMode:Pe,alphaCutoff:Be,normalTexture:We?be[We.index]:void 0,occlusionTexture:Ht,emissionTexture:nt?be[nt.index]:void 0,defined:me.defined===void 0}}(he!==void 0?m.json.materials[he]:{defined:!1},x),P}function lOe(w,m,x){const{matrix:k,rotation:E,translation:P,scale:O,mesh:U,extras:H,children:X,name:le}=w,he={};if(he.name=le,he.localMatrix=k||function(me,be,Se,Pe){var Be=be[0],We=be[1],ot=be[2],nt=be[3],ft=Be+Be,bt=We+We,wt=ot+ot,Yt=Be*ft,zt=Be*bt,Kt=Be*wt,Vt=We*bt,Ht=We*wt,Os=ot*wt,Vs=nt*ft,Js=nt*bt,nn=nt*wt,en=Pe[0],xn=Pe[1],Ls=Pe[2];return me[0]=(1-(Vt+Os))*en,me[1]=(zt+nn)*en,me[2]=(Kt-Js)*en,me[3]=0,me[4]=(zt-nn)*xn,me[5]=(1-(Yt+Os))*xn,me[6]=(Ht+Vs)*xn,me[7]=0,me[8]=(Kt+Js)*Ls,me[9]=(Ht-Vs)*Ls,me[10]=(1-(Yt+Vt))*Ls,me[11]=0,me[12]=Se[0],me[13]=Se[1],me[14]=Se[2],me[15]=1,me}([],E||[0,0,0,1],P||[0,0,0],O||[1,1,1]),he.globalMatrix=b(he.localMatrix),U!==void 0){he.meshes=x[U];const me=he.anchor=[0,0];for(const be of he.meshes){const{min:Se,max:Pe}=be.aabb;me[0]+=Se[0]+Pe[0],me[1]+=Se[1]+Pe[1]}me[0]=Math.floor(me[0]/he.meshes.length/2),me[1]=Math.floor(me[1]/he.meshes.length/2)}if(H&&(H.id&&(he.id=H.id),H.lights&&(he.lights=function(me){if(!me.length)return[];const be=function(ot){const nt=atob(ot),ft=new Uint8Array(nt.length);for(let bt=0;bt1&&k[k.length-1].equals(k[0])&&k.pop();let E=0;for(let O=0;O0&&k.reverse();const P=U6(k.flatMap(O=>[O.x,O.y]),[]);return P.length===0?null:{vertices:k,indices:P}}function WCt(w,m){const x=[],k=[];let E=0;const P=[];for(const O of w){E=x.length;const U=O.vertexArray.float32,H=O.indexArray.uint16;for(let X=0;X0&&([k[O+1],k[O+2]]=[k[O+2],k[O+1]])}return{vertices:x,indices:k}}function x_e(w){const m=function(H,X){const le=[],he=WebGL2RenderingContext;if(H.json.textures)for(const me of H.json.textures){const be={magFilter:he.LINEAR,minFilter:he.NEAREST,wrapS:he.REPEAT,wrapT:he.REPEAT};me.sampler!==void 0&&Object.assign(be,H.json.samplers[me.sampler]),le.push({image:X[me.source],sampler:be,uploaded:!1})}return le}(w,w.images),x=function(H,X){const le=[];for(const he of H.json.meshes){const me=[];for(const be of he.primitives)me.push(VCt(be,H,X));le.push(me)}return le}(w,m),{scenes:k,scene:E,nodes:P}=w.json,O=k?k[E||0].nodes:[...P.keys()],U=[];for(const H of O)U.push(lOe(P[H],w,x));return function(H,X,le){const he={},me=new Set;for(let be=0;be0){const be=Array.from(me.values()).sort((Se,Pe)=>Se-Pe);for(let Se=be.length-1;Se>=0;Se--)H.splice(be[Se],1)}}(U,O,w.json.nodes),U}function KCt(w){w.heightmap=new Float32Array(4096),w.heightmap.fill(-1);const m=w.vertexArray.float32,x=w.aabb.min[0]-1,k=w.aabb.min[1]-1,E=e3/(w.aabb.max[0]-x+2),P=e3/(w.aabb.max[1]-k+2);for(let O=0;Ow.heightmap[X*e3+H]&&(w.heightmap[X*e3+H]=U)}}function cOe(w,m,x,k,E){x.reserve(x.length+4*w.length),k.reserve(k.length+10*w.length),E.reserve(E.length+10*w.length);let P=k.length;for(const O of w){const U=Math.min(10,Math.max(4,1.3*O.height))*m,H=[-O.normal[1],O.normal[0],0],X=Math.min(.29,.1*O.width/O.depth),le=O.width-2*O.depth*m*(X+.01),he=Me([],O.pos,H,le/2),me=Me([],O.pos,H,-le/2),be=[he[0],he[1],he[2]+O.height],Se=[me[0],me[1],me[2]+O.height],Pe=Me([],O.normal,H,X);_e(Pe,Pe,U);const Be=Me([],O.normal,H,-X);_e(Be,Be,U),pe(Pe,he,Pe),pe(Be,me,Be),he[2]+=.1,me[2]+=.1,k.emplaceBack(Pe[0],Pe[1],Pe[2]),k.emplaceBack(Be[0],Be[1],Be[2]),k.emplaceBack(he[0],he[1],he[2]),k.emplaceBack(me[0],me[1],me[2]),k.emplaceBack(be[0],be[1],be[2]),k.emplaceBack(Se[0],Se[1],Se[2]),k.emplaceBack(he[0],he[1],he[2]),k.emplaceBack(me[0],me[1],me[2]),k.emplaceBack(Pe[0],Pe[1],Pe[2]),k.emplaceBack(Be[0],Be[1],Be[2]);const We=le/U/2;E.emplaceBack(-We-X,-1,We,.8),E.emplaceBack(We+X,-1,We,.8),E.emplaceBack(-We,0,We,1.3),E.emplaceBack(We,0,We,1.3),E.emplaceBack(We+X,-.8,We,.7),E.emplaceBack(We+X,-.8,We,.7),E.emplaceBack(0,0,We,1.3),E.emplaceBack(0,0,We,1.3),E.emplaceBack(We+X,-1.2,We,.8),E.emplaceBack(We+X,-1.2,We,.8),x.emplaceBack(6+P,4+P,8+P),x.emplaceBack(7+P,9+P,5+P),x.emplaceBack(0+P,1+P,2+P),x.emplaceBack(1+P,3+P,2+P),P+=10}}function YCt(w,m){const x={};x.indexArray=new sc,x.vertexArray=new _g,x.colorArray=new T1,cOe(w,m,x.indexArray,x.vertexArray,x.colorArray);const k={defined:!0};k.emissiveFactor=Wn.black;const E={};return E.baseColorFactor=Wn.white,k.pbrMetallicRoughness=E,x.material=k,x.aabb=new so([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),x}const dOe=cn([{name:"a_pos_3f",components:3,type:"Float32"}]),ZCt=cn([{name:"a_normal_3",components:3,type:"Int16"}]),QCt=cn([{name:"a_centroid_3",components:3,type:"Int16"}]),uOe=cn([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),XCt=cn([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),JCt=cn([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),e3t=cn([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),t3t=cn([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),s3t=cn([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),hOe=_a.types,Uq=32767;function n3t(w,m){const x=Bn+m;for(const k of w)for(const E of k)if(E.x<-m||E.x>x||E.y<-m||E.y>x)return!1;return!0}function r3t(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}`)}}class g_e{constructor(){this.layoutVertexArray=new _g,this.layoutAttenuationArray=new T1,this.layoutColorArray=new wg,this.indexArray=new sc,this.indexArrayForConflation=new sc,this.segmentsBucket=new Po}}class y_e{constructor(m){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Po,this.entranceBloom=new g_e;const x=66560;this.layoutVertexArray=new _g,this.layoutVertexArray.reserve(x),this.layoutNormalArray=new Ui,this.layoutNormalArray.reserve(x),this.layoutCentroidArray=new Ui,this.layoutCentroidArray.reserve(x),this.layoutColorArray=new wg,this.layoutColorArray.reserve(x),this.layoutFloodLightDataArray=new R6,this.layoutFloodLightDataArray.reserve(x),this.layoutAOArray=new O6,this.layoutAOArray.reserve(x),this.indexArray=new sc,this.indexArray.reserve(66560),this.indexArrayForConflation=new sc,this.segmentsBucket=new Po,this.entranceBloom=new g_e,m&&(this.layoutFacadePaintArray=new wg,this.layoutFacadeDataArray=new lk,this.layoutFacadeVerticalRangeArray=new wg)}reserve(m,x,k){this.layoutVertexArray.reserveForAdditional(m),this.layoutCentroidArray.reserveForAdditional(m),this.layoutFloodLightDataArray.reserveForAdditional(m),this.layoutNormalArray.reserveForAdditional(m),this.layoutAOArray.reserveForAdditional(m),this.layoutColorArray.reserveForAdditional(m),this.indexArray.reserveForAdditional(x),k&&(this.layoutFacadePaintArray.reserveForAdditional(m),this.layoutFacadeDataArray.reserveForAdditional(m),this.layoutFacadeVerticalRangeArray.reserveForAdditional(m))}}class mOe{constructor(m){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new Hj,this.footprintsIndices=new Gj,this.footprintsMin=new Ms(1/0,1/0),this.footprintsMax=new Ms(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new y_e(!1),this.buildingWithFacade=new y_e(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=m.zoom,this.canonical=m.canonical,this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.worldview=m.worldview,this.lut=m.lut,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut}),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.projection=m.projection,this.groundEffect=new r_e(m),this.groundEffect.groundRadiusArray=new ro,this.hasAppearances=null}updateFootprints(m,x){const k=new kq([],[],1),E={vertices:[],indices:new Uint32Array(0),grid:k,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};x.push({footprint:E,id:m})}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(Lq!=null||qRe!=null)return null;if(G6!=null)return G6;const m=fetch(Yi());return G6=function(x){let k,E,P,O,U;function H(){k=new Uint8Array(U.buffer),E=new Int16Array(U.buffer),P=new Int32Array(U.buffer),O=new Float32Array(U.buffer)}function X(){throw new Error("Unexpected BuildingGen error.")}const le=()=>{},he={a:{a:X,f:function(me){const be=k.length,Se=Math.max(me>>>0,Math.ceil(1.2*be)),Pe=Math.ceil((Se-be)/65536);try{return U.grow(Pe),H(),!0}catch{return!1}},g:X,b:le,c:le,d:le,e:le}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(x,he):x.then(me=>me.arrayBuffer()).then(me=>WebAssembly.instantiate(me,he))).then(me=>{const be=me.instance.exports;return(0,be.g)(),U=be.f,H(),new TCt({setStyle:be.h,setAOOptions:be.i,setMetricOptions:be.j,setStructuralOptions:be.k,setFacadeOptions:be.l,setFauxFacadeOptions:be.m,setFacadeClassifierOptions:be.n,addFeature:be.o,addFacade:be.p,generateMesh:be.q,getLastError:be.r,getOuterRingLength:be.s,getMeshCount:be.t,getPositionsPtr:be.u,getPositionsLength:be.v,getNormalsPtr:be.w,getNormalsLength:be.x,getAOPtr:be.y,getAOLength:be.z,getUVPtr:be.A,getUVLength:be.B,getFauxFacadePtr:be.C,getFauxFacadeLength:be.D,getIndicesPtr:be.E,getIndicesLength:be.F,getBuildingPart:be.G,getRingCount:be.H,getRingPtr:be.I,getRingLength:be.J,malloc:be.K,free:be.L,heapU8:k,heap16:E,heap32:P,heapF32:O})})}(m).then(x=>(G6=null,Lq=x,Lq)).catch(x=>{sr("Could not load building-gen"),G6=null,qRe=x instanceof Error?x:new Error("Unknown error")}),G6}()}populate(m,x,k,E){const P=ECt();if(!P)return;const O=dn(k);this.tileToMeter=O,this.brightness=x.brightness,P.setStyle({normalScale:[1,-1,O],tileToMeters:O}),P.setAOOptions(!1,.3),P.setMetricOptions(!1,16),P.setStructuralOptions(!0),P.setFacadeClassifierOptions(3);const U=new Map,H=new Map;let X=0;for(const{feature:We}of m){if(hOe[We.type]!=="LineString"){U.set(We.id,We.properties.source_id);continue}const ot=this.layers[0]._featureFilter.needGeometry;if(ot&&!this.layers[0]._featureFilter.filter(new Ra(this.zoom),We,k))continue;const nt=Ya(We,ot);if(!ot&&!this.layers[0]._featureFilter.filter(new Ra(this.zoom),nt,k))continue;const ft=ot?nt.geometry:Kr(We,k,E),bt=[];for(const Kt of ft)for(const Vt of Kt)bt.push(Vt.x),bt.push(Vt.y);const wt={coordinates:bt,crossPerc:We.properties.cross_perc,distanceToRoad:We.properties.distance_to_road,entrances:We.properties.entrances,sourceId:0},Yt=We.properties.source_id;let zt=H.get(Yt);zt||(zt=[],H.set(Yt,zt)),zt.push(wt),++X}this.maxHeight=0;const le=new Array,he=new Set,me=We=>{We!=null&&he.add(We)},be=(We,ot)=>{We!=null&&le.push({buildingId:We,footprintIndex:ot})},Se=64*(m.length-X),Pe=Se/2;this.buildingWithFacade.reserve(Se,Pe,!0),this.buildingWithoutFacade.reserve(2*Se,2*Pe,!1),this.footprintsIndices.reserve(16*(m.length-X)),this.footprintsVertices.reserve(8*(m.length-X));for(const{feature:We,id:ot,index:nt,sourceLayerIndex:ft}of m){if(hOe[We.type]==="LineString")continue;const bt=this.layers[0]._featureFilter.needGeometry;if(bt&&!this.layers[0]._featureFilter.filter(new Ra(this.zoom),We,k))continue;let wt=null;if(We.properties&&We.properties.hasOwnProperty("building_id")&&(wt=Number(We.properties.building_id),he.has(wt)))continue;const Yt=Ya(We,bt);if(!bt&&!this.layers[0]._featureFilter.filter(new Ra(this.zoom),Yt,k))continue;const zt=bt?Yt.geometry:Kr(We,k,E),Kt=mO(zt,500);let Vt=!1;for(const ii of Kt)if(ii.length!==1){Vt=!0;break}if(Vt){me(wt);continue}if(!n3t(zt,163)){me(wt);continue}const Ht=this.layers[0],Os=r3t(Ht.layout.get("building-roof-shape").evaluate(We,{},k)),Vs=Ht.layout.get("building-base").evaluate(We,{},k),Js=Ht.layout.get("building-height").evaluate(We,{},k),nn=Ht.layout.get("building-flood-light-ground-radius").evaluate(We,{},k),en=Ht.paint.get("building-ambient-occlusion-intensity"),xn=nn/this.tileToMeter;We.properties["building-part"]="roof";const Ls=Ht.paint.get("building-color").evaluate(We,{},this.canonical).toPremultipliedRenderColor(this.lut),tn=Ht.paint.get("building-emissive-strength").evaluate(We,{},this.canonical);We.properties["building-part"]="wall";const on=Ht.paint.get("building-color").evaluate(We,{},this.canonical).toPremultipliedRenderColor(this.lut),gn=Ht.paint.get("building-emissive-strength").evaluate(We,{},this.canonical);We.properties["building-part"]="window";const En=Ht.paint.get("building-color").evaluate(We,{},this.canonical).toPremultipliedRenderColor(this.lut),ir=Ht.paint.get("building-emissive-strength").evaluate(We,{},this.canonical);We.properties["building-part"]="door";const On=Ht.paint.get("building-color").evaluate(We,{},this.canonical).toPremultipliedRenderColor(this.lut),Rn=Ht.paint.get("building-emissive-strength").evaluate(We,{},this.canonical);let An=Ht.layout.get("building-flood-light-wall-radius").evaluate(We,{},k);An=Qe(An,0,2048);const nr=An/2048*Uq,pr=U.get(ot),Gr=H.get(pr)||[],Sr=Gr.length!==0&&Ht.layout.get("building-facade").evaluate(We,{},k);P.setFacadeOptions(4,!0),P.setFauxFacadeOptions(Sr,!1,1);let Ma=0,ki=0,Ia=0,Ei=0,Za=0,zl=0,Ji=0,Fi=0,Ro=0,Il=0,eu=0;if(Sr){let ii=Math.round(Ht.layout.get("building-facade-floors").evaluate(We,{},k));if(Vs===0){ii=Math.max(1,ii-(Gr.length>0?1:0));let ac=4;if(Js>100){const Md=[10,13,15];ac=Md[We.id?We.id%Md.length:0]}else Js<=10&&(ac=3);P.setFacadeOptions(ac,!0),Za=(Js<15?1.3:1.61803)*ac/O}else Za=Vs/O;zl=Js/O,Za=Math.min(Za,zl),Ia=Ht.layout.get("building-facade-unit-width").evaluate(We,{},k)/O,Ei=(zl-Za)/ii,P.setFauxFacadeOptions(!0,!0,Ia);const ku=Ht.layout.get("building-facade-window").evaluate(We,{},k);Ma=ku[0],ki=ku[1],Ji=Math.floor(65535*Math.min(1,Za/Bn)),Fi=Math.floor(65535*Math.min(1,zl/Bn)),Ro=Math.floor(255*Ma)<<8|Math.floor(255*ki),Il=Math.floor(65535*Math.min(1,Ia/Bn)),eu=Math.floor(65535*Math.min(1,Ei/Bn))}const Pl=Array(Kt.length),nc={x:1/0,y:1/0},qc={x:-1/0,y:-1/0},rc={x:0,y:0};let Sh=0;for(let ii=0;ii0){const ac=[],Md=Array(ku.length+1);Md[0]=0;for(let A0=0;A0Bn||nc.y<0||qc.y>Bn)&&this.featuresOnBorder.push({featureId:We.id,footprintIndex:this.footprints.length});{const ii=U6(s2,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+ii.length),this.footprintsIndices.uint16.set(ii,iI),this.buildingIds.add(wt??We.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,T0.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,T0.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,E0.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,E0.y);const ku={footprintVertexOffset:t2,footprintVertexLength:this.footprintsVertices.length-t2,footprintIndexOffset:iI,footprintIndexLength:this.footprintsIndices.length-iI,min:T0,max:E0,hiddenFlags:0,indicesOffset:gV,indicesLength:lwe,bloomIndicesOffset:Ch,bloomIndicesLength:Bl,groundEffectVertexOffset:l3,groundEffectVertexLength:oI,hasFauxFacade:Sr,height:aI,promoteId:ot,feature:Yt,parts:ju,buildingBloom:mp},ac=this.footprints.length;We.id!==void 0&&this.featureFootprintLookup.set(We.id,ac),be(wt,ac),this.footprints.push(ku)}this.programConfigurations.populatePaintArrays(ei.layoutVertexArray.length,We,nt,{},x.availableImages,k,x.brightness),this.groundEffect.addPaintPropertiesData(We,nt,{},x.availableImages,k,x.brightness),x.featureIndex.insert(We,zt,nt,ft,this.index,Sm)}le.forEach(({buildingId:We,footprintIndex:ot})=>{he.has(We)&&(this.footprints[ot].hiddenFlags|=4)});const Be=new Set;this.buildingIds.forEach((We,ot,nt)=>{he.has(We)||Be.add(We)}),this.buildingIds=Be,this.groundEffect.prepareBorderSegments()}update(m,x,k,E,P,O,U){this.programConfigurations.updatePaintArrays(m,x,P,k,E,O,U),this.groundEffect.update(m,x,P,k,E,O,U),this.evaluate(this.layers[0],m),this.colorBufferUploaded=!1}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(m){const x=k=>{k.layoutVertexBuffer=m.createVertexBuffer(k.layoutVertexArray,dOe.members),k.layoutNormalBuffer=m.createVertexBuffer(k.layoutNormalArray,ZCt.members),k.layoutCentroidBuffer=m.createVertexBuffer(k.layoutCentroidArray,QCt.members),k.layoutFloodLightDataBuffer=m.createVertexBuffer(k.layoutFloodLightDataArray,s3t.members),k.layoutFacadeDataArray&&k.layoutFacadeDataArray.length&&(k.layoutFacadeDataBuffer=m.createVertexBuffer(k.layoutFacadeDataArray,JCt.members)),k.layoutFacadeVerticalRangeArray&&k.layoutFacadeVerticalRangeArray.length&&(k.layoutFacadeVerticalRangeBuffer=m.createVertexBuffer(k.layoutFacadeVerticalRangeArray,e3t.members)),k.entranceBloom.layoutVertexArray.length&&(k.entranceBloom.layoutVertexBuffer=m.createVertexBuffer(k.entranceBloom.layoutVertexArray,dOe.members),k.entranceBloom.layoutAttenuationBuffer=m.createVertexBuffer(k.entranceBloom.layoutAttenuationArray,t3t.members)),this.uploadUpdatedColorBuffer(m),this.uploadUpdatedIndexBuffer(m)};this.uploaded||(x(this.buildingWithoutFacade),x(this.buildingWithFacade),this.groundEffect.upload(m)),this.groundEffect.uploadPaintProperties(m),this.programConfigurations.upload(m),this.uploaded=!0}destroy(){const m=x=>{x.layoutVertexBuffer&&(x.layoutVertexBuffer.destroy(),x.layoutNormalBuffer.destroy(),x.layoutColorBuffer.destroy(),x.segmentsBucket.destroy(),x.indexBuffer&&x.indexBuffer.destroy(),x.entranceBloom.layoutVertexBuffer&&(x.entranceBloom.layoutVertexBuffer.destroy(),x.entranceBloom.layoutColorBuffer.destroy(),x.entranceBloom.layoutAttenuationBuffer.destroy(),x.entranceBloom.indexBuffer.destroy(),x.entranceBloom.segmentsBucket.destroy()))};m(this.buildingWithoutFacade),m(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(m,x,k=!0){let E=!1;const P=k?x:0,O=0|(k?-1:~x);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const U of m){const H=this.footprints[U],X=H.hiddenFlags&O|P;H.hiddenFlags!==X&&(H.hiddenFlags=X,E=!0,this.groundEffect.updateHiddenByLandmarkRange(H.groundEffectVertexOffset,H.groundEffectVertexLength,H.hiddenFlags!==0))}return E&&(this.indexArrayForConflationUploaded=!1),E}uploadUpdatedIndexBuffer(m){if(this.groundEffect.uploadHiddenByLandmark(m),this.indexArrayForConflationUploaded)return;const x=E=>{E.indexArray.length!==0&&(E.indexArrayForConflation.resize(E.indexArray.length),E.indexArrayForConflation.uint16.set(E.indexArray.uint16),E.entranceBloom.indexArrayForConflation.resize(E.entranceBloom.indexArray.length),E.entranceBloom.indexArrayForConflation.uint16.set(E.entranceBloom.indexArray.uint16))};x(this.buildingWithoutFacade),x(this.buildingWithFacade);for(const E of this.footprints){const P=E.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,O=E.indicesOffset+E.indicesLength;if(E.hiddenFlags!==0){for(let H=E.indicesOffset;H{E.indexArray.length!==0&&(E.indexBuffer?E.indexBuffer.updateData(E.indexArrayForConflation):E.indexBuffer=m.createIndexBuffer(E.indexArrayForConflation,!0),E.entranceBloom.indexBuffer?E.entranceBloom.indexBuffer.updateData(E.entranceBloom.indexArrayForConflation):E.entranceBloom.indexBuffer=m.createIndexBuffer(E.entranceBloom.indexArrayForConflation,!0))};k(this.buildingWithoutFacade),k(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(m){const x=k=>{k.layoutColorBuffer?k.layoutColorBuffer.updateData(k.layoutColorArray):k.layoutColorBuffer=m.createVertexBuffer(k.layoutColorArray,uOe.members,!0),k.layoutFacadePaintArray&&(k.layoutFacadePaintBuffer?k.layoutFacadePaintBuffer.updateData(k.layoutFacadePaintArray):k.layoutFacadePaintBuffer=m.createVertexBuffer(k.layoutFacadePaintArray,XCt.members,!0)),k.entranceBloom.layoutColorBuffer?k.entranceBloom.layoutColorBuffer.updateData(k.entranceBloom.layoutColorArray):k.entranceBloom.layoutColorBuffer=m.createVertexBuffer(k.entranceBloom.layoutColorArray,uOe.members,!0)};x(this.buildingWithoutFacade),x(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(m,x){const k=m.paint.get("building-ambient-occlusion-intensity");for(const E of this.footprints){if(4&E.hiddenFlags)continue;const P=x[E.promoteId],O=E.feature;O.properties["building-part"]="roof";const U=m.paint.get("building-color").evaluate(O,P,this.canonical).toPremultipliedRenderColor(this.lut),H=m.paint.get("building-emissive-strength").evaluate(O,P,this.canonical);O.properties["building-part"]="wall";const X=m.paint.get("building-color").evaluate(O,P,this.canonical).toPremultipliedRenderColor(this.lut),le=m.paint.get("building-emissive-strength").evaluate(O,P,this.canonical);O.properties["building-part"]="window";const he=m.paint.get("building-color").evaluate(O,P,this.canonical).toPremultipliedRenderColor(this.lut),me=m.paint.get("building-emissive-strength").evaluate(O,P,this.canonical);O.properties["building-part"]="door";const be=m.paint.get("building-color").evaluate(O,P,this.canonical).toPremultipliedRenderColor(this.lut),Se=m.paint.get("building-emissive-strength").evaluate(O,P,this.canonical),Pe=E.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const We of E.parts){let ot,nt=U;We.part===1?(nt=U,ot=H):We.part===0?(nt=X,ot=le):We.part===2?(nt=he,ot=me):We.part===3&&(nt=be,ot=Se),ot=Qe(ot,0,1);for(let ft=0;ftO.max.x||H.max.xO.max.y||H.max.yU.max.x||U.min.x>m||x>U.max.y||U.min.y>x||U.height<=k||a3t(O,this.footprintsVertices.float32.subarray(2*U.footprintVertexOffset,2*(U.footprintVertexOffset+U.footprintVertexLength)),this.footprintsIndices.uint16.subarray(U.footprintIndexOffset,U.footprintIndexOffset+U.footprintIndexLength))&&(k=U.height,this.footprintLookup[P]=U,E=U.hiddenFlags!==0);if(k!==Number.NEGATIVE_INFINITY)return{height:k,hidden:E};this.footprintLookup[P]=void 0}}function a3t(w,m,x){for(let k=0;k1&&(H=m[++U]);const le=Math.abs(X-H.left),he=Math.abs(X-H.right),me=Math.min(le,he);let be;const Se=P/k*(E+1);if(H.isDash){const Pe=E-Math.abs(Se);be=Math.sqrt(me*me+Pe*Pe)}else be=E-Math.sqrt(me*me+Se*Se);this.image.data[O+X]=Math.max(0,Math.min(255,be+128))}}}addRegularDash(m,x){for(let H=m.length-1;H>=0;--H){const X=m[H],le=m[H+1];X.zeroLength?m.splice(H,1):le&&le.isDash===X.isDash&&(le.left=X.left,m.splice(H,1))}const k=m[0],E=m[m.length-1];k.isDash===E.isDash&&(k.left=E.left-this.width,E.right=k.right+this.width);const P=this.width*this.nextRow;let O=0,U=m[O];for(let H=0;H1&&(U=m[++O]);const X=Math.abs(H-U.left),le=Math.abs(H-U.right),he=Math.min(X,le);this.image.data[P+H]=Math.max(0,Math.min(255,(U.isDash?he:-he)+x+128))}}addDash(m,x){const k=this.getKey(m,x);if(this.positions[k])return this.positions[k];const E=x==="round",P=E?7:0,O=2*P+1;if(this.nextRow+O>this.height)return sr("LineAtlas out of space"),null;m.length===0&&m.push(1);let U=0;for(let he=0;hex.fqid),this.index=m.index,this.projection=m.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(x=>{this.gradients[x.id]={}}),this.layoutVertexArray=new BC,this.layoutVertexArray2=new _g,this.patternVertexArray=new _g,this.indexArray=new sc,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut}),this.segments=new Po,this.maxLineLength=0,this.zOffsetVertexArray=new _g,this.elevationGroundScaleVertexArray=new ro,this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.tessellationStep=m.tessellationStep?m.tessellationStep:128,this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){this.hasPattern=$be("line",this.layers,this.pixelRatio,x);const P=this.layers[0].layout.get("line-sort-key");this.tileToMeter=dn(k);const O=this.layers[0].layout.get("line-elevation-reference");if(O==="hd-road-markup")this.elevationType="road";else{const me=this.layers[0].layout.get("line-z-offset"),be=me.isConstant()&&!me.constantOr(0);this.elevationType=O!=="sea"&&O!=="ground"&&be?"none":"offset",this.elevationType==="offset"&&O==="none"&&sr(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=O==="sea"}const U=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&U!==void 0;const H=[];for(const{feature:me,id:be,index:Se,sourceLayerIndex:Pe}of m){const Be=this.layers[0]._featureFilter.needGeometry,We=Ya(me,Be);if(!this.layers[0]._featureFilter.filter(new Ra(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),We,k))continue;const ot=P?P.evaluate(We,{},k):void 0,nt={id:be,properties:me.properties,type:me.type,sourceLayerIndex:Pe,index:Se,geometry:Be?We.geometry:Kr(me,k,E),patterns:{},sortKey:ot};H.push(nt)}P&&H.sort((me,be)=>me.sortKey-be.sortKey);const{lineAtlas:X,featureIndex:le}=x,he=this.addConstantDashes(X);for(const me of H){const{geometry:be,index:Se,sourceLayerIndex:Pe}=me;if(he&&this.addFeatureDashes(me,X),this.hasPattern){const Be=Ube("line",this.layers,me,this.zoom,this.pixelRatio,x);this.patternFeatures.push(Be)}else this.addFeature(me,be,Se,k,X.positions,x.availableImages,x.brightness,x.elevationFeatures);le.insert(m[Se].feature,be,Se,Pe,this.index)}}addConstantDashes(m){let x=!1;for(const k of this.layers){const E=k.paint.get("line-dasharray").value,P=k.layout.get("line-cap").value;if(E.kind!=="constant"||P.kind!=="constant")x=!0;else{const O=P.value,U=E.value;if(!U)continue;m.addDash(U,O)}}return x}addFeatureDashes(m,x){const k=this.zoom;for(const E of this.layers){const P=E.paint.get("line-dasharray").value,O=E.layout.get("line-cap").value;if(P.kind==="constant"&&O.kind==="constant")continue;let U,H;if(P.kind==="constant"){if(U=P.value,!U)continue}else U=P.evaluate({zoom:k},m);H=O.kind==="constant"?O.value:O.evaluate({zoom:k},m),x.addDash(U,H),m.patterns[E.id]=[x.getKey(U,H)]}}update(m,x,k,E,P,O,U,H,X){this.programConfigurations.updatePaintArrays(m,x,P,k,E,O,U,X)}addFeatures(m,x,k,E,P,O){for(const U of this.patternFeatures)this.addFeature(U,U.geometry,U.index,x,k,E,O,m.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=m.createVertexBuffer(this.layoutVertexArray2,h3t)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=m.createVertexBuffer(this.patternVertexArray,p3t)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=m.createVertexBuffer(this.zOffsetVertexArray,l3t.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=m.createVertexBuffer(this.elevationGroundScaleVertexArray,c3t.members,!0)),this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,d3t),this.indexBuffer=m.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(m),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(m,x){let k,E;if(x&&x>0?(k=`mapbox_clip_start_${x}`,E=`mapbox_clip_end_${x}`):(k="mapbox_clip_start",E="mapbox_clip_end"),m.properties&&m.properties.hasOwnProperty(k)&&m.properties.hasOwnProperty(E))return{start:+m.properties[k],end:+m.properties[E]}}addFeature(m,x,k,E,P,O,U,H){const X=this.layers[0].layout,le=X.get("line-join").evaluate(m,{}),he=X.get("line-cap").evaluate(m,{}),me=X.get("line-miter-limit"),be=X.get("line-round-limit");this.lineClips=this.lineFeatureClips(m),this.lineFeature=m;const Se=!(!m.properties||!m.properties.hasOwnProperty("mapbox_line_metrics"))&&m.properties.mapbox_line_metrics;this.zOffsetValue=X.get("line-z-offset").value;const Pe=this.layers[0].paint.get("line-width").value;if(Pe.kind!=="constant"&&Pe.isLineProgressConstant===!1&&(this.variableWidthValue=Pe),this.isSeaLevelReference){const Be=X.get("line-elevation-ground-scale").value;Be.kind==="constant"&&Be.value===0||(this.elevationGroundScaleValue=Be)}if(this.elevationType==="road"){const Be=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(m,x,E,H,le,he,me,be)){const[We,ot]=this.clipRuntimeLinesToTile(x,1);for(let nt=0;nt0?bt.parentIndex:null)}this.fillNonElevatedRoadSegment(Be)}}else for(let Be=0;Be0?Be:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,m,k,P,O,E,U,void 0,this.worldview)}computeSegNextDir(m,x){return m.nextPoint.sub(x.at(-2)).unit()}computeSegPrevDir(m,x){return x[1].sub(m.prevPoint).unit()}clipLinesToTile(m,x){return Pq(m,-x,-x,Bn+x,Bn+x)}clipRuntimeLinesToTile(m,x){const k=[];return[Pq(m,-x,-x,Bn+x,Bn+x,k),k]}addElevatedRoadFeature(m,x,k,E,P,O,U,H){const X=[],le=$o.getElevationFeature(m,E);if(le){const he=this.clipLinesToTile(x,1),me=this.prepareElevatedLines(he,le,k);for(const be of me)X.push({geometry:be,elevation:le,elevationTileID:k,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(X.length===0)return!1;for(const he of X){const me=this.layoutVertexArray.length;this.addLine(he.geometry,m,k,P,O,U,H);const be=new Qo(k,he.elevationTileID);if(he.elevation)for(let Se=me;Se>1,this.layoutVertexArray.int16[6*Se+1]>>1),Be=be.pointElevation(Pe,he.elevation,.05);this.updateHeightRange(Be),this.zOffsetVertexArray.emplaceBack(Be,0,0)}else this.fillNonElevatedRoadSegment(me)}return!0}prepareElevatedLines(m,x,k){if(x.constantHeight!=null)return m;const E=[],P=1/dn(k);for(const O of m)CCt(O,new Tx(x,P),0,E);return E}fillNonElevatedRoadSegment(m){for(let x=m;x0,me=H&&H.progress.max<1;if(this.lineClips){let Kt={min:this.lineClips.start,max:this.lineClips.end},Vt=1;if(H){const Vs=this.lineClips.end-this.lineClips.start;Kt=function(Js,nn,en){return{min:Mi(Js.min,nn,en),max:Mi(Js.max,nn,en)}}(H.progress,{min:0,max:1},Kt),Vs>0&&(Vt=(Kt.max-Kt.min)/Vs)}const Ht=+x.properties.mapbox_clip_feature_len,Os=+x.properties.mapbox_clip_seg_len;if(Number.isNaN(Ht)||Number.isNaN(Os)){for(let Js=0;Js=2&&m[Se-1].equals(m[Se-2]);)Se--;let Pe=0;for(;Pe0,tn=this.overscaling<=16?122880/(512*this.overscaling):0;if(Vt&&Ht==="round"){if(nnO&&(Ht="bevel"),Ht==="bevel"&&(nn>2&&(Ht="flipbevel"),nn2*tn){const En=We.sub(We.sub(ot)._mult(tn/on)._round());this.updateDistance(ot,En),this.addCurrentVertex(En,ft,0,0,Be,zt),ot=En}this.updateDistance(ot,We),Vs._mult(nn),this.addCurrentVertex(We,Vs,0,0,Be,zt);const gn=We.dist(nt);if(gn>2*tn){const En=We.add(nt.sub(We)._mult(tn/gn)._round());this.updateDistance(We,En),this.addCurrentVertex(En,bt,0,0,Be,zt),We=En}}else Vs._mult(nn),this.addCurrentVertex(We,Vs,0,0,Be,zt);else if(Ht==="flipbevel"){if(nn>100)Vs=bt.mult(-1);else{const on=nn*ft.add(bt).mag()/ft.sub(bt).mag();Vs._perp()._mult(on*(Ls?-1:1))}this.addCurrentVertex(We,Vs,0,0,Be,zt),this.addCurrentVertex(We,Vs.mult(-1),0,0,Be,zt)}else if(Ht==="bevel"||Ht==="fakeround"){const on=We.dist(ot);let gn=1;if(this.elevationType==="offset"&&Ht==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&zt!=null&&ot&&nt){const nr=4*tn;on1){this.lineSoFar=m.w;const Pe=(x.x-m.x)/he,Be=(x.y-m.y)/he,We=(x.z-m.z)/he,ot=(x.w-m.w)/he,nt=x.x-m.x,ft=x.y-m.y,bt=Math.sqrt(nt*nt+ft*ft);if(bt===0)return;const wt=-ft/bt,Yt=nt/bt,zt=wt,Kt=Yt,Vt=-wt,Ht=-Yt;for(let Os=1;Os=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,le),H.primitiveLength++),O?this.e2=le:this.e1=le,X!=null&&this.zOffsetVertexArray.emplaceBack(X.zOffset,X.variableWidth,X.variableWidth),this.elevationGroundScaleValue){const he=X?X.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(he)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(m,x){this.prevDistance=this.distance,this.distance+=m.dist(x),this.updateScaledDistance()}}function v_e(w,m,x){return w.xx||w.yx}let gOe,yOe;function vOe(w,m,x){return m*(Bn/(w.tileSize*Math.pow(2,x-w.tileID.overscaledZ)))}Yn(qq,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const bOe=(w,m,x)=>(1-x)*w+x*m;function _Oe(w,m){return 1/vOe(w,1,m.tileZoom)}function wOe(w,m,x,k){return w.translatePosMatrix(k||m.tileID.projMatrix,m,x.paint.get("line-translate"),x.paint.get("line-translate-anchor"))}const jOe=w=>{const m=[];NOe(w)&&m.push("RENDER_LINE_DASH"),w.paint.get("line-gradient")&&m.push("RENDER_LINE_GRADIENT"),w.paint.get("line-blend-mode")==="multiply"&&m.push("LINE_BLEND_MULTIPLY");const x=w.paint.get("line-trim-offset");x[0]===0&&x[1]===0||m.push("RENDER_LINE_TRIM_OFFSET"),w.paint.get("line-border-width").constantOr(1)!==0&&m.push("RENDER_LINE_BORDER");const k=w.layout.get("line-join").constantOr("miter")==="none",E=!!w.paint.get("line-pattern").constantOr(1);return k&&E&&m.push("LINE_JOIN_NONE"),m};function NOe(w){const m=w.paint.get("line-dasharray").value;return m.kind!=="constant"||m.value}let b_e;const kOe=()=>b_e||(b_e={layout:gOe||(gOe=new Zo({"line-cap":new Nn(fs.layout_line["line-cap"]),"line-join":new Nn(fs.layout_line["line-join"]),"line-miter-limit":new kn(fs.layout_line["line-miter-limit"]),"line-round-limit":new kn(fs.layout_line["line-round-limit"]),"line-sort-key":new Nn(fs.layout_line["line-sort-key"]),"line-z-offset":new Nn(fs.layout_line["line-z-offset"]),"line-elevation-reference":new kn(fs.layout_line["line-elevation-reference"]),"line-cross-slope":new kn(fs.layout_line["line-cross-slope"]),visibility:new kn(fs.layout_line.visibility),"line-width-unit":new kn(fs.layout_line["line-width-unit"]),"line-elevation-ground-scale":new Nn(fs.layout_line["line-elevation-ground-scale"])})),paint:yOe||(yOe=new Zo({"line-opacity":new Nn(fs.paint_line["line-opacity"]),"line-color":new Nn(fs.paint_line["line-color"]),"line-translate":new kn(fs.paint_line["line-translate"]),"line-translate-anchor":new kn(fs.paint_line["line-translate-anchor"]),"line-width":new Nn(fs.paint_line["line-width"]),"line-gap-width":new Nn(fs.paint_line["line-gap-width"]),"line-offset":new Nn(fs.paint_line["line-offset"]),"line-blur":new Nn(fs.paint_line["line-blur"]),"line-dasharray":new Nn(fs.paint_line["line-dasharray"]),"line-pattern":new Nn(fs.paint_line["line-pattern"]),"line-pattern-cross-fade":new kn(fs.paint_line["line-pattern-cross-fade"]),"line-gradient":new Wp(fs.paint_line["line-gradient"]),"line-trim-offset":new kn(fs.paint_line["line-trim-offset"]),"line-trim-fade-range":new kn(fs.paint_line["line-trim-fade-range"]),"line-trim-color":new kn(fs.paint_line["line-trim-color"]),"line-emissive-strength":new Nn(fs.paint_line["line-emissive-strength"]),"line-border-width":new Nn(fs.paint_line["line-border-width"]),"line-border-color":new Nn(fs.paint_line["line-border-color"]),"line-occlusion-opacity":new kn(fs.paint_line["line-occlusion-opacity"]),"line-blend-mode":new kn(fs.paint_line["line-blend-mode"]),"line-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"})}))},b_e);class y3t extends Nn{possiblyEvaluate(m,x){return x=new Ra(Math.floor(x.zoom),{now:x.now,fadeDuration:x.fadeDuration,transition:x.transition,worldview:x.worldview}),super.possiblyEvaluate(m,x)}evaluate(m,x,k,E){return x=Object.assign({},x,{zoom:Math.floor(x.zoom)}),super.evaluate(m,x,k,E)}}let kO;function SOe(w,m){return m>0?m+2*w:w}const v3t=cn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),b3t=cn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),_3t=cn([{name:"a_projected_pos",components:4,type:"Float32"}],4);cn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const w3t=cn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),j3t=cn([{name:"a_feature_index",components:1,type:"Float32"}],4),N3t=cn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),k3t=cn([{name:"a_texb",components:2,type:"Uint16"}]),S3t=cn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),C3t=cn([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);cn([{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 COe=cn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),T3t=cn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);cn([{name:"triangle",components:3,type:"Uint16"}]),cn([{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"}]),cn([{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"}]),cn([{type:"Float32",name:"offsetX"}]),cn([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const __e=class Pme{constructor(m=null,x=0,k=4096){this.batchIndex=x,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=m||null,this.propsDwords=k,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(Pme.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let E=0;Em.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${m.maxUniformBlockSize}`);if(this.headerBuffer=x.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(x.bindBuffer(x.UNIFORM_BUFFER,this.headerBuffer),x.bufferData(x.UNIFORM_BUFFER,Pme.HEADER_BYTES,x.DYNAMIC_DRAW),this.propertiesBuffer=x.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(x.bindBuffer(x.UNIFORM_BUFFER,this.propertiesBuffer),x.bufferData(x.UNIFORM_BUFFER,this.totalBytes,x.DYNAMIC_DRAW),this.blockIndicesBuffer=x.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");x.bindBuffer(x.UNIFORM_BUFFER,this.blockIndicesBuffer),x.bufferData(x.UNIFORM_BUFFER,this.totalBytes,x.DYNAMIC_DRAW),x.bindBuffer(x.UNIFORM_BUFFER,null)}writeHeader(m){const x=this.headerData;x[0]=m.dataDrivenMask,x[1]=m.zoomDependentMask,x[2]=m.dataDrivenBlockSizeVec4,x[3]=m.offsets[0],x[4]=m.offsets[1],x[5]=m.offsets[2],x[6]=m.offsets[3],x[7]=m.offsets[4],x[8]=m.offsets[5],x[9]=m.offsets[6],x[10]=m.offsets[7],x[11]=m.offsets[8]}writeDataDrivenBlock(m,x,k){const E=4*k.dataDrivenBlockSizeVec4;if(E===0)return;const P=x*E;if(P+E>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${x} exceeds propertiesData capacity`);for(let O=0;O<9;O++)k.dataDrivenMask&1<{if(!U)return;const X=k.getUniformBlockIndex(x,O);X!==k.INVALID_INDEX&&(k.uniformBlockBinding(x,X,H),k.bindBufferBase(k.UNIFORM_BUFFER,H,U))},P=3*this.batchIndex;E("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,P),E("SymbolPaintPropertiesUniform",this.propertiesBuffer,P+1),E("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,P+2)}destroy(){if(this.context){const m=this.context.gl;this.headerBuffer&&(m.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(m.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(m.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};__e.HEADER_DWORDS=12,__e.HEADER_BYTES=48;let w_e=__e;function j_e(w,m,x,k){return[F6(255*w,255*m),F6(255*x,255*k)]}function TOe(w,m,x,k,E,P,O,U){return!!w&&(w.kind==="constant"?w.value==="none":w.kind==="composite"||w.kind==="source"?w.evaluate({zoom:0,brightness:P,worldview:U},m,x,E,k,O)==="none":typeof w=="string"&&w==="none")}Yn(w_e,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class N_e{constructor(m,x,k,E,P="",O,U){this.layer=m,this.zoom=x,this.lut=k,this.isText=E,this.propDefs=this._getPropDefs(),this.worldview=P,this.maxUniformBufferBindings=O||24,this.uboSizeDwords=U||4096,this.featureVertexRangesFromId=new Map,this.allFeatures=[],this.ubos=[],this.featureCount=0,this.cachedHeader=null,this.maxFeaturesPerBatch=0,this.propertyHashToUBOIndex=new Map,this.canDeduplicate=this._checkIfAllPropertiesAreConstant(m,E),this.cachedParams=null,this.cachedParamsNext=null,this.cachedBrightness=void 0,this.cachedConstantUniforms=null,this.cachedConstantRenderZoom=null,this.cachedConstantBrightness=void 0,this.activeAppearanceByVtIndex=new Map}_getPropDefs(){const m=this.isText?"text":"icon";return[{name:`${m}-color`,useThemeName:`${m}-color-use-theme`,isColor:!0},{name:`${m}-halo-color`,useThemeName:`${m}-halo-color-use-theme`,isColor:!0},{name:`${m}-opacity`,useThemeName:null,isColor:!1},{name:`${m}-halo-width`,useThemeName:null,isColor:!1},{name:`${m}-halo-blur`,useThemeName:null,isColor:!1},{name:`${m}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${m}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${m}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const m=this.layer.paint,x=this.propDefs;let k=0,E=0,P=0,O=0;const U=[0,0,0,0,0,0,0,0,0];for(let H=0;H<9;H++){const{name:X,isColor:le,isVec2:he}=x[H],me=m.get(X),be=!(!me||typeof me.isConstant!="function"||me.isConstant()),Se=this._appearancesHavePaintProperties(X),Pe=be||Se,Be=!(!me||!me.value||me.value.kind!=="composite"),We=this.layer._transitionablePaint._values[X],ot=!Pe&&(We&&We.value&&We.value.expression&&We.value.expression.kind)==="camera";Pe?(k|=1<x.hasPaintProperty(m):this.isText?x=>x.hasTextPaintProperties():x=>x.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(m,x){const k=m.paint,E=x?"text":"icon",P=[`${E}-color`,`${E}-halo-color`,`${E}-opacity`,`${E}-halo-width`,`${E}-halo-blur`,`${E}-emissive-strength`,`${E}-occlusion-opacity`,"symbol-z-offset",`${E}-translate`];for(const O of P){const U=k.get(O);if(U&&typeof U=="object"&&"isConstant"in U&&!U.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(m,x){if(x.dataDrivenMask===0)return"";const k=[];for(let E=0;E<9;E++){if(!(x.dataDrivenMask&1<=Se){sr(`Too many symbol features: batch ${me} requires binding points up to ${3*me+2}, device limit ${Se}. Some features will render incorrectly.`);const Be={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:x,featureId:H};return this.allFeatures.push(Be),H!=null&&(this.featureVertexRangesFromId.has(H)||this.featureVertexRangesFromId.set(H,[]),this.featureVertexRangesFromId.get(H).push(Be)),0}this.ubos[me]||(this.ubos[me]=new w_e(U,me,this.uboSizeDwords),this.ubos[me].writeHeader(X)),this.ubos[me].writeDataDrivenBlock(le,be,X);const Pe={batchIndex:me,localFeatureIndex:be,vtFeatureIndex:x,featureId:H};return this.allFeatures.push(Pe),H!=null&&(this.featureVertexRangesFromId.has(H)||this.featureVertexRangesFromId.set(H,[]),this.featureVertexRangesFromId.get(H).push(Pe)),be}updateFeatures(m,x,k,E,P,O,U){if(this.layer=x,this.cachedConstantUniforms=null,!this.cachedHeader)return;const H=this.cachedHeader;for(const X of m){const le=this.featureVertexRangesFromId.get(X);if(!le)continue;const he=O[X]||{};for(const me of le){if(!k)continue;const be=k.feature(me.vtFeatureIndex);if(!be)continue;const Se={type:be.type,id:X,properties:be.properties||{},geometry:[]},Pe=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(me.vtFeatureIndex):void 0,Be=this.evaluateAllProperties(Se,he,E,P,U,void 0,Pe);this.ubos[me.batchIndex]&&this.ubos[me.batchIndex].writeDataDrivenBlock(Be,me.localFeatureIndex,H)}}}updateDynamicExpressions(m,x,k,E,P,O){if(this.layer=m,this.cachedConstantUniforms=null,!this.cachedHeader)return;const U=this.cachedHeader;for(const H of this.allFeatures){if(!x)continue;const X=x.feature(H.vtFeatureIndex);if(!X)continue;const le=H.featureId!=null&&P[H.featureId]||{},he={type:X.type,id:H.featureId,properties:X.properties||{},geometry:[]},me=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(H.vtFeatureIndex):void 0,be=this.evaluateAllProperties(he,le,k,E,O,void 0,me);this.ubos[H.batchIndex]&&this.ubos[H.batchIndex].writeDataDrivenBlock(be,H.localFeatureIndex,U)}}updateFeaturePaintForAppearance(m,x,k,E,P,O,U){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(m,U||null),!this.cachedHeader))return!1;const H=this.cachedHeader;if(H.dataDrivenMask===0)return!1;let X=!1;for(const le of this.allFeatures){if(le.vtFeatureIndex!==m)continue;const he=this.evaluateAllProperties(x,k,E,P,O,void 0,U);this.ubos[le.batchIndex]&&(this.ubos[le.batchIndex].writeDataDrivenBlock(he,le.localFeatureIndex,H),X=!0)}return X}getConstantUniformValues(m,x){const k=this.cachedHeader,E=!(!k||!k.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===x&&(!E||this.cachedConstantRenderZoom===m))return this.cachedConstantUniforms;const P=this.layer.paint,O=this.propDefs,U=E?new Ra(m,{brightness:x,worldview:this.worldview}):null,H={type:1,id:void 0,properties:{},geometry:[]},X=me=>{const be=O[me],Se=P.get(be.name);if(!Se)return[0,0,0,1];const Pe=be.useThemeName?P.get(be.useThemeName):void 0,Be=TOe(Pe&&typeof Pe!="string"?Pe.value:void 0,H,{},[],void 0,x,void 0,this.worldview)?null:this.lut;let We;We=k&&k.cameraMask&1<{const Se=P.get(O[me].name);if(!Se)return be;if(k&&k.cameraMask&1<{k.text=function(E,P,O){const U=P.layout.get("text-transform").evaluate(O,{});return U==="uppercase"?E=E.toLocaleUpperCase():U==="lowercase"&&(E=E.toLocaleLowerCase()),km.applyArabicShaping&&(E=km.applyArabicShaping(E)),E}(k.text,m,x)}),w}const SO={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function A3t(w){return w==="︶"||w==="﹈"||w==="︸"||w==="﹄"||w==="﹂"||w==="︾"||w==="︼"||w==="︺"||w==="︘"||w==="﹀"||w==="︐"||w==="︓"||w==="︔"||w==="`"||w===" ̄"||w==="︑"||w==="︒"}function M3t(w){return w==="︵"||w==="﹇"||w==="︷"||w==="﹃"||w==="﹁"||w==="︽"||w==="︻"||w==="︹"||w==="︗"||w==="︿"}const k_e=4294967296,EOe=1/k_e,AOe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let Vq=class{constructor(w=new Uint8Array(16)){this.buf=ArrayBuffer.isView(w)?w:new Uint8Array(w),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(w,m,x=this.length){for(;this.pos>3,P=this.pos;this.type=7&k,w(E,m,this),this.pos===P&&this.skip(k)}return m}readMessage(w,m){return this.readFields(w,m,this.readVarint()+this.pos)}readFixed32(){const w=this.dataView.getUint32(this.pos,!0);return this.pos+=4,w}readSFixed32(){const w=this.dataView.getInt32(this.pos,!0);return this.pos+=4,w}readFixed64(){const w=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*k_e;return this.pos+=8,w}readSFixed64(){const w=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*k_e;return this.pos+=8,w}readFloat(){const w=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,w}readDouble(){const w=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,w}readVarint(w){const m=this.buf;let x,k;return k=m[this.pos++],x=127&k,k<128?x:(k=m[this.pos++],x|=(127&k)<<7,k<128?x:(k=m[this.pos++],x|=(127&k)<<14,k<128?x:(k=m[this.pos++],x|=(127&k)<<21,k<128?x:(k=m[this.pos],x|=(15&k)<<28,function(E,P,O){const U=O.buf;let H,X;if(X=U[O.pos++],H=(112&X)>>4,X<128||(X=U[O.pos++],H|=(127&X)<<3,X<128)||(X=U[O.pos++],H|=(127&X)<<10,X<128)||(X=U[O.pos++],H|=(127&X)<<17,X<128)||(X=U[O.pos++],H|=(127&X)<<24,X<128)||(X=U[O.pos++],H|=(1&X)<<31,X<128))return K6(E,H,P);throw new Error("Expected varint not more than 10 bytes")}(x,w,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const w=this.readVarint();return w%2==1?(w+1)/-2:w/2}readBoolean(){return!!this.readVarint()}readString(){const w=this.readVarint()+this.pos,m=this.pos;return this.pos=w,w-m>=12&&AOe?AOe.decode(this.buf.subarray(m,w)):function(x,k,E){let P="",O=k;for(;O239?4:U>223?3:U>191?2:1;if(O+me>E)break;me===1?U<128&&(he=U):me===2?(H=x[O+1],(192&H)==128&&(he=(31&U)<<6|63&H,he<=127&&(he=null))):me===3?(H=x[O+1],X=x[O+2],(192&H)==128&&(192&X)==128&&(he=(15&U)<<12|(63&H)<<6|63&X,(he<=2047||he>=55296&&he<=57343)&&(he=null))):me===4&&(H=x[O+1],X=x[O+2],le=x[O+3],(192&H)==128&&(192&X)==128&&(192&le)==128&&(he=(15&U)<<18|(63&H)<<12|(63&X)<<6|63&le,(he<=65535||he>=1114112)&&(he=null))),he===null?(he=65533,me=1):he>65535&&(he-=65536,P+=String.fromCharCode(he>>>10&1023|55296),he=56320|1023&he),P+=String.fromCharCode(he),O+=me}return P}(this.buf,m,w)}readBytes(){const w=this.readVarint()+this.pos,m=this.buf.subarray(this.pos,w);return this.pos=w,m}readPackedVarint(w=[],m){const x=this.readPackedEnd();for(;this.pos127;);else if(m===2)this.pos=this.readVarint()+this.pos;else if(m===5)this.pos+=4;else{if(m!==1)throw new Error(`Unimplemented type: ${m}`);this.pos+=8}}writeTag(w,m){this.writeVarint(w<<3|m)}realloc(w){let m=this.length||16;for(;m268435455||w<0?function(m,x){let k,E;if(m>=0?(k=m%4294967296|0,E=m/4294967296|0):(k=~(-m%4294967296),E=~(-m/4294967296),4294967295^k?k=k+1|0:(k=0,E=E+1|0)),m>=18446744073709552e3||m<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");x.realloc(10),function(P,O,U){U.buf[U.pos++]=127&P|128,P>>>=7,U.buf[U.pos++]=127&P|128,P>>>=7,U.buf[U.pos++]=127&P|128,P>>>=7,U.buf[U.pos++]=127&P|128,U.buf[U.pos]=127&(P>>>=7)}(k,0,x),function(P,O){const U=(7&P)<<4;O.buf[O.pos++]|=U|((P>>>=3)?128:0),P&&(O.buf[O.pos++]=127&P|((P>>>=7)?128:0),P&&(O.buf[O.pos++]=127&P|((P>>>=7)?128:0),P&&(O.buf[O.pos++]=127&P|((P>>>=7)?128:0),P&&(O.buf[O.pos++]=127&P|((P>>>=7)?128:0),P&&(O.buf[O.pos++]=127&P)))))}(E,x)}(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 m=this.pos;this.pos=function(k,E,P){for(let O,U,H=0;H55295&&O<57344){if(!U){O>56319||H+1===E.length?(k[P++]=239,k[P++]=191,k[P++]=189):U=O;continue}if(O<56320){k[P++]=239,k[P++]=191,k[P++]=189,U=O;continue}O=U-55296<<10|O-56320|65536,U=null}else U&&(k[P++]=239,k[P++]=191,k[P++]=189,U=null);O<128?k[P++]=O:(O<2048?k[P++]=O>>6|192:(O<65536?k[P++]=O>>12|224:(k[P++]=O>>18|240,k[P++]=O>>12&63|128),k[P++]=O>>6&63|128),k[P++]=63&O|128)}return P}(this.buf,w,this.pos);const x=this.pos-m;x>=128&&MOe(m,x,this),this.pos=m-1,this.writeVarint(x),this.pos+=x}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 m=w.length;this.writeVarint(m),this.realloc(m);for(let x=0;x=128&&MOe(x,k,this),this.pos=x-1,this.writeVarint(k),this.pos+=k}writeMessage(w,m,x){this.writeTag(w,2),this.writeRawMessage(m,x)}writePackedVarint(w,m){m.length&&this.writeMessage(w,I3t,m)}writePackedSVarint(w,m){m.length&&this.writeMessage(w,P3t,m)}writePackedBoolean(w,m){m.length&&this.writeMessage(w,R3t,m)}writePackedFloat(w,m){m.length&&this.writeMessage(w,L3t,m)}writePackedDouble(w,m){m.length&&this.writeMessage(w,D3t,m)}writePackedFixed32(w,m){m.length&&this.writeMessage(w,O3t,m)}writePackedSFixed32(w,m){m.length&&this.writeMessage(w,F3t,m)}writePackedFixed64(w,m){m.length&&this.writeMessage(w,z3t,m)}writePackedSFixed64(w,m){m.length&&this.writeMessage(w,B3t,m)}writeBytesField(w,m){this.writeTag(w,2),this.writeBytes(m)}writeFixed32Field(w,m){this.writeTag(w,5),this.writeFixed32(m)}writeSFixed32Field(w,m){this.writeTag(w,5),this.writeSFixed32(m)}writeFixed64Field(w,m){this.writeTag(w,1),this.writeFixed64(m)}writeSFixed64Field(w,m){this.writeTag(w,1),this.writeSFixed64(m)}writeVarintField(w,m){this.writeTag(w,0),this.writeVarint(m)}writeSVarintField(w,m){this.writeTag(w,0),this.writeSVarint(m)}writeStringField(w,m){this.writeTag(w,2),this.writeString(m)}writeFloatField(w,m){this.writeTag(w,5),this.writeFloat(m)}writeDoubleField(w,m){this.writeTag(w,1),this.writeDouble(m)}writeBooleanField(w,m){this.writeVarintField(w,+m)}};function K6(w,m,x){return x?4294967296*m+(w>>>0):4294967296*(m>>>0)+(w>>>0)}function MOe(w,m,x){const k=m<=16383?1:m<=2097151?2:m<=268435455?3:Math.floor(Math.log(m)/(7*Math.LN2));x.realloc(k);for(let E=x.pos-1;E>=w;E--)x.buf[E+k]=x.buf[E]}function I3t(w,m){for(let x=0;x=0&&k>=m&&Hq[this.text.charCodeAt(k)];k--)x--;this.text=this.text.substring(m,x),this.sectionIndex=this.sectionIndex.slice(m,x)}substring(m,x){const k=new Y6;return k.text=this.text.substring(m,x),k.sectionIndex=this.sectionIndex.slice(m,x),k.sections=this.sections,k}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((m,x)=>Math.max(m,this.sections[x].scale),0)}addTextSection(m,x){this.text+=m.text,this.sections.push(CO.forText(m.scale,m.fontStack||x));const k=this.sections.length-1;for(let E=0;E=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function S_e(w,m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe=1,Be=1){const We=Y6.fromFeature(w,E,Pe,Be);he===Ix.vertical&&We.verticalizePunctuation(me);let ot=[];const nt=function(zt,Kt,Vt,Ht,Os,Vs,Js=1){if(!zt)return[];const nn=[],en=function(tn,on,gn,En,ir,On,Rn=1){let An=0;for(let nr=0;nr=0;let Ls=0;for(let tn=0;tn0&&Sm>Za&&(Za=Sm)}else{const ju=Vt[Il.fontStack];if(!ju)continue;ju[Pl]&&(rc=ju[Pl]);const mp=Kt[Il.fontStack];if(!mp)continue;const Ch=mp.glyphs[Pl];if(!Ch)continue;if(qc=Ch.metrics,tu=Pl!==8203?Jd:0,Rn){const Bl=mp.ascender!==void 0?Math.abs(mp.ascender):0,Sm=mp.descender!==void 0?Math.abs(mp.descender):0,Nu=(Bl+Sm)*nc;zl-x/2;){if(O--,O<0)return!1;U-=w[O].dist(P),P=w[O]}U+=w[O].dist(w[O+1]),O++;const H=[];let X=0;for(;Uk;)X-=H.shift().angleDelta;if(X>E)return!1;O++,U+=le.dist(he)}return!0}function $Oe(w){let m=0;for(let x=0;xX){const Se=(X-H)/be,Pe=Br(he.x,me.x,Se),Be=Br(he.y,me.y,Se),We=new e2(Pe,Be,0,me.angleTo(he),le);return!O||BOe(w,We,U,O,m)?We:void 0}H+=be}}function W3t(w,m,x,k,E,P,O,U,H){const X=UOe(k,P,O),le=qOe(k,E),he=le*O,me=w[0].x===0||w[0].x===H||w[0].y===0||w[0].y===H;return m-he=0&&ft=0&&bt=0&&me+X<=le){const wt=new e2(ft,bt,0,ot,Se);k&&!BOe(w,wt,P,k,E)||be.push(wt)}}he+=We}return U||be.length||O||(be=VOe(w,he/2,x,k,E,P,O,!0,H)),be}function HOe(w){let m=0,x=0;for(const O of w)m+=O.w*O.h,x=Math.max(x,O.w);w.sort((O,U)=>U.h-O.h);const k=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(m/.95)),x),h:1/0}];let E=0,P=0;for(const O of w)for(let U=k.length-1;U>=0;U--){const H=k[U];if(!(O.w>H.w||O.h>H.h)){if(O.x=H.x,O.y=H.y,P=Math.max(P,O.y+O.h),E=Math.max(E,O.x+O.w),O.w===H.w&&O.h===H.h){const X=k.pop();X&&Um.id?1:w.versionm.version?1:w.sxm.sx?1:w.sym.sy?1:0}function M_e(w){let m=0;for(let x=0;x0,GOe(m,k,this.iconDescriptors,P),GOe(x,k,this.patternDescriptors,P),this.iconDescriptors.sort(Wq),this.patternDescriptors.sort(Wq);let O=0;const U=E?E.data:"";U&&(O=M1(O,M_e(U))),O=M1(O,1);for(const H of this.iconDescriptors)O=M1(O,M_e(H.id)),O=M1(O,H.version),O=M1(O,H.sx),O=M1(O,H.sy);O=M1(O,1);for(const H of this.patternDescriptors)O=M1(O,M_e(H.id)),O=M1(O,H.version),O=M1(O,H.sx),O=M1(O,H.sy);this.hash=O}subsetOf(m){return this.isSubsetArray(this.iconDescriptors,m.iconDescriptors,Wq)&&this.isSubsetArray(this.patternDescriptors,m.patternDescriptors,Wq)}isSubsetArray(m,x,k){let E=0,P=0;if(m.length>x.length)return!1;for(;E{const O=E.variant.id.toString().localeCompare(P.variant.id.toString());return O!==0?O:E.variant.sx!==P.variant.sx?E.variant.sx-P.variant.sx:E.variant.sy!==P.variant.sy?E.variant.sy-P.variant.sy:0});const k=new Map;for(const E of x)k.set(E.key,E.value);return k}class WOe{constructor(m){this.sourceAtlasHash=m}}class KOe{constructor(m,x,k,E){const P=new Map,O=new Map;this.haveRenderCallbacks=[];const U=[],H=E!==void 0,X=H?new Map:void 0,le=H?L_e(m,X):m,he=H?L_e(x,X):x;this.addImages(le,P,1,U),this.addImages(he,O,2,U);const{w:me,h:be}=HOe(U),Se=new Yh({width:me||1,height:be||1});for(const[Pe,Be]of le.entries()){const We=P.get(Pe).paddedRect;Yh.copy(Be.data,Se,{x:0,y:0},{x:We.x+1,y:We.y+1},Be.data,null,Be.sdf)}for(const[Pe,Be]of he.entries()){const We=O.get(Pe),ot=We.paddedRect;let nt=We.padding;const ft=ot.x+nt,bt=ot.y+nt,wt=Be.data.width,Yt=Be.data.height;nt=nt>1?nt-1:nt,Yh.copy(Be.data,Se,{x:0,y:0},{x:ft,y:bt},Be.data,k),Yh.copy(Be.data,Se,{x:0,y:Yt-nt},{x:ft,y:bt-nt},{width:wt,height:nt},k),Yh.copy(Be.data,Se,{x:0,y:0},{x:ft,y:bt+Yt},{width:wt,height:nt},k),Yh.copy(Be.data,Se,{x:wt-nt,y:0},{x:ft-nt,y:bt},{width:nt,height:Yt},k),Yh.copy(Be.data,Se,{x:0,y:0},{x:ft+wt,y:bt},{width:nt,height:Yt},k),Yh.copy(Be.data,Se,{x:wt-nt,y:Yt-nt},{x:ft-nt,y:bt-nt},{width:nt,height:nt},k),Yh.copy(Be.data,Se,{x:0,y:Yt-nt},{x:ft+wt,y:bt-nt},{width:nt,height:nt},k),Yh.copy(Be.data,Se,{x:0,y:0},{x:ft+wt,y:bt+Yt},{width:nt,height:nt},k),Yh.copy(Be.data,Se,{x:wt-nt,y:0},{x:ft-nt,y:bt+Yt},{width:nt,height:nt},k)}this.lut=k,this.image=Se,this.iconPositions=P,this.patternPositions=O,H&&(this.contentDescriptor=new I_e(le,he,E,k,X))}addImages(m,x,k,E){for(const[P,O]of m.entries()){const{bin:U,imagePosition:H,imageVariant:X}=P_e(P,O,k);x.set(P,H),E.push(U),O.hasRenderCallback&&this.haveRenderCallbacks.push(X.id)}}patchUpdatedImages(m,x,k,E){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(P=>m.hasImage(P,k)),m.dispatchRenderCallbacks(this.haveRenderCallbacks,k);for(const P of m.getUpdatedImages(k)){for(const O of this.iconPositions.keys()){const U=rp.parse(O);if(Lt.isEqual(U.id,P)){const H=m.getImage(P,k);this.patchUpdatedImage(this.iconPositions.get(O),H,x,null)}}for(const O of this.patternPositions.keys()){const U=rp.parse(O);if(Lt.isEqual(U.id,P)){const H=m.getImage(P,k);this.patchUpdatedImage(this.patternPositions.get(O),H,x,E||this.lut)}}}}patchUpdatedImage(m,x,k,E=null){if(!m||!x||m.version===x.version)return;m.version=x.version;const[P,O]=m.tl,U=m.sdf;if(this.lut||U){const H={width:x.data.width,height:x.data.height},X=new Yh(H);Yh.copy(x.data,X,{x:0,y:0},{x:0,y:0},H,E,U),k.update(X,{position:{x:P,y:O},recreateWhenResize:!1})}else k.update(x.data,{position:{x:P,y:O},recreateWhenResize:!1})}}Yn(TO,"ImagePosition"),Yn(KOe,"ImageAtlas",{omit:["lut"]}),Yn(WOe,"ImageAtlasReference");class EO{constructor(m){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!m||m.useServerFontComposition===void 0||m.useServerFontComposition}loadGlyphRange(m,x,k,E,P){if(this.useServerFontComposition)return void EO.loadGlyphRange(m,x,k,E,P);const O=m.split(",").map(U=>U.trim()).filter(U=>U.length>0);O.length!==0?O.length!==1?this._loadMultipleFonts(O,x,k,E,P):this._loadFont(O[0],x,k,E,P):P(new Error("Empty fontstack"))}_loadMultipleFonts(m,x,k,E,P){const O=m.map(()=>null),U={completed:0,firstError:null,callbackCalled:!1},H=(X,le,he)=>{if(!U.callbackCalled&&(le&&!U.firstError&&(U.firstError=le),he&&(O[X]=he),U.completed++,U.completed===m.length)){U.callbackCalled=!0;const me=O.filter(Se=>Se!==null);if(me.length===0)return void P(U.firstError||new Error("All fonts failed to load"));const be=this._composeGlyphs(me);P(null,be)}};for(let X=0;X{H(X,le,he)})}_loadFont(m,x,k,E,P){const O=`${m}:${x}`;if(this.cachedRanges.has(O)){const H=this.cachedRanges.get(O);return void Gd.frame(()=>P(null,H))}const U=this.pendingRequests.get(O);U?U.push(P):(this.pendingRequests.set(O,[P]),EO.loadGlyphRange(m,x,k,E,(H,X)=>{H||this.cachedRanges.set(O,X||null);const le=this.pendingRequests.get(O);if(this.pendingRequests.delete(O),le)for(const he of le)he(H,X)}))}_composeGlyphs(m){const x={};let k,E;for(const P of m)if(k===void 0&&P.ascender!==void 0&&(k=P.ascender),E===void 0&&P.descender!==void 0&&(E=P.descender),P.glyphs)for(const O in P.glyphs)x[O]===void 0&&(x[O]=P.glyphs[O]);return{glyphs:x,ascender:k,descender:E}}}EO.loadGlyphRange=function(w,m,x,k,E){const P=256*m,O=P+255,U=k.transformRequest(k.normalizeGlyphsURL(x).replace("{fontstack}",w).replace("{range}",`${P}-${O}`),h0.Glyphs);Dy(U,(H,X)=>{if(H)E(H);else if(X){const le={},he=function(me){return new Vq(me).readFields($3t,{})}(X);for(const me of he.glyphs)le[me.id]=me;E(null,{glyphs:le,ascender:he.ascender,descender:he.descender})}})};const AO=1e20;function YOe(w,m,x,k,E,P,O,U,H){for(let X=m;X-1);H++,P[H]=U,O[H]=X,O[H+1]=AO}for(let U=0,H=0;U{if(O){E.ascender=O.ascender,E.descender=O.descender;for(const U in O.glyphs)this._doesCharSupportLocalGlyph(+U)||(E.glyphs[+U]=O.glyphs[+U]);E.ranges[x]=!0}for(const U of E.requests[x]||[])U(P,O);delete E.requests[x]}))}getGlyphs(m,x){const k=[],E=this.url||da.GLYPHS_URL;for(const P in m)for(const O of m[P])k.push({stack:P,id:O});It(k,({stack:P,id:O},U)=>{let H=this.entries[P];H||(H=this.entries[P]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let X=H.glyphs[O];if(X!==void 0)return void U(null,{stack:P,id:O,glyph:X});if(X=this._tinySDF(H,P,O),X)return H.glyphs[O]=X,void U(null,{stack:P,id:O,glyph:X});const le=Math.floor(O/256);if(256*le>65535)return sr("glyphs > 65535 not supported"),void U(null,{stack:P,id:O,glyph:X});if(H.ranges[le])return void U(null,{stack:P,id:O,glyph:X});let he=H.requests[le];he||(he=H.requests[le]=[],this.glyphLoader.loadGlyphRange(P,le,E,this.requestManager,(me,be)=>{if(be){H.ascender=be.ascender,H.descender=be.descender;for(const Se in be.glyphs)this._doesCharSupportLocalGlyph(+Se)||(H.glyphs[+Se]=be.glyphs[+Se]);H.ranges[le]=!0}for(const Se of he)Se(me,be);delete H.requests[le]})),he.push((me,be)=>{me?U(me):be&&U(null,{stack:P,id:O,glyph:be.glyphs[O]||null})})},(P,O)=>{if(P)x(P);else if(O){const U={};for(const{stack:H,id:X,glyph:le}of O)U[H]===void 0&&(U[H]={}),U[H].glyphs===void 0&&(U[H].glyphs={}),U[H].glyphs[X]=le&&{id:le.id,bitmap:le.bitmap.clone(),metrics:le.metrics},U[H].ascender=this.entries[H].ascender,U[H].descender=this.entries[H].descender;x(null,U)}})}_doesCharSupportLocalGlyph(m){return this.localGlyphMode!==D_e.none&&(this.localGlyphMode===D_e.all?!!this.localFontFamily:!!this.localFontFamily&&(Sx(m)||h_(m)||N1(m)||kx(m)||Ky(m)||Oj(m)||(x=m)>=131072&&x<=173791||(k=>k>=66736&&k<=66815)(m)));var x}_tinySDF(m,x,k){const E=this.localFontFamily;if(!E||!this._doesCharSupportLocalGlyph(k))return;let P=m.tinySDF;if(!P){let Be="400";/bold/i.test(x)?Be="900":/medium/i.test(x)?Be="500":/light/i.test(x)&&(Be="200"),P=m.tinySDF=new Kq.TinySDF({fontFamily:E,fontWeight:Be,fontSize:48,buffer:6,radius:16}),P.fontWeight=Be}const O=P.fontWeight;if(this.localGlyphs[O][k])return this.localGlyphs[O][k];const U=String.fromCodePoint(k),{data:H,width:X,height:le,glyphWidth:he,glyphHeight:me,glyphLeft:be,glyphTop:Se,glyphAdvance:Pe}=P.draw(U);return this.localGlyphs[O][k]={id:k,bitmap:new hk({width:X,height:le},H),metrics:{width:he/2,height:me/2,left:be/2,top:Se/2-27,advance:Pe/2,localGlyph:!0}}}}function QOe(w,m){return w+m[1]-m[0]}function R_e(w,m,x,k,E=1){const P=[],O=w.imagePrimary,U=O.pixelRatio,H=O.paddedRect.w-2,X=O.paddedRect.h-2,le=(w.right-w.left)*E,he=(w.bottom-w.top)*E,me=O.stretchX||[[0,H]],be=O.stretchY||[[0,X]],Se=me.reduce(QOe,0),Pe=be.reduce(QOe,0),Be=H-Se,We=X-Pe;let ot=0,nt=Se,ft=0,bt=Pe,wt=0,Yt=Be,zt=0,Kt=We;if(O.content&&k){const Ht=O.content;ot=Yq(me,0,Ht[0]),ft=Yq(be,0,Ht[1]),nt=Yq(me,Ht[0],Ht[2]),bt=Yq(be,Ht[1],Ht[3]),wt=Ht[0]-ot,zt=Ht[1]-ft,Yt=Ht[2]-Ht[0]-nt,Kt=Ht[3]-Ht[1]-bt}const Vt=(Ht,Os,Vs,Js)=>{const nn=Zq(Ht.stretch-ot,nt,le,w.left*E),en=Qq(Ht.fixed-wt,Yt,Ht.stretch,Se),xn=Zq(Os.stretch-ft,bt,he,w.top*E),Ls=Qq(Os.fixed-zt,Kt,Os.stretch,Pe),tn=Zq(Vs.stretch-ot,nt,le,w.left*E),on=Qq(Vs.fixed-wt,Yt,Vs.stretch,Se),gn=Zq(Js.stretch-ft,bt,he,w.top*E),En=Qq(Js.fixed-zt,Kt,Js.stretch,Pe),ir=new Ms(nn,xn),On=new Ms(tn,xn),Rn=new Ms(tn,gn),An=new Ms(nn,gn),nr=new Ms(en/U,Ls/U),pr=new Ms(on/U,En/U),Gr=m*Math.PI/180;if(Gr){const Za=Math.sin(Gr),zl=Math.cos(Gr),Ji=[zl,-Za,Za,zl];ir._matMult(Ji),On._matMult(Ji),An._matMult(Ji),Rn._matMult(Ji)}const Sr=Ht.stretch+Ht.fixed,Ma=Vs.stretch+Vs.fixed,ki=Os.stretch+Os.fixed,Ia=Js.stretch+Js.fixed,Ei=w.imageSecondary;return{tl:ir,tr:On,bl:An,br:Rn,texPrimary:{x:O.paddedRect.x+1+Sr,y:O.paddedRect.y+1+ki,w:Ma-Sr,h:Ia-ki},texSecondary:Ei?{x:Ei.paddedRect.x+1+Sr,y:Ei.paddedRect.y+1+ki,w:Ma-Sr,h:Ia-ki}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:nr,pixelOffsetBR:pr,minFontScaleX:Yt/U/le,minFontScaleY:Kt/U/he,isSDF:x}};if(O.stretchX||O.stretchY){const Ht=XOe(me,Be,Se),Os=XOe(be,We,Pe);for(let Vs=0;Vs0?[ot,-nt]:ft<0?[-ot,nt]:ot===0?[nt,ot]:[nt,-ot]}(x);let be=Math.abs(m.top-m.bottom);for(const We of m.positionedLines)be-=We.lineOffset;const Se=m.positionedLines.length,Pe=be/Se;let Be=m.top-x[1];for(let We=0;WeP)&&(P=Se.x),(!be||Se.y>O)&&(O=Se.y)}const H=Math.min(P-k,O-E);let X=H/2;const le=new f0([],Q3t);if(H===0)return new Ms(k,E);for(let be=k;behe.d||!he.d)&&(he=be,x&&console.log("found best %d after %d probes",Math.round(1e4*be.d)/1e4,me)),be.max-he.d<=m||(X=be.h/2,le.push(new Q6(be.p.x-X,be.p.y-X,X,w)),le.push(new Q6(be.p.x+X,be.p.y-X,X,w)),le.push(new Q6(be.p.x-X,be.p.y+X,X,w)),le.push(new Q6(be.p.x+X,be.p.y+X,X,w)),me+=4)}return x&&(console.log(`num probes: ${me}`),console.log(`best distance: ${he.d}`)),he.p}function Q3t(w,m){return m.max-w.max}Kq.TinySDF=class{constructor({fontSize:w=24,buffer:m=3,radius:x=8,cutoff:k=.25,fontFamily:E="sans-serif",fontWeight:P="normal",fontStyle:O="normal",lang:U=null}={}){this.buffer=m,this.cutoff=k,this.radius=x,this.lang=U;const H=this.size=w+4*m,X=this._createCanvas(H),le=this.ctx=X.getContext("2d",{willReadFrequently:!0});le.font=`${O} ${P} ${w}px ${E}`,le.textBaseline="alphabetic",le.textAlign="left",le.fillStyle="black",this.gridOuter=new Float64Array(H*H),this.gridInner=new Float64Array(H*H),this.f=new Float64Array(H),this.z=new Float64Array(H+1),this.v=new Uint16Array(H)}_createCanvas(w){const m=document.createElement("canvas");return m.width=m.height=w,m}draw(w){const{width:m,actualBoundingBoxAscent:x,actualBoundingBoxDescent:k,actualBoundingBoxLeft:E,actualBoundingBoxRight:P}=this.ctx.measureText(w),O=Math.ceil(x),U=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(P-E))),H=Math.min(this.size-this.buffer,O+Math.ceil(k)),X=U+2*this.buffer,le=H+2*this.buffer,he=Math.max(X*le,0),me=new Uint8ClampedArray(he),be={data:me,width:X,height:le,glyphWidth:U,glyphHeight:H,glyphTop:O,glyphLeft:0,glyphAdvance:m};if(U===0||H===0)return be;const{ctx:Se,buffer:Pe,gridInner:Be,gridOuter:We}=this;this.lang&&(Se.lang=this.lang),Se.clearRect(Pe,Pe,U,H),Se.fillText(w,Pe,Pe+O);const ot=Se.getImageData(Pe,Pe,U,H);We.fill(AO,0,he),Be.fill(0,0,he);for(let nt=0;nt0?Yt*Yt:0,Be[wt]=Yt<0?Yt*Yt:0}}YOe(We,0,0,X,le,X,this.f,this.v,this.z),YOe(Be,Pe,Pe,U,H,X,this.f,this.v,this.z);for(let nt=0;ntP.y!=Pe.y>P.y&&P.x<(Pe.x-Se.x)*(P.y-Se.y)/(Pe.y-Se.y)+Se.x&&(U=!U),H=Math.min(H,Jy(P,Se,Pe))}}return(U?1:-1)*Math.sqrt(H)}(this.p,E),this.max=this.d+this.h*Math.SQRT2}}const X3t=Object.keys,O_e=Number.POSITIVE_INFINITY,J3t=Math.sqrt(2);function xk(w,m,x,k,E,P){const O=T_e(w)&&w.collisionPadding?w.collisionPadding:[0,0,0,0],U={top:w.top-O[1],bottom:w.bottom+O[3],left:w.left-O[0],right:w.right+O[2],scaled:!1};return k!==void 0&&function(H,X){H.top*=X,H.bottom*=X,H.left*=X,H.right*=X,H.scaled=!0}(U,k),P&&(U.left+=P[0],U.right+=P[0],U.top+=P[1],U.bottom+=P[1]),x&&function(H,X,le){if(!X)return;const he=lr(X),me=new Ms(le?le[0]:0,le?le[1]:0),be=new Ms(H.left,H.top),Se=new Ms(H.right,H.top),Pe=new Ms(H.left,H.bottom),Be=new Ms(H.right,H.bottom);be._rotateAround(he,me),Se._rotateAround(he,me),Pe._rotateAround(he,me),Be._rotateAround(he,me),H.left=Math.min(be.x,Se.x,Pe.x,Be.x),H.right=Math.max(be.x,Se.x,Pe.x,Be.x),H.top=Math.min(be.y,Se.y,Pe.y,Be.y),H.bottom=Math.max(be.y,Se.y,Pe.y,Be.y)}(U,x,E),m?{top:Math.min(m.top,U.top),bottom:Math.max(m.bottom,U.bottom),left:Math.min(m.left,U.left),right:Math.max(m.right,U.right),scaled:m.scaled||U.scaled}:U}function tFe(w,[m,x]){let k=0,E=0;if(x===O_e){m<0&&(m=0);const P=m/J3t;switch(w){case"top-right":case"top-left":E=P-7;break;case"bottom-right":case"bottom-left":E=7-P;break;case"bottom":E=7-m;break;case"top":E=m-7}switch(w){case"top-right":case"bottom-right":k=-P;break;case"top-left":case"bottom-left":k=P;break;case"left":k=m;break;case"right":k=-m}}else{switch(m=Math.abs(m),x=Math.abs(x),w){case"top-right":case"top-left":case"top":E=x-7;break;case"bottom-right":case"bottom-left":case"bottom":E=7-x}switch(w){case"top-right":case"bottom-right":case"right":k=-m;break;case"top-left":case"bottom-left":case"left":k=m}}return[k,E]}function e5t(w,m,x,k,E,P,O,U,H,X,le,he,me,be,Se){const Pe=w.layers[0],Be=Pe.appearances;if(Be.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const We={iconBBox:null,iconVerticalBBox:null},ot={textBBox:null,textVerticalBBox:null},{baseIconRotate:nt,baseTextRotate:ft,iconScaleFactor:bt}=function(Yt,zt,Kt){const Vt=Yt.get("icon-rotate").evaluate(zt,{},Kt),Ht=Yt.get("text-rotate").evaluate(zt,{},Kt),[Os,Vs]=Yt.get("icon-size-scale-range");return{baseIconRotate:Vt,baseTextRotate:Ht,iconScaleFactor:Qe(1,Os,Vs)}}(k,E,P);m&&(We.iconBBox=xk(m,We.iconBBox,nt),x)&&(We.iconVerticalBBox=xk(x,We.iconVerticalBBox,nt+90));const wt=Jq(he.horizontal);wt&&(ot.textBBox=xk(wt,ot.textBBox,ft,1,be)),he.vertical&&(ot.textVerticalBBox=xk(he.vertical,ot.textVerticalBBox,ft+90,1,be));for(const Yt of Be)Yt.hasIconLayoutProperties()&&t5t(We,w,Pe,Yt,E,P,U,nt,O,H,m,X,bt,le,Se),Yt.hasTextLayoutProperties()&&s5t(ot,Pe,Yt,E,P,be,ft,me,wt,he.vertical);return{iconBBox:We.iconBBox,iconVerticalBBox:We.iconVerticalBBox,textBBox:ot.textBBox,textVerticalBBox:ot.textVerticalBBox}}function t5t(w,m,x,k,E,P,O,U,H,X,le,he,me,be,Se){const{appearanceIconOffset:Pe,appearanceIconRotate:Be,appearanceIconSize:We}=sFe(k,x,E,P,O,U,H,X.iconScaleFactor);let ot=null,nt=null,ft=null;k.hasLayoutProperty("icon-image")?ft=function(wt,Yt,zt,Kt,Vt,Ht,Os,Vs){let Js=null;const nn=Yt.getAppearanceValueAndResolveTokens(zt,"icon-image",Kt,Vt,Vs);if(nn){const en=wt.getResolvedImageFromTokens(nn),xn=zt.hasLayoutProperty("icon-size")?zt.getUnevaluatedLayoutProperty("icon-size"):Yt._unevaluatedLayout._values["icon-size"],Ls=MO(en,s3(wt.zoom,xn,wt.worldview,Vs),xn,Vt,wt.zoom,Kt,wt.pixelRatio,Os,wt.worldview,Vs);Js=Ht.get(Ls.iconPrimary.toString())}return Js}(m,x,k,E,P,he,me,Se):le&&(ft=le.imagePrimary),ft&&(ot=Gq(ft,null,Pe,be),m.allowVerticalPlacement&&(nt=Gq(ft,null,Pe,be)));const bt=H>0?We/H:1;ot&&(w.iconBBox=xk(ot,w.iconBBox,Be,bt!==1?bt:void 0)),nt&&(w.iconVerticalBBox=xk(nt,w.iconVerticalBBox,Be+90,bt!==1?bt:void 0))}function sFe(w,m,x,k,E,P,O,U){const H=w.hasLayoutProperty("icon-offset")?m.getAppearanceValueAndResolveTokens(w,"icon-offset",x,k,[]):null,X=H&&Array.isArray(H)?H:E,le=w.hasLayoutProperty("icon-rotate")?m.getAppearanceValueAndResolveTokens(w,"icon-rotate",x,k,[]):null,he=typeof le=="number"?le:P,me=w.hasLayoutProperty("icon-size")?m.getAppearanceValueAndResolveTokens(w,"icon-size",x,k,[]):null;return{appearanceIconOffset:X,appearanceIconRotate:he,appearanceIconSize:typeof me=="number"?me*U:O}}function s5t(w,m,x,k,E,P,O,U,H,X){const{appearanceTextOffset:le,appearanceTextRotate:he,appearanceTextSize:me}=nFe(x,m,k,E,P,O,U),be=me/U,Se=[(le[0]-P[0])*be,(le[1]-P[1])*be],Pe=Se[0]!==0||Se[1]!==0;H&&(w.textBBox=xk(H,w.textBBox,he,be,le,Pe?Se:void 0)),X&&(w.textVerticalBBox=xk(X,w.textVerticalBBox,he+90,be,le,Pe?Se:void 0))}function nFe(w,m,x,k,E,P,O){const U=w.hasLayoutProperty("text-offset")?m.getAppearanceValueAndResolveTokens(w,"text-offset",x,k,[]):null,H=U&&Array.isArray(U)?[U[0]*Jd,U[1]*Jd]:E,X=w.hasLayoutProperty("text-rotate")?m.getAppearanceValueAndResolveTokens(w,"text-rotate",x,k,[]):null,le=typeof X=="number"?X:P,he=w.hasLayoutProperty("text-size")?m.getAppearanceValueAndResolveTokens(w,"text-size",x,k,[]):null;return{appearanceTextOffset:H,appearanceTextRotate:le,appearanceTextSize:typeof he=="number"?he:O}}function Xq(w,m,x,k,E,P,O,U,H){if(!m||!m.usvg)return;const X=zOe(k),le=zOe(E),he=P!=="both"&&P!=="width"||!OOe(k)?1:le.width/X.width,me=P!=="both"&&P!=="height"||!FOe(k)?1:le.height/X.height;x.scaleSelf(he,me);const be=x.toString();O.set(be,x),U.set(be,m);const{imagePosition:Se}=P_e(be,m,1);H.set(be,Se)}function rFe(w,m,x,k,E,P,O,U,H,X){if(!w)return;const le=function(he,me,be,Se,Pe,Be,We){if(he.kind==="camera")return he.maxSize;if(he.kind==="composite"){const ot=me.possiblyEvaluate(new Ra(he.maxZoom,{worldview:Be}),be,We).evaluate(Pe,{},be,We),nt=me.possiblyEvaluate(new Ra(he.minZoom,{worldview:Be}),be,We).evaluate(Pe,{},be,We);return Math.max(ot,nt)}return me.possiblyEvaluate(new Ra(Se,{worldview:Be}),be,We).evaluate(Pe,{},be,We)}(m,x,k,E,P,H,X);return w.scaleSelf(le*U*O)}function MO(w,m,x,k,E,P,O,U,H,X){return{iconPrimary:rFe(w.getPrimary(),m,x,k,E,P,O,U,H,X),iconSecondary:rFe(w.getSecondary(),m,x,k,E,P,O,U,H,X)}}function n5t(w,m,x){if(!m)return;const k=x.get(w.toString()),E=x.get(m.toString());k&&E&&(k.paddedRect.w===E.paddedRect.w&&k.paddedRect.h===E.paddedRect.h||sr(`Mismatch in icon variant sizes: ${w.toString()} and ${m.toString()}`),k.usvg!==E.usvg&&sr(`Mismatch in icon variant image types: ${w.id} and ${m.id}`))}function aFe(w,m,x,k){if(!w)return;const E=m.get(x.toString());if(E&&(w.imagePrimary=E),k){const P=m.get(k.toString());w.imageSecondary=P}}function r5t(w,m){for(const x in w.horizontal)iFe(w.horizontal[x],m);iFe(w.vertical,m)}function iFe(w,m){if(w){for(const x of w.positionedLines)for(const k of x.positionedGlyphs)if(k.image!==null){const E=k.image.toString();k.rect=m.get(E).paddedRect}}}function F_e(w){switch(w){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function a5t(w,m,x,k,E,P,O,U,H){const X=Jq(P.horizontal)||P.vertical,le=x.get("icon-text-fit-padding").evaluate(k,{},E);let he,me=m;return m&&H!=="none"&&(w.allowVerticalPlacement&&P.vertical&&(he=E_e(m,P.vertical,H,le,U,O)),X&&(me=E_e(m,X,H,le,U,O))),{defaultShapedIcon:me,verticallyShapedIcon:he}}function oFe(w,m){return w*m/24}function i5t(w,m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be,We,ot,nt,ft,bt,wt,Yt){let zt=O.textMaxSize.evaluate(m,{},me);zt===void 0?zt=U*O.textScaleFactor:zt*=O.textScaleFactor;const Kt=w.layers[0].layout,Vt=oFe(U,O.textScaleFactor),Ht=Jq(x.horizontal)||x.vertical,Os=w.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),Vs=w.getAppearanceFeatureData(m.index);(Be!=="none"||Os)&&Vs&&(Vs.textShaping=Ht,Vs.iconTextFitPadding=Kt.get("icon-text-fit-padding").evaluate(m,{},me),Vs.fontScale=Vt,Vs.textScaleFactor=O.textScaleFactor);const Js=be.name==="globe",nn=w.tilePixelRatio*zt/24,en=(En=w.overscaling,w.zoom>18&&En>2&&(En>>=1),Math.max(Bn/(512*En),1)*Kt.get("symbol-spacing")),xn=Kt.get("text-padding")*w.tilePixelRatio,Ls=Kt.get("icon-padding")*w.tilePixelRatio,tn=lr(Kt.get("text-max-angle")),on=Kt.get("icon-rotation-alignment")==="map"&&nt!=="point",gn=en/2;var En;w.hasAnyIconTextFit===!1&&Be!=="none"&&(w.hasAnyIconTextFit=!0);const ir=m.properties?+m.properties[$a]:null,On=ir&&w.elevationFeatureIdToIndex?w.elevationFeatureIdToIndex.get(ir):65535,Rn=(An,nr,pr)=>{if(nr.x<0||nr.x>=Bn||nr.y<0||nr.y>=Bn)return;let Gr=null;if(Js){const{x:Sr,y:Ma,z:ki}=be.projectTilePoint(nr.x,nr.y,pr);Gr={anchor:new e2(Sr,Ma,ki,0,void 0),up:be.upVector(pr,nr.x,nr.y)}}(function(Sr,Ma,ki,Ia,Ei,Za,zl,Ji,Fi,Ro,Il,eu,Pl,nc,qc,rc,Sh,tu,ei,hp,pc,ju,mp,Ch,Bl,Sm,Nu,gV,aI,Zp,lwe,iI){const t2=Sr.addToLineVertexArray(Ma,Ia);let s2,T0,E0,l3,oI,ii,ku,ac=0,Md=0,A0=0,Px=0,Lx=-1,Dx=-1;const sv={};let yV=Td("");const D1=ki?ki.anchor:Ma,lI=gV!=="none";let cI=0,md=0;if(Fi._unevaluatedLayout.getValue("text-radial-offset")===void 0){const fc=Fi.layout.get("text-offset").evaluate(pc,{},Bl);cI=fc[0]*Jd,md=fc[1]*Jd}else cI=Fi.layout.get("text-radial-offset").evaluate(pc,{},Bl)*Jd,md=O_e;if(Sr.allowVerticalPlacement&&Ei.vertical){const fc=Ei.vertical;if(qc)ii=$_e(fc),Ji&&(ku=$_e(Ji));else{const pp=Fi.layout.get("text-rotate").evaluate(pc,{},Bl)+90;E0=eV(Ro,D1,Ma,Il,eu,Pl,fc,nc,pp,rc,iI),Ji&&(l3=eV(Ro,D1,Ma,Il,eu,Pl,Ji,tu,pp,null,lwe))}}if(Za){const fc=Fi.layout.get("icon-rotate").evaluate(pc,{},Bl),pp=R_e(Za,fc,mp,lI,ju.iconScaleFactor),Qp=Ji?R_e(Ji,fc,mp,lI,ju.iconScaleFactor):void 0;T0=eV(Ro,D1,Ma,Il,eu,Pl,Za,tu,fc,null,Zp);const rv=function(R1,GO,dI,_Tt,wTt,T7e,E7e,jTt,bxn,dwe){const A7e=R1.layers[0],M7e=A7e.appearances;let uI=GO.length;if(dI&&(uI=Math.max(uI,dI.length)),M7e.length===0)return uI;const[NTt,kTt]=_Tt.get("icon-size-scale-range"),STt=Qe(1,NTt,kTt);for(const wV of M7e)if(wV.hasLayoutProperty("icon-image")){const I7e=A7e.getAppearanceValueAndResolveTokens(wV,"icon-image",T7e,E7e,dwe);if(I7e){const P7e=R1.getResolvedImageFromTokens(I7e);if(P7e){const L7e=wV.hasLayoutProperty("icon-size")?wV.getUnevaluatedLayoutProperty("icon-size"):wTt._values["icon-size"],CTt=MO(P7e,s3(R1.zoom,L7e,R1.worldview,dwe),L7e,E7e,R1.zoom,T7e,R1.pixelRatio,STt,R1.worldview,dwe),D7e=jTt.get(CTt.iconPrimary.toString());D7e&&(uI=Math.max(uI,K3t(D7e)))}}}return uI}(Sr,pp,Qp,Fi.layout,Fi._unevaluatedLayout,pc,Bl,Sr.iconAtlasPositions,0,Ch);ac=4*rv;const vV=Fi.layout.get("icon-size").evaluate(pc,{},Bl,Ch),bV=ju.compositeIconSizes?ju.compositeIconSizes[0].evaluate(pc,{},Bl,Ch):0,cwe=ju.compositeIconSizes?ju.compositeIconSizes[1].evaluate(pc,{},Bl,Ch):0,_V=B_e(Sr.layerIds[0],Sr.iconSizeData,vV,ju.iconScaleFactor,bV,cwe);Sr.addSymbols(Sr.icon,pp,_V,hp,ei,pc,void 0,ki,Ma,t2.lineStartIndex,t2.lineLength,-1,Ch,Bl,Sm,Nu,Sr.symbolInstances.length,rv),Lx=Sr.icon.placedSymbolArray.length-1,Qp&&(Md=4*rv,Sr.addSymbols(Sr.icon,Qp,_V,hp,ei,pc,Ix.vertical,ki,Ma,t2.lineStartIndex,t2.lineLength,-1,Ch,Bl,Sm,Nu,Sr.symbolInstances.length,rv),Dx=Sr.icon.placedSymbolArray.length-1)}for(const fc in Ei.horizontal){const pp=fc,Qp=Ei.horizontal[pp];s2||(yV=Td(Qp.text),qc?oI=$_e(Qp):s2=eV(Ro,D1,Ma,Il,eu,Pl,Qp,nc,Fi.layout.get("text-rotate").evaluate(pc,{},Bl),rc,iI));const rv=Qp.positionedLines.length===1;if(A0+=lFe(Sr,ki,Ma,Qp,zl,Fi,qc,pc,rc,t2,Ei.vertical?Ix.horizontal:Ix.horizontalOnly,rv?X3t(Ei.horizontal):[pp],sv,Lx,ju,Ch,Bl,Sr.symbolInstances.length,Sm),rv)break}Ei.vertical&&(Px+=lFe(Sr,ki,Ma,Ei.vertical,zl,Fi,qc,pc,rc,t2,Ix.vertical,["vertical"],sv,Dx,ju,Ch,Bl,Sr.symbolInstances.length,Sm));let Jc=-1;const Id=(fc,pp)=>fc?Math.max(fc,pp):pp;Jc=Id(oI,Jc),Jc=Id(ii,Jc),Jc=Id(ku,Jc);const nv=Jc>-1?1:0;Sr.glyphOffsetArray.length>=65535&&sr("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),pc.sortKey!==void 0&&Sr.addToSortKeyRanges(Sr.symbolInstances.length,pc.sortKey),Sr.symbolInstances.emplaceBack(Ma.x,Ma.y,D1.x,D1.y,D1.z,sv.right>=0?sv.right:-1,sv.center>=0?sv.center:-1,sv.left>=0?sv.left:-1,sv.vertical>=0?sv.vertical:-1,Lx,Dx,yV,s2!==void 0?s2:Sr.collisionBoxArray.length,s2!==void 0?s2+1:Sr.collisionBoxArray.length,E0!==void 0?E0:Sr.collisionBoxArray.length,E0!==void 0?E0+1:Sr.collisionBoxArray.length,T0!==void 0?T0:Sr.collisionBoxArray.length,T0!==void 0?T0+1:Sr.collisionBoxArray.length,l3||Sr.collisionBoxArray.length,l3?l3+1:Sr.collisionBoxArray.length,Il,A0,Px,ac,Md,nv,0,cI,md,Jc,0,lI?1:0,aI)})(w,nr,Gr,An,x,k,P,E,w.layers[0],w.collisionBoxArray,m.index,m.sourceLayerIndex,w.index,xn,ot,X,0,Ls,on,We,m,O,le,he,me,Se,Pe,Be,On,ft,bt,wt)};if(nt==="line")for(const An of Pq(m.geometry,0,0,Bn,Bn)){const nr=W3t(An,en,tn,x.vertical||Ht,k,24,nn,w.overscaling,Bn);for(const pr of nr)Ht&&o5t(w,Ht.text,gn,pr)||Rn(An,pr,me)}else if(nt==="line-center"){for(const An of m.geometry)if(An.length>1){const nr=G3t(An,tn,x.vertical||Ht,k,24,nn);nr&&Rn(An,nr,me)}}else if(m.type==="Polygon")for(const An of mO(m.geometry,0)){const nr=Z3t(An,16);Rn(An[0],new e2(nr.x,nr.y,0,0,void 0),me)}else if(m.type==="LineString")for(const An of m.geometry)Rn(An,new e2(An[0].x,An[0].y,0,0,void 0),me);else if(m.type==="Point")for(const An of m.geometry)for(const nr of An)Rn([nr],new e2(nr.x,nr.y,0,0,void 0),me)}const z_e=255,n3=z_e*Jj;function lFe(w,m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be,We,ot){const nt=eFe(0,k,H,P,O,U,E,w.allowVerticalPlacement,void 0,Se.textScaleFactor),ft=P.layout.get("text-size").evaluate(U,{},Be),bt=Se.compositeTextSizes?Se.compositeTextSizes[0].evaluate(U,{},Be):0,wt=Se.compositeTextSizes?Se.compositeTextSizes[1].evaluate(U,{},Be):0,Yt=B_e(w.layerIds[0],w.textSizeData,ft,Se.textScaleFactor,bt,wt);w.addSymbols(w.text,nt,Yt,H,O,U,le,m,x,X.lineStartIndex,X.lineLength,be,Pe,Be,ot,!1,We,nt.length);for(const zt of he)me[zt]=w.text.placedSymbolArray.length-1;return 4*nt.length}function B_e(w,m,x,k,E,P){const O=m;let U=null;return O.kind==="source"?(U=[Jj*x*k],U[0]>n3&&sr(`${w}: Value for "text-size" is >= ${z_e}. Reduce your "text-size".`)):O.kind==="composite"&&(U=[Jj*E*k,Jj*P*k],(U[0]>n3||U[1]>n3)&&sr(`${w}: Value for "text-size" is >= ${z_e}. Reduce your "text-size".`)),U}function Jq(w){for(const m in w)return w[m];return null}function eV(w,m,x,k,E,P,O,U,H,X,le){let he,me,be,Se;if(he=le?le.top:O.top,me=le?le.bottom:O.bottom,be=le?le.left:O.left,Se=le?le.right:O.right,T_e(O)&&O.collisionPadding){const Pe=O.collisionPadding;be-=Pe[0],he-=Pe[1],Se+=Pe[2],me+=Pe[3]}if(H){const Pe=new Ms(be,he),Be=new Ms(Se,he),We=new Ms(be,me),ot=new Ms(Se,me),nt=lr(H);let ft=new Ms(0,0);X&&(ft=new Ms(X[0],X[1])),Pe._rotateAround(nt,ft),Be._rotateAround(nt,ft),We._rotateAround(nt,ft),ot._rotateAround(nt,ft),be=Math.min(Pe.x,Be.x,We.x,ot.x),Se=Math.max(Pe.x,Be.x,We.x,ot.x),he=Math.min(Pe.y,Be.y,We.y,ot.y),me=Math.max(Pe.y,Be.y,We.y,ot.y)}return w.emplaceBack(m.x,m.y,m.z,x.x,x.y,be,he,Se,me,U,k,E,P),w.length-1}function $_e(w){T_e(w)&&w.collisionPadding&&(w.top-=w.collisionPadding[1],w.bottom+=w.collisionPadding[3]);const m=w.bottom-w.top;return m>0?Math.max(10,m):null}function o5t(w,m,x,k){const E=w.compareText;if(m in E){const P=E[m];for(let O=P.length-1;O>=0;O--)if(k.dist(P[O])nt&&(ft(wt,Js,zt,Kt,Os,Vs),ft(Js,Yt,Os,Vs,Vt,Ht))}ft(he,me,k,P,E,P),ft(me,be,E,P,E,O),ft(be,Se,E,O,k,O),ft(Se,he,k,O,k,P),Pe-=nt,Be-=nt,We+=nt,ot+=nt;const bt=1/Math.max(We-Pe,ot-Be);return{scale:bt,x:Pe*bt,y:Be*bt,x2:We*bt,y2:ot*bt,projection:m}}function dFe(w,{x:m,y:x},k=0){return new Ms(((m-k)*w.scale-w.x)*Bn,(x*w.scale-w.y)*Bn)}const l5t=v(new Float32Array(16));class gk{constructor(m){this.spec=m,this.name=m.name,this.wrap=!1,this.requiresDraping=!1,this.supportsWorldCopies=!1,this.supportsTerrain=!1,this.supportsFog=!1,this.supportsFreeCamera=!1,this.zAxisUnit="meters",this.isReprojectedInTileSpace=!0,this.unsupportedLayers=["custom"],this.center=[0,0],this.range=[3.5,7]}project(m,x){return{x:0,y:0,z:0}}unproject(m,x){return new rs(0,0)}projectTilePoint(m,x,k){return{x:m,y:x,z:0}}locationPoint(m,x,k,E=!0){return m._coordinatePoint(m.locationCoordinate(x,k),E)}pixelsPerMeter(m,x){return js(1,m)*x}pixelSpaceConversion(m,x,k){return 1}farthestPixelDistance(m){return cFe(m,m.pixelsPerMeter)}pointCoordinate(m,x,k,E){const P=m.horizonLineFromTop(!1),O=new Ms(x,Math.max(P,k));return m.rayIntersectionCoordinate(m.pointRayIntersection(O,E))}pointCoordinate3D(m,x,k){const E=new Ms(x,k);if(m.elevation)return m.elevation.pointCoordinate(E);{const P=this.pointCoordinate(m,E.x,E.y,0);return[P.x,P.y,P.z]}}isPointAboveHorizon(m,x){if(m.elevation&&m.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(m,x.x,x.y);const k=m.horizonLineFromTop();return x.y0?x<-X6+k&&(x=-X6+k):x>X6-k&&(x=X6-k);const O=P/Math.pow(sV(x),E);let U=O*Math.sin(E*m),H=P-O*Math.cos(E*m);return U=.5*(U/Math.PI+.5),H=.5*(H/Math.PI+.5),{x:U,y:this.southernCenter?H:1-H,z:0}}unproject(m,x){m=(2*m-.5)*Math.PI,this.southernCenter&&(x=1-x),x=(2*(1-x)-.5)*Math.PI;const{n:k,f:E}=this,P=E-x,O=Math.sign(P),U=Math.sign(k)*Math.sqrt(m*m+P*P);let H=Math.atan2(m,Math.abs(P))*O;P*k<0&&(H-=Math.PI*Math.sign(m)*O);const X=Qe(Fs(H/k)+this.center[0],-180,180),le=Qe(Fs(2*Math.atan(Math.pow(E/U,1/k))-X6),-85.051129,Qs);return new rs(X,this.southernCenter?-le:le)}}class uFe extends gk{constructor(m){super(m),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(m,x){return{x:an(m),y:mn(x),z:0}}unproject(m,x){const k=ms(m),E=Rs(x);return new rs(k,E)}}const hFe=lr(Qs);class m5t extends gk{project(m,x){const k=(x=lr(x))*x,E=k*k;return{x:.5*((m=lr(m))*(.8707-.131979*k+E*(E*(.003971*k-.001529*E)-.013791))/Math.PI+.5),y:1-.5*(x*(1.007226+k*(.015085+E*(.028874*k-.044475-.005916*E)))/Math.PI+1),z:0}}unproject(m,x){m=(2*m-.5)*Math.PI;let k=x=(2*(1-x)-1)*Math.PI,E=25,P=0,O=k*k;do{O=k*k;const X=O*O;P=(k*(1.007226+O*(.015085+X*(.028874*O-.044475-.005916*X)))-x)/(1.007226+O*(.045255+X*(.259866*O-.311325-.005916*11*X))),k=Qe(k-P,-hFe,hFe)}while(Math.abs(P)>1e-6&&--E>0);O=k*k;const U=Qe(Fs(m/(.8707+O*(O*(O*O*O*(.003971-.001529*O)-.013791)-.131979))),-180,180),H=Fs(k);return new rs(U,H)}}const mFe=lr(Qs);class p5t extends gk{project(m,x){x=lr(x),m=lr(m);const k=Math.cos(x),E=2/Math.PI,P=Math.acos(k*Math.cos(m/2)),O=Math.sin(P)/P,U=.5*(m*E+2*k*Math.sin(m/2)/O)||0,H=.5*(x+Math.sin(x)/O)||0;return{x:.5*(U/Math.PI+.5),y:1-.5*(H/Math.PI+1),z:0}}unproject(m,x){let k=m=(2*m-.5)*Math.PI,E=x=(2*(1-x)-1)*Math.PI,P=25;const O=1e-6;let U=0,H=0;do{const X=Math.cos(E),le=Math.sin(E),he=2*le*X,me=le*le,be=X*X,Se=Math.cos(k/2),Pe=Math.sin(k/2),Be=2*Se*Pe,We=Pe*Pe,ot=1-be*Se*Se,nt=ot?1/ot:0,ft=ot?Math.acos(X*Se)*Math.sqrt(1/ot):0,bt=.5*(2*ft*X*Pe+2*k/Math.PI)-m,wt=.5*(ft*le+E)-x,Yt=.5*nt*(be*We+ft*X*Se*me)+1/Math.PI,zt=nt*(Be*he/4-ft*le*Pe),Kt=.125*nt*(he*Pe-ft*le*be*Be),Vt=.5*nt*(me*Se+ft*We*X)+.5,Ht=zt*Kt-Vt*Yt;U=(wt*zt-bt*Vt)/Ht,H=(bt*Kt-wt*Yt)/Ht,k=Qe(k-U,-Math.PI,Math.PI),E=Qe(E-H,-mFe,mFe)}while((Math.abs(U)>O||Math.abs(H)>O)&&--P>0);return new rs(Fs(k),Fs(E))}}class pFe extends gk{constructor(m){super(m),this.center=m.center||[0,0],this.parallels=m.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(lr(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(m,x){const{scale:k,cosPhi:E}=this;return{x:lr(m)*E*k+.5,y:-Math.sin(lr(x))/E*k+.5,z:0}}unproject(m,x){const{scale:k,cosPhi:E}=this,P=-(x-.5)/k,O=Qe(Fs((m-.5)/k)/E,-180,180),U=Math.asin(Qe(P*E,-1,1)),H=Qe(Fs(U),-85.051129,Qs);return new rs(O,H)}}class f5t extends uFe{constructor(m){super(m),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(m,x,k){const E=iO(m,x,k);return Je(E,E,oO(__(k))),{x:E[0],y:E[1],z:E[2]}}locationPoint(m,x,k){const E=Rt(x.lat,x.lng),P=Ie([],E),O=k?m._centerAltitude+k:m.elevation?m.elevation.getAtPointOrZero(m.locationCoordinate(x),m._centerAltitude):m._centerAltitude;Me(E,E,P,js(1,0)*Bn*O);const U=v(new Float64Array(16));return _(U,m.pixelMatrix,m.globeMatrix),Je(E,E,U),new Ms(E[0],E[1])}pixelsPerMeter(m,x){return js(1,0)*x}pixelSpaceConversion(m,x,k){const E=js(1,m)*x,P=Br(js(1,45)*x,E,k);return this.pixelsPerMeter(m,x)/P}createTileMatrix(m,x,k){const E=Dbe(__(k.canonical));return _(new Float64Array(16),m.globeMatrix,E)}createInversionMatrix(m,x){const{center:k}=m,E=oO(__(x));return D(E,E,lr(k.lng)),T(E,E,lr(k.lat)),A(E,E,[m._pixelsPerMercatorPixel,m._pixelsPerMercatorPixel,1]),Float32Array.from(E)}pointCoordinate(m,x,k,E){return ADe(m,x,k,!0)||new mr(0,0)}pointCoordinate3D(m,x,k){const E=this.pointCoordinate(m,x,k,0);return[E.x,E.y,E.z]}isPointAboveHorizon(m,x){return!ADe(m,x.x,x.y,!1)}farthestPixelDistance(m){const x=function(E,P){const O=E.cameraToCenterDistance,U=E._centerAltitude*P,H=E._camera,X=E._camera.forward(),le=pe([],_e([],X,-O),[0,0,U]),he=E.worldSize/(2*Math.PI),me=[0,0,-he],be=E.width/E.height,Se=Math.tan(E.fovAboveCenter),Pe=_e([],H.up(),Se),Be=_e([],H.right(),Se*be),We=Ie([],pe([],pe([],X,Pe),Be)),ot=[];let nt;if(new li(le,We).closestPointOnSphere(me,he,ot)){const ft=pe([],ot,me),bt=$e([],ft,le);nt=Math.cos(E.fovAboveCenter)*ee(bt)}else{const ft=$e([],le,me),bt=$e([],me,le);Ie(bt,bt);const wt=ee(ft)-he;nt=Math.sqrt(wt*(wt+2*he));const Yt=Math.acos(nt/(he+wt))-Math.acos(Fe(X,bt));nt*=Math.cos(Yt)}return 1.01*nt}(m,this.pixelsPerMeter(m.center.lat,m.worldSize)),k=Zj(m.zoom);if(k>0){const E=cFe(m,js(1,m.center.lat)*m.worldSize),P=m.worldSize/(2*Math.PI),O=Math.max(m.width,m.height)/m.worldSize*Math.PI;return Br(x,E+P*(1-Math.cos(O)),Math.pow(k,10))}return x}upVector(m,x,k){return iO(x,k,m,1)}upVectorScale(m){return{metersToTile:fq(gq(__(m)))}}}function fFe(w){const m=w.parallels,x=!!m&&Math.abs(m[0]+m[1])<.01;switch(w.name){case"mercator":return new uFe(w);case"equirectangular":return new u5t(w);case"naturalEarth":return new m5t(w);case"equalEarth":return new d5t(w);case"winkelTripel":return new p5t(w);case"albers":return x?new pFe(w):new c5t(w);case"lambertConformalConic":return x?new pFe(w):new h5t(w);case"globe":return new f5t(w)}throw new Error(`Invalid projection name: ${w.name}`)}class x5t{constructor(m,x){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=x,this.appearances=m;const k=m.map(E=>function(P){if(!P.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const O=P.condition.expression;return{featureDependent:!qy(O),stateDependent:!Vy(O),zoomDependent:!_m(O,["zoom"]),pitchDependent:!_m(O,["pitch"]),brightnessDependent:!_m(O,["brightness","measure-light"]),worldviewDependent:!_m(O,["worldview"])}}(E));this.anyFeatureDependent=k.some(E=>E.featureDependent),this.anyStateDependent=k.some(E=>E.stateDependent)}update(m,x){const k=this.lastParams,E=!k||k.zoom!==m.zoom||k.pitch!==(m.pitch||0)||k.brightness!==(m.brightness||0)||k.worldview!==m.worldview;this.lastParams={zoom:m.zoom,pitch:m.pitch||0,brightness:m.brightness||0,worldview:m.worldview};const P=x&&this.anyStateDependent;if(!E&&!P&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!P){const O=this.evaluateAllFeatures(m);return O===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=O,{kind:"all-features",appearanceIndex:O})}return{kind:"per-feature"}}evaluateAllFeatures(m){for(let x=0;x{for(let E=0;EO-U),P=new Map;for(const O of E){const U=k.get(O);P.set(O,new Po(U))}return x&&(this.cachedBatchIndices=E,this.cachedBatchSegments=P),{batchIndices:E,batchSegments:P}}snapshotSymbolVertexData(m,x){const k=m*eI;return this.layoutVertexArray.uint16.slice(k,k+x*eI)}restoreSymbolVertexData(m,x){this.layoutVertexArray.uint16.set(x,m*eI)}updateSymbolVertexData(m,x,k,E,P,O,U,H,X,le,he,me,be){const Se=this.layoutVertexArray.uint16,Pe=m*eI;Se[Pe]=x,Se[Pe+1]=k,Se[Pe+2]=E,Se[Pe+3]=P,Se[Pe+4]=O,Se[Pe+5]=U,Se[Pe+6]=H,Se[Pe+7]=X,Se[Pe+8]=le,Se[Pe+9]=he,Se[Pe+10]=me,Se[Pe+11]=be}upload(m,x,k,E,P,O){this.isEmpty()||(k&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,v3t.members,!!O),this.indexBuffer=m.createIndexBuffer(this.indexArray,x),this.dynamicLayoutVertexBuffer=m.createVertexBuffer(this.dynamicLayoutVertexArray,_3t.members,!0),this.opacityVertexBuffer=m.createVertexBuffer(this.opacityVertexArray,y5t,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=m.createVertexBuffer(this.iconTransitioningVertexArray,k3t.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=m.createVertexBuffer(this.globeExtVertexArray,b3t.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||P)&&(this.zOffsetVertexBuffer=m.createVertexBuffer(this.zOffsetVertexArray,w3t.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=m.createVertexBuffer(this.orientationVertexArray,N3t.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=m.createVertexBuffer(this.featureIdArray,j3t.members,!1))),(k||E)&&(this.programConfigurations.upload(m),this.uboBinder&&this.uboBinder.upload(m)))}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy(),this.iconTransitioningVertexBuffer&&this.iconTransitioningVertexBuffer.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.orientationVertexBuffer&&this.orientationVertexBuffer.destroy(),this.featureIdBuffer&&this.featureIdBuffer.destroy(),this.uboBinder&&this.uboBinder.destroy())}}Yn(U_e,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class q_e{constructor(m,x,k){this.layoutVertexArray=new m,this.layoutAttributes=x,this.indexArray=new k,this.segments=new Po,this.collisionVertexArray=new qC,this.collisionVertexArrayExt=new T1}upload(m){this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=m.createVertexBuffer(this.collisionVertexArray,S3t.members,!0),this.collisionVertexBufferExt=m.createVertexBuffer(this.collisionVertexArrayExt,C3t.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}Yn(q_e,"CollisionBuffers");class I1{constructor(m){this.collisionBoxArray=m.collisionBoxArray,this.zoom=m.zoom,this.overscaling=m.overscaling,this.layers=m.layers,this.layerIds=this.layers.map(O=>O.fqid),this.index=m.index,this.pixelRatio=m.pixelRatio,this.sourceLayerIndex=m.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=v([]),this.placementViewportMatrix=v([]);const x=this.layers[0]._unevaluatedLayout._values;this.worldview=m.worldview,this.localizable=m.localizable,this.maxUniformBufferBindings=m.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=m.maxUniformBlockSizeDwords,this.disableSymbolUBO=m.disableSymbolUBO,this.textSizeData=s3(this.zoom,x["text-size"],this.worldview,m.availableImages),this.iconSizeData=s3(this.zoom,x["icon-size"],this.worldview,m.availableImages);const k=this.layers[0].layout,E=k.get("symbol-sort-key"),P=k.get("symbol-z-order");this.lut=m.lut,this.canOverlap=k.get("text-allow-overlap")||k.get("icon-allow-overlap")||k.get("text-ignore-placement")||k.get("icon-ignore-placement"),this.sortFeaturesByKey=P!=="viewport-y"&&E.constantOr(1)!==void 0,this.sortFeaturesByY=(P==="viewport-y"||P==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=k.get("text-writing-mode").map(O=>Ix[O]),this.stateDependentLayerIds=this.layers.filter(O=>O.isStateDependent()).map(O=>O.id),this.sourceID=m.sourceID,this.projection=m.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.elevationStateComplete=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(m){const x=this.layers[0].getAppearances();if(!x||x.length===0)return!1;const k=Array.isArray(m)?m:[m];return x.some(E=>k.some(P=>E.hasLayoutProperty(P)))}getAppearanceFeatureData(m){return this.featureAppearanceData.get(m)}createArrays(){this.text=new U_e(new Ue(this.layers,{zoom:this.zoom,lut:this.lut},m=>m.startsWith("text")||m.startsWith("symbol"))),this.icon=new U_e(new Ue(this.layers,{zoom:this.zoom,lut:this.lut},m=>m.startsWith("icon")||m.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new N_e(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new N_e(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new cq,this.lineVertexArray=new GC,this.symbolInstances=new lq}calculateGlyphDependencies(m,x,k,E,P){for(const O of m){const U=O.codePointAt(0);if(U===void 0)break;if(x[U]=!0,E&&P&&U<=65535){const H=SO[O];H&&(x[H.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(m,x,k,E,P,O,U){if(!m.hasLayoutProperty("icon-size"))return U*O;let H=1;const X=m.getUnevaluatedLayoutProperty("icon-size"),le=s3(this.zoom,X,this.worldview,P),he=Z6(le,x);if(le.kind!=="constant"&&le.kind!=="camera"||(H=he.uSize),le.kind==="composite"){const{minZoom:me,maxZoom:be}=le,Se=X.possiblyEvaluate(new Ra(me,{worldview:this.worldview}),E),Pe=X.possiblyEvaluate(new Ra(be,{worldview:this.worldview}),E),Be=Se.evaluate(k,{},E,P);H=Be+(Pe.evaluate(k,{},E,P)-Be)*he.uSizeT}return le.kind==="source"&&(H=X.possiblyEvaluate(new Ra(this.zoom,{worldview:this.worldview}),E).evaluate(k,{},E,P)),H*O}updateFootprints(m,x){}updateReplacement(m,x){if(x.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=x.updateTime;const k=x.getReplacementRegionsForTile(m.toUnwrapped(),!0);return!Cq(this.activeReplacements,k)&&(this.activeReplacements=k,!0)}getResolvedImageFromTokens(m){return typeof m=="string"?Kd.build(m):m}populate(m,x,k,E){const P=this.layers[0],O=P.layout,U=this.projection.name==="globe",H=O.get("text-font"),X=O.get("text-field"),le=O.get("icon-image"),[he,me]=O.get("icon-size-scale-range"),be=Qe(x.scaleFactor||1,he,me),[Se,Pe]=O.get("text-size-scale-range"),Be=Qe(x.scaleFactor||1,Se,Pe),We=(X.value.kind!=="constant"||X.value.value instanceof Wd&&!X.value.value.isEmpty()||X.value.value.toString().length>0)&&(H.value.kind!=="constant"||H.value.value.length>0),ot=le.value.kind!=="constant"||!!le.value.value||Object.keys(le.parameters).length>0,nt=this.hasAnyAppearanceLayoutProperty("icon-image"),ft=O.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!We&&!ot&&!nt)return;const bt=x.iconDependencies,wt=x.glyphDependencies,Yt=x.availableImages,zt=new Ra(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),Kt=Vt=>{const Ht=Vt.id.toString();bt.has(Ht)?bt.get(Ht).push(Vt):bt.set(Ht,[Vt])};for(const Vt of m){const{feature:Ht,id:Os,index:Vs,sourceLayerIndex:Js}=Vt,nn=P._featureFilter.needGeometry,en=Ya(Ht,nn);if(!P._featureFilter.filter(zt,en,k))continue;if(nn||(en.geometry=Kr(Ht,k,E)),U&&Ht.type!==1&&k.z<=5){const On=en.geometry,Rn=.98078528056,An=(nr,pr)=>Fe(iO(nr.x,nr.y,k,1),iO(pr.x,pr.y,k,1)){if(!On.getLayoutProperty("icon-image"))return;const Rn=this.getCombinedIconPrimary(On,tn,en,k,Yt,En,be);Rn&&Kt(Rn)}),xn){const On=H.evaluate(en,{},k).join(","),Rn=O.get("text-rotation-alignment")==="map"&&O.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Ix.vertical)>=0;for(const An of xn.sections)if(An.image){const nr=An.image.getPrimary().scaleSelf(this.pixelRatio*Be),pr=nr.id.toString(),Gr=bt.get(pr)||[];Gr.push(nr),bt.set(pr,Gr)}else{const nr=Wh(xn.toString()),pr=An.fontStack||On,Gr=wt[pr]=wt[pr]||{};this.calculateGlyphDependencies(An.text,Gr,Rn,this.allowVerticalPlacement,nr)}}}if(O.get("symbol-placement")==="line"&&(this.features=function(Vt){const Ht={},Os={},Vs=[];let Js=0;function nn(tn){Vs.push(Vt[tn]),Js++}function en(tn,on,gn){const En=Os[tn];return delete Os[tn],Os[on]=En,Vs[En].geometry[0].pop(),Vs[En].geometry[0]=Vs[En].geometry[0].concat(gn[0]),En}function xn(tn,on,gn){const En=Ht[on];return delete Ht[on],Ht[tn]=En,Vs[En].geometry[0].shift(),Vs[En].geometry[0]=gn[0].concat(Vs[En].geometry[0]),En}function Ls(tn,on,gn){const En=gn?on[0][on[0].length-1]:on[0][0];return`${tn}:${En.x}:${En.y}`}for(let tn=0;tntn.geometry)}(this.features)),O.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",x.elevationFeatures){!this.elevationFeatures&&x.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const Vt of x.elevationFeatures)this.elevationFeatureIdToIndex.set(Vt.id,this.elevationFeatures.length),this.elevationFeatures.push(Vt)}}else O.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Vt,Ht)=>Vt.sortKey-Ht.sortKey)}getCombinedIconPrimary(m,x,k,E,P,O,U){let H,X;if(m.hasLayoutProperty("icon-image")){const le=x.getAppearanceValueAndResolveTokens(m,"icon-image",k,E,P);H=this.getResolvedImageFromTokens(le)}else{const le=x.getValueAndResolveTokens("icon-image",k,E,P);H=this.getResolvedImageFromTokens(le)}if(H){const le=m.hasLayoutProperty("icon-size")?m.getUnevaluatedLayoutProperty("icon-size"):x._unevaluatedLayout._values["icon-size"];X=MO(H,s3(this.zoom,le,this.worldview,P),le,E,this.zoom,O,this.pixelRatio,U,this.worldview,P).iconPrimary}return X}updateSymbolInstanceIconVertices(m,x,k,E,P,O){const{canonical:U,availableImages:H,globalProperties:X,layer:le,iconScaleFactor:he,featureState:me,layoutIconOffset:be,layoutIconSize:Se,layoutIconRotate:Pe}=O;if(m.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(x.activeAppearanceIndex===k)return{vertexOffsetDelta:m.numIconVertices,hasChanges:!1};const Be=k>=0?le.appearances[k]:null;if(Be){const We=this.getCombinedIconPrimary(Be,le,E,U,H,{sortKey:void 0,text:void 0,icon:null,index:m.featureIndex,sourceLayerIndex:m.featureIndex,geometry:[],properties:x.properties,type:"Point",id:x.id},he);if(!We)return{vertexOffsetDelta:0,hasChanges:!1};const ot=We.toString(),nt=this.iconAtlasPositions&&this.iconAtlasPositions.get(ot);if(nt){const{appearanceIconOffset:ft,appearanceIconRotate:bt}=sFe(Be,le,E,U,be,Pe,Se,he);let wt=Gq(nt,void 0,ft,le.layout.get("icon-anchor").evaluate(E,me,U));const Yt=nt.sdf,zt=le.layout.get("icon-text-fit").constantOr("none");zt!=="none"&&x.textShaping&&x.iconTextFitPadding&&x.fontScale&&(wt=E_e(wt,x.textShaping,zt,x.iconTextFitPadding,ft,x.fontScale));const Kt=this.calculateEffectiveAppearanceIconSize(Be,X.zoom,E,U,H,he,Se),Vt=0,Ht=1+(Math.min(n3,Math.round(Kt*Jj))<<1),Os=R_e(wt,bt,Yt,zt!=="none",he);x.isUsingAppearanceIconVertexData||(x.isUsingAppearanceIconVertexData=!0,x.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(P,m.numIconVertices));const Vs=Math.floor(m.numIconVertices/4),Js=Math.min(Os.length,Vs);let nn=P;for(let xn=0;xn0||m.numVerticalGlyphVertices>0;if(!ft)return{vertexOffsetDelta:ft?m.numHorizontalGlyphVertices+m.numVerticalGlyphVertices:0,hasChanges:!1};if(x.activeAppearanceIndex===k)return{vertexOffsetDelta:m.numHorizontalGlyphVertices+m.numVerticalGlyphVertices,hasChanges:!1};const bt=k>=0?H.appearances[k]:null;if(bt&&x.textShaping){const{appearanceTextOffset:wt,appearanceTextRotate:Yt,appearanceTextSize:zt}=nFe(bt,H,E,U,me,Se,be);x.fontScale=oFe(zt,x.textScaleFactor);const Kt=bt.getUnevaluatedLayoutProperty("text-size");let Vt=this.textSizeData,Ht=We,Os=ot;bt.hasLayoutProperty("text-size")&&(Vt=s3(this.zoom,Kt,this.worldview,nt),Ht=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Os=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const Vs=x.textShaping.bottom-me[1],Js=x.textShaping.left-me[0],nn=x.textShaping.right-me[0];x.textShaping.top=wt[1]+(x.textShaping.top-me[1]),x.textShaping.bottom=wt[1]+Vs,x.textShaping.left=wt[0]+Js,x.textShaping.right=wt[0]+nn;const en=eFe(0,x.textShaping,wt,H,!1,E,le,this.allowVerticalPlacement,Yt),xn=zt&&Vt.kind==="composite"?Kt.possiblyEvaluate(new Ra(Ht,{}),U).evaluate(E,he,U):Pe,Ls=zt&&Vt.kind==="composite"?Kt.possiblyEvaluate(new Ra(Os,{}),U).evaluate(E,he,U):Be,tn=B_e(bt.name,Vt,zt,X,xn,Ls),on=Array.isArray(tn)?tn[1]:zt,gn=0,En=1+(Math.min(n3,Math.round(on*Jj))<<1);x.isUsingAppearanceTextVertexData||(x.isUsingAppearanceTextVertexData=!0,x.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(P,m.numHorizontalGlyphVertices+m.numVerticalGlyphVertices));for(let ir=0;ir0){const X=new Set(Object.keys(m).map(le=>{const he=Number(le);return!isNaN(he)&&Number.isSafeInteger(he)&&String(he)===le?he:le}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(X,P[0],x,H,k,m,U),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(X,P[0],x,H,k,m,U)}}}updateRoadElevation(m){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let x=!1;const k=dn(m),E=1/k;let P=!1,O=!1;for(let U=0;U0||me>0,Be=be>0,We=this.elevationFeatures[H.elevationFeatureIndex];if(We){const ot=new Ms(H.tileAnchorX,H.tileAnchorY),nt=.075+We.pointElevation(ot);H.zOffset!==nt&&(x=!0,H.zOffset=nt),nt!==0&&(this.hasAnyZOffset=!0);const ft=We.computeSlopeNormal(ot,E),bt=$t(Bt(),ne(0,0,1),ft);it(X,X,bt),it(le,le,bt),X[2]*=k,le[2]*=k,X[0]===1&&X[1]===0&&X[2]===0&&le[0]===0&&le[1]===1&&le[2]===0||(P=P||Pe,O=O||Be)}if(Pe&&(nV(this.text.orientationVertexArray,he,X,le),nV(this.text.orientationVertexArray,me,X,le)),Be){const{placedIconSymbolIndex:ot,verticalPlacedIconSymbolIndex:nt}=H;ot>=0&&nV(this.icon.orientationVertexArray,be,X,le),nt>=0&&nV(this.icon.orientationVertexArray,Se,X,le)}}P||(this.text.orientationVertexArray=void 0),O||(this.icon.orientationVertexArray=void 0),x&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const m=(P,O,U)=>{k+=O,k>P.length&&P.resize(k);for(let H=-O;H<0;H++)P.emplace(H+k,U)},x=(P,O,U)=>{E+=O,E>P.length&&P.resize(E);for(let H=-O;H<0;H++)P.emplace(H+E,U)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let k=0,E=0;for(let P=0;P0;if((U>0||H>0)&&(m(this.text.zOffsetVertexArray,U,le),m(this.text.zOffsetVertexArray,H,le)),he){const{placedIconSymbolIndex:me,verticalPlacedIconSymbolIndex:be}=O;me>=0&&x(this.icon.zOffsetVertexArray,X,le),be>=0&&x(this.icon.zOffsetVertexArray,O.numVerticalIconVertices,le)}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(m,x,k,E,P){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(m),this.iconCollisionBox.upload(m)),this.text.upload(m,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(O=>O.appearances&&O.appearances.length>0)),this.icon.upload(m,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(m,x,k,E,P,O=!1){const U={hasLayoutChanges:!1,hasUboChanges:!1};if(!m||!k||!this.featureAppearanceData)return U;const H=x||{},X=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,le=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!X&&!le)return U;const he=this.layers[0],me=he.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===he.appearancesVersion||(this.featureAppearances=new x5t(he.appearances,he.appearancesVersion));const be=this.featureAppearances.update(E,O);if(be.kind==="no-changes")return U;let Se=1,Pe=0,Be=!1,We=!1;if(X){const[wt,Yt]=me.get("icon-size-scale-range");Se=Qe(1,wt,Yt)}let ot=1,nt=0,ft=!1;if(le){const[wt,Yt]=me.get("text-size-scale-range");ot=Qe(1,wt,Yt)}const bt=new Map;if(P&&k)for(const wt of k){const Yt=P.getImage(wt,he.scope);if(Yt){const zt=new rp(wt.toString());bt.set(zt.toString(),Yt)}}for(let wt=0;wtnn.isActive({globals:E,feature:Ht,canonical:m,featureState:Vt})):-1;Os=Js>=0?Js:-1}const Vs=zt.activeAppearanceIndex!==Os;if(le){const Js=me.get("text-size"),nn=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,en=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,xn={canonical:m,layer:he,featureState:Vt,availableImages:k,textScaleFactor:ot,imageMap:bt,layoutTextOffset:me.get("text-offset").evaluate(Ht,Vt,m).map(tn=>tn*Jd),layoutTextSize:Js.evaluate(Ht,Vt,m),layoutTextRotate:me.get("text-rotate").evaluate(Ht,Vt,m),layoutMinZoomSize:Js.evaluate(Ht,{zoom:nn},m),layoutMaxZoomSize:Js.evaluate(Ht,{zoom:en},m),layoutTextSizeMinZoom:nn,layoutTextSizeMaxZoom:en},Ls=this.updateSymbolInstanceTextVertices(Yt,zt,Os,Ht,nt,xn);nt+=Ls.vertexOffsetDelta,ft=ft||Ls.hasChanges}if(X){const Js={canonical:m,layer:he,featureState:Vt,availableImages:k,globalProperties:E,iconScaleFactor:Se,layoutIconOffset:me.get("icon-offset").evaluate(Ht,Vt,m),layoutIconSize:me.get("icon-size").evaluate(Ht,Vt,m,k),layoutIconRotate:me.get("icon-rotate").evaluate(Ht,Vt,m)},nn=this.updateSymbolInstanceIconVertices(Yt,zt,Os,Ht,Pe,Js);Pe+=nn.vertexOffsetDelta,Be=Be||nn.hasChanges}if(Vs){const Js=Yt.featureIndex,nn=E?E.brightness:null,en=Vt||{},xn=Os>=0?he.appearances[Os]:null;this.text.uboBinder&&(this.text.uboBinder.layer=he,We=this.text.uboBinder.updateFeaturePaintForAppearance(Js,Ht,en,m,k,nn,xn)||We),this.icon.uboBinder&&(this.icon.uboBinder.layer=he,We=this.icon.uboBinder.updateFeaturePaintForAppearance(Js,Ht,en,m,k,nn,xn)||We)}zt.activeAppearanceIndex=Os}return Be&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),ft&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:Be||ft,hasUboChanges:We}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=fFe(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(m,x){const k=this.lineVertexArray.length;if(m.segment!==void 0)for(const{x:E,y:P}of x)this.lineVertexArray.emplaceBack(E,P);return{lineStartIndex:k,lineLength:this.lineVertexArray.length-k}}addSymbols(m,x,k,E,P,O,U,H,X,le,he,me,be,Se,Pe,Be,We,ot){const nt=m.indexArray,ft=m.layoutVertexArray,bt=m.globeExtVertexArray,wt=ot,Yt=m.uboBinder?m.uboBinder.getCurrentBatchIndex():void 0,zt=m.segments.prepareSegment(4*wt,ft,nt,this.canOverlap?O.sortKey:void 0,Yt),Kt=this.glyphOffsetArray.length,Vt=zt.vertexLength,Ht=this.allowVerticalPlacement&&U===Ix.vertical?Math.PI/2:0,Os=O.text&&O.text.sections;let Vs=ft.length,Js=-1;for(let xn=0;xn=0)){const xn=4*nn;for(let Ls=0;Ls=0?x.rightJustifiedTextSymbolIndex:x.centerJustifiedTextSymbolIndex>=0?x.centerJustifiedTextSymbolIndex:x.leftJustifiedTextSymbolIndex>=0?x.leftJustifiedTextSymbolIndex:x.verticalPlacedTextSymbolIndex>=0?x.verticalPlacedTextSymbolIndex:E),O=A_e(this.textSizeData,m,P)/Jd;return this.tilePixelRatio*O}getSymbolInstanceIconSize(m,x,k){const E=this.icon.placedSymbolArray.get(k),P=A_e(this.iconSizeData,m,E);return this.tilePixelRatio*P}_commitDebugCollisionVertexUpdate(m,x,k,E){m.emplaceBack(x,-k,-k,E),m.emplaceBack(x,k,-k,E),m.emplaceBack(x,k,k,E),m.emplaceBack(x,-k,k,E)}_updateTextDebugCollisionBoxes(m,x,k,E,P,O,U){for(let H=E;H0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(m,x){const k=m.placedSymbolArray.get(x),E=k.vertexStartIndex+4*k.numGlyphs;for(let P=k.vertexStartIndex;PE[U]-E[H]||P[H]-P[U]),O}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let m=0;mthis.symbolInstances.get(x).zOffset-this.symbolInstances.get(m).zOffset)}addToSortKeyRanges(m,x){const k=this.sortKeyRanges[this.sortKeyRanges.length-1];k&&k.sortKey===x?k.symbolInstanceEnd=m+1:this.sortKeyRanges.push({sortKey:x,symbolInstanceStart:m,symbolInstanceEnd:m+1})}sortFeatures(m){if(this.sortFeaturesByY&&this.sortedAngle!==m)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(m),this.sortedAngle=m,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const x of this.symbolInstanceIndexes){const k=this.symbolInstances.get(x);this.featureSortOrder.push(k.featureIndex);const{rightJustifiedTextSymbolIndex:E,centerJustifiedTextSymbolIndex:P,leftJustifiedTextSymbolIndex:O,verticalPlacedTextSymbolIndex:U,placedIconSymbolIndex:H,verticalPlacedIconSymbolIndex:X}=k;E>=0&&this.addIndicesForPlacedSymbol(this.text,E),P>=0&&P!==E&&this.addIndicesForPlacedSymbol(this.text,P),O>=0&&O!==P&&O!==E&&this.addIndicesForPlacedSymbol(this.text,O),U>=0&&this.addIndicesForPlacedSymbol(this.text,U),H>=0&&this.addIndicesForPlacedSymbol(this.icon,H),X>=0&&this.addIndicesForPlacedSymbol(this.icon,X)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(m,x){const k=(this.text.uboBinder&&this.text.uboBinder.maxFeaturesPerBatch>0?this.text.uboBinder:this.icon.uboBinder&&this.icon.uboBinder.maxFeaturesPerBatch>0?this.icon.uboBinder:null).maxFeaturesPerBatch;if(this.symbolsByBatch)for(const E of this.symbolsByBatch.values())for(const P of E){const O=this.symbolInstances.get(P.index);P.rotatedY=0|Math.round(m*O.tileAnchorX+x*O.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let E=0;EP.rotatedY-O.rotatedY||O.featureIndex-P.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(m,x){for(const k of m){const E=k.batchIndex;if(E===void 0)continue;const P=x.get(E);if(!P){k.primitiveOffset=this.text.indexArray.length,k.primitiveLength=0;continue}k.primitiveOffset=this.text.indexArray.length;const O=this.text.indexArray.length;for(const{index:U}of P){const H=this.symbolInstances.get(U),{rightJustifiedTextSymbolIndex:X,centerJustifiedTextSymbolIndex:le,leftJustifiedTextSymbolIndex:he,verticalPlacedTextSymbolIndex:me}=H;X>=0&&this.addIndicesForPlacedSymbol(this.text,X),le>=0&&le!==X&&this.addIndicesForPlacedSymbol(this.text,le),he>=0&&he!==le&&he!==X&&this.addIndicesForPlacedSymbol(this.text,he),me>=0&&this.addIndicesForPlacedSymbol(this.text,me)}k.primitiveLength=this.text.indexArray.length-O}}rebuildIconSegmentIndices(m,x){for(const k of m){const E=k.batchIndex;if(E===void 0)continue;const P=x.get(E);if(!P){k.primitiveOffset=this.icon.indexArray.length,k.primitiveLength=0;continue}k.primitiveOffset=this.icon.indexArray.length;const O=this.icon.indexArray.length;for(const{index:U}of P){const H=this.symbolInstances.get(U),{placedIconSymbolIndex:X,verticalPlacedIconSymbolIndex:le}=H;X>=0&&this.addIndicesForPlacedSymbol(this.icon,X),le>=0&&this.addIndicesForPlacedSymbol(this.icon,le)}k.primitiveLength=this.icon.indexArray.length-O}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const m=Math.sin(this.sortedAngle),x=Math.cos(this.sortedAngle),k=this.getOrCreateSortedSymbolsByBatch(m,x),E=Array.from(k.keys()).sort((P,O)=>P-O);for(const P of E){const O=k.get(P);for(const{index:U}of O){const H=this.symbolInstances.get(U);this.featureSortOrder.push(H.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),k),this.rebuildIconSegmentIndices(this.icon.segments.get(),k),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(m){const x=this.symbolInstances.get(this.text.symbolInstanceIndices[m]).elevationFeatureIndex;let k;return this.elevationFeatures&&xk in w?String(w[k]):"")}let gFe,yFe,V_e;Yn(I1,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),I1.addDynamicAttributes=J6;class vFe{constructor(m){this.type=m.property.overrides?m.property.overrides.runtimeType:If,this.defaultValue=m}evaluate(m){if(m.formattedSection){const x=this.defaultValue.property.overrides;if(x&&x.hasOverride(m.formattedSection))return x.getOverride(m.formattedSection)}return m.feature&&m.featureState?this.defaultValue.evaluate(m.feature,m.featureState):this.defaultValue.property.specification.default}eachChild(m){this.defaultValue.isConstant()||m(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Yn(vFe,"FormatSectionOverride",{omit:["defaultValue"]});const H_e=()=>V_e||(V_e={layout:gFe||(gFe=new Zo({"symbol-placement":new kn(fs.layout_symbol["symbol-placement"]),"symbol-spacing":new kn(fs.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new kn(fs.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Nn(fs.layout_symbol["symbol-sort-key"]),"symbol-z-order":new kn(fs.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new kn(fs.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new kn(fs.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new kn(fs.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new kn(fs.layout_symbol["icon-ignore-placement"]),"icon-optional":new kn(fs.layout_symbol["icon-optional"]),"icon-rotation-alignment":new kn(fs.layout_symbol["icon-rotation-alignment"]),"icon-size":new Nn(fs.layout_symbol["icon-size"]),"icon-size-scale-range":new kn(fs.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new Nn(fs.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Nn(fs.layout_symbol["icon-text-fit-padding"]),"icon-image":new Nn(fs.layout_symbol["icon-image"]),"icon-image-use-theme":new kn({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new Nn(fs.layout_symbol["icon-rotate"]),"icon-padding":new kn(fs.layout_symbol["icon-padding"]),"icon-keep-upright":new kn(fs.layout_symbol["icon-keep-upright"]),"icon-offset":new Nn(fs.layout_symbol["icon-offset"]),"icon-anchor":new Nn(fs.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new kn(fs.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new kn(fs.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new kn(fs.layout_symbol["text-rotation-alignment"]),"text-field":new Nn(fs.layout_symbol["text-field"]),"text-font":new Nn(fs.layout_symbol["text-font"]),"text-size":new Nn(fs.layout_symbol["text-size"]),"text-size-scale-range":new kn(fs.layout_symbol["text-size-scale-range"]),"text-max-width":new Nn(fs.layout_symbol["text-max-width"]),"text-line-height":new Nn(fs.layout_symbol["text-line-height"]),"text-letter-spacing":new Nn(fs.layout_symbol["text-letter-spacing"]),"text-justify":new Nn(fs.layout_symbol["text-justify"]),"text-radial-offset":new Nn(fs.layout_symbol["text-radial-offset"]),"text-variable-anchor":new kn(fs.layout_symbol["text-variable-anchor"]),"text-anchor":new Nn(fs.layout_symbol["text-anchor"]),"text-max-angle":new kn(fs.layout_symbol["text-max-angle"]),"text-writing-mode":new kn(fs.layout_symbol["text-writing-mode"]),"text-rotate":new Nn(fs.layout_symbol["text-rotate"]),"text-padding":new kn(fs.layout_symbol["text-padding"]),"text-keep-upright":new kn(fs.layout_symbol["text-keep-upright"]),"text-transform":new Nn(fs.layout_symbol["text-transform"]),"text-offset":new Nn(fs.layout_symbol["text-offset"]),"text-allow-overlap":new kn(fs.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new kn(fs.layout_symbol["text-ignore-placement"]),"text-optional":new kn(fs.layout_symbol["text-optional"]),visibility:new kn(fs.layout_symbol.visibility)})),paint:yFe||(yFe=new Zo({"icon-opacity":new Nn(fs.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Nn(fs.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Nn(fs.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Nn(fs.paint_symbol["text-emissive-strength"]),"icon-color":new Nn(fs.paint_symbol["icon-color"]),"icon-halo-color":new Nn(fs.paint_symbol["icon-halo-color"]),"icon-halo-width":new Nn(fs.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Nn(fs.paint_symbol["icon-halo-blur"]),"icon-translate":new kn(fs.paint_symbol["icon-translate"]),"icon-translate-anchor":new kn(fs.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new kn(fs.paint_symbol["icon-image-cross-fade"]),"text-opacity":new Nn(fs.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Nn(fs.paint_symbol["text-occlusion-opacity"]),"text-color":new Nn(fs.paint_symbol["text-color"],{runtimeType:Uh,getOverride:w=>w.textColor,hasOverride:w=>!!w.textColor}),"text-halo-color":new Nn(fs.paint_symbol["text-halo-color"]),"text-halo-width":new Nn(fs.paint_symbol["text-halo-width"]),"text-halo-blur":new Nn(fs.paint_symbol["text-halo-blur"]),"text-translate":new kn(fs.paint_symbol["text-translate"]),"text-translate-anchor":new kn(fs.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new kn(fs.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new kn(fs.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new kn(fs.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new kn(fs.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new Nn(fs.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"})}))},V_e);class rV extends lo{constructor(m,x,k,E){super(m,H_e(),x,k,E,m.layout?m.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=v([]),this.hasOcclusionOpacityProperties=m.paint!==void 0&&("icon-occlusion-opacity"in m.paint||"text-occlusion-opacity"in m.paint)}_handleSpecialPaintPropertyUpdate(m){m!=="icon-occlusion-opacity"&&m!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(m,x){super.recalculate(m,x),this.appearances&&this.appearances.forEach(E=>{E.recalculate(m,x,this.iconImageUseTheme)}),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));const k=this.layout.get("text-writing-mode");if(k){const E=[];for(const P of k)E.indexOf(P)<0&&E.push(P);this.layout._values["text-writing-mode"]=E}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(m,x,k,E){return this._saturation===m&&this._contrast===x&&this._brightnessMin===k&&this._brightnessMax===E||(this._colorAdjustmentMatrix=function(P,O,U,H){P=ya(P),O=ea(O);const X=g(),le=P/3,he=1-2*le,me=[he,le,le,0,le,he,le,0,le,le,he,0,0,0,0,1],be=.5-.5*O,Se=H-U;return _(X,[Se,0,0,0,0,Se,0,0,0,0,Se,0,U,U,U,1],[O,0,0,0,0,O,0,0,0,0,O,0,be,be,be,1]),_(X,X,me),X}(m,x,k,E),this._saturation=m,this._contrast=x,this._brightnessMin=k,this._brightnessMax=E),this._colorAdjustmentMatrix}getValueAndResolveTokens(m,x,k,E){const P=this.layout.get(m).evaluate(x,{},k,E),O=this._unevaluatedLayout._values[m];return O.isDataDriven()||Wy(O.value)||!P?P:xFe(x.properties,P)}getAppearanceValueAndResolveTokens(m,x,k,E,P){const O=m.getLayoutProperty(x);if(!O)return;const U=O.evaluate(k,{},E,P),H=m.getUnevaluatedLayoutProperties()._values[x];return H.isDataDriven()||Wy(H.value)||!U||typeof U!="string"?U:xFe(k.properties,U)}createBucket(m){return new I1(m)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const m of H_e().paint.overridableProperties){if(!rV.hasPaintOverride(this.layout,m))continue;const x=this.paint.get(m),k=new vFe(x),E=new j1(k,x.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let P=null;P=x.value.kind==="constant"||x.value.kind==="source"?new b0("source",E):new Nx("composite",E,x.value.zoomStops,x.value.interpolationType),this.paint._values[m]=new S1(x.property,P,x.parameters)}}_handleOverridablePaintPropertyUpdate(m,x,k){return!(!this.layout||x.isDataDriven()||k.isDataDriven())&&rV.hasPaintOverride(this.layout,m)}static hasPaintOverride(m,x){const k=m.get("text-field"),E=H_e().paint.properties[x];let P=!1;const O=U=>{for(const H of U)if(E.overrides&&E.overrides.hasOverride(H))return void(P=!0)};if(k.value.kind==="constant"&&k.value.value instanceof Wd)O(k.value.value.sections);else if(k.value.kind==="source"){const U=X=>{P||(X instanceof rr&&Ml(X.value)===Oy?O(X.value.sections):X instanceof vm?O(X.sections):X.eachChild(U))},H=k.value;H._styleExpression&&U(H._styleExpression.expression)}return P}getProgramIds(){return["symbol"]}getDefaultProgramParams(m,x,k){return{config:new Le(this,{zoom:x,lut:k}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let bFe,_Fe,wFe,jFe;var aV=cn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function iV(w,m,x,k,E,P,O,U){const H=[w,m,1,x,k,1,E,P,1],X=[O,U,1],le=p([],H),[he,me,be]=we(X,X,le);return f(H,H,[he,0,0,0,me,0,0,0,be])}function NFe(w,m,x,k,E,P,O,U){const H=function(X,le,he,me,be,Se,Pe,Be){const We=iV(0,0,1,0,1,1,0,1),ot=iV(X,le,he,me,be,Se,Pe,Be);return f(ot,ot,p([],We))}(w,m,x,k,E,P,O,U);return[H[2]/H[8]/Bn,H[5]/H[8]/Bn]}function oV(w){return[w[0],Math.min(Math.max(w[1],-85.051129),Qs)]}class kFe extends Op{constructor(m,x,k,E){super(),this.id=m,this.dispatcher=k,this.coordinates=x.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(E),this.options=x,this._dirty=!1}load(m,x){if(this._loaded=x||!1,this.fire(new Bc("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return m&&(this.coordinates=m),this._loaded=!0,void this._finishLoading();this._imageRequest=xx(this.map._requestManager.transformRequest(this.url,h0.Image),(k,E)=>{this._imageRequest=null,this._loaded=!0,k?this.fire(new sp(k)):E&&(this.image=E,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,m&&(this.coordinates=m),this._finishLoading())})}loaded(){return this._loaded}updateImage(m){return m.url?(this._imageRequest&&m.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=m.url,this.load(m.coordinates,this._loaded),this):this}setTexture(m){if(!(m.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new jO(this.map.painter.context,m.handle),this.width=m.dimensions[0],this.height=m.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Bc("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(m){this.map=m,this.load()}onRemove(m){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof jO||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(m){if(this.coordinates=m,this._boundsArray=void 0,this._unsupportedCoords=!1,!m.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let x=m[0][1],k=m[0][1];for(const P of m)P[1]>k&&(k=P[1]),P[1]Qs?this.onNorthPole=!0:E<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const P=m.map(mr.fromLngLat);this.tileID=function(O){let U=1/0,H=1/0,X=-1/0,le=-1/0;for(const Pe of O)U=Math.min(U,Pe.x),H=Math.min(H,Pe.y),X=Math.max(X,Pe.x),le=Math.max(le,Pe.y);const he=Math.max(X-U,le-H),me=Math.max(0,Math.floor(-Math.log2(he))),be=Math.pow(2,me);let Se=Math.floor((U+X)/2*be);return Se>1&&(Se-=1),new QC(me,Se,Math.floor((H+le)/2*be))}(P),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Bc("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof jO||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(m){for(const Be in this.tiles){const We=this.tiles[Be];We.state!=="loaded"&&(We.state="loaded",We.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const x=r3(new QC(0,0,0),this.map.transform.projection),k=[x.projection.project(this.coordinates[0][0],this.coordinates[0][1]),x.projection.project(this.coordinates[1][0],this.coordinates[1][1]),x.projection.project(this.coordinates[2][0],this.coordinates[2][1]),x.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(Be){const We=Be[1].x-Be[0].x,ot=Be[1].y-Be[0].y,nt=Be[2].x-Be[1].x,ft=Be[2].y-Be[1].y,bt=Be[3].x-Be[2].x,wt=Be[3].y-Be[2].y,Yt=Be[0].x-Be[3].x,zt=Be[0].y-Be[3].y,Kt=We*ft-nt*ot,Vt=nt*wt-bt*ft,Ht=bt*zt-Yt*wt,Os=Yt*ot-We*zt;return Kt>0&&Vt>0&&Ht>0&&Os>0||Kt<0&&Vt<0&&Ht<0&&Os<0}(k))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const E=r3(this.tileID,this.map.transform.projection),[P,O,U,H]=this.coordinates.map(Be=>{const We=E.projection.project(Be[0],Be[1]);return dFe(E,We)._round()});this.perspectiveTransform=NFe(P.x,P.y,O.x,O.y,U.x,U.y,H.x,H.y);const X=this._boundsArray=new ai;X.emplaceBack(P.x,P.y,0,0),X.emplaceBack(O.x,O.y,Bn,0),X.emplaceBack(H.x,H.y,0,Bn),X.emplaceBack(U.x,U.y,Bn,Bn),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=m.createVertexBuffer(X,aV.members),this.boundsSegments=Po.simpleSegment(0,0,4,2);const le=[],he=function(Be){return[oV(Be[0]),oV(Be[1]),oV(Be[2]),oV(Be[3])]}(this.coordinates),[me,be,Se,Pe]=function(Be){let We=Be[0][0],ot=We,nt=Be[0][1],ft=nt;for(let bt=1;btot&&(ot=Be[bt][0]),Be[bt][1]ft&&(ft=Be[bt][1]);return[We,nt,ot-We,ft-nt]}(he);{const Be=new ai,[We,ot,nt,ft]=function(en){let xn=en[0].x,Ls=xn,tn=en[0].y,on=tn;for(let gn=1;gnLs&&(Ls=en[gn].x),en[gn].yon&&(on=en[gn].y);return[xn,tn,Ls-xn,on-tn]}(k),bt=en=>[(en.x-We)/nt,(en.y-ot)/ft],[wt,Yt,zt,Kt]=k.map(bt),Vt=function(en,xn,Ls,tn,on,gn,En,ir){const On=iV(0,0,1,0,1,1,0,1);return f(On,On,p([],iV(en,xn,Ls,tn,on,gn,En,ir)))}(wt[0],wt[1],Yt[0],Yt[1],zt[0],zt[1],Kt[0],Kt[1]);this.elevatedGlobePerspectiveTransform=NFe(wt[0],wt[1],Yt[0],Yt[1],zt[0],zt[1],Kt[0],Kt[1]);const Ht=(en,xn)=>{le.push(en.lng);const Ls=Math.round((en.lng-me)/Se*Bn),tn=Math.round((en.lat-be)/Pe*Bn),on=bt(xn),gn=we([],[on[0],on[1],1],Vt),En=Math.round(gn[0]/gn[2]*Bn),ir=Math.round(gn[1]/gn[2]*Bn);Be.emplaceBack(Ls,tn,En,ir)},Os=k[3].x-k[0].x,Vs=k[3].y-k[0].y,Js=k[2].x-k[1].x,nn=k[2].y-k[1].y;for(let en=0;en<65;en++){const xn=en/64,Ls=[k[0].x+xn*Os,k[0].y+xn*Vs],tn=[k[1].x+xn*Js,k[1].y+xn*nn],on=tn[0]-Ls[0],gn=tn[1]-Ls[1];for(let En=0;En<65;En++){const ir=En/64,On={x:Ls[0]+on*ir,y:Ls[1]+gn*ir};Ht(x.projection.unproject(On.x,On.y),On)}}this.elevatedGlobeVertexBuffer=m.createVertexBuffer(Be,aV.members)}{this.maxLongitudeTriangleSize=0;let Be=[],We=new sc;const ot=(nt,ft,bt)=>{We.emplaceBack(nt,ft,bt);const wt=le[nt],Yt=le[ft],zt=le[bt],Kt=Math.min(Math.min(wt,Yt),zt),Vt=Math.max(Math.max(wt,Yt),zt)-Kt;Vt>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Vt),Be.push(Kt+Vt/2)};for(let nt=0;nt<64;nt++)for(let ft=0;ft<64;ft++){const bt=65*nt+ft,wt=bt+1,Yt=bt+65,zt=Yt+1;ot(bt,Yt,wt),ot(wt,Yt,zt)}[Be,We]=function(nt,ft){const bt=Array.from({length:nt.length},(zt,Kt)=>Kt);bt.sort((zt,Kt)=>nt[zt]-nt[Kt]);const wt=[],Yt=new sc;for(let zt=0;zt{O.segments.push({vertexOffset:0,primitiveOffset:he,vertexLength:x.segments[0].vertexLength,primitiveLength:me,sortKey:void 0,vaos:{}})},H=.51*this.maxLongitudeTriangleSize;if(Math.abs(k[0]-E)<=H){const he=Oi(k,0,k.length,E+H);return he===k.length||U(he,wi(k,he+1,k.length,E+360-H)-he),O}E0}}let CFe,TFe,EFe,AFe,MFe,IFe,PFe;class LFe extends lo{constructor(m,x,k,E){super(m,{layout:CFe||(CFe=new Zo({visibility:new kn(fs["layout_raster-particle"].visibility)})),paint:TFe||(TFe=new Zo({"raster-particle-array-band":new kn(fs["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new kn(fs["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new Wp(fs["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new kn(fs["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new kn(fs["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new kn(fs["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new kn(fs["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new kn(fs["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"})}))},x,k,E),this._updateColorRamp(),this.lastInvalidatedAt=Gd.now()}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this.tileFramebuffer&&(this.tileFramebuffer.destroy(),this.tileFramebuffer=null),this.particleFramebuffer&&(this.particleFramebuffer.destroy(),this.particleFramebuffer=null)}onRemove(m){this.colorRampTexture&&this.colorRampTexture.destroy(),this.tileFramebuffer&&this.tileFramebuffer.destroy(),this.particleFramebuffer&&this.particleFramebuffer.destroy()}hasColorMap(){return!!this._transitionablePaint._values["raster-particle-color"].value.value}getProgramIds(){return["rasterParticle"]}hasOffscreenPass(){return this.visibility!=="none"}isDraped(m){return!1}_handleSpecialPaintPropertyUpdate(m){m!=="raster-particle-color"&&m!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),m==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const m=this._transitionablePaint._values["raster-particle-color"].value.expression,x=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=lO({expression:m,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:x}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=Gd.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class _5t extends lo{constructor(m,x){super(m,{},x,null),this.implementation=m,m.slot&&(this.slot=m.slot)}is3D(m){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(m){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(m){this.implementation.onAdd&&this.implementation.onAdd(m,m.painter.context.gl)}onRemove(m){this.implementation.onRemove&&this.implementation.onRemove(m,m.painter.context.gl)}}function W_e(w,m,x){const k=[0,0,1],E=kt([]);return ns(E,E,x?-lr(w)+Math.PI:lr(w)),Qt(E,E,-lr(m)),it(k,k,E),Ie(k,k)}class lV{constructor(m,x,k,E){this.message=(m?`${m}: `:"")+k,E&&(this.identifier=E),x!=null&&x.__line__&&(this.line=x.__line__)}}function K_e(w,m){const x=w.indexOf("://")===-1;try{return new URL(w,x&&m?"http://example.com":void 0),!0}catch{return!1}}class DFe{constructor(m,x){this.feature=m,this.instancedDataOffset=x,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class RFe{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new JR,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(m){const x=16*m,k=this.instancedDataArray.float32;let E=Math.floor(k[x+2]);const P=1.05*(k[x+2]-E);return E/=100,[k[x]%1*1.05,k[x+1]%1*1.05,P,E]}tileCoordinatesForInstance(m){const x=16*m,k=this.instancedDataArray.float32;let E=k[x+0];return E=E>Bn?E-Bn:E,new Ms(Math.trunc(E),Math.trunc(k[x+1]))}translationForInstance(m){const x=16*m,k=this.instancedDataArray.float32;return[k[x+4],k[x+5],k[x+6]]}rotationScaleForInstance(m){const x=16*m,k=this.instancedDataArray.float32;return[k[x+7],k[x+8],k[x+9],k[x+10],k[x+11],k[x+12],k[x+13],k[x+14],k[x+15]]}transformForInstance(m){const x=16*m,k=this.instancedDataArray.float32;return[k[x+7],k[x+8],k[x+9],k[x+4],k[x+10],k[x+11],k[x+12],k[x+5],k[x+13],k[x+14],k[x+15],k[x+6],0,0,0,1]}}class Y_e{constructor(m){this.zoom=m.zoom,this.canonical=m.canonical,this.overscaledZ=this.canonical.z+Math.log2(m.overscaling),this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.projection=m.projection,this.index=m.index,this.worldview=m.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.hasPattern=!1,this.instancesPerModel={},this.validForExaggeration=0,this.maxVerticalOffset=0,this.maxScale=0,this.maxHeight=0,this.lookupDim=this.zoom>this.canonical.z+1?0:this.zoom>this.canonical.z?256:this.zoom>15?75:100,this.instanceCount=0,this.terrainElevationMin=0,this.terrainElevationMax=0,this.validForDEMTile={id:null,timestamp:0},this.modelUris=[],this.modelsRequested=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.styleDefinedModelURLs=m.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){this.tileToMeter=dn(k);const P=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const O=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?x.elevationFeatures:void 0;for(const{feature:U,id:H,index:X,sourceLayerIndex:le}of m){const he=H??(U.properties&&U.properties.hasOwnProperty("id")?U.properties.id:void 0),me=Ya(U,P);if(!this.layers[0]._featureFilter.filter(new Ra(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),me,k))continue;const be={id:he,sourceLayerIndex:le,index:X,geometry:P?me.geometry:Kr(U,k,E),properties:U.properties,type:U.type,patterns:{}},Se=this.addFeature(be,be.geometry,me,O,k);Se&&x.featureIndex.insert(U,be.geometry,X,le,this.index,this.instancesPerModel[Se].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const m=this.layers[0].modelManager,x=this.layers[0].scope;let k=0;for(const E of this.modelUris){const P=m.getModel(E,x);if(!P)continue;const O=this.instancesPerModel[E];if(O){const U=.5*Te(P.aabb.max,P.aabb.min)*O.maxScale+O.maxXYTranslationDistance,H=Math.min(Bn,Math.max(U/this.tileToMeter,256));k=Math.max(H,k)}}return k}update(m,x,k,E){for(const P in this.instancesPerModel){const O=this.instancesPerModel[P];for(const U in m)O.idToFeaturesIndex.hasOwnProperty(U)&&(this.evaluate(O.features[O.idToFeaturesIndex[U]],m[U],O,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let m=!1;for(const x in this.instancesPerModel){const k=this.instancesPerModel[x];for(const E of k.features){const P=this.layers[0],O=E.feature,U=this.canonical,H=P.paint.get("model-rotation").evaluate(O,{},U),X=P.paint.get("model-scale").evaluate(O,{},U),le=P.paint.get("model-translation").evaluate(O,{},U);He(E.rotation,H)&&He(E.scale,X)&&He(E.translation,le)||(this.evaluate(E,E.featureStates,k,!0),m=!0)}}return m}updateReplacement(m,x,k,E){if(x.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=x.updateTime;const P=x.getReplacementRegionsForTile(m.toUnwrapped(),!0);if(Cq(this.activeReplacements,P))return!1;this.activeReplacements=P;let O=!1;for(const U in this.instancesPerModel){const H=this.instancesPerModel[U],X=H.instancedDataArray;for(const le of H.features){const he=le.instancedDataOffset,me=le.instancedDataCount;for(let be=0;beBn;Pe=Be?Pe-Bn:Pe;const We=Math.floor(Pe),ot=Math.floor(X.float32[Se+1]);let nt=!1;for(const ft of this.activeReplacements)if(!gRe(ft,k,Tq.Model,E)&&!(ft.min.x>We||We>ft.max.x||ft.min.y>ot||ot>ft.max.y)&&(nt=wRe(_Re(We,ot,m.canonical,ft.footprintTileId.canonical),ft.footprint),nt))break;X.float32[Se]=nt?Pe+Bn:Pe,O=O||nt!==Be}}}return O}isEmpty(){for(const m in this.instancesPerModel)if(this.instancesPerModel[m].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(m){if(!this.uploaded)for(const x in this.instancesPerModel){const k=this.instancesPerModel[x];k.instancedDataArray.length<0||k.instancedDataArray.length===0||(k.instancedDataBuffer?k.instancedDataBuffer.updateData(k.instancedDataArray):k.instancedDataBuffer=m.createVertexBuffer(k.instancedDataArray,BCt.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(m){for(const k in this.instancesPerModel){const E=this.instancesPerModel[k];E.instancedDataArray.length!==0&&E.instancedDataBuffer&&E.instancedDataBuffer.destroy()}const x=this.layers[0].modelManager;if(m&&x&&this.modelUris&&this.modelsRequested)for(const k of this.modelUris)x.removeModel(k,"",!0)}addFeature(m,x,k,E,P){const O=this.layers[0],U=O.layout.get("model-id"),H=O.layout.get("model-allow-density-reduction"),X=U.evaluate(k,{},this.canonical);if(!X)return sr(`modelId is not evaluated for layer ${O.id} and it is not going to get rendered.`),X;(K_e(X,!1)||this.styleDefinedModelURLs[X]!==void 0)&&(this.modelUris.includes(X)||this.modelUris.push(X)),this.instancesPerModel[X]||(this.instancesPerModel[X]=new RFe);const le=this.instancesPerModel[X],he=le.instancedDataArray,me=new DFe(k,he.length);let be;E&&(be=$o.getElevationFeature(m,E));for(const Se of x)for(const Pe of Se){if(Pe.x<0||Pe.x>=Bn||Pe.y<0||Pe.y>=Bn)continue;if(this.lookupDim!==0&&H){const We=(this.lookupDim-1)/Bn,ot=this.lookupDim*(Pe.y*We|0)+Pe.x*We|0;if(this.lookup){if(this.lookup[ot]!==0)continue;this.lookup[ot]=1}}this.instanceCount++;const Be=he.length;if(he.resize(Be+1),E){le.instancesRoadElevation||(le.instancesRoadElevation=[]);const We=be?be.pointElevation(new Ms(Pe.x,Pe.y)):0;le.instancesRoadElevation.push(We)}le.instancesEvaluatedElevation.push(0),he.float32[16*Be]=Pe.x,he.float32[16*Be+1]=Pe.y}return me.instancedDataCount=le.instancedDataArray.length-me.instancedDataOffset,me.instancedDataCount>0&&(m.id&&(le.idToFeaturesIndex[m.id]=le.features.length),le.features.push(me),this.evaluate(me,{},le,!1)),X}getModelUris(){return this.modelUris}evaluate(m,x,k,E){const P=this.layers[0],O=m.feature,U=this.canonical,H=m.rotation=P.paint.get("model-rotation").evaluate(O,x,U),X=m.scale=P.paint.get("model-scale").evaluate(O,x,U),le=m.translation=P.paint.get("model-translation").evaluate(O,x,U),he=Object.assign({},P.paint.get("model-color").evaluate(O,x,U));he.a=P.paint.get("model-color-mix-intensity").evaluate(O,x,U);const me=[];this.maxVerticalOffset0?Math.sqrt(be):0;k.maxScale=Math.max(Math.max(k.maxScale,X[0]),Math.max(X[1],X[2])),k.maxXYTranslationDistance=Math.max(k.maxXYTranslationDistance,Se),this.maxScale=Math.max(Math.max(this.maxScale,X[0]),Math.max(X[1],X[2])),iOe(me,H,X);const Pe=Math.round(100*he.a)+he.b/1.05;for(let Be=0;Be10?this.tileToMeter:dn(U,bt)),nt[ot+4]=le[0],nt[ot+5]=le[1],nt[ot+6]=le[2]+(k.instancesRoadElevation?k.instancesRoadElevation[We]:0)+ft,nt[ot+7]=me[0],nt[ot+8]=me[1],nt[ot+9]=me[2],nt[ot+10]=me[4],nt[ot+11]=me[5],nt[ot+12]=me[6],nt[ot+13]=me[8],nt[ot+14]=me[9],nt[ot+15]=me[10],k.instancesEvaluatedElevation[We]=le[2]}}}Yn(Y_e,"ModelBucket",{omit:["layers"]}),Yn(RFe,"PerModelAttributes"),Yn(DFe,"ModelFeature");class tI{constructor(m,x,k){this._demTile=m,this._dem=this._demTile.dem,this._scale=x,this._offset=k}static create(m,x,k){const E=k||m.findDEMTileFor(x);if(!E||!E.dem)return;const P=E.dem,O=E.tileID,U=1<X.fqid),this.stateDependentLayerIds=this.layers.filter(X=>X.isStateDependent()).map(X=>X.id),this.modelTraits|=W6.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,E&&(this.modelTraits|=W6.HasMapboxMeshFeatures),P&&(this.modelTraits|=W6.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=O,this.worldview=H,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const X of x)this.nodesInfo.push(new BFe(X)),FFe(X,U.featureIndexArray.length,U.grid),U.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,U.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(m,x){for(const k of this.getNodesInfo()){const E=k.node;E.footprint&&x.push({footprint:E.footprint,id:m})}}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(m){const x=Object.keys(m).length!==0;if(x&&!this.stateDependentLayers.length)return;const k=x?this.stateDependentLayers:this.layers;if(!bi(m,this.states))for(const E of k)this.evaluate(E,m);this.states=structuredClone(m)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(m){if(!this.needsUpload)return;const x=this.getNodesInfo();for(const k of x){const E=k.node;this.uploaded?this.updatePbrBuffer(E):m_e(E,m,!0)}for(const k of x)$q(k.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(m){let x=!1;if(!m.meshes)return x;for(const k of m.meshes)k.pbrBuffer&&(k.pbrBuffer.updateData(k.featureArray),x=!0);return x}needsReEvaluation(m,x,k){const E=m.transform.projectionOptions,P=m.style.getBrightness(),O=this.brightness!==P;if(!this.uploaded||this.dirty||E.name!==this.projection.name||zO(k.paint.get("model-color").value,O)||zO(k.paint.get("model-color-mix-intensity").value,O)||zO(k.paint.get("model-roughness").value,O)||zO(k.paint.get("model-emissive-strength").value,O)||zO(k.paint.get("model-height-based-emissive-strength-multiplier").value,O)){this.projection=E,this.brightness=P;const U=this.getNodesInfo();for(const H of U)H.state=null;return!0}return!1}evaluateTransform(m,x){if(m.transform.zoom===this.zoom)return;this.zoom=m.transform.zoom;const k=this.getNodesInfo(),E=this.id.canonical;for(const P of k){const O=P.feature;P.evaluatedTranslation=x.paint.get("model-translation").evaluate(O,{},E),P.evaluatedScale=x.paint.get("model-scale").evaluate(O,{},E)}}evaluate(m,x){const k=this.getNodesInfo();for(const E of k){if(!E.node.meshes)continue;const P=E.feature,O=x&&x[P.id];if(bi(O,E.state))continue;E.state=structuredClone(O);const U=E.node.meshes&&E.node.meshes[0].featureData,H=E.evaluatedColor[2],X=E.evaluatedRMEA[2],le=this.id.canonical;if(E.hasTranslucentParts=!1,U){for(let he=0;he=wt)continue;const xn=Z_e[en],Ls=Math.abs(xn);Ls>Ht&&(Vt=xn,Ht=Ls,Os=nn,Vs=Js)}if(Ht>.1){const Js=1-(wt+.5*Math.abs(Os*Vs))/Se;let nn=x._dem.get(zt,Yt)+Vt*Js;const en=x._dem.get(zt+Os,Yt+Vs),xn=x._dem.get(zt-Os,Yt-Vs,!0);(nn-en)*(nn-xn)>0&&(nn=(en+xn)/2),Z_e[Kt]=x._dem.set(zt,Yt,nn),a3[Kt]=wt}}}}}U&&(x._demTile.needsDEMTextureUpload=!0,x._dem._timestamp=Gd.now())}setFilter(m){this.filter=m?ak(m):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(m=>this.filter.filter(new Ra(this.id.overscaledZ,{worldview:this.worldview}),m.feature,this.id.canonical)):this.nodesInfo}destroy(){const m=this.getNodesInfo();for(const x of m)$q(x.node),p_e(x.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(m,x){if(x.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=x.updateTime;const k=x.getReplacementRegionsForTile(m.toUnwrapped());for(const E of this.getNodesInfo()){const P=E.node.footprint;E.hiddenByReplacement=!!P&&!k.find(O=>O.footprint===P)}}getHeightAtTileCoord(m,x){const k=[],E=[0,0,0],P=v([]);for(const O of this.getNodesInfo()){const U=O.node.meshes[0],H=U.transformedAabb;if(mH.max[0]||x>H.max[1])continue;if(O.node.hidden===!0)return{height:1/0,maxHeight:O.feature.properties.height,hidden:!1,verticalScale:O.evaluatedScale[2]};j(P,O.node.globalMatrix),E[0]=m,E[1]=x,Je(E,E,P);const X=(E[0]-U.aabb.min[0])/(U.aabb.max[0]-U.aabb.min[0])*e3|0,le=Math.min(63,(E[1]-U.aabb.min[1])/(U.aabb.max[1]-U.aabb.min[1])*e3|0)*e3+Math.min(63,X),he=U.heightmap[le];if(!(he<0&&O.node.footprint))return O.hiddenByReplacement?void 0:{height:he,maxHeight:O.feature.properties.height,hidden:!1,verticalScale:O.evaluatedScale[2]};if(O.node.footprint.grid.query(new Ms(m,x),new Ms(m,x),k),k.length>0)return{height:void 0,maxHeight:O.feature.properties.height,hidden:O.hiddenByReplacement,verticalScale:O.evaluatedScale[2]}}}}function zO(w,m){return w instanceof b0&&!w.isLightConstant&&m}function w5t(w,m,x,k,E,P,O,U){let H=(61440&m|(61440&m)>>4)>>8,X=(3840&m|(3840&m)>>4)>>4,le=240&m|(240&m)>>4;x[3]>0&&(H=Br(H,255*x[0],x[3]),X=Br(X,255*x[1],x[3]),le=Br(le,255*x[2],x[3]));const he=H<<8|X,me=le<<8|Math.floor(255*k[3]),be=function(wt){const Yt=Qe(wt,0,2);return Math.min(Math.round(.5*Yt*255),255)}(k[2])<<8|15*k[0]<<4|15*k[1],Se=Qe(E[0],0,1),Pe=Qe(E[1],0,1),Be=Qe(E[2],0,1),We=Qe(E[3],0,1);let ot,nt,ft,bt;if(Se!==Pe&&O!==P&&Pe!==Se){const wt=O-P;nt=1/(wt*(Pe-Se)),ft=-(P+wt*Se)/(wt*(Pe-Se));const Yt=Qe(E[4],-1,1);bt=Math.pow(10,Yt),ot=255*Be<<8|255*We}else ot=65535,nt=0,ft=1,bt=1;if(w.emplaceBack(he,me,be,ot,nt,ft,bt),U){const wt=U.length;U.clear();for(let Yt=0;Yt>16&65535,le=P?H>>16&65535:65535&H,he=(15&le)<8?15&le:0,me=w.evaluatedRMEA[he],be=w.evaluatedColor[he],Se=w.emissionHeightBasedParams[he];let Pe;if(U&&he===2&&k.lights&&(Pe=new D6,Pe.resize(10*k.lights.length)),w5t(O.featureArray,X,be,me,Se,O.aabb.min[2],O.aabb.max[2],Pe),Pe&&U){U=!1;const Be=k.meshes[k.lightMeshIndex];Be.featureArray=Pe,Be.featureArray._trim()}}O.featureArray._trim(),E++}}Yn(cV,"Tiled3dModelBucket",{omit:["layers"]}),Yn(BFe,"Tiled3dModelFeature");const N5t=["id","tile","layer","source","sourceLayer","state"];class i3{constructor(m,x,k,E,P){this.type="Feature",this._vectorTileFeature=m,this._z=x,this._x=k,this._y=E,this.properties=m?m.properties:{},this.id=P}clone(){const m=new i3(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(m.state=Object.assign({},this.state)),this.layer&&(m.layer=Object.assign({},this.layer)),this.source&&(m.source=this.source),this.sourceLayer&&(m.sourceLayer=this.sourceLayer),m}get geometry(){return this._geometry===void 0&&this._vectorTileFeature&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._x,this._y,this._z).geometry),this._geometry}set geometry(m){this._geometry=m}toJSON(){const m={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const x of N5t)this[x]!==void 0&&(m[x]=this[x]);return m}}class o3 extends Op{constructor(m,x,k,E){super(),this.id=m,this.type="model",this.models=[],this._options=x,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(m,x){return sOe(this.map._requestManager.transformRequest(m,h0.Model).url,x)}async loadModel(m,x,k){try{const E=await this.loadGLTFFromURI(x.uri,k);if(k.aborted)return;const P=this._modelsInfo.get(m);if(!P)return;const O=x_e(E),U=P.modelSpec,H=new oOe(m,U.uri,U.position,U.orientation,O);o3.applyModelSpecification(H,U),H.computeBoundsAndApplyParent(),this.models.push(H),P.model=H}catch(E){if(E instanceof Error&&E.name==="AbortError")return;const P=E instanceof Error?E.message:"Unknown error";this.fire(new sp(new Error(`Could not load model ${m} from ${x.uri}: ${P}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const m=this._abortController.signal,x=[];for(const k in this._options.models){const E=this._options.models[k],P=this._modelsInfo.get(k);if(P&&P.model){P.modelSpec=E;const O=P.model;O.position=E.position!=null?new rs(E.position[0],E.position[1]):new rs(0,0),O.orientation=E.orientation!=null?E.orientation:[0,0,0],o3.applyModelSpecification(O,E),O.computeBoundsAndApplyParent(),this.models.push(O)}else P?P.modelSpec=E:(this._modelsInfo.set(k,{modelSpec:E,model:null}),x.push(this.loadModel(k,E,m)))}x.length!==0?(await Promise.allSettled(x),m.aborted||this.fire(new Bc("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Bc("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(m,x){x.nodeOverrides&&o3.convertNodeOverrides(m,x.nodeOverrides),x.materialOverrides&&o3.convertMaterialOverrides(m,x.materialOverrides),x.nodeOverrideNames&&(m.nodeOverrideNames=[...x.nodeOverrideNames]),x.materialOverrideNames&&(m.materialOverrideNames=[...x.materialOverrideNames]),x.featureProperties&&(m.featureProperties=x.featureProperties)}static convertNodeOverrides(m,x){if(Array.isArray(x)&&x.every(k=>typeof k=="string")){m.nodeOverrideNames=[];for(const k of x)m.nodeOverrideNames.push(k)}else Object.entries(x).forEach(([k,E])=>{const P={orientation:[0,0,0]};if(E.hasOwnProperty("orientation")){const O=E.orientation;O&&(P.orientation=O)}m.nodeOverrides.set(k,P)})}static convertMaterialOverrides(m,x){if(Array.isArray(x)&&x.every(k=>typeof k=="string")){m.materialOverrideNames=[];for(const k of x)m.materialOverrideNames.push(k)}else Object.entries(x).forEach(([k,E])=>{const P={color:new Wn(1,1,1),colorMix:0,emissionStrength:0,opacity:1},O=E["model-color"];O!==void 0&&(P.color.r=O[0],P.color.g=O[1],P.color.b=O[2]);const U=E["model-color-mix-intensity"];U!==void 0&&(P.colorMix=U);const H=E["model-emissive-strength"];H!==void 0&&(P.emissionStrength=H);const X=E["model-opacity"];X!==void 0&&(P.opacity=X),m.materialOverrides.set(k,P)})}onAdd(m){this.map=m,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const m of this._modelsInfo.values())if(m.model==null)return!1;return!0}getModels(){return this.models}loadTile(m,x){}serialize(){return this._options}setProperty(m,x){return!1}reload(){this.cancelModelRequests();const m=yt(this.id,this.scope);this.map.style.clearSource(m),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(m){this.cancelModelRequests()}setModels(m){this.models=[];const x=new Map;for(const k in m){const E=m[k],P=this._modelsInfo.get(k);P&&P.modelSpec.uri===E.uri&&x.set(k,P)}if(this._modelsInfo.size!==x.size){this.cancelModelRequests();for(const[k,E]of x)E.model||x.delete(k)}this._modelsInfo=x,this._options.models=m,this.load()}}function Q_e(w,m,x,k){const E=1<H>=bt.vertexArrayOffset&&Hft.polygon).flat());const Be=be?U:null,[We,ot]=$Re(P,k,he,le,X,O,Be,me,Se,P.center.lat,w.tileID.canonical),nt=w.queryGeometry;return BRe(We,ot,nt.isPointQuery()?nt.screenBounds:nt.screenGeometry)}},building:class extends lo{constructor(w,m,x,k){super(w,{layout:pOe||(pOe=new Zo({visibility:new kn(fs.layout_building.visibility),"building-facade":new Nn(fs.layout_building["building-facade"]),"building-facade-floors":new Nn(fs.layout_building["building-facade-floors"]),"building-facade-unit-width":new Nn(fs.layout_building["building-facade-unit-width"]),"building-facade-window":new Nn(fs.layout_building["building-facade-window"]),"building-roof-shape":new Nn(fs.layout_building["building-roof-shape"]),"building-height":new Nn(fs.layout_building["building-height"]),"building-base":new Nn(fs.layout_building["building-base"]),"building-flood-light-wall-radius":new Nn(fs.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new Nn(fs.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new Nn(fs.layout_building["building-flip-roof-orientation"])})),paint:fOe||(fOe=new Zo({"building-opacity":new kn(fs.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new kn(fs.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new kn(fs.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new kn(fs.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new kn(fs.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new kn(fs.paint_building["building-vertical-scale"]),"building-cast-shadows":new kn(fs.paint_building["building-cast-shadows"]),"building-color":new Nn(fs.paint_building["building-color"]),"building-emissive-strength":new Nn(fs.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new kn(fs.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new kn(fs.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new kn(fs.paint_building["building-front-cutoff"]),"building-flood-light-color":new kn(fs.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new kn(fs.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new kn(fs.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new Nn({type:"string",default:"default","property-type":"data-driven"})}))},m,x,k),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(w){return new mOe(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,m,x,k,E,P,O,U,H,X){let le=this.layout.get("building-height").evaluate(m,x);const he=this.layout.get("building-base").evaluate(m,x),me=w.tile.getBucket(this).getFootprint(m);if(me){if(me.hiddenFlags!==0)return!1;le=me.height}const[be,Se]=$Re(P,k,he,le,new Ms(0,0),O,null,[0,0],1,P.center.lat,w.tileID.canonical),Pe=w.queryGeometry;return BRe(be,Se,Pe.isPointQuery()?Pe.screenBounds:Pe.screenGeometry)}},line:class extends lo{constructor(w,m,x,k){const E=kOe();super(w,E,m,x,k),E.layout&&(this.layout=new Qd(E.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(w){if(w==="line-gradient"){const m=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=m._styleExpression&&m._styleExpression.expression instanceof kj,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}widthExpression(){return this._transitionablePaint._values["line-width"].value.expression}emissiveStrengthExpression(){return this._transitionablePaint._values["line-emissive-strength"].value.expression}recalculate(w,m){super.recalculate(w,m),this.paint._values["line-floorwidth"]=(()=>{if(kO)return kO;const x=kOe();return kO=new y3t(x.paint.properties["line-width"].specification),kO.useIntegerZoom=!0,kO})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,w)}createBucket(w){return new qq(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,m,x){if(w==="lineBlendComposite")return{};const k=jOe(this);return{config:new Le(this,{zoom:m,lut:x}),defines:k,overrideFog:!1}}queryRadius(w){const m=w,x=SOe(uk("line-width",this,m),uk("line-gap-width",this,m)),k=uk("line-offset",this,m);return x/2+Math.abs(k)+mq(this.paint.get("line-translate"))}queryIntersectsFeature(w,m,x,k,E,P){if(w.queryGeometry.isAboveHorizon)return!1;const O=NDe(w.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),P.angle,w.pixelToTileUnitsFactor),U=w.pixelToTileUnitsFactor/2*SOe(this.paint.get("line-width").evaluate(m,x),this.paint.get("line-gap-width").evaluate(m,x)),H=this.paint.get("line-offset").evaluate(m,x);return H&&(k=function(X,le){const he=[],me=new Ms(0,0);for(let be=0;be=3){for(let Se=0;Se{this._triggered=!1,this._callback()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout(()=>{this._triggered=!1,this._callback()},0))}remove(){this._channel=void 0,this._callback=()=>{}}}class $Fe{constructor(m){this._stringToNumber={},this._numberToString=[];for(let x=0;x=0&&me[3]>=0&&X.insert(H,me[0],me[1],me[2],me[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new Vi(new Vq(this.rawTileData)).layers,this.sourceLayerCoder=new $Fe(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const m in this.vtLayers)this.vtFeatures[m]=[]}return this.vtLayers}query(m,x){const{tilespaceGeometry:k,transform:E,tileTransform:P,pixelPosMatrix:O,availableImages:U,worldview:H}=x;this.loadVTLayers(),this.serializedLayersCache.clear();const X=x.queryRadius?x.queryRadius:0,le=k.bufferedTilespaceBounds,he=this.grid.query(le.min.x,le.min.y,le.max.x,le.max.y,(Pe,Be,We,ot)=>y_(k.bufferedTilespaceGeometry,Pe-X,Be-X,We+X,ot+X));he.sort(T5t);let me=null;E.elevation&&he.length>0&&(me=tI.create(E.elevation,this.tileID));const be={};let Se;for(let Pe=0;Pe(ot||(ot=Kr(nt,this.tileID.canonical,P)),ft.queryIntersectsFeature(k,nt,bt,ot,this.z,E,O,me,wt,x.scope)))}return be}loadMatchingFeature(m,x,k,E,P,O){const{featureIndex:U,bucketIndex:H,sourceLayerIndex:X,layoutVertexArrayOffset:le}=x,he=this.bucketLayerIDs[H],me=k.layers,be=Object.keys(me);if(be.length&&!br(be,he))return;const Se=k.sourceCache,Pe=this.sourceLayerCoder.decode(X),Be=this.vtLayers[Pe].feature(U),We=this.getId(Be,Pe);for(let ot=0;ot`${U.key}: ${U.message}`).join(", ");return void sr(`Failed to create expression for promoteId: ${O}`)}this.promoteIdExpression=P.value}k=this.promoteIdExpression.evaluate({zoom:0},m)}else k=m.properties[E];typeof k=="boolean"&&(k=Number(k))}return k}}function qFe(w,m,x,k,E){return ln(w,(P,O)=>{const U=m instanceof Qd?m.get(O):null;return U&&U.evaluate?U.evaluate(x,k,void 0,E):U})}function T5t(w,m){return m-w}function VFe(w,m){const x={};if(!m)return x;for(const k of w){const E=k.layerIds.map(P=>m.getLayer(P)).filter(Boolean);if(E.length!==0){k.layers=E,k.stateDependentLayerIds&&(k.stateDependentLayers=k.stateDependentLayerIds.map(P=>E.filter(O=>O.id===P)[0]));for(const P of E)x[P.fqid]=k}}return x}Yn(UFe,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const ev=32,k_=33,yk=new Uint16Array(8184);for(let w=0;w<2046;w++){let m=w+2,x=0,k=0,E=0,P=0,O=0,U=0;for(1&m?E=P=O=ev:x=k=U=ev;(m>>=1)>1;){const X=x+E>>1,le=k+P>>1;1&m?(E=x,P=k,x=O,k=U):(x=E,k=P,E=O,P=U),O=X,U=le}const H=4*w;yk[H+0]=x,yk[H+1]=k,yk[H+2]=E,yk[H+3]=P}const S_=new Uint16Array(2178),vk=new Uint8Array(1089),dV=new Uint16Array(1089);function HFe(w){return w===0?-.03125:w===32?.03125:0}const GFe={Other:0,Symbol:1,FillExtrusion:2},WFe={type:2,extent:Bn,loadGeometry:()=>[[new Ms(0,0),new Ms(8193,0),new Ms(8193,8193),new Ms(0,8193),new Ms(0,0)]]};class E5t{constructor(){this.tasks={},this.taskQueue=[],Ns(["process"],this),this.invoker=new C5t(this.process),this.nextId=0}add(m,x){const k=this.nextId++,E=function({type:P,renderSourceType:O,zoom:U}){U=U||0;const H=O===GFe.Symbol;return P==="message"?0:P!=="maybePrepare"||H?P!=="parseTile"||H?P==="parseTile"&&H?300-U:P==="maybePrepare"&&H?400-U:500:200-U:100-U}(x);if(E===0){try{m()}finally{}return null}return this.tasks[k]={fn:m,metadata:x,priority:E,id:k},this.taskQueue.push(k),this.invoker.trigger(),{cancel:()=>{delete this.tasks[k]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(k=>!!this.tasks[k]),!this.taskQueue.length)return;const m=this.pick();if(m===null)return;const x=this.tasks[m];if(delete this.tasks[m],this.taskQueue.length&&this.invoker.trigger(),!x)return;x.fn()}finally{}}pick(){let m=null,x=1/0;for(let E=0;E>16&255)/255,(w>>8&255)/255,(255&w)/255,1)}function $5t(w,m,x){w===1?(m.rgb_color=mV(x.readVarint()),m.paint="rgb_color"):w===2?(m.linear_gradient_idx=x.readVarint(),m.paint="linear_gradient_idx"):w===3?(m.radial_gradient_idx=x.readVarint(),m.paint="radial_gradient_idx"):w===5?x.readPackedFloat(m.dasharray):w===6?m.dashoffset=x.readFloat():w===7?m.miterlimit=x.readFloat():w===8?m.opacity=x.readVarint():w===9?m.width=x.readFloat():w===10?m.linecap=x.readVarint():w===11&&(m.linejoin=x.readVarint())}function U5t(w,m,x){w===1?m.transform=hV(x,x.readVarint()+x.pos):w===2?m.spread_method=x.readVarint():w===3?m.stops.push(ZFe(x,x.readVarint()+x.pos)):w===4?m.x1=x.readFloat():w===5?m.y1=x.readFloat():w===6?m.x2=x.readFloat():w===7&&(m.y2=x.readFloat())}function ZFe(w,m){return w.readFields(q5t,{offset:0,opacity:255,rgb_color:X_e},m)}function q5t(w,m,x){w===1?m.offset=x.readFloat():w===2?m.opacity=x.readVarint():w===3&&(m.rgb_color=mV(x.readVarint()))}function V5t(w,m,x){w===1?m.transform=hV(x,x.readVarint()+x.pos):w===2?m.spread_method=x.readVarint():w===3?m.stops.push(ZFe(x,x.readVarint()+x.pos)):w===4?m.cx=x.readFloat():w===5?m.cy=x.readFloat():w===6?m.r=x.readFloat():w===7?m.fx=x.readFloat():w===8?m.fy=x.readFloat():w===9&&(m.fr=x.readFloat())}function H5t(w,m,x){w===1?m.transform=hV(x,x.readVarint()+x.pos):w===2?m.clip_path_idx=x.readVarint():w===3&&m.children.push(uV(x,x.readVarint()+x.pos))}function G5t(w,m,x){w===1?m.left=m.top=x.readFloat():w===2?m.width=m.height=x.readFloat():w===3?m.top=x.readFloat():w===4?m.height=x.readFloat():w===5?m.mask_type=x.readVarint():w===6?m.mask_idx=x.readVarint():w===7&&m.children.push(uV(x,x.readVarint()+x.pos))}class W5t{static calculate(m={},x=[]){const k=new Map,E=new Map;if(Object.keys(m).length===0)return k;x.forEach(P=>{E.set(P.name,P.rgb_color||new Wn(0,0,0))});for(const[P,O]of Object.entries(m))E.has(P)?k.set(E.get(P).toString(),O):console.warn(`Ignoring unknown image variable "${P}"`);return k}}function sI(w,m=255,x){const k=m/255,E=w.toString(),P=x.has(E)?x.get(E).clone():w.clone();return P.a*=k,P.toString()}function BO(w,m){if(!uc()){const x=document.createElement("canvas");return x.width=w,x.height=m,x}return new OffscreenCanvas(w,m)}let J_e,$O=null;function ewe(w,m,x,k,E){for(const P of k.children)QFe(w,m,x,P,E)}function QFe(w,m,x,k,E){k.group?(w.save(),function(P,O,U,H,X){const le=H.mask_idx!=null?U.masks[H.mask_idx]:null,he=H.clip_path_idx!=null?U.clip_paths[H.clip_path_idx]:null;if(H.transform&&(O=nI(H.transform).preMultiplySelf(O)),!function(Se,Pe,Be){return Se.opacity!==255||Pe||Be}(H,he!=null,le!=null))return void ewe(P,O,U,H,X);const me=BO(P.canvas.width,P.canvas.height),be=me.getContext("2d");ewe(be,O,U,H,X),he&&r7e(be,O,U,he),le&&a7e(be,O,U,le,X),P.globalAlpha=H.opacity/255,P.drawImage(me,0,0)}(w,m,x,k.group,E),w.restore()):k.path&&(w.save(),function(P,O,U,H,X){P.setTransform(O),H.paint_order===1?(XFe(P,U,H,X),e7e(P,U,H,X)):(e7e(P,U,H,X),XFe(P,U,H,X))}(w,m,x,k.path,E),w.restore())}function XFe(w,m,x,k){const E=x.fill;if(!E)return;const P=E.opacity/255;switch(w.save(),w.beginPath(),i7e(x,w),E.paint){case"rgb_color":w.fillStyle=sI(E.rgb_color,E.opacity,k);break;case"linear_gradient_idx":{const O=m.linear_gradients[E.linear_gradient_idx];O.transform&&w.setTransform(nI(O.transform).preMultiplySelf(w.getTransform())),w.fillStyle=t7e(w,O,P,k);break}case"radial_gradient_idx":{const O=m.radial_gradients[E.radial_gradient_idx];O.transform&&w.setTransform(nI(O.transform).preMultiplySelf(w.getTransform())),w.fillStyle=s7e(w,O,P,k)}}w.fill(JFe(x)),w.restore()}function JFe(w){return w.rule===1?"nonzero":w.rule===2?"evenodd":void 0}function e7e(w,m,x,k){const E=x.stroke;if(!E)return;const P=o7e(x);w.lineWidth=E.width,w.miterLimit=E.miterlimit,w.setLineDash(E.dasharray),w.lineDashOffset=E.dashoffset;const O=E.opacity/255;switch(E.paint){case"rgb_color":w.strokeStyle=sI(E.rgb_color,E.opacity,k);break;case"linear_gradient_idx":w.strokeStyle=t7e(w,m.linear_gradients[E.linear_gradient_idx],O,k,!0);break;case"radial_gradient_idx":w.strokeStyle=s7e(w,m.radial_gradients[E.radial_gradient_idx],O,k,!0)}switch(E.linejoin){case 2:case 1:w.lineJoin="miter";break;case 3:w.lineJoin="round";break;case 4:w.lineJoin="bevel"}switch(E.linecap){case 1:w.lineCap="butt";break;case 2:w.lineCap="round";break;case 3:w.lineCap="square"}w.stroke(P)}function t7e(w,m,x,k,E=!1){if(m.stops.length===1){const me=m.stops[0];return sI(me.rgb_color,me.opacity*x,k)}const{x1:P,y1:O,x2:U,y2:H}=m;let X=new DOMPoint(P,O),le=new DOMPoint(U,H);if(E){const me=nI(m.transform);X=me.transformPoint(X),le=me.transformPoint(le)}const he=w.createLinearGradient(X.x,X.y,le.x,le.y);for(const me of m.stops)he.addColorStop(me.offset,sI(me.rgb_color,me.opacity*x,k));return he}function s7e(w,m,x,k,E=!1){if(m.stops.length===1){const We=m.stops[0];return sI(We.rgb_color,We.opacity*x,k)}const P=nI(m.transform),{fx:O,fy:U,fr:H,cx:X,cy:le,r:he}=m;let me=new DOMPoint(O,U),be=new DOMPoint(X,le),Se=H,Pe=he;if(E){me=P.transformPoint(me),be=P.transformPoint(be);const We=(P.a+P.d)/2;Se=H*We,Pe=m.r*We}const Be=w.createRadialGradient(me.x,me.y,Se,be.x,be.y,Pe);for(const We of m.stops)Be.addColorStop(We.offset,sI(We.rgb_color,We.opacity*x,k));return Be}function n7e(w,m,x,k){const E=k.transform?nI(k.transform).preMultiplySelf(m):m,P=BO(w.canvas.width,w.canvas.height),O=P.getContext("2d");for(const H of k.children)if(H.group)n7e(O,E,x,H.group);else if(H.path){const X=H.path,le=new Path2D;le.addPath(o7e(X),E),O.fill(le,JFe(X))}const U=k.clip_path_idx!=null?x.clip_paths[k.clip_path_idx]:null;U&&r7e(O,E,x,U),w.globalCompositeOperation="source-over",w.drawImage(P,0,0)}function r7e(w,m,x,k){const E=BO(w.canvas.width,w.canvas.height);n7e(E.getContext("2d"),m,x,k),w.globalCompositeOperation="destination-in",w.drawImage(E,0,0)}function a7e(w,m,x,k,E){if(k.children.length===0)return;const P=k.mask_idx!=null?x.masks[k.mask_idx]:null;P&&a7e(w,m,x,P,E);const O=w.canvas.width,U=w.canvas.height,H=BO(O,U),X=H.getContext("2d"),le=k.width,he=k.height,me=k.left,be=k.top,Se=new Path2D,Pe=new Path2D;Pe.rect(me,be,le,he),Se.addPath(Pe,m),X.clip(Se);for(const ot of k.children)QFe(X,m,x,ot,E);const Be=X.getImageData(0,0,O,U),We=Be.data;if(k.mask_type===1)for(let ot=0;otm[O])return null}else{const U=1/k[O];let H=(w[O]-x[O])*U,X=(m[O]-x[O])*U;if(H>X){const le=H;H=X,X=le}if(H>E&&(E=H),XP)return null}return E}function d7e(w,m,x,k,E,P,O,U,H,X,le){const he=k-w,me=E-m,be=P-x,Se=O-w,Pe=U-m,Be=H-x,We=le[1]*Be-le[2]*Pe,ot=le[2]*Se-le[0]*Be,nt=le[0]*Pe-le[1]*Se,ft=he*We+me*ot+be*nt;if(Math.abs(ft)<1e-15)return null;const bt=1/ft,wt=X[0]-w,Yt=X[1]-m,zt=X[2]-x,Kt=(wt*We+Yt*ot+zt*nt)*bt;if(Kt<0||Kt>1)return null;const Vt=Yt*be-zt*me,Ht=zt*he-wt*be,Os=wt*me-Yt*he,Vs=(le[0]*Vt+le[1]*Ht+le[2]*Os)*bt;return Vs<0||Kt+Vs>1?null:(Se*Vt+Pe*Ht+Be*Os)*bt}function u7e(w,m,x){return(w-m)/(x-m)}function h7e(w,m,x,k,E,P,O,U,H){const X=1<{const ot=Be?1:0,nt=(be+1)*Pe-ot,ft=Se*Pe,bt=(Se+1)*Pe-ot;We[0]=be*Pe,We[1]=ft,We[2]=nt,We[3]=bt};let he=new l7e(H);const me=[];for(let be=0;be=1;H/=2){const be=U[U.length-1];he=new l7e(H);for(let Se=0;Se0;){const{idx:Se,t:Pe,nodex:Be,nodey:We,depth:ot}=be.pop();if(this.leaves[Se]){h7e(Be,We,ot,m,x,k,E,he,me);const ft=1<=en[2])return Pe}continue}let nt=0;for(let ft=0;ft=X[le[zt]]&&(le.splice(zt,0,ft),Yt=!0);Yt||(le[nt]=ft),nt++}}for(let ft=0;ft=this.dim+1||x<-1||x>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(x+1)*this.stride+(m+1)}static pack(m,x){const k=[0,0,0,0],E=fV.getUnpackVector(x);let P=Math.floor((m+E[3])/E[2]);return k[2]=P%256,P=Math.floor(P/256),k[1]=P%256,P=Math.floor(P/256),k[0]=P,k}getPixels(){return new YDe({width:this.stride,height:this.stride},this.pixels)}backfillBorder(m,x,k){if(this.dim!==m.dim)throw new Error("dem dimension mismatch");let E=x*this.dim,P=x*this.dim+this.dim,O=k*this.dim,U=k*this.dim+this.dim;switch(x){case-1:E=P-1;break;case 1:P=E+1}switch(k){case-1:O=U-1;break;case 1:U=O+1}const H=-x*this.dim,X=-k*this.dim;for(let le=O;le=1;k--){const E=k===1?1:0,P=k===2?1:0;for(let O=0;O>>1^-(1&w[m]);return w}function oTt(w,m){switch(m){case"uint32":return w;case"uint16":for(let x=0;x>4|(61440&k)>>8|(240&E)<<4|61440&E,w[x+1]=15&k|(3840&k)>>4|(15&E)<<8|(3840&E)<<4}return w;case"uint8":for(let x=0;x>6|(192&E)>>4|(192&P)>>2|192&O,w[x+1]=(48&k)>>4|(48&E)>>2|48&P|(48&O)<<2,w[x+2]=(12&k)>>2|12&E|(12&P)<<2|(12&O)<<4,w[x+3]=3&k|(3&E)<<2|(3&P)<<4|(3&O)<<6}return w;default:throw new Error(`Invalid pixel format, "${m}"`)}}Yn(fV,"DEMData"),Yn(m7e,"DemMinMaxQuadTree",{omit:["dem"]});var C0=Uint8Array,UO=Uint16Array,lTt=Int32Array,f7e=new C0([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]),x7e=new C0([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]),cTt=new C0([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),g7e=function(w,m){for(var x=new UO(31),k=0;k<31;++k)x[k]=m+=1<>1|(21845&Ad)<<1;b7e[Ad]=((65280&(rI=(61680&(rI=(52428&rI)>>2|(13107&rI)<<2))>>4|(3855&rI)<<4))>>8|(255&rI)<<8)>>1}var qO=function(w,m,x){for(var k=w.length,E=0,P=new UO(m);E>H]=X;return O},VO=new C0(288);for(Ad=0;Ad<144;++Ad)VO[Ad]=8;for(Ad=144;Ad<256;++Ad)VO[Ad]=9;for(Ad=256;Ad<280;++Ad)VO[Ad]=7;for(Ad=280;Ad<288;++Ad)VO[Ad]=8;var _7e=new C0(32);for(Ad=0;Ad<32;++Ad)_7e[Ad]=5;var hTt=qO(VO,9),mTt=qO(_7e,5),swe=function(w){for(var m=w[0],x=1;xm&&(m=w[x]);return m},P1=function(w,m,x){var k=m/8|0;return(w[k]|w[k+1]<<8)>>(7&m)&x},nwe=function(w,m){var x=m/8|0;return(w[x]|w[x+1]<<8|w[x+2]<<16)>>(7&m)},pTt=function(w){return(w+7)/8|0},fTt=["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"],L1=function(w,m,x){var k=new Error(m||fTt[w]);if(k.code=w,Error.captureStackTrace&&Error.captureStackTrace(k,L1),!x)throw k;return k},xTt=new C0(0),gTt=typeof TextDecoder<"u"&&new TextDecoder;try{gTt.decode(xTt,{stream:!0})}catch{}const yTt={gzip_data:"gzip"};class tv extends Error{constructor(m){super(m),this.name="MRTError"}}const vTt={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},w7e={uint32:1,uint16:2,uint8:4},bTt={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let rwe;class xV{constructor(m=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=m}getLayer(m){const x=this.layers[m];if(!x)throw new tv(`Layer '${m}' not found`);return x}getHeaderLength(m){const x=new Uint8Array(m),k=new DataView(m);if(x[0]!==13)throw new tv("File is not a valid MRT.");return k.getUint32(1,!0)}parseHeader(m){const x=new Uint8Array(m),k=this.getHeaderLength(m);if(x.length= ${k} but got buffer of length ${x.length}`);const E=new rwe(x.subarray(0,k)).readFields(Q5t,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==E.x||this.y!==E.y||this.z!==E.z))throw new tv(`Invalid attempt to parse header ${E.z}/${E.x}/${E.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=E.x,this.y=E.y,this.z=E.z;for(const P of E.layers)this.layers[P.name]=new j7e(P,{cacheSize:this._cacheSize});return this}createDecodingTask(m){const x=[],k=this.getLayer(m.layerName);for(let E of m.blockIndices){const P=k.dataIndex[E],O=P.firstByte-m.firstByte,U=P.lastByte-m.firstByte;if(k._blocksInProgress.has(E))continue;const H={layerName:k.name,firstByte:O,lastByte:U,pixelFormat:k.pixelFormat,blockIndex:E,blockShape:[P.bands.length].concat(k.bandShape),buffer:k.buffer,codec:P.codec.codec,filters:P.filters.map(X=>X.filter)};k._blocksInProgress.add(E),x.push(H)}return new N7e(x,()=>{x.forEach(E=>k._blocksInProgress.delete(E.blockIndex))},(E,P)=>{if(x.forEach(O=>k._blocksInProgress.delete(O.blockIndex)),E)throw E;P.forEach(O=>{this.getLayer(O.layerName).processDecodedData(O)})})}}class j7e{constructor({version:m,name:x,units:k,tileSize:E,pixelFormat:P,buffer:O,dataIndex:U},H){if(this.version=m,this.version!==1)throw new tv(`Cannot parse raster layer encoded with MRT version ${m}`);this.name=x,this.units=k,this.tileSize=E,this.buffer=O,this.pixelFormat=vTt[P],this.dataIndex=U,this.bandShape=[E+2*O,E+2*O,w7e[this.pixelFormat]],this._decodedBlocks=new pV(H?H.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return w7e[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:m})=>m).flat()}processDecodedData(m){const x=m.blockIndex.toString();this._decodedBlocks.get(x)||this._decodedBlocks.put(x,m.data)}getBlockForBand(m){let x=0;switch(typeof m){case"string":for(const[k,E]of this.dataIndex.entries()){for(const[P,O]of E.bands.entries())if(O===m)return{bandIndex:x+P,blockIndex:k,blockBandIndex:P};x+=E.bands.length}break;case"number":for(const[k,E]of this.dataIndex.entries()){if(m>=x&&mthis.cacheSize)throw new tv(`Number of blocks to decode (${P.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:x,lastByte:k,blockIndices:E}}hasBand(m){const{blockIndex:x}=this.getBlockForBand(m);return x>=0}hasDataForBand(m){const{blockIndex:x}=this.getBlockForBand(m);return x>=0&&!!this._decodedBlocks.get(x.toString())}getBandView(m){const{blockIndex:x,blockBandIndex:k}=this.getBlockForBand(m);if(x<0)throw new tv(`Band not found: ${JSON.stringify(m)}`);const E=this._decodedBlocks.get(x.toString());if(!E)throw new tv(`Data for band ${JSON.stringify(m)} of layer "${this.name}" not decoded.`);const P=this.dataIndex[x],O=this.bandShape.reduce((X,le)=>X*le,1),U=k*O,H=E.subarray(U,U+O);return{data:H,bytes:new Uint8Array(H.buffer).subarray(H.byteOffset,H.byteOffset+H.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:P.offset,scale:P.scale}}}xV.setPbf=function(w){rwe=w};class N7e{constructor(m,x,k){this.tasks=m,this._onCancel=x,this._onComplete=k,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(m,x){this._finalized||(this._onComplete(m,x),this._finalized=!0)}}xV.performDecoding=function(w,m){const x=new Uint8Array(w);return Promise.all(m.tasks.map(k=>{const{layerName:E,firstByte:P,lastByte:O,pixelFormat:U,blockShape:H,blockIndex:X,filters:le,codec:he}=k,me=x.subarray(P,O+1),be=new Uint32Array(H[0]*H[1]*H[2]);let Se;if(he!=="gzip_data")throw new tv(`Unhandled codec: ${he}`);return Se=function(Pe,Be){if(!globalThis.DecompressionStream&&Be==="gzip_data")return Promise.resolve((bt=function(zt){zt[0]==31&&zt[1]==139&&zt[2]==8||L1(6,"invalid gzip data");var Kt=zt[3],Vt=10;4&Kt&&(Vt+=2+(zt[10]|zt[11]<<8));for(var Ht=(Kt>>3&1)+(Kt>>4&1);Ht>0;Ht-=!zt[Vt++]);return Vt+(2&Kt)}(We=Pe),bt+8>We.length&&L1(6,"invalid gzip data"),function(zt,Kt,Vt,Ht){var Os=zt.length;if(!Os||Kt.f&&!Kt.l)return Vt||new C0(0);var Vs=!Vt,Js=Vs||Kt.i!=2,nn=Kt.i;Vs&&(Vt=new C0(3*Os));var en=function(Bl){var Sm=Vt.length;if(Bl>Sm){var Nu=new C0(Math.max(2*Sm,Bl));Nu.set(Vt),Vt=Nu}},xn=Kt.f||0,Ls=Kt.p||0,tn=Kt.b||0,on=Kt.l,gn=Kt.d,En=Kt.m,ir=Kt.n,On=8*Os;do{if(!on){xn=P1(zt,Ls,1);var Rn=P1(zt,Ls+1,3);if(Ls+=3,!Rn){var An=zt[(Ji=pTt(Ls)+4)-4]|zt[Ji-3]<<8,nr=Ji+An;if(nr>Os){nn&&L1(0);break}Js&&en(tn+An),Vt.set(zt.subarray(Ji,nr),tn),Kt.b=tn+=An,Kt.p=Ls=8*nr,Kt.f=xn;continue}if(Rn==1)on=hTt,gn=mTt,En=9,ir=5;else if(Rn==2){var pr=P1(zt,Ls,31)+257,Gr=P1(zt,Ls+10,15)+4,Sr=pr+P1(zt,Ls+5,31)+1;Ls+=14;for(var Ma=new C0(Sr),ki=new C0(19),Ia=0;Ia>4)<16)Ma[Ia++]=Ji;else{var Ro=0,Il=0;for(Ji==16?(Il=3+P1(zt,Ls,3),Ls+=2,Ro=Ma[Ia-1]):Ji==17?(Il=3+P1(zt,Ls,7),Ls+=3):Ji==18&&(Il=11+P1(zt,Ls,127),Ls+=7);Il--;)Ma[Ia++]=Ro}}var eu=Ma.subarray(0,pr),Pl=Ma.subarray(pr);En=swe(eu),ir=swe(Pl),on=qO(eu,En),gn=qO(Pl,ir)}else L1(1);if(Ls>On){nn&&L1(0);break}}Js&&en(tn+131072);for(var nc=(1<>4;if((Ls+=15&Ro)>On){nn&&L1(0);break}if(Ro||L1(2),Sh<256)Vt[tn++]=Sh;else{if(Sh==256){rc=Ls,on=null;break}var tu=Sh-254;Sh>264&&(tu=P1(zt,Ls,(1<<(pc=f7e[Ia=Sh-257]))-1)+v7e[Ia],Ls+=pc);var ei=gn[nwe(zt,Ls)&qc],hp=ei>>4;if(ei||L1(3),Ls+=15&ei,Pl=uTt[hp],hp>3){var pc=x7e[hp];Pl+=nwe(zt,Ls)&(1<On){nn&&L1(0);break}Js&&en(tn+131072);var ju=tn+tu;if(tnBl.length)&&(Nu=Bl.length),new C0(Bl.subarray(0,Nu))}(Vt,0,tn):Vt.subarray(0,tn)}(We.subarray(bt,-8),{i:2},new C0(((nt=We)[(ft=nt.length)-4]|nt[ft-3]<<8|nt[ft-2]<<16|nt[ft-1]<<24)>>>0),ot)));var We,ot,nt,ft,bt;const wt=yTt[Be];if(!wt)throw new Error(`Unhandled codec: ${Be}`);const Yt=new globalThis.DecompressionStream(wt);return new Response(new Blob([Pe]).stream().pipeThrough(Yt)).arrayBuffer().then(zt=>new Uint8Array(zt))}(me,he).then(Pe=>(function(Be,We){Be.readFields(nTt,We)}(new rwe(Pe),be),new bTt[U](be.buffer))),Se.then(Pe=>{for(let Be=le.length-1;Be>=0;Be--)switch(le[Be]){case"delta_filter":aTt(Pe,H);break;case"zigzag_filter":iTt(Pe);break;case"bitshuffle_filter":oTt(Pe,U);break;default:throw new tv(`Unhandled filter "${le[Be]}"`)}return{layerName:E,blockIndex:X,data:Pe}}).catch(Pe=>{throw Pe})}))},Yn(N7e,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),Yn(xV,"MapboxRasterTile"),Yn(j7e,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const k7e=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class awe{static from(m){if(!(m instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[x,k]=new Uint8Array(m,0,2);if(x!==219)throw new Error("Data does not appear to be in a KDBush format.");const E=k>>4;if(E!==1)throw new Error(`Got v${E} data when expected v1.`);const P=k7e[15&k];if(!P)throw new Error("Unrecognized array type.");const[O]=new Uint16Array(m,2,1),[U]=new Uint32Array(m,4,1);return new awe(U,O,P,m)}constructor(m,x=64,k=Float64Array,E){if(isNaN(m)||m<0)throw new Error(`Unpexpected numItems value: ${m}.`);this.numItems=+m,this.nodeSize=Math.min(Math.max(+x,2),65535),this.ArrayType=k,this.IndexArrayType=m<65536?Uint16Array:Uint32Array;const P=k7e.indexOf(this.ArrayType),O=2*m*this.ArrayType.BYTES_PER_ELEMENT,U=m*this.IndexArrayType.BYTES_PER_ELEMENT,H=(8-U%8)%8;if(P<0)throw new Error(`Unexpected typed array class: ${k}.`);E&&E instanceof ArrayBuffer?(this.data=E,this.ids=new this.IndexArrayType(this.data,8,m),this.coords=new this.ArrayType(this.data,8+U+H,2*m),this._pos=2*m,this._finished=!0):(this.data=new ArrayBuffer(8+O+U+H),this.ids=new this.IndexArrayType(this.data,8,m),this.coords=new this.ArrayType(this.data,8+U+H,2*m),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+P]),new Uint16Array(this.data,2,1)[0]=x,new Uint32Array(this.data,4,1)[0]=m)}add(m,x){const k=this._pos>>1;return this.ids[k]=k,this.coords[this._pos++]=m,this.coords[this._pos++]=x,k}finish(){const m=this._pos>>1;if(m!==this.numItems)throw new Error(`Added ${m} items when expected ${this.numItems}.`);return iwe(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(m,x,k,E){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:P,coords:O,nodeSize:U}=this,H=[0,P.length-1,0],X=[];for(;H.length;){const le=H.pop()||0,he=H.pop()||0,me=H.pop()||0;if(he-me<=U){for(let Be=me;Be<=he;Be++){const We=O[2*Be],ot=O[2*Be+1];We>=m&&We<=k&&ot>=x&&ot<=E&&X.push(P[Be])}continue}const be=me+he>>1,Se=O[2*be],Pe=O[2*be+1];Se>=m&&Se<=k&&Pe>=x&&Pe<=E&&X.push(P[be]),(le===0?m<=Se:x<=Pe)&&(H.push(me),H.push(be-1),H.push(1-le)),(le===0?k>=Se:E>=Pe)&&(H.push(be+1),H.push(he),H.push(1-le))}return X}within(m,x,k){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:E,coords:P,nodeSize:O}=this,U=[0,E.length-1,0],H=[],X=k*k;for(;U.length;){const le=U.pop()||0,he=U.pop()||0,me=U.pop()||0;if(he-me<=O){for(let Be=me;Be<=he;Be++)C7e(P[2*Be],P[2*Be+1],m,x)<=X&&H.push(E[Be]);continue}const be=me+he>>1,Se=P[2*be],Pe=P[2*be+1];C7e(Se,Pe,m,x)<=X&&H.push(E[be]),(le===0?m-k<=Se:x-k<=Pe)&&(U.push(me),U.push(be-1),U.push(1-le)),(le===0?m+k>=Se:x+k>=Pe)&&(U.push(be+1),U.push(he),U.push(1-le))}return H}}function iwe(w,m,x,k,E,P){if(E-k<=x)return;const O=k+E>>1;S7e(w,m,O,k,E,P),iwe(w,m,x,k,O-1,1-P),iwe(w,m,x,O+1,E,1-P)}function S7e(w,m,x,k,E,P){for(;E>k;){if(E-k>600){const X=E-k+1,le=x-k+1,he=Math.log(X),me=.5*Math.exp(2*he/3),be=.5*Math.sqrt(he*me*(X-me)/X)*(le-X/2<0?-1:1);S7e(w,m,x,Math.max(k,Math.floor(x-le*me/X+be)),Math.min(E,Math.floor(x+(X-le)*me/X+be)),P)}const O=m[2*x+P];let U=k,H=E;for(HO(w,m,k,x),m[2*E+P]>O&&HO(w,m,k,E);UO;)H--}m[2*k+P]===O?HO(w,m,k,H):(H++,HO(w,m,H,E)),H<=x&&(k=H+1),x<=H&&(E=H-1)}}function HO(w,m,x,k){owe(w,x,k),owe(m,2*x,2*k),owe(m,2*x+1,2*k+1)}function owe(w,m,x){const k=w[m];w[m]=w[x],w[x]=k}function C7e(w,m,x,k){const E=w-x,P=m-k;return E*E+P*P}o.$=Vy,o.A=class{constructor(w,m,x){this.target=w,this.parent=m,this.mapId=x,this.callbacks={},this.cancelCallbacks={},Ns(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new E5t}send(w,m,x,k,E=!1,P){const O=Math.round(1e18*Math.random()).toString(36).substring(0,10);x&&(x.metadata=P,this.callbacks[O]=x);const U=new Set;return this.target.postMessage({id:O,type:w,hasCallback:!!x,targetMapId:k,mustQueue:E,sourceMapId:this.mapId,data:hc(m,U)},U),{cancel:()=>{x&&delete this.callbacks[O],this.target.postMessage({id:O,type:"",targetMapId:k,sourceMapId:this.mapId})}}}receive(w){const m=w.data;if(!m)return;const x=m.id;if(x&&(!m.targetMapId||this.mapId===m.targetMapId))if(m.type===""){const k=this.cancelCallbacks[x];delete this.cancelCallbacks[x],k&&k.cancel()}else if(m.mustQueue||kr(self)){const k=this.callbacks[x],E=this.scheduler.add(()=>this.processTask(x,m),k&&k.metadata||{type:"message"});E&&(this.cancelCallbacks[x]=E)}else this.processTask(x,m)}processTask(w,m){if(delete this.cancelCallbacks[w],m.type===""){const x=this.callbacks[w];delete this.callbacks[w],x&&(m.error?x(tc(m.error)):x(null,tc(m.data)))}else{const x=new Set,k=m.hasCallback?(P,O)=>{this.target.postMessage({id:w,type:"",sourceMapId:this.mapId,error:P?hc(P):null,data:hc(O,x)},x)}:()=>{},E=tc(m.data);if(this.parent[m.type])this.parent[m.type](m.sourceMapId,E,k);else if(this.parent.getWorkerSource){const P=m.type.split("."),{source:O,scope:U}=E;this.parent.getWorkerSource(m.sourceMapId,{type:P[0],source:O,scope:U,uid:0})[P[1]](E,k)}else k(new Error(`Could not find function ${m.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=sp,o.C=Bc,o.D=rp,o.E=Op,o.F=yt,o.G=2,o.H=TO,o.I=Lt,o.J=HOe,o.K=uj,o.L=Uj,o.M=zy,o.N=Zb,o.O=cp,o.P=Ms,o.Q=qp,o.R=h0,o.S=ZN,o.T=N_,o.U=Wy,o.V=lV,o.W=x_,o.X=jx,o.Y=Lj,o.Z=_m,o._=qy,o.a=function(w){return da.API_CDN_URL_REGEX.test(w)},o.a$=Vq,o.a0=$c,o.a1=m0,o.a2=o1,o.a3=Or,o.a4=qj,o.a5=class extends lV{},o.a6=QN,o.a7=YN,o.a8=fs,o.a9=function(w){const m=w.value;return m?o1(m)?K_e(m,!0)?[]:[new lV(w.key,m,`invalid url "${m}"`)]:[new lV(w.key,m,`string expected, "${zy(m)}" found`)]:[]},o.aA=vOe,o.aB=function(w){let m=1/0,x=1/0,k=-1/0,E=-1/0;for(const P of w)m=Math.min(m,P.x),x=Math.min(x,P.y),k=Math.max(k,P.x),E=Math.max(E,P.y);return{min:new Ms(m,x),max:new Ms(k,E)}},o.aC=Qe,o.aD=_,o.aE=dt,o.aF=Tt,o.aG=Yp,o.aH=an,o.aI=ar,o.aJ=function(w,m){const x={};for(let k=0;k=0?m.slice(x+1):""}catch{return""}},o.aN=class{constructor(w){this.entries={},this.scheduler=w}request(w,m,x,k){const E=this.entries[w]=this.entries[w]||{callbacks:[]};if(E.result){const[P,O]=E.result;return this.scheduler?this.scheduler.add(()=>{k(P,O)},m):k(P,O),()=>{}}return E.callbacks.push(k),E.cancel||(E.cancel=x((P,O)=>{E.result=[P,O];for(const U of E.callbacks)this.scheduler?this.scheduler.add(()=>{U(P,O)},m):U(P,O);setTimeout(()=>delete this.entries[w],3e3)})),()=>{E.result||(E.callbacks=E.callbacks.filter(P=>P!==k),E.callbacks.length||(E.cancel(),delete this.entries[w]))}}},o.aO=function(w,m,x){const k=JSON.stringify(w.request);return w.data&&(this.deduped.entries[k]={result:[null,w.data]}),this.deduped.request(k,{type:"parseTile",renderSourceType:w.renderSourceType,zoom:w.tileZoom},E=>{const P=Dy(w.request,(O,U,H)=>{O?Af(O)?E(null,null):E(O):U&&E(null,{rawData:U,vectorTile:x?void 0:new Vi(new Vq(U)),responseHeaders:new Map(H.entries())})});return()=>{P.cancel(),E(null,null)}},m)},o.aP=function(w){return w?{cacheControl:w.get("cache-control"),expires:w.get("expires")}:{cacheControl:void 0,expires:void 0}},o.aQ=function(w){Vb++,Vb>Py&&(w.getActor().send("enforceCacheSizeLimit",Iy),Vb=0)},o.aR=up,o.aS=SFe,o.aT=LFe,o.aU=rs,o.aV=kFe,o.aW=function(w,m){const x=document.createElement("video");x.muted=!0,x.onloadstart=function(){m(null,x)};for(let k=0;k{}}},o.aX=jO,o.aY=o3,o.aZ=Ns,o.a_=xV,o.aa=sk,o.ab=Zo,o.ac=kn,o.ad=class{constructor(w){this.specification=w}possiblyEvaluate(w,m){return wn(w.expression.evaluate(m))}interpolate(w,m,x){return{x:Br(w.x,m.x,x),y:Br(w.y,m.y,x),z:Br(w.z,m.z,x),azimuthal:Br(w.azimuthal,m.azimuthal,x),polar:Br(w.polar,m.polar,x)}}},o.ae=Ra,o.af=Nx,o.ag=mr,o.ah=Je,o.ai=ee,o.aj=ct,o.ak=Qd,o.al=Zj,o.am=Br,o.an=Bn,o.ao=Ed,o.ap=lr,o.aq=Wn,o.ar=class{constructor(w){this.specification=w}possiblyEvaluate(w,m){return function([x,k]){const E=wn([1,x,k]);return{x:E.x,y:E.y,z:E.z}}(w.expression.evaluate(m))}interpolate(w,m,x){return{x:Br(w.x,m.x,x),y:Br(w.y,m.y,x),z:Br(w.z,m.z,x)}}},o.as=function(w,m,x=0,k=!0){const E=new Ms(x,x),P=w.sub(E),O=m.add(E),U=[P,new Ms(O.x,P.y),O,new Ms(P.x,O.y)];return k&&U.push(P.clone()),U},o.at=function(w,m){const x=[];for(let k=0;kthis.buckets[he].layers.some(me=>O.has(me.fqid))),H=Object.keys(this.buckets).some(he=>this.buckets[he].layers.some(me=>me.hasTransition&&me.hasTransition())),X=this._firstPrepareComplete&&P!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(m));const le=this._lastUpdatedBrightness!==k;this._lastAvailableImagesCount=P,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||k||this._hasAppearances||U||H||X)&&(!(this._hasAppearances||U||H||X)&&this._lastUpdatedBrightness&&k&&Math.abs(this._lastUpdatedBrightness-k)<.001||(this.updateBuckets(m,le,void 0,X||U||H,O,E),this._lastUpdatedBrightness=k))}evaluateQueryRenderedFeaturePadding(){let w=0;for(const m in this.buckets){const x=this.buckets[m];x.evaluateQueryRenderedFeaturePadding&&(w=Math.max(w,x.evaluateQueryRenderedFeaturePadding()))}return w}queryRenderedFeatures(w,m,x,k,E,P,O){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const U=this.evaluateQueryRenderedFeaturePadding(),H=function(X,le){const he=M([],[.5*X.width,.5*-X.height,1]);return S(he,he,[1,-1,0]),_(he,he,X.calculateProjMatrix(le.toUnwrapped())),Float32Array.from(he)}(E,this.tileID);return this.latestFeatureIndex.query(w,{tilespaceGeometry:m,pixelPosMatrix:H,transform:k,availableImages:x,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:U,scope:O})}querySourceFeatures(w,m){const x=this.latestFeatureIndex;if(!x||!x.rawTileData)return;const k=x.loadVTLayers(),E=m?m.sourceLayer:"",P=k._geojsonTileLayer||k[E];if(!P)return;const O=ak(m&&m.filter),{z:U,x:H,y:X}=this.tileID.canonical,le={z:U,x:H,y:X};for(let he=0;hex)k=!1;else if(m)if(this.expirationTimex.appearances&&x.appearances.length>0))return!0;return!1}updateBuckets(w,m,x,k,E,P){if(!this.latestFeatureIndex||!w.style)return;const O=P||w.style.listImages(),U=w.style.getBrightness(),H=E||new Set;for(const X in this.buckets){if(!w.style.hasLayer(X))continue;const le=this.buckets[X],he=le.layers[0],me=he.sourceLayer||"_geojsonTileLayer",be=w.style.getLayerSourceCache(he),Se=le.layers.some(bt=>H.has(bt.fqid)),Pe=(k||Se)&&le instanceof I1?w.style.getOwnLayer(X):void 0;let Be=x&&x[me]||{};be&&!x&&(Be=be._state.getState(me,void 0));const We=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},ot=Object.keys(Be).length>0&&!m;le.hasAppearances=le.layers.some(bt=>bt.appearances&&bt.appearances.length>0);const nt=ot?le.stateDependentLayers:le.layers;if(ot&&le.stateDependentLayers.length!==0||m||Se||k){const bt=this.latestFeatureIndex.loadVTLayers()[me];if(le.update(Be,bt,O,We,nt,m,U,this.tileID.canonical),(k||Se)&&!m&&le instanceof I1&&Pe&&Pe.type==="symbol"){const wt=le;wt.text&&wt.text.uboBinder&&wt.text.uboBinder.updateDynamicExpressions(Pe,bt,this.tileID.canonical,O,Be,U),wt.icon&&wt.icon.uboBinder&&wt.icon.uboBinder.updateDynamicExpressions(Pe,bt,this.tileID.canonical,O,Be,U)}if(le instanceof I1){const wt=le,Yt=w.context;wt.text&&wt.text.uboBinder&&wt.text.uboBinder.upload(Yt),wt.icon&&wt.icon.uboBinder&&wt.icon.uboBinder.upload(Yt)}}if(ot&&le.stateDependentLayers.length!==0||m||le.hasAppearances){const bt={zoom:w.transform.zoom,pitch:w.transform.pitch,brightness:w.style.getBrightness()||0,worldview:w.worldview},wt=le.updateAppearances(this.tileID.canonical,Be,O,bt,w.imageManager,ot&&le.stateDependentLayers.length!==0);if(wt&&wt.hasUboChanges){const Yt=w.context;le instanceof I1&&le.text&&le.text.uboBinder&&le.text.uboBinder.upload(Yt),le instanceof I1&&le.icon&&le.icon.uboBinder&&le.icon.uboBinder.upload(Yt)}}(le instanceof qq||le instanceof Nq)&&w._terrain&&w._terrain.enabled&&be&&le.uploadPending()&&w._terrain._clearRenderCacheForTile(be.id,this.tileID);const ft=w&&w.style&&w.style.getOwnLayer(X);ft&&(this.queryPadding=Math.max(this.queryPadding,ft.queryRadius(le)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Pe--){const Be=4*Pe,We=yk[Be+0],ot=yk[Be+1],nt=yk[Be+2],ft=yk[Be+3],bt=We+nt>>1,wt=ot+ft>>1,Yt=bt+wt-ot,zt=wt+We-bt,Kt=ot*k_+We,Vt=ft*k_+nt,Ht=wt*k_+bt,Os=Math.hypot((S_[2*Kt+0]+S_[2*Vt+0])/2-S_[2*Ht+0],(S_[2*Kt+1]+S_[2*Vt+1])/2-S_[2*Ht+1])>=16;vk[Ht]=vk[Ht]||(Os?1:0),Pe<1022&&(vk[Ht]=vk[Ht]||vk[(ot+zt>>1)*k_+(We+Yt>>1)]||vk[(ft+zt>>1)*k_+(nt+Yt>>1)])}const le=new ai,he=new sc;let me=0;function be(Pe,Be){const We=Be*k_+Pe;return dV[We]===0&&(le.emplaceBack(S_[2*We+0],S_[2*We+1],Pe*Bn/ev,Be*Bn/ev),dV[We]=++me),dV[We]-1}function Se(Pe,Be,We,ot,nt,ft){const bt=Pe+We>>1,wt=Be+ot>>1;if(Math.abs(Pe-nt)+Math.abs(Be-ft)>1&&vk[wt*k_+bt])Se(nt,ft,Pe,Be,bt,wt),Se(We,ot,nt,ft,bt,wt);else{const Yt=be(Pe,Be),zt=be(We,ot),Kt=be(nt,ft);he.emplaceBack(Yt,zt,Kt)}}return Se(0,0,ev,ev,ev,0),Se(ev,ev,0,0,0,ev),{vertices:le,indices:he}}(this.tileID.canonical,m);k=P.vertices,E=P.indices}else{k=new ai,E=new sc;for(const{x:O,y:U}of x)k.emplaceBack(O,U,0,0);const P=U6(k.int16.subarray(0,4*k.length),void 0,4);for(let O=0;O0&&(O=j(new Float64Array(16),m.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(w,k,m,E,O,P),this._makeGlobeTileDebugTextBuffer(w,k,m,E,O,P)}_globePoint(w,m,x,k,E,P,O){let U=iO(w,m,x);if(P){const H=1<.5?me=-1:he<-.5&&(me=1);let be=(w/Bn+x.x)/H+me,Se=(m/Bn+x.y)/H;be=(be-X)*k._pixelsPerMercatorPixel+X,Se=(Se-le)*k._pixelsPerMercatorPixel+le;const Pe=[be*k.worldSize,Se*k.worldSize,0];Je(Pe,Pe,P),U=Yj(U,Pe,O)}return Je(U,U,E)}_makeGlobeTileDebugBorderBuffer(w,m,x,k,E,P){const O=new Wa,U=new Gj,H=new Ui,X=(he,me,be,Se,Pe)=>{const Be=(be-he)/(Pe-1),We=(Se-me)/(Pe-1),ot=O.length;for(let nt=0;ntX*he+me;for(let he=0;he1)return!1;const x=m.getSource().maxzoom,k=1<1)return m;const E=k.getSource().maxzoom,P=1<{const U=this.getAtTileOffset(w,E,P,O),H=k.upVector(w.canonical,E.x,E.y);return _e(H,H,U*k.upVectorScale(w.canonical,m,x).metersToTile),H}}getForTilePoints(w,m,x,k){if(this.isUsingMockSource())return!1;const E=tI.create(this,w,k);return!!E&&(m.forEach(P=>{P[2]=this.exaggeration()*E.getElevationAt(P[0],P[1],x)}),!0)}getMinMaxForTile(w){if(this.isUsingMockSource())return null;const m=this.findDEMTileFor(w);if(!m||!m.dem)return null;const x=m.dem.tree,k=m.tileID,E=1<0&&(k+=(w[E]-0)*(w[E]-0)),m[E]<0&&(k+=(0-m[E])*(0-m[E]));return k},o.cL=function(w){return w*w*w*w*w},o.cM=Is,o.cN=45,o.cO=z6,o.cP=function(w,m,x){const k=Math.sqrt(w*w+m*m+x*x),E=k>0?Math.acos(x/k)*er:0;let P=w!==0||m!==0?Math.atan2(-m,-w)*er+90:0;return P<0&&(P+=360),[k,P,E]},o.cQ=ne,o.cR=wn,o.cS=dn,o.cT=pe,o.cU=so,o.cV=ce,o.cW=function(w){return[Math.pow(w[0],1/2.2),Math.pow(w[1],1/2.2),Math.pow(w[2],1/2.2)]},o.cX=sOe,o.cY=x_e,o.cZ=oOe,o.c_=K_e,o.ca=2,o.cb=7,o.cc=6,o.cd=ve,o.ce=K,o.cf=Y,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=$6,o.cl=$f,o.cm=rOe,o.cn=QC,o.co=PDe,o.cp=function(w,m,x,k,E,P,O,U,H){if(H.name==="globe")return PDe(w,m,new QC(x,k,E),!1);const X=r3({z:x,x:k,y:E},H);return new so([(P+X.x/X.scale)*m,m*(X.y/X.scale),O],[(P+X.x2/X.scale)*m,m*(X.y2/X.scale),U])},o.cq=function(w,m,x){return w[0]=Math.min(m[0],x[0]),w[1]=Math.min(m[1],x[1]),w[2]=Math.min(m[2],x[2]),w[3]=Math.min(m[3],x[3]),w},o.cr=function(w,m,x){return w[0]=Math.max(m[0],x[0]),w[1]=Math.max(m[1],x[1]),w[2]=Math.max(m[2],x[2]),w[3]=Math.max(m[3],x[3]),w},o.cs=function(w){const m=Math.round((w+45+360)%360/90)%4;return $n[m]},o.ct=Qs,o.cu=tt,o.cv=6,o.cw=function(w){const m=v(new Float64Array(16));_(m,w.pixelMatrix,w.globeMatrix);const x=[0,Ft,0],k=[0,Jt,0];return Je(x,x,m),Je(k,k,m),[x[0]>0&&x[0]<=w.width&&x[1]>0&&x[1]<=w.height&&!Obe(w,new rs(w.center.lat,90)),k[0]>0&&k[0]<=w.width&&k[1]>0&&k[1]<=w.height&&!Obe(w,new rs(w.center.lat,-90))]},o.cx=function(w,m){const{scale:x}=w.tileTransform,k=x*Bn/(w.tileSize*Math.pow(2,m.zoom-w.tileID.overscaledZ+w.tileID.canonical.z));return function(E,P,O){var U=P[1],H=P[2],X=P[3],le=O[0],he=O[1];return E[0]=P[0]*le,E[1]=U*le,E[2]=H*he,E[3]=X*he,E}(new Float32Array(4),m.inverseAdjustmentMatrix,[k,k])},o.cy=Oq,o.cz=W,o.d=function(w){return da.API_TILEJSON_REGEX.test(w)},o.d$=E4t,o.d0=Fl,o.d1=class{static calculate(w,m,x){const k=new Set,E=new Map,P=new Set,O=new Set;for(const H of Object.values(w))for(const[X,le]of Object.entries(H.floors)){P.add(X),le.isDefault&&O.add(X),le.conflicts&&E.set(X,le.conflicts);const he=X===m,me=le.connections&&m&&le.connections.has(m);(he||me)&&k.add(X)}const U=H=>{const X=E.get(H)||new Set;for(const le of k)if((E.get(le)||new Set).has(H)||X.has(le))return!0;return!1};if(x)for(const H of x)P.has(H)&&(U(H)||k.add(H));for(const H of O)k.has(H)||U(H)||k.add(H);return k}},o.d2=Kq,o.d3=D_e,o.d4=Xa,o.d5=function(){return{API_URL:da.API_URL,DRACO_URL:da.DRACO_URL,MESHOPT_URL:da.MESHOPT_URL,MESHOPT_SIMD_URL:da.MESHOPT_SIMD_URL,BUILDING_GEN_URL:da.BUILDING_GEN_URL}},o.d6=T6,o.d7=lj,o.d8=Td,o.d9=Un,o.dA=fq,o.dB=Wa,o.dC=sc,o.dD=function(w,m){return[Math.pow(w[0],2.2)*m,Math.pow(w[1],2.2)*m,Math.pow(w[2],2.2)*m]},o.dE=h,o.dF=function(w,m){var x=Math.sin(m),k=Math.cos(m);return w[0]=k,w[1]=x,w[2]=0,w[3]=-x,w[4]=k,w[5]=0,w[6]=0,w[7]=0,w[8]=1,w},o.dG=we,o.dH=DDe,o.dI=ea,o.dJ=ya,o.dK=G_e,o.dL=function(w,m){const x=[0,0,0];return Je(x,x,oO(__(m.canonical))),Je(x,x,w),x},o.dM=w=>({u_matrix:new y(w),u_texsize:new Ng(w),u_pixels_to_tile_units:new $(w),u_device_pixel_ratio:new ud(w),u_width_scale:new ud(w),u_floor_width_scale:new ud(w),u_image:new YC(w),u_units_to_pixels:new Ng(w),u_tile_units_to_pixels:new ud(w),u_alpha_discard_threshold:new ud(w),u_trim_offset:new Ng(w),u_trim_fade_range:new Ng(w),u_trim_gradient_mix_range:new Ng(w),u_trim_color:new z6(w),u_zbias_factor:new ud(w),u_tile_to_meter:new ud(w),u_ground_shadow_factor:new ZC(w),u_pattern_transition:new ud(w)}),o.dN=w=>({u_matrix:new y(w),u_pixels_to_tile_units:new $(w),u_device_pixel_ratio:new ud(w),u_width_scale:new ud(w),u_floor_width_scale:new ud(w),u_units_to_pixels:new Ng(w),u_dash_image:new YC(w),u_gradient_image:new YC(w),u_image_height:new ud(w),u_texsize:new Ng(w),u_tile_units_to_pixels:new ud(w),u_alpha_discard_threshold:new ud(w),u_trim_offset:new Ng(w),u_trim_fade_range:new Ng(w),u_trim_gradient_mix_range:new Ng(w),u_trim_color:new z6(w),u_zbias_factor:new ud(w),u_tile_to_meter:new ud(w),u_ground_shadow_factor:new ZC(w)}),o.dO=w=>({u_camera_to_center_distance:new ud(w),u_extrude_scale:new $(w),u_device_pixel_ratio:new ud(w),u_matrix:new y(w),u_inv_rot_matrix:new y(w),u_merc_center:new Ng(w),u_tile_id:new ZC(w),u_zoom_transition:new ud(w),u_up_dir:new ZC(w),u_emissive_strength:new ud(w)}),o.dP=KR,o.dQ=T3t,o.dR=class{constructor(w,m,x,k){this.context=w,this.format=k,this.size=x,this.texture=w.gl.createTexture();const[E,P,O]=this.size,{gl:U}=w;U.bindTexture(U.TEXTURE_3D,this.texture),w.pixelStoreUnpackFlipY.set(!1),w.pixelStoreUnpack.set(1),w.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in m&&m.data&&U.texImage3D(U.TEXTURE_3D,0,this.format,E,P,O,0,c_e(this.format),d_e(this.format),m.data)}bind(w,m){const{context:x}=this,{gl:k}=x;k.bindTexture(k.TEXTURE_3D,this.texture),w!==this.minFilter&&(k.texParameteri(k.TEXTURE_3D,k.TEXTURE_MAG_FILTER,w),k.texParameteri(k.TEXTURE_3D,k.TEXTURE_MIN_FILTER,w),this.minFilter=w),m!==this.wrapS&&(k.texParameteri(k.TEXTURE_3D,k.TEXTURE_WRAP_S,m),k.texParameteri(k.TEXTURE_3D,k.TEXTURE_WRAP_T,m),this.wrapS=m)}destroy(){const{gl:w}=this.context;w.deleteTexture(this.texture),this.texture=null}},o.dS=zDe,o.dT=(w,m,x,k,E,P)=>{const O=w.transform,U=O.projection.name==="globe";let H;if(P.paint.get("circle-pitch-alignment")==="map")if(U){const le=DDe(O.zoom,m.canonical)*O._pixelsPerMercatorPixel;H=Float32Array.from([le,0,0,le])}else H=O.calculatePixelsToTileUnitsMatrix(x);else H=new Float32Array([O.pixelsToGLUnits[0],0,0,O.pixelsToGLUnits[1]]);const X={u_camera_to_center_distance:w.transform.getCameraToCenterDistance(O.projection),u_matrix:w.translatePosMatrix(m.projMatrix,x,P.paint.get("circle-translate"),P.paint.get("circle-translate-anchor")),u_device_pixel_ratio:Gd.devicePixelRatio,u_extrude_scale:H,u_inv_rot_matrix:D4t,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:P.paint.get("circle-emissive-strength")};if(U){X.u_inv_rot_matrix=k,X.u_merc_center=E,X.u_tile_id=[m.canonical.x,m.canonical.y,1<{const le=w.transform,he=le.pitch<15?bOe(.07,.7,Qe((14-le.zoom)/5,0,1)):.07,me=x.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:wOe(w,m,x,k),u_texsize:m.imageAtlasTexture?m.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:le.calculatePixelsToTileUnitsMatrix(m),u_device_pixel_ratio:E,u_width_scale:P,u_floor_width_scale:O,u_image:0,u_tile_units_to_pixels:_Oe(m,le),u_units_to_pixels:[1/le.pixelsToGLUnits[0],1/le.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:U,u_trim_fade_range:x.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:x.paint.get("line-trim-color").toPremultipliedRenderColor(me?null:x.lut).toArray01(),u_zbias_factor:he,u_tile_to_meter:dn(m.tileID.canonical,0),u_ground_shadow_factor:H,u_pattern_transition:X}},o.dX=(w,m,x,k,E,P,O,U,H,X)=>{const le=w.transform,he=le.calculatePixelsToTileUnitsMatrix(m),me=x.paint.get("line-trim-color-use-theme").constantOr("default")==="none",be=le.pitch<15?bOe(.07,.7,Qe((14-le.zoom)/5,0,1)):.07;return{u_matrix:wOe(w,m,x,k),u_pixels_to_tile_units:he,u_device_pixel_ratio:P,u_width_scale:O,u_floor_width_scale:U,u_units_to_pixels:[1/le.pixelsToGLUnits[0],1/le.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:E,u_texsize:NOe(x)&&m.lineAtlasTexture?m.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:_Oe(m,w.transform),u_alpha_discard_threshold:0,u_trim_offset:H,u_trim_fade_range:x.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:x.paint.get("line-trim-color").toPremultipliedRenderColor(me?null:x.lut).toArray01(),u_zbias_factor:be,u_tile_to_meter:dn(m.tileID.canonical,0),u_ground_shadow_factor:X}},o.dY=as,o.dZ=lO,o.d_=qs,o.da=function(w){const m=w.indexOf(et);return m>=0?w.slice(0,m):w},o.db=function(w){return w.indexOf(et)>=0},o.dc=function(w){const m=w.lastIndexOf(et);return m>=0?w.slice(m+1):""},o.dd=function(w){const m=[],x=w.id;return x===void 0&&m.push({message:`layers.${x}: missing required property "id"`}),w.render===void 0&&m.push({message:`layers.${x}: missing required method "render"`}),w.renderingMode&&w.renderingMode!=="2d"&&w.renderingMode!=="3d"&&m.push({message:`layers.${x}: property "renderingMode" must be either "2d" or "3d"`}),m},o.de=function(w,m,x,k){return w.type==="custom"?new _5t(w,m):new S5t[w.type](w,m,x,k)},o.df=Ks,o.dg=ak,o.dh=ps,o.di=class extends i3{constructor(w,m){super(w._vectorTileFeature,w._z,w._x,w._y,w.id),w.state&&(this.state=Object.assign({},w.state)),this.target=m.target,this.namespace=m.namespace,m.properties&&(this.properties=m.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=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}},o.dj=tk,o.dk=function(w){return w({pluginStatus:Zd,pluginURL:Gp}),tk.on("pluginStateChange",w),w},o.dl=Ibe,o.dm=class extends jg{constructor(w){super(w),this.current=C}set(w,m,x){if(this.fetchUniformLocation(w,m)){for(let k=0;k<9;k++)if(x[k]!==this.current[k]){this.current=x,this.gl.uniformMatrix3fv(this.location,!1,x);break}}}},o.dn=Cr,o.dp=function(w,m,x){const k=Zj(x.zoom),E=w.style.map._antialias,P=w.terrain&&w.terrain.exaggeration()>0;return k===0&&!E&&!P},o.dq=function(w){const m=w.pixelsPerMeter,x=m/js(1,w.center.lat),k=v(new Float64Array(16));return S(k,k,[w.point.x,w.point.y,0]),A(k,k,[x,x,m]),Float32Array.from(k)},o.dr=xq,o.ds=function(w){const m=80.051129;w=Qe(w,-80.051129,m)/m*90;const x=Math.pow(Math.abs(Math.sin(lr(w))),3);return Math.round(x*(es.length-1))},o.dt=function(w,m,x,k){const E=m.getNorth(),P=m.getSouth(),O=m.getWest(),U=m.getEast(),H=1<0){const Se=180/k;f(be,be,[Se/X+1,0,0,0,Se/le+1,0,-.5*Se/he,.5*Se/me,1])}return be[2]=H,be[5]=w.x,be[8]=w.y,be},o.du=oO,o.dv=__,o.dw=function(w,m,x){const k=v(new Float64Array(16)),E=(m/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(w,m=!1){const x=vRe(new Ms(0,0),new Ms(Bn,Bn),w),k=[];if(m&&!Xbe(x,this._globalClipBounds))return k;for(const E of this._activeRegions){if(E.hiddenByOverlap||!Xbe(x,E))continue;const P=gCt(E.min,E.max,w);k.push({min:P.min,max:P.max,sourceId:this._sourceIds[E.priority],footprint:E.footprint,footprintTileId:E.tileId,order:E.order,clipMask:E.clipMask,clipScope:E.clipScope})}return k}setSources(w){this._setSources(w.map(m=>({getSourceId:()=>m.cache.id,getFootprints:()=>{const x=[];for(const k of m.cache.getVisibleCoordinates()){const E=m.cache.getTile(k).buckets[m.layer];E&&E.updateFootprints(k.toUnwrapped(),x)}return x},getOrder:()=>m.order,getClipMask:()=>m.clipMask,getClipScope:()=>m.clipScope})))}_addSource(w){const m=w.getFootprints();if(m.length===0)return;const x=w.getOrder(),k=w.getClipMask(),E=w.getClipScope();for(const P of m){if(!P.footprint)continue;const O=vRe(P.footprint.min,P.footprint.max,P.id);this._activeRegions.push({min:O.min,max:O.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:P.id,footprint:P.footprint,order:x,clipMask:k,clipScope:E})}this._sourceIds.push(w.getSourceId())}_computeReplacement(){this._activeRegions.sort((m,x)=>m.priority-x.priority||Sq(m.min,x.min)||Sq(m.max,x.max)||m.order-x.order||m.clipMask-x.clipMask||function(k,E){const P=(O,U)=>O+U;return k.length-E.length||k.reduce(P,"").localeCompare(E.reduce(P,""))}(m.clipScope,x.clipScope));let w=this._activeRegions.length!==this._prevRegions.length;if(!w){let m=0;for(;!w&&m!==this._activeRegions.length;){const x=this._activeRegions[m],k=this._prevRegions[m];w=x.priority!==k.priority||!yRe(x,k)||x.order!==k.order||x.clipMask!==k.clipMask||!bi(x.clipScope,k.clipScope),this._activeRegions[m].hiddenByOverlap=k.hiddenByOverlap,++m}}if(w){++this._updateTime;for(const x of this._activeRegions)x.order!==xO&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,x.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,x.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,x.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,x.max.y));const m=x=>{const k=this._activeRegions;if(x>=k.length)return x;const E=k[x].priority;for(;x1){let x=0,k=m(x);for(;x!==k;){let E=x;const P=x;for(;E!==k;){const O=this._activeRegions[E];O.hiddenByOverlap=!1;for(let U=0;U=0;m--)this._addSource(w[m]);this._computeReplacement()}},o.eH=ai,o.eI=aV,o.eJ=Gj,o.eK=xO,o.eL=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,m){const x=new Wa,k=new sc,E=[],P=w+1+2,O=m[0]+1,U=m[0]+1+(1+m.length),H=(X,le,he)=>{let me=X===P-1?X-2:X===0?X:X-1;return me+=he?24575:0,[me,le]};for(let X=0;X>>=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},o.ec=MDe,o.ed=Dbe,o.ee=_g,o.ef=D,o.eg=function(w,m){return w[0]=m[0],w[1]=m[1],w[2]=m[2],w[3]=m[4],w[4]=m[5],w[5]=m[6],w[6]=m[8],w[7]=m[9],w[8]=m[10],w},o.eh=Vj,o.ei=VC,o.ej=function(w,m,x,k,E){return Qe((w-m)/(x-m)*(E-k)+k,k,E)},o.ek=ns,o.el=function(w,m){var x=m[0],k=m[1],E=m[2],P=m[3],O=m[4],U=m[5],H=m[6],X=m[7],le=m[8],he=le*O-U*X,me=-le*P+U*H,be=X*P-O*H,Se=x*he+k*me+E*be;return Se?(w[0]=he*(Se=1/Se),w[1]=(-le*k+E*X)*Se,w[2]=(U*k-E*O)*Se,w[3]=me*Se,w[4]=(le*x-E*H)*Se,w[5]=(-U*x+E*P)*Se,w[6]=be*Se,w[7]=(-X*x+k*H)*Se,w[8]=(O*x-k*P)*Se,w):null},o.em=EC,o.en=2,o.eo=De,o.ep=Bt,o.eq=z,o.er=function(w,m){var x=new d(3);z(x,m);var k=1/x[0],E=1/x[1],P=1/x[2],O=m[0]*k,U=m[1]*E,H=m[2]*P,X=m[4]*k,le=m[5]*E,he=m[6]*P,me=m[8]*k,be=m[9]*E,Se=m[10]*P,Pe=O+le+Se,Be=0;return Pe>0?(Be=2*Math.sqrt(Pe+1),w[3]=.25*Be,w[0]=(he-be)/Be,w[1]=(me-H)/Be,w[2]=(U-X)/Be):O>le&&O>Se?(Be=2*Math.sqrt(1+O-le-Se),w[3]=(he-be)/Be,w[0]=.25*Be,w[1]=(U+X)/Be,w[2]=(me+H)/Be):le>Se?(Be=2*Math.sqrt(1+le-O-Se),w[3]=(me-H)/Be,w[0]=(U+X)/Be,w[1]=.25*Be,w[2]=(he+be)/Be):(Be=2*Math.sqrt(1+Se-O-le),w[3]=(U-X)/Be,w[0]=(me+H)/Be,w[1]=(he+be)/Be,w[2]=.25*Be),w},o.es=function(w,m){var x=2*Math.acos(m[3]),k=Math.sin(x/2);return k>c?(w[0]=m[0]/k,w[1]=m[1]/k,w[2]=m[2]/k):(w[0]=1,w[1]=0,w[2]=0),x},o.et=Q_e,o.eu=Bq,o.ev=zq,o.ew=[1,1,1],o.ex=tI,o.ey=function(w,m,x,k){var E=m[0],P=m[1],O=m[2],U=m[3];return w[0]=E+k*(x[0]-E),w[1]=P+k*(x[1]-P),w[2]=O+k*(x[2]-O),w[3]=U+k*(x[3]-U),w},o.ez=W6,o.f=Bo,o.f0=ODe,o.f1=function(w){const m=[0,0,0],x=v(new Float64Array(16));return _(x,w.pixelMatrix,w.globeMatrix),Je(m,m,x),new Ms(m[0],m[1])},o.f2=S0,o.f3=function(w,m,x=!1){if(Zd===Nm.deferred||Zd===Nm.loading||Zd===Nm.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");Gp=Gd.resolveURL(w),Zd=Nm.deferred,Bf=m,ek(),x||E6()},o.f4=Yi,o.f5=Aa,o.f6=jn,o.f7=function(w){const m=px();if(!m)return;const x=m.delete(xm);w&&x.then(()=>w()).catch(w)},o.f8=Yn,o.f9=hk,o.fA=_a,o.fB=function(w){let m=0;if(new Uint32Array(w,0,1)[0]!==QRe){const x=new Uint32Array(w,0,7),[,,k,E,P,O]=x;m=x.byteLength+E+P+O+P,(k!==w.byteLength||m>=w.byteLength)&&sr("Invalid b3dm header information.")}return tOe(w,m)},o.fC=function(w,m){const x=x_e(w);for(const k of x){for(const E of k.meshes)KCt(E);k.lights&&(k.lightMeshIndex=k.meshes.length,k.meshes.push(YCt(k.lights,m)))}return x},o.fD=cV,o.fE=kr,o.fF=km,o.fG=Nm,o.fH=function(w){fo(),_h!=null&&_h.then(m=>{m.keys().then(x=>{for(let k=0;ksr(E.message))}).catch(x=>sr(x.message))}).catch(m=>sr(m.message))},o.fa=2,o.fb=fg,o.fc=r3,o.fd=eO,o.fe=$Fe,o.ff=UFe,o.fg=xOe,o.fh=$a,o.fi="hd_road_elevation",o.fj=$o,o.fk=ln,o.fl=Nq,o.fm=Qj,o.fn=P_e,o.fo=1,o.fp=I1,o.fq=function(w,m,x,k,E,P,O,U=1,H,X,le,he){w.createArrays(),w.tilePixelRatio=Bn/(512*w.overscaling),w.compareText={},w.iconsNeedLinear=!1;const me=w.layers[0].layout,be=w.layers[0]._unevaluatedLayout._values,Se={};Se.scaleFactor=U,Se.textSizeScaleRange=me.get("text-size-scale-range"),Se.iconSizeScaleRange=me.get("icon-size-scale-range");const[Pe,Be]=Se.textSizeScaleRange,[We,ot]=Se.iconSizeScaleRange;Se.textScaleFactor=Qe(Se.scaleFactor,Pe,Be),Se.iconScaleFactor=Qe(Se.scaleFactor,We,ot);const nt=be["text-size"],ft=be["icon-size"];if(w.textSizeData.kind==="composite"){const{minZoom:Vt,maxZoom:Ht}=w.textSizeData;Se.compositeTextSizes=[nt.possiblyEvaluate(new Ra(Vt,{worldview:le}),P),nt.possiblyEvaluate(new Ra(Ht,{worldview:le}),P)]}if(w.iconSizeData.kind==="composite"){const{minZoom:Vt,maxZoom:Ht}=w.iconSizeData;Se.compositeIconSizes=[ft.possiblyEvaluate(new Ra(Vt,{worldview:le}),P,he),ft.possiblyEvaluate(new Ra(Ht,{worldview:le}),P,he)]}Se.layoutTextSize=nt.possiblyEvaluate(new Ra(O+1,{worldview:le}),P),Se.layoutIconSize=ft.possiblyEvaluate(new Ra(O+1,{worldview:le}),P,he),Se.textMaxSize=nt.possiblyEvaluate(new Ra(18,{worldview:le}),P);const bt=me.get("symbol-placement"),wt=me.get("text-rotation-alignment")==="map"&&bt!=="point",Yt=me.get("text-size");let zt=!1;const Kt=[];for(const Vt of w.features){const Ht=me.get("text-font").evaluate(Vt,{},P).join(","),Os=Yt.evaluate(Vt,{},P)*Se.textScaleFactor,Vs=Se.layoutTextSize.evaluate(Vt,{},P)*Se.textScaleFactor,Js=Se.layoutIconSize.evaluate(Vt,{},P,he)*Se.iconScaleFactor,nn={horizontal:{},vertical:void 0},en=Vt.text;let xn,Ls=[0,0];if(en){const Za=en.toString(),zl=me.get("text-letter-spacing").evaluate(Vt,{},P)*Jd,Ji=me.get("text-line-height").evaluate(Vt,{},P)*Jd,Fi=S6(Za)?zl:0,Ro=me.get("text-anchor").evaluate(Vt,{},P),Il=me.get("text-variable-anchor");if(!Il){const rc=me.get("text-radial-offset").evaluate(Vt,{},P);if(rc)Ls=tFe(Ro,[rc*Jd,O_e]);else{const Sh=me.get("text-offset").evaluate(Vt,{},P);Ls=[Sh[0]*Jd,Sh[1]*Jd]}}let eu=wt?"center":me.get("text-justify").evaluate(Vt,{},P);const Pl=bt==="point",nc=Pl?me.get("text-max-width").evaluate(Vt,{},P)*Jd:1/0,qc=rc=>{w.allowVerticalPlacement&&Wh(Za)&&(nn.vertical=S_e(en,m,x,E,Ht,nc,Ji,Ro,rc,Fi,Ls,Ix.vertical,!0,Vs,Os,H,Se.textScaleFactor))};if(!wt&&Il){const rc=eu==="auto"?Il.map(tu=>F_e(tu)):[eu];let Sh=!1;for(let tu=0;tu=0||!Wh(Za)){const rc=S_e(en,m,x,E,Ht,nc,Ji,Ro,eu,Fi,Ls,Ix.horizontal,!1,Vs,Os,H,Se.textScaleFactor);rc&&(nn.horizontal[eu]=rc)}qc(Pl?"left":eu)}}let tn,on,gn,En,ir,On,Rn=!1;const An=me.get("icon-text-fit").evaluate(Vt,{},P);if(Vt.icon&&Vt.icon.hasPrimary()){const Za=MO(Vt.icon,w.iconSizeData,be["icon-size"],P,w.zoom,Vt,H,Se.iconScaleFactor,le,he);tn=Za.iconPrimary,gn=Za.iconSecondary;const zl=tn.toString();if(on=k.get(zl),on&&(ir=me.get("icon-offset").evaluate(Vt,{},P),On=me.get("icon-anchor").evaluate(Vt,{},P),xn=Gq(E.get(zl),gn?E.get(gn.toString()):void 0,ir,On),Rn=on.sdf,w.sdfIcons===void 0?w.sdfIcons=on.sdf:w.sdfIcons!==on.sdf&&sr("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(on.pixelRatio!==w.pixelRatio||me.get("icon-rotate").constantOr(1)!==0)&&(w.iconsNeedLinear=!0)),gn){const Ji=gn.toString();En=k.get(Ji)}}zt=zt||!(!Vt.icon||!Vt.icon.hasSecondary());const nr=Jq(nn.horizontal)||nn.vertical;w.iconsInText||(w.iconsInText=!!nr&&nr.iconsInText);const pr=Vs*Se.textScaleFactor/Jd,{defaultShapedIcon:Gr,verticallyShapedIcon:Sr}=a5t(w,xn,me,Vt,P,nn,pr,ir,An);An!=="none"&&xn&&(OOe(xn)||FOe(xn))&&(Xq(0,on,tn,xn,Gr,An,X,k,E),Xq(0,En,gn,xn,Gr,An,X,k,E),Sr&&(Xq(0,on,tn,xn,Sr,An,X,k,E),Xq(0,En,gn,xn,Sr,An,X,k,E))),xn=Gr;const{iconBBox:Ma,iconVerticalBBox:ki,textBBox:Ia,textVerticalBBox:Ei}=e5t(w,xn,Sr,me,Vt,P,Js,ir,Se,E,On,nn,Vs,Ls,he);Kt.push({feature:Vt,shapedTextOrientations:nn,shapedText:nr,shapedIcon:xn,iconPrimary:tn,iconSecondary:gn,iconOffset:ir,iconAnchor:On,verticallyShapedIcon:Sr,layoutTextSize:Vs,layoutIconSize:Js,textOffset:Ls,isSDFIcon:Rn,iconTextFit:An,iconCollisionBounds:Ma,iconVerticalCollisionBounds:ki,textCollisionBounds:Ia,textVerticalCollisionBounds:Ei})}return{featureData:Kt,sizes:Se,hasAnySecondaryIcon:zt,textAlongLine:wt,symbolPlacement:bt}},o.fr=L_e,o.fs=I_e,o.ft=WOe,o.fu=KOe,o.fv=function(w,m,x,k,E,P,O,U,H,X){w.iconAtlasPositions=X.iconPositions;const{featureData:le,hasAnySecondaryIcon:he,sizes:me,textAlongLine:be,symbolPlacement:Se}=m;for(const Pe of le){const{shapedIcon:Be,verticallyShapedIcon:We,feature:ot,shapedTextOrientations:nt,shapedText:ft,layoutTextSize:bt,textOffset:wt,isSDFIcon:Yt,iconPrimary:zt,iconSecondary:Kt,iconTextFit:Vt,iconOffset:Ht,iconCollisionBounds:Os,iconVerticalCollisionBounds:Vs,textCollisionBounds:Js}=Pe;aFe(Be,X.iconPositions,zt,Kt),aFe(We,X.iconPositions,zt,Kt),r5t(nt,X.iconPositions),n5t(zt,Kt,X.iconPositions),(ft||Be)&&i5t(w,ot,nt,Be,We,H,me,bt,0,wt,Yt,k,E,O,U,he,Vt,Ht,be,Se,Os,Vs,Js)}x&&w.generateCollisionDebugBuffers(P,w.collisionBoxArray,me.textScaleFactor)},o.fw=qq,o.fx=Vi,o.fy=function(w){return w<=1?1:Math.pow(2,Math.floor(Math.log2(w)))},o.fz=fV,o.g=da,o.h=function(w,m){return Ly(Object.assign(w,{method:"GET"}),m)},o.i=function(w){return da.API_STYLE_REGEX.test(w)&&!rl(w)},o.j=function(w){return btoa(encodeURIComponent(w).replace(/%([0-9A-F]{2})/g,(m,x)=>String.fromCharCode(+("0x"+x))))},o.k=gm,o.l=function(w){return decodeURIComponent(atob(w).split("").map(m=>"%"+("00"+m.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(w,m){return Ly(Object.assign(w,{type:"json"}),m)},o.n=xx,o.o=Gd,o.p=function(w,m){return Ly(Object.assign(w,{method:"POST"}),m)},o.q=Yh,o.r=xs,o.s=function(w){try{const m=self[w];return m.setItem("_mapbox_test_",1),m.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=It,o.u=function(){return function w(m){return m?(m^Math.random()*(16>>m/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,w)}()},o.v=function(w){return!!w&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(w)},o.w=sr,o.x=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.finalizationRegistry=new FinalizationRegistry(m=>{this.cache.delete(m),this.clearExpiredTextures()})}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 m=this.textures.get(w);if(m){const x=this.calculateTextureMemory(w);m.destroy(),this.textures.delete(w),this.textureAccessTimes.delete(w),this.textureMemoryUsed-=x}}evictTexturesIfNeeded(w){for(;this.textureMemoryUsed+w>this.maxTextureMemory&&this.textures.size>0;){let m=null,x=1/0;for(const[k]of this.textures.entries()){const E=this.textureAccessTimes.get(k)||0;Ethis._layers[Un.id]),xs=qt[0];if(xs.visibility==="none")continue;const as=xs.source||"";let Ns=this.familiesBySource[as];Ns||(Ns=this.familiesBySource[as]=Object.create(null));const ln=xs.sourceLayer||"_geojsonTileLayer";let Ks=Ns[ln];Ks||(Ks=Ns[ln]=[]),Ks.push(qt)}}}const g=1*c.fa;class b{constructor(Oe){const Qe={},ct=[];for(const xs in Oe){const as=Oe[xs],Ns=Qe[xs]={};for(const ln in as.glyphs){const Ks=as.glyphs[+ln];if(!Ks||Ks.bitmap.width===0||Ks.bitmap.height===0)continue;const Un=Ks.metrics.localGlyph?g:1,br={x:0,y:0,w:Ks.bitmap.width+2*Un,h:Ks.bitmap.height+2*Un};ct.push(br),Ns[ln]=br}}const{w:vt,h:It}=c.J(ct),qt=new c.f9({width:vt||1,height:It||1});for(const xs in Oe){const as=Oe[xs];for(const Ns in as.glyphs){const ln=as.glyphs[+Ns];if(!ln||ln.bitmap.width===0||ln.bitmap.height===0)continue;const Ks=Qe[xs][Ns],Un=ln.metrics.localGlyph?g:1;c.f9.copy(ln.bitmap,qt,{x:0,y:0},{x:Ks.x+Un,y:Ks.y+Un},ln.bitmap)}}this.image=qt,this.positions=Qe}}function v(ts,Oe,Qe){ts[Oe]?Qe&&(ts[Oe].center=Qe):ts[Oe]={floorIds:new Set,center:Qe||[0,0],floors:{}}}function j(ts,Oe,Qe,ct){for(const vt of Oe)v(ts,vt),ts[vt].floors[Qe]=ct,ts[vt].floorIds.add(Qe)}function _(ts){return{id:ts.properties.id.toString(),center:[ts.properties.center_lon||0,ts.properties.center_lat||0]}}function S(ts,Oe){const Qe=ts.properties.id.toString(),ct=!!ts.properties.is_default&&ts.properties.is_default,vt=ts.properties.connected_floor_ids?new Set(ts.properties.connected_floor_ids.toString().split(";")):new Set,It=ts.properties.conflicted_floor_ids?new Set(ts.properties.conflicted_floor_ids.toString().split(";")):new Set,qt=ts.properties.structure_ids?new Set(ts.properties.structure_ids.toString().split(";")):new Set,xs=ts.properties.name.toString(),as=ts.properties.z_index,Ns=function(ln,Ks){const Un=ln.loadGeometry();if(!Un||Un.length===0)return;const br=Un.map(Ar=>Ar.map(sr=>c.fb(sr,Ks,ln.extent)));return br.length===0?void 0:{type:"Polygon",coordinates:[br[0]]}}(ts,Oe);return{id:Qe,isDefault:ct,connections:vt,conflicts:It,buildings:qt,name:xs,zIndex:as,geometry:Ns}}function A(ts,Oe){return Oe.every(Qe=>ts.properties&&ts.properties[Qe]!=null)}function T(ts){return A(ts,["type","id","name"])&&ts.properties.type==="structure"}function D(ts){return A(ts,["type","id","name","z_index"])&&ts.properties.type==="floor"}c.f8(b,"GlyphAtlas");class L{constructor(Oe){this.tileID=new c.aR(Oe.tileID.overscaledZ,Oe.tileID.wrap,Oe.tileID.canonical.z,Oe.tileID.canonical.x,Oe.tileID.canonical.y),this.tileZoom=Oe.tileZoom,this.uid=Oe.uid,this.zoom=Oe.zoom,this.lut=Oe.lut,this.canonical=Oe.tileID.canonical,this.pixelRatio=Oe.pixelRatio,this.tileSize=Oe.tileSize,this.source=Oe.source,this.scope=Oe.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=Oe.showCollisionBoxes,this.collectResourceTiming=!!Oe.request&&Oe.request.collectResourceTiming,this.promoteId=Oe.promoteId,this.renderSourceType=Oe.renderSourceType,this.tileTransform=c.fc(Oe.tileID.canonical,Oe.projection),this.projection=Oe.projection,this.worldview=Oe.worldview,this.localizableLayerIds=Oe.localizableLayerIds,this.brightness=Oe.brightness,this.extraShadowCaster=!!Oe.extraShadowCaster,this.tessellationStep=Oe.tessellationStep,this.scaleFactor=Oe.scaleFactor,this.worldview=Oe.worldview,this.indoor=Oe.indoor}parse(Oe,Qe,ct,vt,It,qt){this.status="parsing",this.data=Oe,this.collisionBoxArray=new c.fd;const xs=new c.fe(Object.keys(Oe.layers).sort()),as=new c.ff(this.tileID,this.promoteId);as.bucketLayerIDs=[];const Ns={},ln=new c.fg(256,256),Ks={featureIndex:as,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:ln,availableImages:ct,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Ks.activeFloors=function(sr,Tr,Ot,wn){const kr=Tr.indoorState.activeFloorsVisible;if(!Tr.sourceLayers)return kr?Tr.indoorState.activeFloors:void 0;const dr=function(qn,wi){if(!qn)return c.w("No source layers defined in indoor specification"),wi;if(qn.size===0)return wi;const Oi=qn.difference(wi);for(const ea of Oi)c.w(`Missing source layer required in indoor specification: ${ea}`);return wi.intersection(wi)}(Tr.sourceLayers,new Set(Object.keys(sr.layers))),Jr=Tr.indoorState,jr=function(qn,wi,Oi,ea,ya){const Mi={};for(const da of wi){const jn=qn.layers[da];if(jn)for(let Aa=0;Aa=ea.maxzoom||ea.visibility==="none")continue;M(Oi,this.zoom,Ks.brightness,ct,this.worldview,Ks.activeFloors);const ya=Ns[ea.id]=ea.createBucket({index:as.bucketLayerIDs.length,layers:Oi,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Jr,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:vt,worldview:this.worldview,localizable:qn,availableImages:ct,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});as.bucketLayerIDs.push(Oi.map(da=>c.F(da.id,da.scope)));let Mi=ya.prepare?ya.prepare():null;Mi!=null?(Mi=Mi.then(()=>ya.populate(jr,Ks,this.tileID.canonical,this.tileTransform)),Un.push(Mi)):ya.populate(jr,Ks,this.tileID.canonical,this.tileTransform)}}const Ar=()=>{ln.trim();const sr=!(!Ks.elevationFeatures||!Ks.elevationFeatures.some(ea=>ea.heightRange.min<0));let Tr,Ot,wn,kr,dr,Jr,jr;const qn={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},wi=()=>{if(Tr)return this.status="done",qt(Tr);if(this.extraShadowCaster)this.status="done",qt(null,{buckets:Object.values(Ns).filter(ea=>!ea.isEmpty()),featureIndex:as,collisionBoxArray:null,hasTunnelGeometry:sr,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Ks.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(Ot&&wn&&kr&&jr){const ya=new b(Ot),Mi=new Map;for(const[Aa,Yi]of wn.entries()){const{imagePosition:Bo}=c.fn(Aa,Yi,c.fo);Mi.set(Aa,Bo)}const da={};for(const Aa in Ns){const Yi=Ns[Aa];Yi instanceof c.fp&&(M(Yi.layers,this.zoom,Ks.brightness,ct,this.worldview,Ks.activeFloors),da[Aa]=c.fq(Yi,Ot,ya.positions,wn,Mi,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,dr,this.worldview,ct))}const jn={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(It,wn,dr,()=>{jn.iconsPending=!1,Oi(da,ya,jn,void 0,jr)}),this.rasterizeIfNeeded(It,kr,Jr,()=>{jn.patternsPending=!1,Oi(da,ya,jn,void 0,jr)})}},Oi=(ea,ya,Mi,da,jn)=>{if(Mi.iconsPending||Mi.patternsPending)return;const Aa=wn.size>0||kr.size>0,Yi=Object.keys(ea).length>0;if(!Aa&&!Yi)return this.status="done",void qt(null,{buckets:Object.values(Ns).filter(rl=>!rl.isEmpty()),featureIndex:as,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:sr,glyphAtlasImage:ya.image,lineAtlas:ln,imageAtlas:null,brightness:Ks.brightness});const Bo=(rl,po)=>{for(const zc in Ns){const Sd=Ns[zc];if(zc in ea)c.fv(Sd,ea[zc],this.showCollisionBoxes,ct,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,wn,po);else if(Sd.hasPattern&&(Sd instanceof c.fw||Sd instanceof c.fl||Sd instanceof c.e0)){M(Sd.layers,this.zoom,Ks.brightness,ct,this.worldview,Ks.activeFloors);const fm=Object.fromEntries(po.patternPositions);Sd.addFeatures(Ks,this.tileID.canonical,fm,ct,this.tileTransform,this.brightness)}}this.status="done",qt(null,{buckets:Object.values(Ns).filter(zc=>!zc.isEmpty()),featureIndex:as,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:sr,glyphAtlasImage:ya.image,lineAtlas:ln,imageAtlas:rl,brightness:Ks.brightness})};if(Aa){const rl=new Map,po=c.fr(wn,rl),zc=c.fr(kr,rl),Sd=new c.fs(po,zc,jn,this.lut,rl);It.send("checkAtlasCache",{descriptor:Sd,scope:this.scope},(fm,Cd)=>{let Hd,uc;if(fm&&c.w(`[Worker] Error checking atlas cache: ${fm.message}`),Cd)Hd=new c.ft(Cd.sourceHash),uc=Cd;else{const Gd=new c.fu(wn,kr,this.lut,jn);Hd=Gd,uc=Gd}Bo(Hd,uc)})}else Bo(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const ea=c.fk(Ks.glyphDependencies,da=>Object.keys(da).map(Number));Object.keys(ea).length?It.send("getGlyphs",{uid:this.uid,stacks:ea},(da,jn)=>{Tr||(Tr=da,Ot=jn,wi())},void 0,!1,qn):Ot={},jr=new Map;const ya=Array.from(Ks.iconDependencies.keys()).map(da=>c.I.parse(da));ya.length?It.send("getImages",{images:ya,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(da,jn)=>{if(!Tr){Tr=da,wn=new Map,dr=this.updateImageMapAndGetImageTaskQueue(wn,jn.images,Ks.iconDependencies);for(const[Aa,Yi]of jn.versions.entries())jr.set(Aa,Yi);wi()}},void 0,!1,qn):(wn=new Map,dr=new Map);const Mi=Array.from(Ks.patternDependencies.keys()).map(da=>c.I.parse(da));Mi.length?It.send("getImages",{images:Mi,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(da,jn)=>{if(!Tr){Tr=da,kr=new Map,Jr=this.updateImageMapAndGetImageTaskQueue(kr,jn.images,Ks.patternDependencies);for(const[Aa,Yi]of jn.versions.entries())jr.set(Aa,Yi);wi()}},void 0,!1,qn):(kr=new Map,Jr=new Map)}if(Ks.elevationFeatures&&Ks.elevationFeatures.length>0){const ea=[];for(const Mi of Object.values(Ns))if(Mi instanceof c.fl){const da=Mi.getUnevaluatedPortalGraph();da&&ea.push(da)}const ya=c.fm.evaluate(ea);for(const Mi of Object.values(Ns))if(Mi instanceof c.fl){const da=Oe.layers[xs.decode(Mi.sourceLayerIndex)];Mi.setEvaluatedPortalGraph(ya,da,this.tileID.canonical,Ks.availableImages,Ks.brightness)}}wi()};Un.length>0?Promise.allSettled(Un).then(Ar).catch(qt):Ar()}updateParameters(Oe){this.scaleFactor=Oe.scaleFactor,this.showCollisionBoxes=Oe.showCollisionBoxes,this.projection=Oe.projection,this.brightness=Oe.brightness,this.tileTransform=c.fc(Oe.tileID.canonical,Oe.projection),this.extraShadowCaster=Oe.extraShadowCaster,this.lut=Oe.lut,this.worldview=Oe.worldview,this.indoor=Oe.indoor}rasterizeIfNeeded(Oe,Qe,ct,vt){Array.from(Qe.values()).some(It=>It.usvg)?this.rasterize(Oe,Qe,ct,vt):vt()}updateImageMapAndGetImageTaskQueue(Oe,Qe,ct){const vt=new Map;for(const It of Qe.keys()){const qt=ct.get(It)||[];for(const xs of qt){const as=xs.toString(),Ns=Qe.get(xs.id.toString());Ns.usvg?vt.has(as)||(vt.set(as,xs),Oe.set(as,Object.assign({},Ns))):Oe.set(as,Ns)}}return vt}rasterize(Oe,Qe,ct,vt){this.rasterizeTask=Oe.send("rasterizeImages",{scope:this.scope,tasks:ct},(It,qt)=>{if(!It)for(const[xs,as]of qt.entries()){const Ns=Object.assign(Qe.get(xs),{data:as});Qe.set(xs,Ns)}vt()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function M(ts,Oe,Qe,ct,vt,It){const qt=new c.ae(Oe,{brightness:Qe,worldview:vt,activeFloors:It});for(const xs of ts)xs.recalculate(qt,ct)}class F extends c.E{constructor({actor:Oe,layerIndex:Qe,availableImages:ct,availableModels:vt,isSpriteLoaded:It,tileProvider:qt,brightness:xs,maxUniformBufferBindings:as,maxUniformBlockSizeDwords:Ns,disableSymbolUBO:ln}){super(),this.actor=Oe,this.layerIndex=Qe,this.availableImages=ct,this.availableModels=vt,this.loadVectorData=c.aO,this.tileProvider=qt,this.loading={},this.loaded={},this.deduped=new c.aN(Oe.scheduler),this.isSpriteLoaded=It,this.scheduler=Oe.scheduler,this.brightness=xs,this.maxUniformBufferBindings=as,this.maxUniformBlockSizeDwords=Ns,this.disableSymbolUBO=ln}loadTileData(Oe,Qe){if(!this.tileProvider)return this.loadVectorData(Oe,Qe);const ct=new AbortController,{z:vt,x:It,y:qt}=Oe.tileID.canonical;return this.tileProvider.loadTile({z:vt,x:It,y:qt},{request:Oe.request,signal:ct.signal}).then(xs=>{if(ct.signal.aborted)return;if(xs==null){const Ns=new Error("Tile not found");return Ns.status=404,Qe(Ns)}if(xs.data===null)return Qe(null,null);const as=new Map;xs.expires&&as.set("expires",xs.expires),xs.cacheControl&&as.set("cache-control",xs.cacheControl),Qe(null,{rawData:xs.data,responseHeaders:as})}).catch(xs=>{ct.signal.aborted||Qe(xs instanceof Error?xs:new Error(String(xs)))}),()=>ct.abort()}loadTile(Oe,Qe){const ct=Oe.uid,vt=Oe&&Oe.request,It=vt&&vt.collectResourceTiming,qt=this.loading[ct]=new L(Oe);qt.maxUniformBufferBindings=this.maxUniformBufferBindings,qt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,qt.disableSymbolUBO=this.disableSymbolUBO,qt.abort=this.loadTileData(Oe,(xs,as)=>{const Ns=!this.loading[ct];if(delete this.loading[ct],qt.cancelRasterize(),Ns||xs||!as)return qt.status="done",Ns||(this.loaded[ct]=qt),Qe(xs);const ln=as.rawData,Ks={},Un=c.aP(as.responseHeaders);Un&&Un.expires&&(Ks.expires=Un.expires),Un&&Un.cacheControl&&(Ks.cacheControl=Un.cacheControl),qt.vectorTile=as.vectorTile||new c.fx(new c.a$(ln));const br=()=>{qt.parse(qt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(Ar,sr)=>{if(Ar||!sr)return Qe(Ar);const Tr={};if(It){const Ot=d(vt);Ot.length>0&&(Tr.resourceTiming=JSON.parse(JSON.stringify(Ot)))}Qe(null,Object.assign({rawTileData:ln.slice(0),responseHeaders:as.responseHeaders},sr,Ks,Tr))})};this.isSpriteLoaded?br():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(br,{type:"parseTile",renderSourceType:Oe.renderSourceType,zoom:Oe.tileZoom}):br()}),this.loaded=this.loaded||{},this.loaded[ct]=qt})}reloadTile(Oe,Qe){const ct=this.loaded,vt=Oe.uid;if(ct&&ct[vt]){const It=ct[vt];It.updateParameters(Oe);const qt=(xs,as)=>{const Ns=It.reloadCallback;Ns&&(delete It.reloadCallback,It.parse(It.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Ns)),Qe(xs,as)};It.status==="parsing"?It.reloadCallback=qt:It.status==="done"&&(It.vectorTile?It.parse(It.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,qt):qt())}else Qe(null,void 0)}abortTile(Oe,Qe){const ct=Oe.uid,vt=this.loading[ct];vt&&(vt.abort&&vt.abort(),delete this.loading[ct]),Qe()}removeTile(Oe,Qe){const ct=this.loaded,vt=Oe.uid;ct&&ct[vt]&&delete ct[vt],Qe()}}class z{constructor(Oe){this.loading={}}loadTile(Oe,Qe){const ct=Oe.uid,{cancel:vt}=c.b1(Oe.request,(It,qt,xs)=>{const as=!this.loading[ct];if(delete this.loading[ct],as||It||!qt)return Qe(It);this.decodeTile(ct,qt,Oe.encoding).then(Ns=>{const{expires:ln,cacheControl:Ks}=c.aP(xs);Qe(null,Object.assign(Ns,{expires:ln,cacheControl:Ks}))}).catch(Ns=>Qe(Ns))});this.loading[ct]={cancel:vt}}async decodeTile(Oe,Qe,ct){const vt=await createImageBitmap(new Blob([new Uint8Array(Qe)],{type:"image/png"})),It=1-(vt.width-c.fy(vt.width))/2,qt=It<1,xs=this.getImageData(vt,It);return vt.close(),{dem:new c.fz(Oe,xs,ct,qt),borderReady:qt}}reloadTile(Oe,Qe){Qe(null,null)}abortTile(Oe,Qe){const ct=Oe.uid,vt=this.loading[ct];vt&&(vt.cancel(),delete this.loading[ct]),Qe()}removeTile(Oe,Qe){Qe()}getImageData(Oe,Qe){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(Oe.width,Oe.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=Oe.width,this.offscreenCanvas.height=Oe.height,this.offscreenCanvasContext.drawImage(Oe,0,0,Oe.width,Oe.height);const ct=this.offscreenCanvasContext.getImageData(-Qe,-Qe,Oe.width+2*Qe,Oe.height+2*Qe);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),ct}}c.a_.setPbf(c.a$);class V{constructor(Oe){this._mrt=new c.a_(Oe.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=Oe.uid,this.tileID=Oe.tileID,this.source=Oe.source}parse(Oe,Qe){const ct=this._mrt;this.status="parsing",this._entireBuffer=Oe;try{ct.parseHeader(Oe),this._isHeaderLoaded=!0;const vt=[];for(const It in ct.layers){const qt=ct.getLayer(It),xs=qt.getDataRange(qt.getBandList()),as=ct.createDecodingTask(xs),Ns=Oe.slice(xs.firstByte,xs.lastByte+1),ln=c.a_.performDecoding(Ns,as).then(Ks=>as.complete(null,Ks)).catch(Ks=>as.complete(Ks,null));vt.push(ln)}Promise.allSettled(vt).then(()=>Qe(null,ct)).catch(It=>Qe(It))}catch(vt){Qe(vt)}}}class W{constructor({actor:Oe}){this.actor=Oe,this.loading={},this.loaded={}}loadTile(Oe,Qe){const ct=Oe.uid,vt=Oe.request,It=this.loading[ct]=new V(Oe),{cancel:qt}=c.b1(vt,(xs,as,Ns)=>{const ln=!this.loading[ct];if(delete this.loading[ct],ln||xs||!as)return It.status="done",ln||(this.loaded[ct]=It),Qe(xs);It.parse(as,(Ks,Un)=>{if(Ks||!Un)return Qe(Ks);Qe(null,Un,Ns)}),this.loaded[ct]=It});It.abort=qt}reloadTile(Oe,Qe){Qe(null,void 0)}abortTile(Oe,Qe){const ct=Oe.uid,vt=this.loading[ct];vt&&(vt.abort&&vt.abort(),delete this.loading[ct]),Qe()}removeTile(Oe,Qe){const ct=Oe.uid;this.loaded[ct]&&delete this.loaded[ct],Qe()}decodeRasterArray(Oe,Qe){c.a_.performDecoding(Oe.buffer,Oe.task).then(ct=>Qe(null,ct)).catch(ct=>Qe(ct))}}const K=c.fA.prototype.toGeoJSON;class Y{constructor(Oe){this._feature=Oe,this.extent=c.an,this.type=Oe.type,this.properties=Oe.tags,"id"in Oe&&!isNaN(Oe.id)&&(this.id=parseInt(Oe.id,10))}loadGeometry(){if(this._feature.type===1){const Oe=[];for(const Qe of this._feature.geometry)Oe.push([new c.P(Qe[0],Qe[1])]);return Oe}{const Oe=[];for(const Qe of this._feature.geometry){const ct=[];for(const vt of Qe)ct.push(new c.P(vt[0],vt[1]));Oe.push(ct)}return Oe}}toGeoJSON(Oe,Qe,ct){return K.call(this,Oe,Qe,ct)}}class ee{constructor(Oe,Qe){this.name=Oe,this.extent=c.an,this.length=Qe.length,this._jsonFeatures=Qe}feature(Oe){return new Y(this._jsonFeatures[Oe])}}class ne{constructor(Oe){this.layers={},this.extent=c.an;for(const Qe of Object.keys(Oe))this.layers[Qe]=new ee(Qe,Oe[Qe])}}const oe=64/4096;class pe{constructor(){this.features=new Map}clear(){this.features.clear()}load(Oe=[],Qe){for(const ct of Oe){const vt=ct.id;if(vt==null)continue;let It=this.features.get(vt);It&&this.updateCache(It,Qe),ct.geometry?(It=de(ct),this.updateCache(It,Qe),this.features.set(vt,It)):this.features.delete(vt),this.updateCache(It,Qe)}}updateCache(Oe,Qe){for(const{canonical:ct,uid:vt}of Object.values(Qe)){const{z:It,x:qt,y:xs}=ct;ce(Oe,Math.pow(2,It),qt,xs)&&delete Qe[vt]}}getTile(Oe,Qe,ct){const vt=Math.pow(2,Oe),It=[];for(const qt of this.features.values())ce(qt,vt,Qe,ct)&&It.push(Me(qt,vt,Qe,ct));return{features:It}}getFeatures(){return[...this.features.values()]}}function ce({minX:ts,minY:Oe,maxX:Qe,maxY:ct},vt,It,qt){return ts<(It+1+oe)/vt&&Oe<(qt+1+oe)/vt&&Qe>(It-oe)/vt&&ct>(qt-oe)/vt}function de(ts){const{id:Oe,geometry:Qe,properties:ct}=ts;if(!Qe)return;if(Qe.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:vt,coordinates:It}=Qe,qt={id:Oe,type:1,geometry:[],tags:ct,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},xs=qt.geometry;if(vt==="Point")ie(It,xs,qt);else if(vt==="MultiPoint")for(const as of It)ie(as,xs,qt);else if(vt==="LineString")qt.type=2,ye(It,xs,qt);else if(vt==="MultiLineString")qt.type=2,_e(It,xs,qt);else if(vt==="Polygon")qt.type=3,_e(It,xs,qt,!0);else{if(vt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");qt.type=3;for(const as of It)_e(as,xs,qt,!0)}return qt}function ie([ts,Oe],Qe,ct){const vt=c.aH(ts);let It=c.aL(Oe);It=It<0?0:It>1?1:It,Qe.push(vt,It),ct.minX=Math.min(ct.minX,vt),ct.minY=Math.min(ct.minY,It),ct.maxX=Math.max(ct.maxX,vt),ct.maxY=Math.max(ct.maxY,It)}function ye(ts,Oe,Qe,ct=!1,vt=!1){const It=[];for(const qt of ts)ie(qt,It,Qe);Oe.push(It),ct&&function(qt,xs){let as=0;for(let Ns=0,ln=qt.length,Ks=ln-2;Ns0===xs)for(let Ns=0,ln=qt.length;Ns=qt&&Ks>=qt||(Ns>=qt?(ln+=Math.round(Ar*((qt-Ns)/br)),Ns=qt):Ks>=qt&&(Un=ln+Math.round(Ar*((qt-Ns)/br)),Ks=qt),ln>=qt&&Un>=qt||(ln>=qt?(Ns+=Math.round(br*((qt-ln)/Ar)),ln=qt):Un>=qt&&(Ks=Ns+Math.round(br*((qt-ln)/Ar)),Un=qt),xs&&Ns===xs[xs.length-1][0]&&ln===xs[xs.length-1][1]||(xs=[[Ns,ln]],vt.push(xs)),xs.push([Ks,Un])))))}}function Ce(ts,Oe,Qe,ct,vt){const It=(Qe-oe)/Oe,qt=(ct-oe)/Oe,xs=(Qe+1+oe)/Oe,as=(ct+1+oe)/Oe;function Ns(Un,br){let Ar=0;return Unxs&&(Ar|=2),bras&&(Ar|=8),Ar}let ln=[];for(let Un=1;Un<=8;Un*=2){let br=ts[ts.length-2],Ar=ts[ts.length-1],sr=!(Ns(br,Ar)&Un);for(let Tr=0;Tr>31}function ve(ts,Oe){const{geometry:Qe,type:ct}=ts;let vt=0,It=0;if(ct===1){Oe.writeVarint(Fe(1,Qe.length));for(const qt of Qe){const xs=qt[0]-vt,as=qt[1]-It;Oe.writeVarint(qe(xs)),Oe.writeVarint(qe(as)),vt+=xs,It+=as}}else for(const qt of Qe){if(qt.length===0)continue;Oe.writeVarint(Fe(1,1));const xs=qt.length-(ct===3?1:0);for(let as=0;asts},it=Math.fround||(Ne=new Float32Array(1),ts=>(Ne[0]=+ts,Ne[0]));var Ne;class He{constructor(Oe){this.options=Object.assign(Object.create(we),Oe),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(Oe){const{log:Qe,minZoom:ct,maxZoom:vt}=this.options;Qe&&console.time("total time");const It=`prepare ${Oe.length} points`;Qe&&console.time(It),this.points=Oe;const qt=[];for(let as=0;as=ct;as--){const Ns=+Date.now();xs=this.trees[as]=this._createTree(this._cluster(xs,as)),Qe&&console.log("z%d: %d clusters in %dms",as,xs.numItems,+Date.now()-Ns)}return Qe&&console.timeEnd("total time"),this}getClusters(Oe,Qe){let ct=((Oe[0]+180)%360+360)%360-180;const vt=Math.max(-90,Math.min(90,Oe[1]));let It=Oe[2]===180?180:((Oe[2]+180)%360+360)%360-180;const qt=Math.max(-90,Math.min(90,Oe[3]));if(Oe[2]-Oe[0]>=360)ct=-180,It=180;else if(ct>It){const Ks=this.getClusters([ct,vt,180,qt],Qe),Un=this.getClusters([-180,vt,It,qt],Qe);return Ks.concat(Un)}const xs=this.trees[this._limitZoom(Qe)],as=xs.range(Ke(ct),rt(qt),Ke(It),rt(vt)),Ns=xs.data,ln=[];for(const Ks of as){const Un=this.stride*Ks;ln.push(Ns[Un+5]>1?$e(Ns,Un,this.clusterProps):this.points[Ns[Un+3]])}return ln}getChildren(Oe){const Qe=this._getOriginId(Oe),ct=this._getOriginZoom(Oe),vt="No cluster with the specified id.",It=this.trees[ct];if(!It)throw new Error(vt);const qt=It.data;if(Qe*this.stride>=qt.length)throw new Error(vt);const xs=this.options.radius/(this.options.extent*Math.pow(2,ct-1)),as=It.within(qt[Qe*this.stride],qt[Qe*this.stride+1],xs),Ns=[];for(const ln of as){const Ks=ln*this.stride;qt[Ks+4]===Oe&&Ns.push(qt[Ks+5]>1?$e(qt,Ks,this.clusterProps):this.points[qt[Ks+3]])}if(Ns.length===0)throw new Error(vt);return Ns}getLeaves(Oe,Qe,ct){const vt=[];return this._appendLeaves(vt,Oe,Qe=Qe||10,ct=ct||0,0),vt}getTile(Oe,Qe,ct){const vt=this.trees[this._limitZoom(Oe)],It=Math.pow(2,Oe),{extent:qt,radius:xs}=this.options,as=xs/qt,Ns=(ct-as)/It,ln=(ct+1+as)/It,Ks={features:[]};return this._addTileFeatures(vt.range((Qe-as)/It,Ns,(Qe+1+as)/It,ln),vt.data,Qe,ct,It,Ks),Qe===0&&this._addTileFeatures(vt.range(1-as/It,Ns,1,ln),vt.data,It,ct,It,Ks),Qe===It-1&&this._addTileFeatures(vt.range(0,Ns,as/It,ln),vt.data,-1,ct,It,Ks),Ks.features.length?Ks:null}getClusterExpansionZoom(Oe){let Qe=this._getOriginZoom(Oe)-1;for(;Qe<=this.options.maxZoom;){const ct=this.getChildren(Oe);if(Qe++,ct.length!==1)break;Oe=ct[0].properties.cluster_id}return Qe}_appendLeaves(Oe,Qe,ct,vt,It){const qt=this.getChildren(Qe);for(const xs of qt){const as=xs.properties;if(as&&as.cluster?It+as.point_count<=vt?It+=as.point_count:It=this._appendLeaves(Oe,as.cluster_id,ct,vt,It):It1;let ln,Ks,Un;if(Ns)ln=Ye(Qe,as,this.clusterProps),Ks=Qe[as],Un=Qe[as+1];else{const sr=this.points[Qe[as+3]];ln=sr.properties;const[Tr,Ot]=sr.geometry.coordinates;Ks=Ke(Tr),Un=rt(Ot)}const br={type:1,geometry:[[Math.round(this.options.extent*(Ks*It-ct)),Math.round(this.options.extent*(Un*It-vt))]],tags:ln};let Ar;Ar=Ns||this.options.generateId?Qe[as+3]:this.points[Qe[as+3]].id,Ar!==void 0&&(br.id=Ar),qt.features.push(br)}}_limitZoom(Oe){return Math.max(this.options.minZoom,Math.min(Math.floor(+Oe),this.options.maxZoom+1))}_cluster(Oe,Qe){const{radius:ct,extent:vt,reduce:It,minPoints:qt}=this.options,xs=ct/(vt*Math.pow(2,Qe)),as=Oe.data,Ns=[],ln=this.stride;for(let Ks=0;KsQe&&(Tr+=as[wn+5])}if(Tr>sr&&Tr>=qt){let Ot,wn=Un*sr,kr=br*sr,dr=-1;const Jr=(Ks/ln<<5)+(Qe+1)+this.points.length;for(const jr of Ar){const qn=jr*ln;if(as[qn+2]<=Qe)continue;as[qn+2]=Qe;const wi=as[qn+5];wn+=as[qn]*wi,kr+=as[qn+1]*wi,as[qn+4]=Jr,It&&(Ot||(Ot=this._map(as,Ks,!0),dr=this.clusterProps.length,this.clusterProps.push(Ot)),It(Ot,this._map(as,qn)))}as[Ks+4]=Jr,Ns.push(wn/Tr,kr/Tr,1/0,Jr,-1,Tr),It&&Ns.push(dr)}else{for(let Ot=0;Ot1)for(const Ot of Ar){const wn=Ot*ln;if(!(as[wn+2]<=Qe)){as[wn+2]=Qe;for(let kr=0;kr>5}_getOriginZoom(Oe){return(Oe-this.points.length)%32}_map(Oe,Qe,ct){if(Oe[Qe+5]>1){const qt=this.clusterProps[Oe[Qe+6]];return ct?Object.assign({},qt):qt}const vt=this.points[Oe[Qe+3]].properties,It=this.options.map(vt);return ct&&It===vt?Object.assign({},It):It}}function $e(ts,Oe,Qe){return{type:"Feature",id:ts[Oe+3],properties:Ye(ts,Oe,Qe),geometry:{type:"Point",coordinates:[(ct=ts[Oe],360*(ct-.5)),tt(ts[Oe+1])]}};var ct}function Ye(ts,Oe,Qe){const ct=ts[Oe+5],vt=ct>=1e4?`${Math.round(ct/1e3)}k`:ct>=1e3?Math.round(ct/100)/10+"k":ct,It=ts[Oe+6],qt=It===-1?{}:Object.assign({},Qe[It]);return Object.assign(qt,{cluster:!0,cluster_id:ts[Oe+3],point_count:ct,point_count_abbreviated:vt})}function Ke(ts){return ts/360+.5}function rt(ts){const Oe=Math.sin(ts*Math.PI/180),Qe=.5-.25*Math.log((1+Oe)/(1-Oe))/Math.PI;return Qe<0?0:Qe>1?1:Qe}function tt(ts){const Oe=(180-360*ts)*Math.PI/180;return 360*Math.atan(Math.exp(Oe))/Math.PI-90}function at(ts,Oe,Qe,ct){let vt=ct;const It=Oe+(Qe-Oe>>1);let qt,xs=Qe-Oe;const as=ts[Oe],Ns=ts[Oe+1],ln=ts[Qe],Ks=ts[Qe+1];for(let Un=Oe+3;Unvt)qt=Un,vt=br;else if(br===vt){const Ar=Math.abs(Un-It);Arct&&(qt-Oe>3&&at(ts,Oe,qt,ct),ts[qt+2]=vt,Qe-qt>3&&at(ts,qt,Qe,ct))}function Ge(ts,Oe,Qe,ct,vt,It){let qt=vt-Qe,xs=It-ct;if(qt!==0||xs!==0){const as=((ts-Qe)*qt+(Oe-ct)*xs)/(qt*qt+xs*xs);as>1?(Qe=vt,ct=It):as>0&&(Qe+=qt*as,ct+=xs*as)}return qt=ts-Qe,xs=Oe-ct,qt*qt+xs*xs}function dt(ts,Oe,Qe,ct){const vt={id:ts??null,type:Oe,geometry:Qe,tags:ct,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(Oe==="Point"||Oe==="MultiPoint"||Oe==="LineString")Bt(vt,Qe);else if(Oe==="Polygon")Bt(vt,Qe[0]);else if(Oe==="MultiLineString")for(const It of Qe)Bt(vt,It);else if(Oe==="MultiPolygon")for(const It of Qe)Bt(vt,It[0]);return vt}function Bt(ts,Oe){for(let Qe=0;Qe0&&(qt+=ct?(vt*ln-Ns*It)/2:Math.sqrt(Math.pow(Ns-vt,2)+Math.pow(ln-It,2))),vt=Ns,It=ln}const xs=Oe.length-3;Oe[2]=1,at(Oe,0,xs,Qe),Oe[xs+2]=1,Oe.size=Math.abs(qt),Oe.start=0,Oe.end=Oe.size}function $s(ts,Oe,Qe,ct){for(let vt=0;vt1?1:Qe}function St(ts,Oe,Qe,ct,vt,It,qt,xs){if(ct/=Oe,It>=(Qe/=Oe)&&qt=ct)return null;const as=[];for(const Ns of ts){const ln=Ns.geometry;let Ks=Ns.type;const Un=vt===0?Ns.minX:Ns.minY,br=vt===0?Ns.maxX:Ns.maxY;if(Un>=Qe&&br=ct)continue;let Ar=[];if(Ks==="Point"||Ks==="MultiPoint")$t(ln,Ar,Qe,ct,vt);else if(Ks==="LineString")ht(ln,Ar,Qe,ct,vt,!1,xs.lineMetrics);else if(Ks==="MultiLineString")Es(ln,Ar,Qe,ct,vt,!1);else if(Ks==="Polygon")Es(ln,Ar,Qe,ct,vt,!0);else if(Ks==="MultiPolygon")for(const sr of ln){const Tr=[];Es(sr,Tr,Qe,ct,vt,!0),Tr.length&&Ar.push(Tr)}if(Ar.length){if(xs.lineMetrics&&Ks==="LineString"){for(const sr of Ar)as.push(dt(Ns.id,Ks,sr,Ns.tags));continue}Ks!=="LineString"&&Ks!=="MultiLineString"||(Ar.length===1?(Ks="LineString",Ar=Ar[0]):Ks="MultiLineString"),Ks!=="Point"&&Ks!=="MultiPoint"||(Ks=Ar.length===3?"Point":"MultiPoint"),as.push(dt(Ns.id,Ks,Ar,Ns.tags))}}return as.length?as:null}function $t(ts,Oe,Qe,ct,vt){for(let It=0;It=Qe&&qt<=ct&&Xt(Oe,ts[It],ts[It+1],ts[It+2])}}function ht(ts,Oe,Qe,ct,vt,It,qt){let xs=Ut(ts);const as=vt===0?Ys:Ss;let Ns,ln,Ks=ts.start;for(let Tr=0;TrQe&&(ln=as(xs,Ot,wn,dr,Jr,Qe),qt&&(xs.start=Ks+Ns*ln)):jr>ct?qn=Qe&&(ln=as(xs,Ot,wn,dr,Jr,Qe),wi=!0),qn>ct&&jr<=ct&&(ln=as(xs,Ot,wn,dr,Jr,ct),wi=!0),!It&&wi&&(qt&&(xs.end=Ks+Ns*ln),Oe.push(xs),xs=Ut(ts)),qt&&(Ks+=Ns)}let Un=ts.length-3;const br=ts[Un],Ar=ts[Un+1],sr=vt===0?br:Ar;sr>=Qe&&sr<=ct&&Xt(xs,br,Ar,ts[Un+2]),Un=xs.length-3,It&&Un>=3&&(xs[Un]!==xs[0]||xs[Un+1]!==xs[1])&&Xt(xs,xs[0],xs[1],xs[2]),xs.length&&Oe.push(xs)}function Ut(ts){const Oe=[];return Oe.size=ts.size,Oe.start=ts.start,Oe.end=ts.end,Oe}function Es(ts,Oe,Qe,ct,vt,It){for(const qt of ts)ht(qt,Oe,Qe,ct,vt,It,!1)}function Xt(ts,Oe,Qe,ct){ts.push(Oe,Qe,ct)}function Ys(ts,Oe,Qe,ct,vt,It){const qt=(It-Oe)/(ct-Oe);return Xt(ts,It,Qe+(vt-Qe)*qt,1),qt}function Ss(ts,Oe,Qe,ct,vt,It){const qt=(It-Qe)/(vt-Qe);return Xt(ts,Oe+(ct-Oe)*qt,It,1),qt}function Bs(ts,Oe){const Qe=[];for(let ct=0;ct0&&Oe.size<(vt?qt:ct))return void(Qe.numPoints+=Oe.length/3);const xs=[];for(let as=0;asqt)&&(Qe.numSimplified++,xs.push(Oe[as],Oe[as+1])),Qe.numPoints++;vt&&function(as,Ns){let ln=0;for(let Ks=0,Un=as.length,br=Un-2;Ks0===Ns)for(let Ks=0,Un=as.length;Ks24)throw new Error("maxZoom should be in the 0-24 range");if(Qe.promoteId&&Qe.generateId)throw new Error("promoteId and generateId cannot be used together.");let vt=function(It,qt){const xs=[];if(It.type==="FeatureCollection")for(let as=0;as1&&console.time("creation"),br=this.tiles[Un]=fn(Oe,Qe,ct,vt,Ns),this.tileCoords.push({z:Qe,x:ct,y:vt}),ln)){ln>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",Qe,ct,vt,br.numFeatures,br.numPoints,br.numSimplified),console.timeEnd("creation"));const wi=`z${Qe}`;this.stats[wi]=(this.stats[wi]||0)+1,this.total++}if(br.source=Oe,It==null){if(Qe===Ns.indexMaxZoom||br.numPoints<=Ns.indexMaxPoints)continue}else{if(Qe===Ns.maxZoom||Qe===It)continue;if(It!=null){const wi=It-Qe;if(ct!==qt>>wi||vt!==xs>>wi)continue}}if(br.source=null,Oe.length===0)continue;ln>1&&console.time("clipping");const Ar=.5*Ns.buffer/Ns.extent,sr=.5-Ar,Tr=.5+Ar,Ot=1+Ar;let wn=null,kr=null,dr=null,Jr=null,jr=St(Oe,Ks,ct-Ar,ct+Tr,0,br.minX,br.maxX,Ns),qn=St(Oe,Ks,ct+sr,ct+Ot,0,br.minX,br.maxX,Ns);Oe=null,jr&&(wn=St(jr,Ks,vt-Ar,vt+Tr,1,br.minY,br.maxY,Ns),kr=St(jr,Ks,vt+sr,vt+Ot,1,br.minY,br.maxY,Ns),jr=null),qn&&(dr=St(qn,Ks,vt-Ar,vt+Tr,1,br.minY,br.maxY,Ns),Jr=St(qn,Ks,vt+sr,vt+Ot,1,br.minY,br.maxY,Ns),qn=null),ln>1&&console.timeEnd("clipping"),as.push(wn||[],Qe+1,2*ct,2*vt),as.push(kr||[],Qe+1,2*ct,2*vt+1),as.push(dr||[],Qe+1,2*ct+1,2*vt),as.push(Jr||[],Qe+1,2*ct+1,2*vt+1)}}getTile(Oe,Qe,ct){Oe=+Oe,Qe=+Qe,ct=+ct;const vt=this.options,{extent:It,debug:qt}=vt;if(Oe<0||Oe>24)return null;const xs=1<1&&console.log("drilling down to z%d-%d-%d",Oe,Qe,ct);let Ns,ln=Oe,Ks=Qe,Un=ct;for(;!Ns&&ln>0;)ln--,Ks>>=1,Un>>=1,Ns=this.tiles[Ms(ln,Ks,Un)];return Ns&&Ns.source?(qt>1&&(console.log("found parent tile z%d-%d-%d",ln,Ks,Un),console.time("drilling down")),this.splitTile(Ns.source,ln,Ks,Un,Oe,Qe,ct),qt>1&&console.timeEnd("drilling down"),this.tiles[as]?sn(this.tiles[as],It):null):null}}function Ms(ts,Oe,Qe){return 32*((1<Ns.tags&&"3d_elevation_id"in Ns.tags&&"source"in Ns.tags&&Ns.tags.source==="elevation",It=ct.features.filter(Ns=>vt(Ns));let qt={_geojsonTileLayer:ct.features};It.length>0&&(qt={_geojsonTileLayer:ct.features.filter(Ns=>!vt(Ns)),hd_road_elevation:It});const xs=new ne(qt),as=function(Ns){const ln=new c.a$;for(const Ks of Object.keys(Ns))ln.writeMessage(3,Ee,{name:Ks,features:Ns[Ks]});return ln.finish()}(qt).buffer;Oe(null,{vectorTile:xs,rawData:as})}class Rr extends F{constructor(Oe){super(Oe),this.loadVectorData=bi,this._dynamicIndex=new pe}loadData(Oe,Qe){const ct=Oe&&Oe.request,vt=ct&&ct.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(Oe,(It,qt)=>{if(It||!qt)return Qe(It);if(typeof qt!="object")return Qe(new Error(`Input data given to '${Oe.source}' is not a valid GeoJSON object.`));{try{if(Oe.filter){const as=c.X(Oe.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(as.result==="error")throw new Error(as.value.map(Ns=>`${Ns.key}: ${Ns.message}`).join(", "));qt.features=qt.features.filter(Ns=>as.value.evaluate({zoom:0},Ns))}Oe.dynamic?(qt.type==="Feature"&&(qt={type:"FeatureCollection",features:[qt]}),Oe.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(qt.features,this.loaded),Oe.cluster&&(qt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=Oe.cluster?new He(function({superclusterOptions:as,clusterProperties:Ns}){if(!Ns||!as)return as;const ln={},Ks={},Un={accumulated:null,zoom:0},br={properties:null},Ar=Object.keys(Ns);for(const sr of Ar){const[Tr,Ot]=Ns[sr],wn=c.X(Ot),kr=c.X(typeof Tr=="string"?[Tr,["accumulated"],["get",sr]]:Tr);ln[sr]=wn.value,Ks[sr]=kr.value}return as.map=sr=>{br.properties=sr;const Tr={};for(const Ot of Ar)Tr[Ot]=ln[Ot].evaluate(Un,br);return Tr},as.reduce=(sr,Tr)=>{br.properties=Tr;for(const Ot of Ar)Un.accumulated=sr[Ot],sr[Ot]=Ks[Ot].evaluate(Un,br)},as}(Oe)).load(qt.features):Oe.dynamic?this._dynamicIndex:function(as,Ns){return new pi(as,Ns)}(qt,Oe.geojsonVtOptions)}catch(as){return Qe(as)}const xs={};if(vt){const as=d(ct);as&&(xs.resourceTiming={},xs.resourceTiming[Oe.source]=JSON.parse(JSON.stringify(as)))}Qe(null,xs)}})}reloadTile(Oe,Qe){const ct=this.loaded;return ct&&ct[Oe.uid]?Oe.partial?Qe(null,void 0):super.reloadTile(Oe,Qe):this.loadTile(Oe,Qe)}loadGeoJSON(Oe,Qe){if(Oe.request)c.m(Oe.request,Qe);else{if(typeof Oe.data!="string")return Qe(new Error(`Input data given to '${Oe.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return Qe(null,JSON.parse(Oe.data))}catch{return Qe(new Error(`Input data given to '${Oe.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(Oe,Qe){try{Qe(null,this._geoJSONIndex.getClusterExpansionZoom(Oe.clusterId))}catch(ct){Qe(ct)}}getClusterChildren(Oe,Qe){try{Qe(null,this._geoJSONIndex.getChildren(Oe.clusterId))}catch(ct){Qe(ct)}}getClusterLeaves(Oe,Qe){try{Qe(null,this._geoJSONIndex.getLeaves(Oe.clusterId,Oe.limit,Oe.offset))}catch(ct){Qe(ct)}}}class er{constructor(Oe,Qe,ct){this.tileID=new c.aR(Oe.tileID.overscaledZ,Oe.tileID.wrap,Oe.tileID.canonical.z,Oe.tileID.canonical.x,Oe.tileID.canonical.y),this.tileZoom=Oe.tileZoom,this.uid=Oe.uid,this.zoom=Oe.zoom,this.canonical=Oe.tileID.canonical,this.pixelRatio=Oe.pixelRatio,this.tileSize=Oe.tileSize,this.source=Oe.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=Oe.projection,this.brightness=Qe,this.worldview=ct}parse(Oe,Qe,ct,vt){this.status="parsing";const It=new c.aR(ct.tileID.overscaledZ,ct.tileID.wrap,ct.tileID.canonical.z,ct.tileID.canonical.x,ct.tileID.canonical.y),qt=[],xs=Qe.familiesBySource[ct.source],as=new c.ff(It,ct.promoteId);as.bucketLayerIDs=[],as.is3DTile=!0,c.fB(Oe).then(Ns=>{const ln=Ns.json.extensionsUsed&&Ns.json.extensionsUsed.includes("MAPBOX_mesh_features")||Ns.json.asset.extras&&Ns.json.asset.extras.MAPBOX_mesh_features,Ks=Ns.json.extensionsUsed&&Ns.json.extensionsUsed.includes("EXT_meshopt_compression"),Un=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const br in xs)for(const Ar of xs[br]){const sr=Ar[0];as.bucketLayerIDs.push(Ar.map(wn=>c.F(wn.id,wn.scope))),sr.recalculate(Un,[]);const Tr=c.fC(Ns,1/c.cS(ct.tileID.canonical)),Ot=new c.fD(Ar,Tr,It,ln,Ks,this.brightness,as,this.worldview);ln||(Ot.needsUpload=!0),qt.push(Ot),Ot.evaluate(sr)}this.status="done",vt(null,{buckets:qt,featureIndex:as,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(Ns=>vt(new Error(Ns.message)))}}class lr{constructor({actor:Oe,layerIndex:Qe,availableImages:ct,availableModels:vt,brightness:It,worldview:qt}){this.actor=Oe,this.layerIndex=Qe,this.availableImages=ct,this.availableModels=vt,this.brightness=It,this.loading={},this.loaded={},this.worldview=qt}loadTile(Oe,Qe){const ct=Oe.uid,vt=this.loading[ct]=new er(Oe,this.brightness,this.worldview);c.b1(Oe.request,(It,qt)=>{const xs=!this.loading[ct];return delete this.loading[ct],xs||It?(vt.status="done",xs||(this.loaded[ct]=vt),Qe(It)):qt&&qt.byteLength!==0?void vt.parse(qt,this.layerIndex,Oe,(as,Ns)=>{vt.status="done",this.loaded=this.loaded||{},this.loaded[ct]=vt,as||!Ns?Qe(as):Qe(null,Ns)}):(vt.status="done",this.loaded[ct]=vt,Qe())})}reloadTile(Oe,Qe){const ct=this.loaded,vt=Oe.uid;if(ct&&ct[vt]){const It=ct[vt];It.projection=Oe.projection,It.brightness=Oe.brightness;const qt=(xs,as)=>{It.reloadCallback&&(delete It.reloadCallback,this.loadTile(Oe,Qe)),Qe(xs,as)};It.status==="parsing"?It.reloadCallback=qt:It.status==="done"&&this.loadTile(Oe,Qe)}}abortTile(Oe,Qe){const ct=Oe.uid;this.loading[ct]&&delete this.loading[ct],Qe()}removeTile(Oe,Qe){const ct=this.loaded,vt=Oe.uid;ct&&ct[vt]&&delete ct[vt],Qe()}}const Fs=new Map,$n=new Map;class Cr{constructor(Oe){this.self=Oe,this.actor=new c.A(Oe,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.imageRasterizer=new c.z,this.rtlPluginParsingListeners=[],this.projections={},this.defaultProjection=c.c0({name:"mercator"}),this.workerSourceTypes={vector:F,geojson:Rr,"raster-dem":z,"raster-array":W,"batched-model":lr},this.workerSources={},this.self.registerWorkerSource=(Qe,ct)=>{if(this.workerSourceTypes[Qe])throw new Error(`Worker source with name "${Qe}" already registered.`);this.workerSourceTypes[Qe]=ct},this.self.registerRTLTextPlugin=Qe=>{if(c.fF.isParsed())throw new Error("RTL text plugin already registered.");c.fF.setState({pluginStatus:c.fG.parsed,pluginURL:c.fF.getPluginURL()}),c.fF.applyArabicShaping=Qe.applyArabicShaping,c.fF.processBidirectionalText=Qe.processBidirectionalText,c.fF.processStyledBidirectionalText=Qe.processStyledBidirectionalText;for(const ct of this.rtlPluginParsingListeners)ct(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(Oe,Qe,ct){delete this.layerIndexes[Oe],delete this.availableImages[Oe],delete this.availableModels[Oe],delete this.workerSources[Oe],ct()}checkIfReady(Oe,Qe,ct){ct()}setReferrer(Oe,Qe){this.referrer=Qe}spriteLoaded(Oe,Qe){this.isSpriteLoaded[Oe]||(this.isSpriteLoaded[Oe]={});const{scope:ct,isLoaded:vt}=Qe;if(this.isSpriteLoaded[Oe][ct]=vt,this.workerSources[Oe]&&this.workerSources[Oe][ct])for(const It in this.workerSources[Oe][ct]){const qt=this.workerSources[Oe][ct][It];for(const xs in qt){const as=qt[xs];as instanceof F&&(as.isSpriteLoaded=vt,as.fire(new c.C("isSpriteLoaded")))}}}setImages(Oe,Qe,ct){this.availableImages[Oe]||(this.availableImages[Oe]={});const{scope:vt,images:It}=Qe;if(this.availableImages[Oe][vt]=It,this.workerSources[Oe]&&this.workerSources[Oe][vt]){for(const qt in this.workerSources[Oe][vt]){const xs=this.workerSources[Oe][vt][qt];for(const as in xs)xs[as].availableImages=It}ct()}else ct()}setModels(Oe,{scope:Qe,models:ct},vt){if(this.availableModels[Oe]||(this.availableModels[Oe]={}),this.availableModels[Oe][Qe]=ct,this.workerSources[Oe]&&this.workerSources[Oe][Qe]){for(const It in this.workerSources[Oe][Qe]){const qt=this.workerSources[Oe][Qe][It];for(const xs in qt)qt[xs].availableModels=ct}vt()}else vt()}setProjection(Oe,Qe){this.projections[Oe]=c.c0(Qe)}setBrightness(Oe,Qe,ct){this.brightness=Qe,ct()}setContextParams(Oe,Qe,ct){this.maxUniformBufferBindings=Qe.maxBindingPoints,this.maxUniformBlockSizeDwords=Qe.maxUniformBlockSizeDwords,this.disableSymbolUBO=Qe.disableSymbolUBO,ct()}setWorldview(Oe,Qe,ct){this.worldview=Qe,ct()}setLayers(Oe,Qe,ct){this.getLayerIndex(Oe,Qe.scope).replace(Qe.layers,Qe.options),ct()}updateLayers(Oe,Qe,ct){this.getLayerIndex(Oe,Qe.scope).update(Qe.layers,Qe.removedIds,Qe.options),ct()}loadTile(Oe,Qe,ct){Qe.projection=this.projections[Oe]||this.defaultProjection,this.getWorkerSource(Oe,Qe).loadTile(Qe,ct)}decodeRasterArray(Oe,Qe,ct){this.getWorkerSource(Oe,Qe).decodeRasterArray(Qe,ct)}reloadTile(Oe,Qe,ct){Qe.projection=this.projections[Oe]||this.defaultProjection,this.getWorkerSource(Oe,Qe).reloadTile(Qe,ct)}abortTile(Oe,Qe,ct){this.getWorkerSource(Oe,Qe).abortTile(Qe,ct)}removeTile(Oe,Qe,ct){this.getWorkerSource(Oe,Qe).removeTile(Qe,ct)}removeSource(Oe,Qe,ct){if(!(this.workerSources[Oe]&&this.workerSources[Oe][Qe.scope]&&this.workerSources[Oe][Qe.scope][Qe.type]&&this.workerSources[Oe][Qe.scope][Qe.type][Qe.source]))return;const vt=this.workerSources[Oe][Qe.scope][Qe.type][Qe.source];delete this.workerSources[Oe][Qe.scope][Qe.type][Qe.source],vt.removeSource!==void 0?vt.removeSource(Qe,ct):ct()}loadTileProvider(Oe,Qe,ct){(async function(vt,It){const qt=$n.get(vt);if(qt)return qt;const xs=Fs.get(vt);if(xs!==void 0)return xs;const as=import(It).then(Ns=>{const ln=Ns.default;if(typeof ln!="function")throw new Error(`TileProvider "${vt}" module must default-export a class`);if(typeof ln.prototype.loadTile!="function")throw new Error(`TileProvider "${vt}" class must have a loadTile method`);return $n.set(vt,ln),ln}).finally(()=>{Fs.delete(vt)});return Fs.set(vt,as),as})(Qe.name,Qe.url).then(vt=>{const It=new vt(Qe.options);return this.getWorkerSource(Oe,{type:Qe.type,source:Qe.source,scope:Qe.scope},It),It.load&&Qe.request?It.load({request:Qe.request}):null}).then(vt=>ct(null,vt)).catch(vt=>ct(vt instanceof Error?vt:new Error(typeof vt=="string"?vt:"Unknown error")))}loadWorkerSource(Oe,Qe,ct){try{this.self.importScripts(Qe.url),ct()}catch(vt){ct(vt)}}syncRTLPluginState(Oe,Qe,ct){if(c.fF.isParsed())ct(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(ct);else try{c.fF.setState(Qe);const vt=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||vt==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(vt),c.fF.isParsed()?ct(null,!0):this.rtlPluginParsingListeners.push(ct))}catch(vt){ct(vt)}}setConfig(Oe,Qe){Object.assign(c.g,Qe)}getAvailableImages(Oe,Qe){this.availableImages[Oe]||(this.availableImages[Oe]={});let ct=this.availableImages[Oe][Qe];return ct||(ct=[]),ct}getAvailableModels(Oe,Qe){this.availableModels[Oe]||(this.availableModels[Oe]={});let ct=this.availableModels[Oe][Qe];return ct||(ct={}),ct}getLayerIndex(Oe,Qe){this.layerIndexes[Oe]||(this.layerIndexes[Oe]={});let ct=this.layerIndexes[Oe][Qe];return ct||(ct=this.layerIndexes[Oe][Qe]=new f,ct.scope=Qe),ct}getWorkerSource(Oe,Qe,ct){const{type:vt,source:It,scope:qt}=Qe,xs=this.workerSources;if(xs[Oe]||(xs[Oe]={}),xs[Oe][qt]||(xs[Oe][qt]={}),xs[Oe][qt][vt]||(xs[Oe][qt][vt]={}),this.isSpriteLoaded[Oe]||(this.isSpriteLoaded[Oe]={}),!xs[Oe][qt][vt][It]){const as={send:(ln,Ks,Un,br,Ar,sr)=>this.actor.send(ln,Ks,Un,Oe,Ar,sr),scheduler:this.actor.scheduler},Ns=this.workerSourceTypes[vt];if(!Ns)throw new Error(`Unknown worker source type "${vt}".`);xs[Oe][qt][vt][It]=new Ns({actor:as,layerIndex:this.getLayerIndex(Oe,qt),availableImages:this.getAvailableImages(Oe,qt),availableModels:this.getAvailableModels(Oe,qt),isSpriteLoaded:this.isSpriteLoaded[Oe][qt],tileProvider:ct,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return xs[Oe][qt][vt][It]}rasterizeImagesWorker(Oe,Qe,ct){const vt=new Map;for(const[It,{image:qt,imageVariant:xs}]of Qe.tasks.entries()){const as=this.imageRasterizer.rasterize(xs,qt,Qe.scope,Oe);vt.set(It,as)}ct(void 0,vt)}removeRasterizedImages(Oe,Qe,ct){this.imageRasterizer.removeImagesFromCacheByIds(Qe.imageIds,Qe.scope,Oe),ct()}enforceCacheSizeLimit(Oe,Qe){c.fH(Qe)}getWorkerPerformanceMetrics(Oe,Qe,ct){ct(void 0,void 0)}}return c.fE(self)&&(self.worker=new Cr(self)),Cr}),i(["./shared"],function(o){var c="3.22.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},u={mark(I){performance.mark(I)},measure(I,y,C){performance.measure(I,y,C)}};function h(I){const y=I.name.split("?")[0];return o.a(y)&&y.includes("mapbox-gl.js")?"javascript":o.a(y)&&y.includes("mapbox-gl.css")?"css":o.b(y)?"fontRange":o.c(y)?"sprite":o.i(y)?"style":o.d(y)?"tilejson":"other"}var p,f={},g=function(){if(p)return f;function I(R){return!y(R)}function y(R){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var G,Z,te=new Blob([""],{type:"text/javascript"}),ue=URL.createObjectURL(te);try{Z=new Worker(ue),G=!0}catch{G=!1}return Z&&Z.terminate(),URL.revokeObjectURL(ue),G}()?function(){var G=document.createElement("canvas");G.width=G.height=1;var Z=G.getContext("2d");if(!Z)return!1;var te=Z.getImageData(0,0,1,1);return te&&te.width===G.width}()?(C[$=R&&R.failIfMajorPerformanceCaveat]===void 0&&(C[$]=function(G){var Z,te=function(ue){var xe=document.createElement("canvas"),je=Object.create(I.webGLContextAttributes);return je.failIfMajorPerformanceCaveat=ue,xe.getContext("webgl2",je)}(G);if(!te)return!1;try{Z=te.createShader(te.VERTEX_SHADER)}catch{return!1}return!(!Z||te.isContextLost())&&(te.shaderSource(Z,"void main() {}"),te.compileShader(Z),te.getShaderParameter(Z,te.COMPILE_STATUS)===!0)}($)),C[$]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var $}p=1,f.supported=I,f.notSupportedReason=y;var C={};return I.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},f}();function b(I,y,C){const R=document.createElement(I);return y!=null&&(R.className=y),C&&C.appendChild(R),R}function v(I,y,C){const R=document.createElementNS("http://www.w3.org/2000/svg",I);for(const $ of Object.keys(y))R.setAttributeNS(null,$,String(y[$]));return C&&C.appendChild(R),R}const j=typeof document<"u"?document.documentElement&&document.documentElement.style:null,_=j&&j.userSelect!==void 0?"userSelect":"WebkitUserSelect";let S;function A(){j&&_&&(S=j[_],j[_]="none")}function T(){j&&_&&(j[_]=S)}function D(I){I.preventDefault(),I.stopPropagation(),window.removeEventListener("click",D,!0)}function L(){window.addEventListener("click",D,!0),window.setTimeout(()=>{window.removeEventListener("click",D,!0)},0)}function M(I,y){const C=I.getBoundingClientRect();return V(I,C,y)}function F(I,y){const C=I.getBoundingClientRect(),R=[];for(let $=0;$this._skuTokenExpiresAt}transformRequest(y,C){return this._transformRequestFn&&this._transformRequestFn(y,C)||{url:y}}normalizeStyleURL(y,C){if(!o.e(y))return y;const R=ne(y);return R.params.push(`sdk=js-${c}`),R.path=`/styles/v1${R.path}`,this._makeAPIURL(R,this._customAccessToken||C)}normalizeGlyphsURL(y,C){if(!o.e(y))return y;const R=ne(y);return R.path=`/fonts/v1${R.path}`,this._makeAPIURL(R,this._customAccessToken||C)}normalizeModelURL(y,C){if(!o.e(y))return y;const R=ne(y);return R.path=`/models/v1${R.path}`,this._makeAPIURL(R,this._customAccessToken||C)}normalizeSourceURL(y,C,R,$){if(!o.e(y))return y;const G=ne(y);return G.path=`/v4/${G.authority}.json`,G.params.push("secure"),R&&G.params.push(`language=${R}`),$&&G.params.push(`worldview=${$}`),this._makeAPIURL(G,this._customAccessToken||C)}normalizeIconsetURL(y,C){const R=ne(y);return o.e(y)?(R.path=`/styles/v1${R.path}/iconset.pbf`,this._makeAPIURL(R,this._customAccessToken||C)):oe(R)}normalizeSpriteURL(y,C,R,$){const G=ne(y);return o.e(y)?(G.path=`/styles/v1${G.path}/sprite${C}${R}`,this._makeAPIURL(G,this._customAccessToken||$)):(G.path+=`${C}${R}`,oe(G))}normalizeTileURL(y,C,R){if(this._isSkuTokenExpired()&&this._createSkuToken(),y&&!o.e(y))return y;const $=ne(y);$.path=$.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${C||R&&$.authority!=="raster"&&R===512?"@2x":""}${o.k.supported?".webp":"$1"}`),$.authority==="raster"?$.path=`/${o.g.RASTER_URL_PREFIX}${$.path}`:$.authority==="rasterarrays"?$.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${$.path}`:$.authority==="3dtiles"?$.path=`/${o.g.TILES3D_URL_PREFIX}${$.path}`:($.path=$.path.replace(/^.+\/v4\//,"/"),$.path=`/${o.g.TILE_URL_VERSION}${$.path}`);const G=this._customAccessToken||function(Z){for(const te of Z){const ue=te.match(/^access_token=(.*)$/);if(ue)return ue[1]}return null}($.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&G&&this._skuToken&&$.params.push(`sku=${this._skuToken}`),this._makeAPIURL($,G)}canonicalizeTileURL(y,C){const R=ne(y);if(!R.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!R.path.match(/\.[\w]+$/))return y;let $="mapbox://";R.path.match(/^\/raster\/v1\//)?$+=`raster/${R.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:R.path.match(/^\/rasterarrays\/v1\//)?$+=`rasterarrays/${R.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:$+=`tiles/${R.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let G=R.params;return C&&(G=G.filter(Z=>!Z.match(/^access_token=/))),G.length&&($+=`?${G.join("&")}`),$}canonicalizeTileset(y,C){const R=!!C&&o.e(C),$=[];for(const G of y.tiles||[])o.f(G)?$.push(this.canonicalizeTileURL(G,R)):$.push(G);return $}_makeAPIURL(y,C){const R="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",$=ne(o.g.API_URL);if(y.protocol=$.protocol,y.authority=$.authority,y.protocol==="http"){const G=y.params.indexOf("secure");G>=0&&y.params.splice(G,1)}if($.path!=="/"&&(y.path=`${$.path}${y.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return oe(y);if(C=C||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!C)throw new Error(`An API access token is required to use Mapbox GL. ${R}`);if(C[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${R}`)}return y.params=y.params.filter(G=>G.indexOf("access_token")===-1),y.params.push(`access_token=${C||""}`),oe(y)}}const ee=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function ne(I){const y=I.match(ee);if(!y)throw new Error("Unable to parse URL object");return{protocol:y[1],authority:y[2],path:y[3]||"/",params:y[4]?y[4].split("&"):[]}}function oe(I){const y=I.params.length?`?${I.params.join("&")}`:"";return`${I.protocol}://${I.authority}${I.path}${y}`}const pe="mapbox.eventData";function ce(I){if(!I)return null;const y=I.split(".");if(!y||y.length!==3)return null;try{return JSON.parse(o.l(y[1]))}catch{return null}}function de(I){return!(!o.g.EVENTS_URL||!I&&!o.g.ACCESS_TOKEN)}class ie{constructor(y){this.type=y,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(y){const C=ce(o.g.ACCESS_TOKEN);let R="";return R=C&&C.u?o.j(C.u):o.g.ACCESS_TOKEN||"",y?`${pe}.${y}:${R}`:`${pe}:${R}`}fetchEventData(){const y=o.s("localStorage"),C=this.getStorageKey(),R=this.getStorageKey("uuid"),$=this.getStorageKey("uuidTimestamp");if(y)try{const G=localStorage.getItem(C);G&&(this.eventData=JSON.parse(G));const Z=localStorage.getItem(R);Z&&(this.anonId=Z);const te=localStorage.getItem($);te&&(this.anonIdTimestamp=Number(te));const ue=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(C,JSON.stringify(this.eventData)),Z&&localStorage.setItem($,Z.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(y){}postEvent(y,C,R,$){if(!o.g.EVENTS_URL)return;const G=ne(o.g.EVENTS_URL);G.params.push(`access_token=${$||o.g.ACCESS_TOKEN||""}`);const Z={event:this.type,created:new Date(y).toISOString()},te=C?Object.assign(Z,C):Z,ue={url:oe(G),headers:{"Content-Type":"text/plain"},body:JSON.stringify([te])};this.pendingRequest=o.p(ue,xe=>{this.pendingRequest=null,R(xe),this.saveEventData(),this.processRequests($)})}queueRequest(y,C){this.queue.push(y),this.processRequests(C)}}class ye extends ie{constructor(y){super("metrics"),y&&(this.data=y)}postMetricsEvent(y){if(!de(y))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const C=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:C},y)}processRequests(y){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:C,payload:R}=this.queue.shift();this.postEvent(C,R,()=>{},y)}}const _e=new class extends ie{constructor(I){super("appUserTurnstile"),this._customAccessToken=I}postTurnstileEvent(I,y){de(y)&&Array.isArray(I)&&I.some(C=>o.e(C)||o.f(C))&&this.queueRequest(Date.now(),y)}processRequests(I){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const y=ce(o.g.ACCESS_TOKEN),C=y?y.u:o.g.ACCESS_TOKEN;let R=C!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),R=!0);const $=this.queue.shift();if(this.eventData.lastSuccess){const G=new Date(this.eventData.lastSuccess),Z=new Date($),te=($-this.eventData.lastSuccess)/864e5;R=R||te>=1||te<-1||G.getDate()!==Z.getDate()}else R=!0;R?this.postEvent($,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:W,"enabled.telemetry":!1,userId:this.anonId},G=>{G||(this.eventData.lastSuccess=$,this.eventData.tokenU=C)},I):this.processRequests()}},Me=_e.postTurnstileEvent.bind(_e),Te=new class extends ie{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(I,y,C,R){this.skuToken=y,this.errorCb=R,o.g.EVENTS_URL&&(C||o.g.ACCESS_TOKEN?this.queueRequest({id:I,timestamp:Date.now()},C):this.errorCb(new Error(K)))}processRequests(I){if(this.pendingRequest||this.queue.length===0)return;const{id:y,timestamp:C}=this.queue.shift();y&&this.success[y]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(C,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:W,skuToken:this.skuToken,userId:this.anonId},R=>{R?this.errorCb(R):y&&(this.success[y]=!0)},I))}remove(){this.errorCb=null}},Ce=Te.postMapLoadEvent.bind(Te),Ee=new class extends ie{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(I){let y=this.mapInstanceIdMap.get(I);return y||(y=o.u(),this.mapInstanceIdMap.set(I,y)),y}getEventId(I){const y=this.eventIdPerMapInstanceMap.get(I)||0;return this.eventIdPerMapInstanceMap.set(I,y+1),y}postStyleLoadEvent(I,y){const{map:C,style:R,importedStyles:$}=y;if(!de(I))return;const G=this.getMapInstanceId(C),Z={mapInstanceId:G,eventId:this.getEventId(G),style:R};$.length&&(Z.importedStyles=$),this.queueRequest({timestamp:Date.now(),payload:Z},I)}processRequests(I){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:y,payload:C}=this.queue.shift();this.postEvent(y,C,()=>{},I)}},De=Ee.postStyleLoadEvent.bind(Ee),Ie=new ye({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Fe=Ie.postMetricsEvent.bind(Ie),qe=new ye({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),ve=qe.postMetricsEvent.bind(qe),Je=new class extends ie{constructor(){super("gljs.performance")}postPerformanceEvent(I,y){de(I)&&this.queueRequest({timestamp:Date.now(),performanceData:y},I)}processRequests(I){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:y,performanceData:C}=this.queue.shift(),R=function($){const G=performance.getEntriesByType("resource"),Z=performance.getEntriesByType("mark"),te=function(Ue){const st={};if(Ue){for(const Xe in Ue)if(Xe!=="other")for(const pt of Ue[Xe]){const mt=`${Xe}ResolveRangeMin`,jt=`${Xe}ResolveRangeMax`,Tt=`${Xe}RequestCount`,xt=`${Xe}RequestCachedCount`;st[mt]=Math.min(st[mt]||1/0,pt.startTime),st[jt]=Math.max(st[jt]||-1/0,pt.responseEnd);const es=Ft=>{st[Ft]===void 0&&(st[Ft]=0),++st[Ft]};pt.transferSize!==void 0&&pt.transferSize===0&&es(xt),es(Tt)}}return st}(function(Ue,st){const Xe={};if(Ue)for(const pt of Ue){const mt=st(pt);Xe[mt]===void 0&&(Xe[mt]=[]),Xe[mt].push(pt)}return Xe}(G,h)),ue=window.devicePixelRatio,xe=navigator.connection||navigator.mozConnection||navigator.webkitConnection,je=xe?xe.effectiveType:void 0,Re={counters:[],metadata:[],attributes:[]},Le=(Ue,st,Xe)=>{Xe!=null&&Ue.push({name:st,value:Xe.toString()})};for(const Ue in te)Le(Re.counters,Ue,te[Ue]);if($.interactionRange[0]!==1/0&&$.interactionRange[1]!==-1/0&&(Le(Re.counters,"interactionRangeMin",$.interactionRange[0]),Le(Re.counters,"interactionRangeMax",$.interactionRange[1])),Z)for(const Ue of Object.values(d)){const st=Z.find(Xe=>Xe.name===Ue);st&&Le(Re.counters,Ue,st.startTime)}return Le(Re.counters,"visibilityHidden",$.visibilityHidden),Le(Re.attributes,"style",function(Ue){if(Ue)for(const st of Ue){const Xe=st.name.split("?")[0];if(o.i(Xe)){const pt=Xe.split("/").slice(-2);if(pt.length===2)return`mapbox://styles/${pt[0]}/${pt[1]}`}}}(G)),Le(Re.attributes,"terrainEnabled",$.terrainEnabled?"true":"false"),Le(Re.attributes,"fogEnabled",$.fogEnabled?"true":"false"),Le(Re.attributes,"projection",$.projection),Le(Re.attributes,"zoom",$.zoom),Le(Re.metadata,"devicePixelRatio",ue),Le(Re.metadata,"connectionEffectiveType",je),Le(Re.metadata,"navigatorUserAgent",navigator.userAgent),Le(Re.metadata,"screenWidth",window.screen.width),Le(Re.metadata,"screenHeight",window.screen.height),Le(Re.metadata,"windowWidth",window.innerWidth),Le(Re.metadata,"windowHeight",window.innerHeight),Le(Re.metadata,"mapWidth",$.width/ue),Le(Re.metadata,"mapHeight",$.height/ue),Le(Re.metadata,"webglRenderer",$.renderer),Le(Re.metadata,"webglVendor",$.vendor),Le(Re.metadata,"sdkVersion",c),Le(Re.metadata,"sdkIdentifier","mapbox-gl-js"),Re}(C);for(const $ of R.metadata);for(const $ of R.counters);for(const $ of R.attributes);this.postEvent(y,R,()=>{},I)}},we=Je.postPerformanceEvent.bind(Je),it=new class extends ie{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(I,y,C,R){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const $=ne(o.g.API_URL+o.g.SESSION_PATH);$.params.push(`sku=${y||""}`),$.params.push(`access_token=${R||o.g.ACCESS_TOKEN||""}`);const G={url:oe($),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(G,Z=>{this.pendingRequest=null,C(Z),this.saveEventData(),this.processRequests(R)})}getSessionAPI(I,y,C,R){this.skuToken=y,this.errorCb=R,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(C||o.g.ACCESS_TOKEN?this.queueRequest({id:I,timestamp:Date.now()},C):this.errorCb(new Error(K)))}processRequests(I){if(this.pendingRequest||this.queue.length===0)return;const{id:y,timestamp:C}=this.queue.shift();y&&this.success[y]||this.getSession(C,this.skuToken,R=>{R?this.errorCb(R):y&&(this.success[y]=!0)},I)}remove(){this.errorCb=null}},Ne=it.getSessionAPI.bind(it),He=new Set;function $e(I,y){y?He.add(I):He.delete(I)}class Ye{constructor(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps=new Set,this._updatedImages={}}isDirty(){return this._changed}setDirty(){this._changed=!0}getUpdatedSourceCaches(){return this._updatedSourceCaches}updateSourceCache(y,C){this._updatedSourceCaches[y]=C,this.setDirty()}discardSourceCacheUpdate(y){delete this._updatedSourceCaches[y]}updateLayer(y){const C=y.scope;this._updatedLayers[C]=this._updatedLayers[C]||new Set,this._updatedLayers[C].add(y.id),this.setDirty()}removeLayer(y){const C=y.scope;this._removedLayers[C]=this._removedLayers[C]||{},this._updatedLayers[C]=this._updatedLayers[C]||new Set,this._removedLayers[C][y.id]=y,this._updatedLayers[C].delete(y.id),this._updatedPaintProps.delete(y.fqid),this.setDirty()}getRemovedLayer(y){return this._removedLayers[y.scope]?this._removedLayers[y.scope][y.id]:null}discardLayerRemoval(y){this._removedLayers[y.scope]&&delete this._removedLayers[y.scope][y.id]}getLayerUpdatesByScope(){const y={};for(const C in this._updatedLayers)y[C]=y[C]||{},y[C].updatedIds=Array.from(this._updatedLayers[C].values());for(const C in this._removedLayers)y[C]=y[C]||{},y[C].removedIds=Object.keys(this._removedLayers[C]);return y}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(y){this._updatedPaintProps.add(y.fqid),this.setDirty()}getUpdatedImages(y){return this._updatedImages[y]?Array.from(this._updatedImages[y].values()):[]}updateImage(y,C){this._updatedImages[C]=this._updatedImages[C]||new Set,this._updatedImages[C].add(o.I.toString(y)),this.setDirty()}resetUpdatedImages(y){this._updatedImages[y]&&this._updatedImages[y].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function Ke(I){const{userImage:y}=I;return!!(y&&y.render&&y.render())&&(I.data.replace(new Uint8Array(y.data.buffer)),!0)}const rt={workerUrl:"",workerClass:null,workerParams:void 0};function tt(I){return rt.workerClass!=null?new rt.workerClass:new self.Worker(rt.workerUrl,Object.assign({name:I},rt.workerParams))}const at="mapboxgl_preloaded_worker_pool";class Ge{constructor(y){this.active={},this.name=y}acquire(y,C=Ge.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{C.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[at]}numActive(){return Object.keys(this.active).length}}Ge.workerCount=2;class dt{constructor(y,C,R="Worker",$=Ge.workerCount){this.workerPool=y,this.actors=[],this.currentActor=0,this.id=o.r();const G=this.workerPool.acquire(this.id,$);for(let Z=0;Z{this.ready=!0})}broadcast(y,C,R){o.t(this.actors,($,G)=>{$.send(y,C,G)},R=R||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(y=>{y.remove()}),this.actors=[],this.workerPool.release(this.id)}}let Bt,kt;function Qt(){return Bt||(Bt=new Ge),Bt}dt.Actor=o.A;class ns extends o.E{constructor(y){super(),this.imageProviders=new Map,this.images=new Map,this.updatedImages=new Map,this.callbackDispatchedThisFrame=new Map,this.imageVersions=new Map,this.loaded=new Map,this.requestors=[],this.patterns=new Map,this.patternsInFlight=new Set,this.atlasImage=new Map,this.atlasTexture=new Map,this.imageAtlasCache=new o.x,this.dirty=!0,this.spriteFormat=y,y!=="raster"&&o.y()&&(this.imageRasterizerDispatcher=new dt((kt||(kt=new Ge("ImageRasterizer")),kt),this,"Image Rasterizer Worker",1))}addScope(y){this.loaded.set(y,!1),this.imageProviders.set(y,new Map),this.images.set(y,new Map),this.updatedImages.set(y,new Set),this.callbackDispatchedThisFrame.set(y,new Set),this.imageVersions.set(y,new Map),this.patterns.set(y,new Map),this.atlasImage.set(y,new o.q({width:1,height:1}))}removeScope(y){this.loaded.delete(y),this.imageProviders.delete(y),this.images.delete(y),this.updatedImages.delete(y),this.callbackDispatchedThisFrame.delete(y),this.imageVersions.delete(y),this.patterns.delete(y),this.atlasImage.delete(y);const C=this.atlasTexture.get(y);C&&(C.destroy(),this.atlasTexture.delete(y))}addImageProvider(y,C){this.imageProviders.has(C)||this.imageProviders.set(C,new Map),this.imageProviders.get(C).set(y.id,y)}removeImageProvider(y,C){this.imageProviders.has(C)&&this.imageProviders.get(C).delete(y)}getPendingImageProviders(){const y=[];for(const C of this.imageProviders.values())for(const R of C.values())R.hasPendingRequests()&&y.push(R);return y}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new o.z),this._imageRasterizer}isLoaded(){for(const y of this.loaded.keys())if(!this.loaded.get(y))return!1;return!0}setLoaded(y,C){if(this.loaded.get(C)!==y&&(this.loaded.set(C,y),y)){for(const{ids:R,callback:$}of this.requestors)this._notify(R,C,$);this.requestors=[]}}hasImage(y,C){return!!this.getImage(y,C)}getImage(y,C){return this.images.get(C).get(y.toString())}addImage(y,C,R){if(this._validate(y,R)){this.images.get(C).set(y.toString(),R);const $=this.imageVersions.get(C),G=$.get(y.toString())||0;$.set(y.toString(),G+1)}}_validate(y,C){let R=!0;return this._validateStretch(C.stretchX,C.data&&C.data.width)||(this.fire(new o.B(new Error(`Image "${y.name}" has invalid "stretchX" value`))),R=!1),this._validateStretch(C.stretchY,C.data&&C.data.height)||(this.fire(new o.B(new Error(`Image "${y.name}" has invalid "stretchY" value`))),R=!1),this._validateContent(C.content,C)||(this.fire(new o.B(new Error(`Image "${y.name}" has invalid "content" value`))),R=!1),R}_validateStretch(y,C){if(!y)return!0;let R=0;for(const $ of y){if($[0]o.I.from(C))}getImageVersions(y){const C=this.imageVersions.get(y);if(C)return C}getImages(y,C,R){const $=[],G=[],Z=this.imageProviders.get(C);for(const je of y){if(!je.iconsetId){$.push(je);continue}const Re=Z.get(je.iconsetId);Re&&(this.getImage(je,C)?G.push(je):Re.addPendingRequest(je))}if($.length===0)return void this._notify(G,C,R);let te=!0;const ue=!!this.loaded.get(C),xe=this.images.get(C);if(!ue)for(const je of $)xe.has(je.toString())||(te=!1);ue||te?this._notify($,C,R):this.requestors.push({ids:$,scope:C,callback:R})}rasterizeImages(y,C){const R=new Map,{tasks:$,scope:G}=y;for(const[Z,te]of $.entries()){const ue=this.getImage(te.id,G);ue&&R.set(Z,{image:ue,imageVariant:te})}this._rasterizeImages(G,R,C)}_rasterizeImages(y,C,R){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:C,scope:y},R);else{const $=new Map;for(const[G,{image:Z,imageVariant:te}]of C.entries())$.set(G,this.imageRasterizer.rasterize(te,Z,y,0));R(void 0,$)}}getUpdatedImages(y){return this.updatedImages.get(y)||new Set}_notify(y,C,R){const $=this.images.get(C),G=new Map;for(const Z of y){if(!$.get(Z.toString())){if(Z.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:Z.name}))}const te=$.get(Z.toString());if(!te){o.w(`Image "${Z.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 ue={data:te.usvg?null:te.data.clone(),pixelRatio:te.pixelRatio,sdf:te.sdf,usvg:te.usvg,stretchX:te.stretchX,stretchY:te.stretchY,content:te.content,hasRenderCallback:!!(te.userImage&&te.userImage.render)};te.usvg&&Object.assign(ue,{width:te.icon.usvg_tree.width,height:te.icon.usvg_tree.height}),G.set(o.I.toString(Z),ue)}R(null,{images:G,versions:this.getImageVersions(C)})}getPixelSize(y){const{width:C,height:R}=this.atlasImage.get(y);return{width:C,height:R}}getPattern(y,C,R){const $=y.toString(),G=this.patterns.get(C),Z=G.get($),te=this.getImage(y,C);if(!te)return null;if(Z){if(Z.position.version===te.version)return Z.position;Z.position.version=te.version}else{if(te.usvg&&!te.data){const ue=this.getPatternInFlightId($,C);if(this.patternsInFlight.has(ue))return null;this.patternsInFlight.add(ue);const xe=new o.D(y).scaleSelf(o.o.devicePixelRatio),je=new Map([[xe.toString(),{image:te,imageVariant:xe}]]);return this._rasterizeImages(C,je,(Re,Le)=>this.storePatternImage(xe,C,te,R,Le)),null}this.storePattern(y,C,te)}return this._updatePatternAtlas(C,R),G.get($).position}getPatternInFlightId(y,C){return o.F(y,C)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(y,C,R,$,G){const Z=y.toString(),te=G?G.get(Z):void 0;te&&(R.data=te,this.storePattern(y.id,C,R),this._updatePatternAtlas(C,$),this.patternsInFlight.delete(this.getPatternInFlightId(y.id.toString(),C)))}storePattern(y,C,R){const $={w:R.data.width+2*o.G,h:R.data.height+2*o.G,x:0,y:0},G=new o.H($,R,o.G);this.patterns.get(C).set(y.toString(),{bin:$,position:G})}destroyAtlasTextures(){for(const y of this.atlasTexture.values())y&&y.destroy();this.atlasTexture.clear()}bind(y,C){const R=y.gl;let $=this.atlasTexture.get(C);$?this.dirty&&($.update(this.atlasImage.get(C)),this.dirty=!1):($=new o.T(y,this.atlasImage.get(C),R.RGBA8),this.atlasTexture.set(C,$)),$.bind(R.LINEAR,R.CLAMP_TO_EDGE)}_updatePatternAtlas(y,C){const R=this.patterns.get(y),$=Array.from(R.values()).map(({bin:xe})=>xe),{w:G,h:Z}=o.J($),te=this.atlasImage.get(y);te.resize({width:G||1,height:Z||1});const ue=this.images.get(y);for(const[xe,{bin:je,position:Re}]of R.entries()){let Le=Re.padding;const Ue=je.x+Le,st=je.y+Le,Xe=ue.get(xe).data,pt=Xe.width,mt=Xe.height;Le=Le>1?Le-1:Le,o.q.copy(Xe,te,{x:0,y:0},{x:Ue,y:st},{width:pt,height:mt},C),o.q.copy(Xe,te,{x:0,y:mt-Le},{x:Ue,y:st-Le},{width:pt,height:Le},C),o.q.copy(Xe,te,{x:0,y:0},{x:Ue,y:st+mt},{width:pt,height:Le},C),o.q.copy(Xe,te,{x:pt-Le,y:0},{x:Ue-Le,y:st},{width:Le,height:mt},C),o.q.copy(Xe,te,{x:0,y:0},{x:Ue+pt,y:st},{width:Le,height:mt},C),o.q.copy(Xe,te,{x:pt-Le,y:mt-Le},{x:Ue-Le,y:st-Le},{width:Le,height:Le},C),o.q.copy(Xe,te,{x:0,y:mt-Le},{x:Ue+pt,y:st-Le},{width:Le,height:Le},C),o.q.copy(Xe,te,{x:0,y:0},{x:Ue+pt,y:st+mt},{width:Le,height:Le},C),o.q.copy(Xe,te,{x:pt-Le,y:0},{x:Ue-Le,y:st+mt},{width:Le,height:Le},C)}this.dirty=!0}beginFrame(){for(const y of this.images.keys())this.callbackDispatchedThisFrame.set(y,new Set)}dispatchRenderCallbacks(y,C){const R=this.images.get(C);for(const $ of y){if(this.callbackDispatchedThisFrame.get(C).has($.toString()))continue;this.callbackDispatchedThisFrame.get(C).add($.toString());const G=R.get($.toString());Ke(G)&&this.updateImage($,C,G)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function $s(I){const y=I.value,C=I.valueSpec,R=I.style,$=I.styleSpec,G=I.key,Z=I.arrayElementValidator||Rr;if(!Array.isArray(y))return[new o.V(G,y,`array expected, ${o.M(y)} found`)];if(C.length&&y.length!==C.length)return[new o.V(G,y,`array length ${C.length} expected, length ${y.length} found`)];if(C["min-length"]&&y.length$)return[new o.V(y,C,`${C} is greater than the maximum value ${$}`)]}return[]}function Dt(I){const y=I.key,C=I.value;if(!o.K(C))return[new o.V(y,C,`object expected, ${o.M(C)} found`)];const R=I.valueSpec,$=o.L(C.type);let G,Z,te,ue={};const xe=$!=="categorical"&&C.property===void 0,je=!xe,Re=function(Xe){const pt=Xe.stops;return Array.isArray(pt)&&Array.isArray(pt[0])&&o.K(pt[0][0])}(C),Le=er({key:I.key,value:I.value,valueSpec:I.styleSpec.function,style:I.style,styleSpec:I.styleSpec,objectElementValidators:{stops:function(Xe){if($==="identity")return[new o.V(Xe.key,Xe.value,'identity function may not have a "stops" property')];let pt=[];const mt=Xe.value;return pt=pt.concat($s({key:Xe.key,value:mt,valueSpec:Xe.valueSpec,style:Xe.style,styleSpec:Xe.styleSpec,arrayElementValidator:Ue})),Array.isArray(mt)&&mt.length===0&&pt.push(new o.V(Xe.key,mt,"array must have at least one stop")),pt},default:function(Xe){return Rr({key:Xe.key,value:Xe.value,valueSpec:R,style:Xe.style,styleSpec:Xe.styleSpec})}}});return $==="identity"&&xe&&Le.push(new o.V(I.key,I.value,'missing required property "property"')),$==="identity"||C.stops||Le.push(new o.V(I.key,I.value,'missing required property "stops"')),$==="exponential"&&R.expression&&!o.O(R)&&Le.push(new o.V(I.key,I.value,"exponential functions not supported")),I.styleSpec.$version>=8&&(je&&!o.Q(R)?Le.push(new o.V(I.key,I.value,"property functions not supported")):xe&&!o.S(R)&&Le.push(new o.V(I.key,I.value,"zoom functions not supported"))),$!=="categorical"&&!Re||C.property!==void 0||Le.push(new o.V(I.key,I.value,'"property" property is required')),Le;function Ue(Xe){let pt=[];const mt=Xe.value,jt=Xe.key;if(!Array.isArray(mt))return[new o.V(jt,mt,`array expected, ${o.M(mt)} found`)];if(mt.length!==2)return[new o.V(jt,mt,`array length 2 expected, length ${mt.length} found`)];if(Re){if(!o.K(mt[0]))return[new o.V(jt,mt,`object expected, ${o.M(mt[0])} found`)];const Tt=mt[0];if(Tt.zoom===void 0)return[new o.V(jt,mt,"object stop key must have zoom")];if(Tt.value===void 0)return[new o.V(jt,mt,"object stop key must have value")];const xt=o.L(Tt.zoom);if(typeof xt!="number")return[new o.V(jt,Tt.zoom,"stop zoom values must be numbers")];if(te&&te>xt)return[new o.V(jt,Tt.zoom,"stop zoom values must appear in ascending order")];xt!==te&&(te=xt,Z=void 0,ue={}),pt=pt.concat(er({key:`${jt}[0]`,value:mt[0],valueSpec:{zoom:{}},style:Xe.style,styleSpec:Xe.styleSpec,objectElementValidators:{zoom:Ds,value:st}}))}else pt=pt.concat(st({key:`${jt}[0]`,value:mt[0],style:Xe.style,styleSpec:Xe.styleSpec},mt));return o.U(o.W(mt[1]))?pt.concat([new o.V(`${jt}[1]`,mt[1],"expressions are not allowed in function stops.")]):pt.concat(Rr({key:`${jt}[1]`,value:mt[1],valueSpec:R,style:Xe.style,styleSpec:Xe.styleSpec}))}function st(Xe,pt){const mt=o.M(Xe.value),jt=o.L(Xe.value),Tt=Xe.value!==null?Xe.value:pt;if(G){if(mt!==G)return[new o.V(Xe.key,Tt,`${mt} stop domain type must match previous stop domain type ${G}`)]}else G=mt;if(mt!=="number"&&mt!=="string"&&mt!=="boolean"&&typeof jt!="number"&&typeof jt!="string"&&typeof jt!="boolean")return[new o.V(Xe.key,Tt,"stop domain value must be a number, string, or boolean")];if(mt!=="number"&&$!=="categorical"){let xt=`number expected, ${mt} found`;return o.Q(R)&&$===void 0&&(xt+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(Xe.key,Tt,xt)]}return $!=="categorical"||mt!=="number"||typeof jt=="number"&&isFinite(jt)&&Math.floor(jt)===jt?$!=="categorical"&&mt==="number"&&typeof jt=="number"&&typeof Z=="number"&&Z!==void 0&&jtnew o.V(`${I.key}${R.key}`,I.value,R.message));const C=y.value.expression||y.value._styleExpression.expression;if(I.expressionContext==="property"&&I.propertyKey==="text-font"&&!C.outputDefined())return[new o.V(I.key,I.value,`Invalid data expression for "${I.propertyKey}". Output values must be contained as literals within the expression.`)];if(I.expressionContext==="property"&&I.propertyType==="layout"&&!o.$(C))return[new o.V(I.key,I.value,'"feature-state" data expressions are not supported with layout properties.')];if(I.expressionContext==="filter")return $t(C,I);if(I.expressionContext==="appearance")return ht(C,I);if(I.expressionContext&&I.expressionContext.indexOf("cluster")===0){if(!o.Z(C,["zoom","feature-state"]))return[new o.V(I.key,I.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(I.expressionContext==="cluster-initial"&&!o._(C))return[new o.V(I.key,I.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function $t(I,y){const C=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(y.valueSpec&&y.valueSpec.expression)for(const $ of y.valueSpec.expression.parameters)C.delete($);if(C.size===0)return[];const R=[];return I instanceof o.a0&&C.has(I.name)?[new o.V(y.key,y.value,`["${I.name}"] expression is not supported in a filter for a ${y.object.type} layer with id: ${y.object.id}`)]:(I.eachChild($=>{R.push(...$t($,y))}),R)}function ht(I,y){const C=new Set;if(y.valueSpec&&y.valueSpec.expression)for(const $ of y.valueSpec.expression.parameters)C.add($);if(C.size===0)return[];const R=[];return I instanceof o.a0&&!C.has(I.name)?[new o.V(y.key,y.value,`["${I.name}"] is not an allowed parameter`)]:(I.eachChild($=>{R.push(...ht($,y))}),R)}function Ut(I){const y=I.key,C=I.value,R=I.valueSpec,$=[];return Array.isArray(R.values)?R.values.indexOf(o.L(C))===-1&&$.push(new o.V(y,C,`expected one of [${R.values.join(", ")}], ${JSON.stringify(C)} found`)):Object.keys(R.values).indexOf(o.L(C))===-1&&$.push(new o.V(y,C,`expected one of [${Object.keys(R.values).join(", ")}], ${JSON.stringify(C)} found`)),$}function Es(I){return o.a4(o.W(I.value))?St(Object.assign({},I,{expressionContext:"filter",valueSpec:I.styleSpec[`filter_${I.layerType||"fill"}`]})):Xt(I)}function Xt(I){const y=I.value,C=I.key;if(!Array.isArray(y))return[new o.V(C,y,`array expected, ${o.M(y)} found`)];if(y.length<1)return[new o.V(C,y,"filter array must have at least 1 element")];const R=I.styleSpec;let $=Ut({key:`${C}[0]`,value:y[0],valueSpec:R.filter_operator});const G=()=>{y.length>=2&&(o.a2(y[1])||$.push(new o.V(`${C}[1]`,y[1],`string expected, ${o.M(y[1])} found`)));for(let Z=2;Z":case">=":y.length>=2&&o.L(y[1])==="$type"&&$.push(new o.V(C,y,`"$type" cannot be use with operator "${y[0]}"`)),y.length!==3&&$.push(new o.V(C,y,`filter array for operator "${y[0]}" must have 3 elements`)),G();break;case"==":case"!=":y.length!==3&&$.push(new o.V(C,y,`filter array for operator "${y[0]}" must have 3 elements`)),G();break;case"in":case"!in":G();break;case"any":case"all":case"none":for(let Z=1;Z{xe in C&&y.push(new o.V(R,C[xe],`"${xe}" is prohibited for ref layers`))}),$.layers.forEach(xe=>{o.L(xe.id)===te&&(ue=xe)}),ue?ue.ref?y.push(new o.V(R,C.ref,"ref cannot reference another ref layer")):Z=o.L(ue.type):typeof te=="string"&&y.push(new o.V(R,C.ref,`ref layer "${te}" not found`))}else if(Z!=="background"&&Z!=="sky"&&Z!=="slot")if(C.source)if(o.a2(C.source)){const ue=$.sources&&$.sources[C.source],xe=ue&&o.L(ue.type);ue?xe==="vector"&&Z==="raster"?y.push(new o.V(R,C.source,`layer "${C.id}" requires a raster source`)):xe==="raster"&&Z!=="raster"?y.push(new o.V(R,C.source,`layer "${C.id}" requires a vector source`)):xe!=="vector"||C["source-layer"]?xe==="raster-dem"&&Z!=="hillshade"?y.push(new o.V(R,C.source,"raster-dem source can only be used with layer type 'hillshade'.")):xe!=="raster-array"||["raster","raster-particle"].includes(Z)?Z==="line"&&C.paint&&(C.paint["line-gradient"]||C.paint["line-trim-offset"])&&xe==="geojson"&&!ue.lineMetrics?y.push(new o.V(R,C,`layer "${C.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):Z==="raster-particle"&&xe!=="raster-array"&&y.push(new o.V(R,C.source,`layer "${C.id}" requires a 'raster-array' source.`)):y.push(new o.V(R,C.source,"raster-array source can only be used with layer type 'raster'.")):y.push(new o.V(R,C,`layer "${C.id}" must specify a "source-layer"`)):y.push(new o.V(R,C.source,`source "${C.source}" not found`))}else y.push(new o.V(`${R}.source`,C.source,'"source" must be a string'));else y.push(new o.V(R,C,'missing required property "source"'));return y=y.concat(er({key:R,value:C,valueSpec:G.layer,style:I.style,styleSpec:I.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Rr({key:`${R}.type`,value:C.type,valueSpec:G.layer.type,style:I.style,styleSpec:I.styleSpec,object:C,objectKey:"type"}),filter:ue=>Es(Object.assign({layerType:Z},ue)),layout:ue=>er({layer:C,key:ue.key,value:ue.value,valueSpec:{},style:ue.style,styleSpec:ue.styleSpec,objectElementValidators:{"*":xe=>Bs(Object.assign({layerType:Z},xe))}}),paint:ue=>er({layer:C,key:ue.key,value:ue.value,valueSpec:{},style:ue.style,styleSpec:ue.styleSpec,objectElementValidators:{"*":xe=>Ss(Object.assign({layerType:Z,layer:C},xe))}}),appearances(ue){const xe=$s({key:ue.key,value:ue.value,valueSpec:ue.valueSpec,style:ue.style,styleSpec:ue.styleSpec,arrayElementValidator:Le=>function(Ue){const{key:st,layer:Xe,layerType:pt}=Ue,mt=o.L(Ue.value),jt=o.L(mt.name),Tt=o.L(mt.condition),xt=er({key:st,value:mt,valueSpec:Ue.styleSpec.appearance,style:Ue.style,styleSpec:Ue.styleSpec,objectElementValidators:{condition:es=>function(Ft){const Jt=[];return Jt.push(...St({key:Ft.key,value:Ft.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),Jt}(Object.assign({layer:Xe,layerType:pt},es)),properties:es=>function(Ft){const Jt=[],{styleSpec:At,layer:Rt,layerType:Wt}=Ft,ys=At[`paint_${Wt}`],rs=At[`layout_${Wt}`],zs=Ft.object[Ft.objectKey];for(const Is in zs){const an=Is in ys?"paint":Is in rs?"layout":void 0;if(!an){Jt.push(new o.V(Ft.key,Is,`unknown property "${Is}" for layer type "${Wt}"`));continue}const mn=Object.assign({},Ft,{key:`${Ft.key}.${Is}`,object:zs,objectKey:Is,layer:Rt,layerType:Wt,value:zs[Is],valueSpec:an==="paint"?ys[Is]:rs[Is]});Jt.push(...Ys(mn,an))}return Jt}(Object.assign({layer:Xe,layerType:pt},es))}});return jt!=="hidden"&&Tt===void 0&&xt.push(new o.V(Ue.key,"name",'Appearance with name different than "hidden" must have a condition')),xt}(Object.assign({layerType:Z,layer:C},Le))}),je=Array.isArray(ue.value)?ue.value:[],Re=new Set;return je.forEach((Le,Ue)=>{const st=o.L(Le.name);if(st)if(Re.has(st)){const Xe=o.L(C.id);xe.push(new o.V(ue.key,st,`Duplicated appearance name "${st}" for layer "${Xe}"`))}else Re.add(st)}),xe}}})),y}function sn({key:I,value:y}){return o.a2(y)?[]:[new o.V(I,y,`string expected, ${o.M(y)} found`)]}const Jn={promoteId:function I({key:y,value:C}){if(o.a2(C))return sn({key:y,value:C});if(Array.isArray(C)){const $=[],G=o.W(C),Z=o.X(G);return Z.result==="error"?(Z.value.forEach(te=>{$.push(new o.V(`${y}${te.key}`,null,`${te.message}`))}),$):(o.Z(Z.value.expression,["zoom","heatmap-density","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed"])||$.push(new o.V(`${y}`,null,"promoteId expression should be only feature dependent")),$)}if(!o.K(C))return[new o.V(y,C,`string, expression or object expected, "${o.M(C)}" found`)];const R=[];for(const $ in C)R.push(...I({key:`${y}.${$}`,value:C[$]}));return R}};function fn(I){const y=I.value,C=I.key,R=I.styleSpec,$=I.style;if(!o.K(y))return[new o.V(C,y,`object expected, ${o.M(y)} found`)];if(!("type"in y))return[new o.V(C,y,'"type" is required')];const G=o.L(y.type);let Z=[];switch(["vector","raster","raster-dem","raster-array"].includes(G)&&("url"in y||"tiles"in y||Z.push(new o.a5(C,y,'Either "url" or "tiles" is required.'))),G){case"vector":case"raster":case"raster-dem":case"raster-array":return Z=Z.concat(er({key:C,value:y,valueSpec:R[`source_${G.replace("-","_")}`],style:I.style,styleSpec:R,objectElementValidators:Jn})),Z;case"geojson":if(Z=er({key:C,value:y,valueSpec:R.source_geojson,style:$,styleSpec:R,objectElementValidators:Jn}),"cluster"in y&&"clusterProperties"in y){if(!o.K(y.clusterProperties))return[new o.V(`${C}.clusterProperties`,y,`object expected, ${o.M(y)} found`)];for(const te in y.clusterProperties){const ue=y.clusterProperties[te];if(!Array.isArray(ue))return[new o.V(`${C}.clusterProperties.${te}`,ue,"array expected")];const[xe,je]=ue,Re=typeof xe=="string"?[xe,["accumulated"],["get",te]]:xe;Z.push(...St({key:`${C}.${te}.map`,value:je,expressionContext:"cluster-map"})),Z.push(...St({key:`${C}.${te}.reduce`,value:Re,expressionContext:"cluster-reduce"}))}}return Z;case"video":return er({key:C,value:y,valueSpec:R.source_video,style:$,styleSpec:R});case"image":return er({key:C,value:y,valueSpec:R.source_image,style:$,styleSpec:R});case"canvas":return[new o.V(C,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Ut({key:`${C}.type`,value:y.type,valueSpec:{values:Sn(R)}})}}function Sn(I){return I.source.reduce((y,C)=>{const R=I[C];return R.type.type==="enum"&&(y=y.concat(Object.keys(R.type.values||{}))),y},[])}function Gn(I){const y=I.value,C=I.styleSpec,R=C.light,$=I.style;if(y===void 0)return[];if(!o.K(y))return[new o.V("light",y,`object expected, ${o.M(y)} found`)];let G=[];for(const Z in y){const te=Z.match(/^(.*)-transition$/),ue=Z.match(/^(.*)-use-theme$/);G=G.concat(ue&&R[ue[1]]?Rr({key:Z,value:y[Z],valueSpec:{type:"string"},style:$,styleSpec:C}):te&&R[te[1]]&&R[te[1]].transition?Rr({key:Z,value:y[Z],valueSpec:C.transition,style:$,styleSpec:C}):R[Z]?Rr({key:Z,value:y[Z],valueSpec:R[Z],style:$,styleSpec:C}):[new o.V(Z,y[Z],`unknown property "${Z}"`)])}return G}function Hr(I){const y=I.value;if(!y)return[];const C=I.key;if(!o.K(y))return[new o.V(C,y,`object expected, ${o.M(y)} found`)];let R=[];const $=I.styleSpec,G=$["light-3d"],Z=I.style,te=I.style.lights;for(const je of["type","id"])if(!(je in y))return R=R.concat([new o.V(C,y,`missing property "${je}"`)]),R;if(!o.a2(y.type))return R=R.concat([new o.V(`${C}.type`,y.type,"string expected")]),R;if(te)for(let je=0;je[],array:$s,boolean:function(I){const y=I.value,C=I.key;return o.a1(y)?[]:[new o.V(C,y,`boolean expected, ${o.M(y)} found`)]},number:Ds,color:function({key:I,value:y}){return o.a2(y)?o.a3.parseCSSColor(y)===null?[new o.V(I,y,`color expected, "${y}" found`)]:[]:[new o.V(I,y,`color expected, ${o.M(y)} found`)]},enum:Ut,filter:Es,function:Dt,layer:Us,object:er,source:fn,model:o.a9,light:Gn,"light-3d":Hr,terrain:pi,fog:Ms,string:sn,formatted:function(I){return sn(I).length===0?[]:St(I)},resolvedImage:function(I){return sn(I).length===0?[]:St(I)},projection:function(I){const y=I.value,C=I.styleSpec,R=C.projection,$=I.style;if(o.K(y)){let G=[];for(const Z in y)G=G.concat(Rr({key:Z,value:y[Z],valueSpec:R[Z],style:$,styleSpec:C}));return G}return o.a2(y)?[]:[new o.V("projection",y,`object or string expected, ${o.M(y)} found`)]},import:function(I){const y=I.key,{value:C,styleSpec:R}=I;if(!o.K(C))return[new o.V(y,C,"import must be an object")];const{data:$,...G}=C;Object.defineProperty(G,"__line__",{value:C.__line__,enumerable:!1});let Z=er(Object.assign({},I,{value:G,valueSpec:R.import}));return o.L(G.id)===""&&Z.push(new o.V(`${I.key}.id`,G,"import id can't be an empty string")),$&&(Z=Z.concat(Fs($,R,{key:`${I.key}.data`}))),Z},iconset:function(I){const y=I.value,C=I.key,R=I.styleSpec,$=I.style;if(!o.K(y))return[new o.V(C,y,"object expected")];if(!y.type)return[new o.V(C,y,'"type" is required')];const G=o.L(y.type);let Z=[];if(Z=Z.concat(er({key:C,value:y,valueSpec:R[`iconset_${G}`],style:$,styleSpec:R})),function(te,ue){return!(te!=="source"||!ue.source)}(G,y)){const te=$.sources&&$.sources[y.source],ue=te&&o.L(te.type);te?ue!=="raster-array"&&Z.push(new o.V(C,y.source,`iconset cannot be used with a source of type ${String(ue)}, it only be used with a "raster-array" source type`)):Z.push(new o.V(C,y.source,`source "${y.source}" not found`))}return Z}};function Rr(I,y=!1){const C=I.value,R=I.valueSpec,$=I.styleSpec;if(R.expression){if(o.a6(o.L(C)))return Dt(I);if(o.U(o.W(C)))return St(I)}if(R.type&&bi[R.type]){const G=bi[R.type](I);return y===!0&&G.length>0&&Array.isArray(I.value)?St(I):G}return er(Object.assign({},I,{valueSpec:R.type?$[R.type]:R}))}function er(I){const y=I.key,C=I.value,R=I.valueSpec||{},$=I.objectElementValidators||{},G=I.style,Z=I.styleSpec;if(!o.K(C))return[new o.V(y,C,`object expected, ${o.M(C)} found`)];let te=[];for(const ue in C){const xe=ue.split(".")[0];let je;$[xe]?je=$[xe]:R[xe]?je=Rr:$["*"]?je=$["*"]:R["*"]&&(je=Rr),je?te=te.concat(je({key:(y&&`${y}.`)+ue,value:C[ue],valueSpec:R[xe]||R["*"],style:G,styleSpec:Z,object:C,objectKey:ue},C)):te.push(new o.a5(y,C[ue],`unknown property "${ue}"`))}for(const ue in R){if($[ue])continue;const xe=R[ue];xe.required&&xe.default===void 0&&C[ue]===void 0&&te.push(new o.V(y,C,`missing required property "${ue}"`))}return te}function lr({key:I,value:y}){const C=sn({key:I,value:y});if(C.length)return C;const R=y;return R.indexOf("{fontstack}")===-1&&C.push(new o.V(I,y,'"glyphs" url must include a "{fontstack}" token')),R.indexOf("{range}")===-1&&C.push(new o.V(I,y,'"glyphs" url must include a "{range}" token')),C}function Fs(I,y=o.a8,C={}){return er({key:C.key||"",value:I,valueSpec:Object.assign(y.$root,{"*":{type:"*"}}),styleSpec:y,style:I,objectElementValidators:{glyphs:lr}})}function $n(I,y=o.a8){return Ks(Fs(I,y))}const Cr=I=>Ks(fn(I)),ts=I=>Ks(Gn(I)),Oe=I=>Ks(Hr(I)),Qe=I=>Ks(pi(I)),ct=I=>Ks(Ms(I)),vt=I=>Ks(function(y){const C=y.value,R=y.style,$=y.styleSpec,G=$.snow;if(C===void 0)return[];if(!o.K(C))return[new o.V("snow",C,`object expected, ${o.M(C)} found`)];let Z=[];for(const te in C){const ue=te.match(/^(.*)-transition$/);Z=Z.concat(ue&&G[ue[1]]&&G[ue[1]].transition?Rr({key:te,value:C[te],valueSpec:$.transition,style:R,styleSpec:$}):G[te]?Rr({key:te,value:C[te],valueSpec:G[te],style:R,styleSpec:$}):[new o.a5(te,C[te],`unknown property "${te}"`)])}return Z}(I)),It=I=>Ks(function(y){const C=y.value,R=y.style,$=y.styleSpec,G=$.rain;if(C===void 0)return[];if(!o.K(C))return[new o.V("rain",C,`object expected, ${o.M(C)} found`)];let Z=[];for(const te in C){const ue=te.match(/^(.*)-transition$/);Z=Z.concat(ue&&G[ue[1]]&&G[ue[1]].transition?Rr({key:te,value:C[te],valueSpec:$.transition,style:R,styleSpec:$}):G[te]?Rr({key:te,value:C[te],valueSpec:G[te],style:R,styleSpec:$}):[new o.a5(te,C[te],`unknown property "${te}"`)])}return Z}(I)),qt=I=>Ks(Us(I)),xs=I=>Ks(Es(I)),as=I=>Ks(Ss(I)),Ns=I=>Ks(Bs(I)),ln=I=>Ks(o.a9(I));function Ks(I){return I.slice().sort((y,C)=>y.line&&C.line?y.line-C.line:0)}function Un(I,y){let C=!1;if(y&&y.length)for(const R of y)R instanceof o.a5?o.w(R.message):(I.fire(new o.B(new Error(R.message))),C=!0);return C}const br=o.a8.light;let Ar;class sr extends o.E{constructor(y,C="flat"){super(),this._transitionable=new o.aa(Ar||(Ar=new o.ab({anchor:new o.ac(br.anchor),position:new o.ad(br.position),color:new o.ac(br.color),intensity:new o.ac(br.intensity)}))),this.setLight(y,C),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(y,C,R={}){this._validate(ts,y,R)||(this._transitionable.setTransitionOrValue(y),this.id=C)}updateTransitions(y){this._transitioning=this._transitionable.transitioned(y,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(y){this.properties=this._transitioning.possiblyEvaluate(y)}_validate(y,C,R){return(!R||R.validate!==!1)&&Un(this,y.call($n,Object.assign({value:C,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const Tr=o.a8.terrain;let Ot=class extends o.E{constructor(I,y,C,R,$){super(),this.scope=C,this._transitionable=new o.aa(new o.ab({source:new o.ac(Tr.source),exaggeration:new o.ac(Tr.exaggeration)}),C,R),this._transitionable.setTransitionOrValue(I,R),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=y,this.worldview=$}get(){return this._transitionable.serialize()}set(I,y){this._transitionable.setTransitionOrValue(I,y)}updateTransitions(I){this._transitioning=this._transitionable.transitioned(I,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(I){this.properties=this._transitioning.possiblyEvaluate(I)}getExaggeration(I){return this._transitioning.possiblyEvaluate(new o.ae(I,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const I=this._transitionable._values.exaggeration;if(!I)return null;const y=I.value.expression;if(!y)return null;let C=-1,R=-1,$=1;for(const G of y.zoomStops)$=y.evaluate(new o.ae(G,{worldview:this.worldview})),$>.01?(C=G,R=-1):R=G;return $<.01&&C>0&&R>C?[C,R]:null}isZoomDependent(){const I=this._transitionable._values.exaggeration;return I!=null&&I.value!=null&&I.value.expression!=null&&I.value.expression instanceof o.af}};const wn=.05;function kr(I,y,C,R){const $=o.aj(45,65,C),[G,Z]=dr(I,R);let te=1-Math.min(1,Math.exp((y-G)/(Z-G)*-6));return te*=te*te,te=Math.min(1,1.00747*te),te*$*I.alpha}function dr(I,y){const C=.5/Math.tan(.5*y);return[I.range[0]+C,I.range[1]+C]}function Jr(I,y,C,R,$){const G=o.ah([],[y,C,R],$.mercatorFogMatrix);return kr(I,o.ai(G),$.pitch,$._fov)}function jr(I,y,C,R,$,G,Z){const te=[[C,R,0],[$,R,0],[$,G,0],[C,G,0]];let ue=Number.MAX_VALUE,xe=-Number.MAX_VALUE;for(const je of te){const Re=o.ah([],je,y),Le=o.ai(Re);ue=Math.min(ue,Le),xe=Math.max(xe,Le)}return[kr(I,ue,Z.pitch,Z._fov),kr(I,xe,Z.pitch,Z._fov)]}const qn=o.a8.fog;class wi extends o.E{constructor(y,C,R,$){super();const G=new o.ab({range:new o.ac(qn.range),color:new o.ac(qn.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(qn["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(qn["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(qn["horizon-blend"]),"star-intensity":new o.ac(qn["star-intensity"]),"vertical-range":new o.ac(qn["vertical-range"])});this._transitionable=new o.aa(G,R,new Map($)),this.set(y,$),this._transitioning=this._transitionable.untransitioned(),this._transform=C,this.properties=new o.ak(G),this.scope=R}get state(){const y=this._transform,C=y.projection.name==="globe",R=o.al(y.zoom),$=this.properties.get("range"),G=[.5,3];return{range:C?[o.am(G[0],$[0],R),o.am(G[1],$[1],R)]:$,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(y,C,R={}){if(this._validate(ct,y,R))return;const $=Object.assign({},y);for(const G of Object.keys(qn))$[G]===void 0&&($[G]=qn[G].default);this._options=$,this._transitionable.setTransitionOrValue(this._options,C)}getOpacity(y){if(!this._transform.projection.supportsFog)return 0;const C=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,y))*C.a}getOpacityAtLatLng(y,C){return this._transform.projection.supportsFog?function(R,$,G){const Z=o.ag.fromLngLat($),te=G.elevation?G.elevation.getAtPointOrZero(Z):0;return Jr(R,Z.x,Z.y,te,G)}(this.state,y,C):0}getOpacityForTile(y){if(!this._transform.projection.supportsFog)return[1,1];const C=this._transform.calculateFogTileMatrix(y.toUnwrapped());return jr(this.state,C,0,0,o.an,o.an,this._transform)}getOpacityForBounds(y,C,R,$,G){return this._transform.projection.supportsFog?jr(this.state,y,C,R,$,G,this._transform):[1,1]}getFovAdjustedRange(y){return this._transform.projection.supportsFog?dr(this.state,y):[0,1]}isVisibleOnFrustum(y){if(!this._transform.projection.supportsFog)return!1;const C=[4,5,6,7];for(const R of C){const $=y.points[R];let G;if($[2]>=0)G=$;else{const Z=y.points[R-4];G=o.ao(Z,$,Z[2]/(Z[2]-$[2]))}if(Jr(this.state,G[0],G[1],0,this._transform)>=wn)return!0}return!1}updateConfig(y){this._transitionable.setTransitionOrValue(this._options,new Map(y))}updateTransitions(y){this._transitioning=this._transitionable.transitioned(y,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(y){this.properties=this._transitioning.possiblyEvaluate(y)}_validate(y,C,R){return(!R||R.validate!==!1)&&Un(this,y.call($n,Object.assign({value:C,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let Oi,ea,ya,Mi=class extends o.E{constructor(I,y,C,R){super();const $=Oi||(Oi=new o.ab({density:new o.ac(o.a8.snow.density),intensity:new o.ac(o.a8.snow.intensity),color:new o.ac(o.a8.snow.color),opacity:new o.ac(o.a8.snow.opacity),vignette:new o.ac(o.a8.snow.vignette),"vignette-color":new o.ac(o.a8.snow["vignette-color"]),"center-thinning":new o.ac(o.a8.snow["center-thinning"]),direction:new o.ac(o.a8.snow.direction),"flake-size":new o.ac(o.a8.snow["flake-size"])}));this._transitionable=new o.aa($,C,new Map(R)),this.set(I,R),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak($),this.scope=C}get state(){const I=this.properties.get("opacity"),y=this.properties.get("color"),C=this.properties.get("direction"),R=o.ap(C[0]),$=-Math.max(o.ap(C[1]),.01),G=[Math.cos(R)*Math.cos($),Math.sin(R)*Math.cos($),Math.sin($)],Z=this.properties.get("vignette"),te=this.properties.get("vignette-color");return te.a=Z,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(y.r,y.g,y.b,y.a*I),direction:G,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:te}}get(){return this._transitionable.serialize()}set(I,y,C={}){if(this._validate(vt,I,C))return;const R=Object.assign({},I),$=o.a8.snow;for(const G of Object.keys($))R[G]===void 0&&(R[G]=$[G].default);this._options=R,this._transitionable.setTransitionOrValue(this._options,y)}updateConfig(I){this._transitionable.setTransitionOrValue(this._options,new Map(I))}updateTransitions(I){this._transitioning=this._transitionable.transitioned(I,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(I){this.properties=this._transitioning.possiblyEvaluate(I)}_validate(I,y,C){return(!C||C.validate!==!1)&&Un(this,I.call($n,Object.assign({value:y,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},da=class extends o.E{constructor(I,y,C,R){super();const $=ea||(ea=new o.ab({density:new o.ac(o.a8.rain.density),intensity:new o.ac(o.a8.rain.intensity),color:new o.ac(o.a8.rain.color),opacity:new o.ac(o.a8.rain.opacity),vignette:new o.ac(o.a8.rain.vignette),"vignette-color":new o.ac(o.a8.rain["vignette-color"]),"center-thinning":new o.ac(o.a8.rain["center-thinning"]),direction:new o.ac(o.a8.rain.direction),"droplet-size":new o.ac(o.a8.rain["droplet-size"]),"distortion-strength":new o.ac(o.a8.rain["distortion-strength"])}));this._transitionable=new o.aa($,C,new Map(R)),this.set(I,R),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak($),this.scope=C}get state(){const I=this.properties.get("opacity"),y=this.properties.get("color"),C=this.properties.get("direction"),R=o.ap(C[0]),$=-Math.max(o.ap(C[1]),.01),G=[Math.cos(R)*Math.cos($),Math.sin(R)*Math.cos($),Math.sin($)],Z=this.properties.get("vignette-color");return Z.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(y.r,y.g,y.b,y.a*I),direction:G,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:Z}}get(){return this._transitionable.serialize()}set(I,y,C={}){if(this._validate(It,I,C))return;const R=Object.assign({},I),$=o.a8.rain;for(const G of Object.keys($))R[G]===void 0&&(R[G]=$[G].default);this._options=R,this._transitionable.setTransitionOrValue(this._options,y)}updateConfig(I){this._transitionable.setTransitionOrValue(this._options,new Map(I))}updateTransitions(I){this._transitioning=this._transitionable.transitioned(I,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(I){this.properties=this._transitioning.possiblyEvaluate(I)}_validate(I,y,C){return(!C||C.validate!==!1)&&Un(this,I.call($n,Object.assign({value:y,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class jn extends o.E{constructor(y,C,R,$){super(),this.scope=R,this._options=y,this.properties=new o.ak(C),this._transitionable=new o.aa(C,R,new Map($)),this._transitionable.setTransitionOrValue(y.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(y){this._transitionable.setTransitionOrValue(this._options.properties,new Map(y))}updateTransitions(y){this._transitioning=this._transitionable.transitioned(y,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(y){this.properties=this._transitioning.possiblyEvaluate(y)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(y,C){this._options=y,this._transitionable.setTransitionOrValue(y.properties,C)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const Aa=()=>ya||(ya=new o.ab({color:new o.ac(o.a8.properties_light_ambient.color),"color-use-theme":new o.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ac(o.a8.properties_light_ambient.intensity)}));let Yi;const Bo=()=>Yi||(Yi=new o.ab({direction:new o.ar(o.a8.properties_light_directional.direction),color:new o.ac(o.a8.properties_light_directional.color),"color-use-theme":new o.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ac(o.a8.properties_light_directional.intensity),"cast-shadows":new o.ac(o.a8.properties_light_directional["cast-shadows"]),"shadow-quality":new o.ac(o.a8.properties_light_directional["shadow-quality"]),"shadow-intensity":new o.ac(o.a8.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new o.ac(o.a8.properties_light_directional["shadow-draw-before-layer"])}));class rl{constructor(y,C,R){this.screenBounds=y,this.cameraPoint=R.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=C,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,R)}static createFromScreenPoints(y,C){let R,$;if(y instanceof o.P||typeof y[0]=="number"){const G=o.P.convert(y);R=[G],$=C.isPointAboveHorizon(G)}else{const G=o.P.convert(y[0]),Z=o.P.convert(y[1]),te=G.add(Z)._div(2);R=[G,Z],$=o.as(G,Z).every(ue=>C.isPointAboveHorizon(ue))&&C.isPointAboveHorizon(te)}return new rl(R,$,C)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(y){return o.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],y)}bufferedCameraGeometry(y){const C=this.screenBounds[0],R=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],$=o.as(C,R,0,!1);return this.cameraPoint.y>R.y&&(this.cameraPoint.x>C.x&&this.cameraPoint.x=R.x?$[2]=this.cameraPoint:this.cameraPoint.x<=C.x&&($[3]=this.cameraPoint)),o.at($,y)}bufferedCameraGeometryGlobe(y){const C=this.screenBounds[0],R=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],$=o.as(C,R,y),G=this.cameraPoint.clone(),Z=+(G.x>C.x)+ +(G.x>R.x);switch(3*(+(G.y>C.y)+ +(G.y>R.y))+Z){case 0:$[0]=G,$[4]=G.clone();break;case 1:$.splice(1,0,G);break;case 2:$[1]=G;break;case 3:$.splice(4,0,G);break;case 5:$.splice(2,0,G);break;case 6:$[3]=G;break;case 7:$.splice(3,0,G);break;case 8:$[2]=G}return $}containsTile(y,C,R,$=0){const G=Math.max(y.queryPadding,y.evaluateQueryRenderedFeaturePadding())/C._pixelsPerMercatorPixel+1,Z=R?this._bufferedCameraMercator(G,C):this._bufferedScreenMercator(G,C);let te=y.tileID.wrap+(Z.unwrapped?$:0);const ue=Z.polygon.map(pt=>o.au(y.tileTransform,pt,te));if(!o.av(ue,0,0,o.an,o.an))return;te=y.tileID.wrap+(this.screenGeometryMercator.unwrapped?$:0);const xe=this.screenGeometryMercator.polygon.map(pt=>o.aw(y.tileTransform,pt,te)),je=xe.map(pt=>new o.P(pt[0],pt[1])),Re=C.getFreeCameraOptions().position||new o.ag(0,0,0),Le=o.aw(y.tileTransform,Re,te),Ue=xe.map(pt=>{const mt=o.ax(pt,pt,Le);return o.ay(mt,mt),new o.az(Le,mt)}),st=o.aA(y,1,C.zoom)*C._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:je,tilespaceRays:Ue,bufferedTilespaceGeometry:ue,bufferedTilespaceBounds:(Xe=o.aB(ue),Xe.min.x=o.aC(Xe.min.x,0,o.an),Xe.min.y=o.aC(Xe.min.y,0,o.an),Xe.max.x=o.aC(Xe.max.x,0,o.an),Xe.max.y=o.aC(Xe.max.y,0,o.an),Xe),tile:y,tileID:y.tileID,pixelToTileUnitsFactor:st};var Xe}_bufferedScreenMercator(y,C){const R=Sd(y);if(this._screenRaycastCache[R])return this._screenRaycastCache[R];{let $;return $=C.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(y),C):{polygon:this.bufferedScreenGeometry(y).map(G=>C.pointCoordinate3D(G)),unwrapped:!0},this._screenRaycastCache[R]=$,$}}_bufferedCameraMercator(y,C){const R=Sd(y);if(this._cameraRaycastCache[R])return this._cameraRaycastCache[R];{let $;return $=C.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(y),C):{polygon:this.bufferedCameraGeometry(y).map(G=>C.pointCoordinate3D(G)),unwrapped:!0},this._cameraRaycastCache[R]=$,$}}_projectAndResample(y,C){const R=function(G,Z){const te=o.aD([],Z.pixelMatrix,Z.globeMatrix),ue=[0,-o.aF,0,1],xe=[0,o.aF,0,1],je=[0,0,0,1];o.aE(ue,ue,te),o.aE(xe,xe,te),o.aE(je,je,te);const Re=new o.P(ue[0]/ue[3],ue[1]/ue[3]),Le=new o.P(xe[0]/xe[3],xe[1]/xe[3]),Ue=o.aG(G,Re)&&ue[3]1?po(G.slice(0,pt),Z):[],Tt=ptnew o.P(zc(Jt.x),Jt.y)),Tt=Tt.map(Jt=>new o.P(zc(Jt.x),Jt.y));const xt=[...jt];xt.length===0&&xt.push(Tt[Tt.length-1]);const es=o.am(xt[xt.length-1].y,(Tt.length===0?jt[0]:Tt[0]).y,mt);let Ft;return Ft=Ue?[new o.P(0,es),new o.P(0,0),new o.P(1,0),new o.P(1,es)]:[new o.P(1,es),new o.P(1,1),new o.P(0,1),new o.P(0,es)],xt.push(...Ft),Tt.length===0?xt.push(jt[0]):xt.push(...Tt),{polygon:xt.map(Jt=>new o.ag(Jt.x,Jt.y)),unwrapped:!1}}(y,C);if(R)return R;const $=function(G,Z){let te=!1,ue=-1/0,xe=0;for(let Re=0;Reue&&(ue=G[Re].x,xe=Re);for(let Re=0;Re.5&&(Ue.x{Re.x-=1}),{polygon:G,unwrapped:te}}(po(y,C).map(G=>new o.P(zc(G.x),G.y)),C);return{polygon:$.polygon.map(G=>new o.ag(G.x,G.y)),unwrapped:$.unwrapped}}}function po(I,y){return o.aI(I,C=>{const R=y.pointCoordinate3D(C);C.x=R.x,C.y=R.y},1/256)}function zc(I){return I<0?1+I%1:I%1}function Sd(I){return 100*I|0}function fm(I,y,C){try{y=function($){if(!$.variants)return $;if(!Array.isArray($.variants))throw new Error("variants must be an array");for(const G of $.variants){if(G==null||typeof G!="object"||G.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(G.capabilities))throw new Error("capabilities must be an array");if(G.capabilities.length===1&&G.capabilities[0]==="meshopt")return Object.assign($,G)}return $}(y)}catch($){return new Error("Failed to process TileJSON variants",{cause:$})}const R=o.aJ(Object.assign({},y,I),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return I.url&&y.tiles&&I.tiles&&(R.tiles=y.tiles),R.tiles=C.canonicalizeTileset(R,I.url),R}function Cd(I,y,C,R,$){const G=function(te,ue){if(te)return $(te);if(ue){I.url&&ue.tiles&&I.tiles&&delete I.tiles;const xe=fm(I,ue,y);if(xe instanceof Error)return $(xe);$(null,xe)}},Z=function(te,ue,xe){if(!te)return null;if(!ue&&!xe)return te;xe=xe||te.worldview_default;const je=Object.values(te.language||{});if(je.length===0)return null;const Re=Object.values(te.worldview||{});if(Re.length===0)return null;const Le=je.every(st=>st===ue),Ue=Re.every(st=>st===xe);return Le&&Ue?te:ue in(te.language_options||{})||xe in(te.worldview_options||{})?null:te.language_options&&te.worldview_options?te:null}(I.data,C,R);return Z?o.o.frame(()=>G(null,Z)):I.url?o.m(y.transformRequest(y.normalizeSourceURL(I.url,null,C,R),o.R.Source),G):o.o.frame(()=>{const{data:te,...ue}=I;G(null,ue)})}function Hd(I,y){const C=Math.pow(2,y.z),R=Math.floor(o.aH(I.getWest())*C),$=Math.floor(o.aL(I.getNorth())*C),G=Math.ceil(o.aH(I.getEast())*C),Z=Math.ceil(o.aL(I.getSouth())*C);return y.x>=R&&y.x=$&&y.ythis.maxzoom||y.z{this._tileJSONRequest=null,this._loaded=!0,Z?(C&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${C}`),R&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${R}`),this.fire(new o.B(Z))):te&&(this._setTileJSON(te),Me(te.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),y&&y(Z)};this.provider=this._options.provider;const G=function(Z){if("provider"in Z&&!Z.provider)return null;let te=Z.provider;if(!te&&"url"in Z&&Z.url&&(te=o.aM(Z.url)),!te)return null;const ue=o.g.TILE_PROVIDER_URLS[te];if(!ue)return null;let xe;try{xe=new URL(ue,o.g.API_URL).href}catch{return o.w(`TileProvider "${te}" has an invalid URL: "${ue}"`),null}return{name:te,url:xe}}(this._options);if(this.provider&&!G)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(y&&y());this._tileJSONRequest=G?this._loadWithProvider(G,$):Cd(this._options,this.map._requestManager,C,R,$)}_loadWithProvider(y,C){this.provider=y.name;const R=new AbortController,$=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,G=$?Object.assign({},this._options,{url:$.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:y.name,url:y.url,source:this.id,scope:this.scope,type:this.type,options:G,request:$},(Z,te)=>{if(R.signal.aborted)return;if(Z)return void C(Z);const ue=te?te.find(xe=>xe!=null):null;if(ue){const xe=fm(this._options,ue,this.map._requestManager);xe instanceof Error?C(xe):C(null,xe)}else C(null,{tiles:this._options.tiles})}),{cancel:()=>{R.abort()}}}_setTileJSON(y){if(Object.assign(this,y),this.hasWorldviews=!!y.worldview_options,y.worldview_default&&(this.worldviewDefault=y.worldview_default),y.vector_layers){this.vectorLayers=y.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const C of y.vector_layers)this.vectorLayerIds.push(C.id),y.worldview&&y.worldview[C.source]&&this.localizableLayerIds.add(C.id)}this.tileBounds=uc.fromTileJSON(y)}loaded(){return this._loaded}hasTile(y){return!this.tileBounds||this.tileBounds.contains(y.canonical)}onAdd(y){this.map=y,this.load()}reload(){this.cancelTileJSONRequest();const y=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(y))}setTiles(y){return this._options.tiles=y,this.reload(),this}setUrl(y){return this.url=y,this._options.url=y,this.reload(),this}onRemove(y){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(y,C){const R=y.tileID.canonical.url(this.tiles,this.scheme),$=this.map._requestManager.normalizeTileURL(R),G=this.map._requestManager.transformRequest($,o.R.Tile),Z=this.map.style?this.map.style.getLut(this.scope):null,te=Z?{image:Z.image.clone()}:null,ue={request:G,data:void 0,uid:y.uid,tileID:y.tileID,tileZoom:y.tileZoom,zoom:y.tileID.overscaledZ,maxZoom:this.maxzoom,lut:te,tileSize:this.tileSize*y.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:y.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:y.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.getIndoorTileOptions(this.id,this.scope)};if(this.hasWorldviews&&o.e(R)&&(ue.localizableLayerIds=this.localizableLayerIds),ue.request.collectResourceTiming=this._collectResourceTiming,y.actor&&y.state!=="expired")y.state==="loading"?y.reloadCallback=C:y.request=y.actor.send("reloadTile",ue,xe.bind(this));else if(y.actor=this._tileWorkers[$]=this._tileWorkers[$]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)y.request=y.actor.send("loadTile",ue,xe.bind(this),void 0,!0);else{const je=o.aO.call({deduped:this._deduped},ue,(Re,Le)=>{if(Re||!Le)xe.call(this,Re);else{const Ue=o.aP(Le.responseHeaders);ue.data={rawData:Le.rawData.slice(0),expires:Ue.expires,cacheControl:Ue.cacheControl},y.actor&&y.actor.send("loadTile",ue,xe.bind(this),void 0,!0)}},!0);y.request={cancel:je}}function xe(je,Re){return delete y.request,y.aborted?C(null):je?C(je):(Re&&Re.resourceTiming&&(y.resourceTiming=Re.resourceTiming),this.map._refreshExpiredTiles&&Re&&y.setExpiryData(Re),y.loadVectorData(Re,this.map.painter),o.aQ(this.dispatcher),C(null,Re),void(y.reloadCallback&&(this.loadTile(y,y.reloadCallback),y.reloadCallback=null)))}}abortTile(y){y.request&&(y.request.cancel(),delete y.request),y.actor&&y.actor.send("abortTile",{uid:y.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(y,C){y.actor&&y.actor.send("removeTile",{uid:y.uid,type:this.type,source:this.id,scope:this.scope}),y.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class i1 extends o.E{constructor(y,C,R,$){super(),this.id=y,this.dispatcher=R,this.setEventedParent($),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=Object.assign({type:"raster"},C),Object.assign(this,o.aJ(C,["url","scheme","tileSize"]))}load(y){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const C=this.map.getWorldview();this._tileJSONRequest=Cd(this._options,this.map._requestManager,null,C,(R,$)=>{this._tileJSONRequest=null,this._loaded=!0,R?this.fire(new o.B(R)):$&&(Object.assign(this,$),$.raster_layers&&(this.rasterLayers=$.raster_layers,this.rasterLayerIds=this.rasterLayers.map(G=>G.id)),this.tileBounds=uc.fromTileJSON($),Me($.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),y&&y(R)})}loaded(){return this._loaded}onAdd(y){this.map=y,this.load()}reload(){this.cancelTileJSONRequest();const y=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(y))}setTiles(y){return this._options.tiles=y,this.reload(),this}setUrl(y){return this.url=y,this._options.url=y,this.reload(),this}onRemove(y){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(y){return!this.tileBounds||this.tileBounds.contains(y.canonical)}loadTile(y,C){const R=o.o.devicePixelRatio>=2,$=this.map._requestManager.normalizeTileURL(y.tileID.canonical.url(this.tiles,this.scheme),R,this.tileSize);y.request=o.n(this.map._requestManager.transformRequest($,o.R.Tile),(G,Z,te)=>{if(delete y.request,y.aborted)return y.state="unloaded",C(null);if(G)return y.state="errored",C(G);if(!Z)return C(null);const ue=o.aP(te);this.map._refreshExpiredTiles&&y.setExpiryData(ue),y.setTexture(Z,this.map.painter),y.state="loaded",o.aQ(this.dispatcher),C(null)})}abortTile(y,C){y.request&&(y.request.cancel(),delete y.request),C&&C()}unloadTile(y,C){y.texture&&y.texture instanceof o.T?(y.destroy(!1),y.texture&&y.texture instanceof o.T&&this.map.painter.saveTileTexture(y.texture)):y.destroy(),C&&C()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function lj([I,y],C,R,{scaled:$=!0}={}){const{tileSize:G,buffer:Z}=R,{x:te,y:ue,z:xe}=C;if(!isFinite(te)||!isFinite(ue)||!isFinite(xe))throw new Error("Invalid MRT header");const je=2**xe,Re=je*o.aH(I),Le=je*o.aL(y);return function([Ue,st],Xe,{scaled:pt=!0}={}){if(!Xe)throw new Error("bandView is undefined");const{data:mt,tileSize:jt,buffer:Tt,offset:xt,scale:es,dimension:Ft}=Xe;if(Ue<-Tt||Ue>jt+Tt||st<-Tt||st>jt+Tt)throw new Error(`Point (${Ue}, ${st}) out of bounds for tileSize=${jt}, buffer=${Tt}`);const Jt=(st+Tt)*(jt+2*Tt)+(Ue+Tt);if(new Uint32Array(mt.buffer)[Jt]===4294967295)return null;let At=[];At=pt?[]:new Xe.data.constructor(Ft);for(let Rt=0;Rt{if(delete y.request,y.aborted)return y.state="unloaded",C(null);if(te)return te.name==="AbortError"?void 0:(y.state="errored",C(te));if(this.map._refreshExpiredTiles&&ue){const je=o.aP(xe);y.setExpiryData(je)}if(this.partial&&y.state!=="expired")y.state="empty";else if(!this.partial){if(!ue)return C(null);y.state="loaded",y._isHeaderLoaded=!0,y._mrt=ue}C(null)};y.request=this.partial?y.fetchHeader(void 0,Z.bind(this)):y.actor.send("loadTile",G,Z.bind(this),void 0,!0)}abortTile(y){y.request&&(y.request.cancel(),delete y.request),y.actor&&y.actor.send("abortTile",{uid:y.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(y,C){const R=y.texturePerLayer;if(y.flushAllQueues(),R.size){y.destroy(!1);for(const $ of R.values())this.map.painter.saveTileTexture($)}else y.destroy()}prepareTile(y,C,R,$){y._isHeaderLoaded&&(y.state!=="empty"&&(y.state="reloading"),y.fetchBandForRender(C,R,$,(G,Z)=>{G?(y.state="errored",this.fire(new o.B(G))):Z&&(y._isHeaderLoaded=!0,y.setTexturePerLayer(R,Z,this.map.painter),y.state="loaded"),this.triggerRepaint(y)}))}getInitialBand(y){if(!this.rasterLayers)return 0;const C=this.rasterLayers.find(({id:G})=>G===y),R=C&&C.fields,$=R&&R.bands&&R.bands;return $?$[0]:0}getTextureDescriptor(y,C,R){if(!y)return;const $=C.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!$)return;let G=null;C instanceof o.aS?G=C.paint.get("raster-array-band"):C instanceof o.aT&&(G=C.paint.get("raster-particle-array-band"));const Z=G||this.getInitialBand($);if(Z==null)return;if(!y.textureDescriptorPerLayer.get(C.id))return void this.prepareTile(y,$,C.id,Z);if(y.updateNeeded(C.id,Z)&&!R)return;const te=y.textureDescriptorPerLayer.get(C.id);return Object.assign({},te,{texture:y.texturePerLayer.get(C.id)})}getImages(y,C){const R=new Map;for(const $ of y)for(const G of C){const[Z,te]=G.split("/"),ue=$.getLayer(Z);if(!ue||!ue.hasBand(te)||!ue.hasDataForBand(te))continue;const{bytes:xe,tileSize:je,buffer:Re}=ue.getBandView(te),Le=je+2*Re,Ue={data:new o.q({width:Le,height:Le},xe),pixelRatio:2,sdf:!1,usvg:!1,version:0};R.set(G,Ue)}return R}queryRasterArrayValueByBandId(y,C,R){const $=C._mrt;return new Promise(G=>{const Z={},te=new Set;for(const[ue,xe]of Object.entries($.layers)){if(R.layerName&&ue!==R.layerName)continue;const je={};Z[ue]=je;for(const{bands:Re}of xe.dataIndex)for(const Le of Re)R.bands&&!R.bands.includes(Le)||(te.add(o.F(ue,Le)),C.fetchBand(ue,null,Le,Ue=>{o.o.frame(()=>{je[Le]=Ue?null:lj([y.lng,y.lat],$,xe.getBandView(Le)),te.delete(o.F(ue,Le)),te.size===0&&G(Z)})},!1))}te.size===0&&G(Z)})}_loadTileForQuery(y,C){if(this._loadTileLoaded[y.uid])return void C(null,y._mrt);if(this._loadTilePending[y.uid])return void this._loadTilePending[y.uid].push(C);this._loadTilePending[y.uid]=[C];const R=this.map._requestManager.normalizeTileURL(y.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),$=this.map._requestManager.transformRequest(R,o.R.Tile);y.actor.send("loadTile",{request:$,uid:y.uid,tileID:y.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(G,Z,te)=>{if(G)return this._loadTilePending[y.uid].forEach(ue=>ue(G,null)),void delete this._loadTilePending[y.uid];if(!Z)return this._loadTilePending[y.uid].forEach(ue=>ue(null,null)),void delete this._loadTilePending[y.uid];if(this.map._refreshExpiredTiles&&Z){const ue=o.aP(te);y.setExpiryData(ue)}y._mrt=Z,y._isHeaderLoaded=!0,y.state="loaded",this._loadTilePending[y.uid].forEach(ue=>ue(null,Z)),this._loadTileLoaded[y.uid]=!0,delete this._loadTilePending[y.uid]},void 0,!0)}queryRasterArrayValueByAllBands(y,C,R){return new Promise(($,G)=>{this._loadTileForQuery(C,(Z,te)=>{Z?G(Z):$(te?this.queryRasterArrayValueByBandId(y,C,R):null)})})}queryRasterArrayValue(y,C){const R=o.aU.convert(y),$=this.findLoadedParent(R);return $&&$._mrt?C.bands||!this.partial?this.queryRasterArrayValueByBandId(R,$,C):this.queryRasterArrayValueByAllBands(R,$,C):Promise.resolve(null)}findLoadedParent(y){const C=o.ag.fromLngLat(y,this.map.transform.tileSize),R=this.maxzoom+1,$=1<0&&(te[new o.aR(I.overscaledZ,$,y.z,R,y.y-1).key]={backfilled:!1},te[new o.aR(I.overscaledZ,I.wrap,y.z,y.x,y.y-1).key]={backfilled:!1},te[new o.aR(I.overscaledZ,Z,y.z,G,y.y-1).key]={backfilled:!1}),y.y+1{if(this._loaded=!0,this._pendingLoad=null,R)this.fire(new o.B(R));else{const G={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&$&&$.resourceTiming&&$.resourceTiming[this.id]&&(G.resourceTiming=$.resourceTiming[this.id]),I&&(this._partialReload=!0),this.fire(new o.C("data",G)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(I),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const I=o.F(this.id,this.scope);this.map.style.clearSource(I),this._updateWorkerData()}loadTile(I,y){const C=I.actor?"reloadTile":"loadTile";I.actor=this.actor;const R=this.map.style?this.map.style.getLut(this.scope):null,$=R?{image:R.image.clone()}:null,G=this._partialReload,Z={type:this.type,uid:I.uid,tileID:I.tileID,tileZoom:I.tileZoom,zoom:I.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:$,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:I.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:G,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};I.request=this.actor.send(C,Z,(te,ue)=>G&&!ue?(I.state="loaded",y(null)):(delete I.request,I.destroy(!1),I.aborted?y(null):te?y(te):(I.loadVectorData(ue,this.map.painter,C==="reloadTile"),y(null))),void 0,C==="loadTile")}abortTile(I){I.request&&(I.request.cancel(),delete I.request),I.aborted=!0}unloadTile(I,y){this.actor.send("removeTile",{uid:I.uid,type:this.type,source:this.id,scope:this.scope}),I.destroy()}onRemove(I){this._pendingLoad&&this._pendingLoad.cancel()}serialize(){return Object.assign({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}},video:class extends o.aV{constructor(I,y,C,R){super(I,y,C,R),this.roundZoom=!0,this.type="video",this.options=y}load(){this._loaded=!1;const I=this.options;this.urls=[];for(const y of I.urls)this.urls.push(this.map._requestManager.transformRequest(y,o.R.Source).url);o.aW(this.urls,(y,C)=>{this._loaded=!0,y?this.fire(new o.B(y)):C&&(this.video=C,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading())})}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(I){if(this.video){const y=this.video.seekable;Iy.end(0)?this.fire(new o.B(new o.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${y.start(0)} and ${y.end(0)}-second mark.`))):this.video.currentTime=I}}getVideo(){return this.video}onAdd(I){this.map||(this.map=I,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 I=this.map.painter.context,y=I.gl;this.texture?this.video.paused||(this.texture.bind(y.LINEAR,y.CLAMP_TO_EDGE),y.texSubImage2D(y.TEXTURE_2D,0,0,0,y.RGBA,y.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(I,this.video,y.RGBA8),this.texture.bind(y.LINEAR,y.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(I)}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:o.aV,model:o.aY,"batched-model":class extends o.E{constructor(I,y,C,R){super(),this.type="batched-model",this.id=I,this.tileSize=512,this._options=y,this.tiles=this._options.tiles,this.maxzoom=y.maxzoom||19,this.minzoom=y.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=C,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(R)}onAdd(I){this.map=I,this.load()}reload(){this.cancelTileJSONRequest();const I=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(I))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(I){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const y=Array.isArray(this.map._language)?this.map._language.join():this.map._language,C=this.map.getWorldview();this._tileJSONRequest=Cd(this._options,this.map._requestManager,y,C,(R,$)=>{this._tileJSONRequest=null,this._loaded=!0,R?(y&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${y}`),C&&C.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${C}`),this.fire(new o.B(R))):$&&(Object.assign(this,$),$.bounds&&(this.tileBounds=new uc($.bounds,this.minzoom,this.maxzoom)),Me($.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),I&&I(R)})}hasTransition(){return!1}hasTile(I){return!this.tileBounds||this.tileBounds.contains(I.canonical)}loaded(){return this._loaded}loadTile(I,y){const C=this.map._requestManager.normalizeTileURL(I.tileID.canonical.url(this.tiles,this.scheme)),R={request:this.map._requestManager.transformRequest(C,o.R.Tile),data:void 0,uid:I.uid,tileID:I.tileID,tileZoom:I.tileZoom,zoom:I.tileID.overscaledZ,tileSize:this.tileSize*I.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:I.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(I.actor&&I.state!=="expired")if(I.state==="loading")I.reloadCallback=y;else{if(I.buckets){const G=Object.values(I.buckets);for(const Z of G)Z.dirty=!0;return void(I.state="loaded")}I.request=I.actor.send("reloadTile",R,$.bind(this))}else I.actor=this.dispatcher.getActor(),I.request=I.actor.send("loadTile",R,$.bind(this),void 0,!0);function $(G,Z){return I.aborted?y(null):G&&G.status!==404?y(G):(this.map._refreshExpiredTiles&&Z&&I.setExpiryData(Z),I.loadModelData(Z,this.map.painter),I.state="loaded",void y(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(I,y,C,R){super(I,y,C,R),y.coordinates?Array.isArray(y.coordinates)&&y.coordinates.length===4&&!y.coordinates.some($=>!Array.isArray($)||$.length!==2||$.some(G=>typeof G!="number"))||this.fire(new o.B(new o.V(`sources.${I}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.B(new o.V(`sources.${I}`,null,'missing required property "coordinates"'))),y.animate&&typeof y.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${I}`,null,'optional "animate" property must be a boolean value'))),y.canvas?typeof y.canvas=="string"||y.canvas instanceof HTMLCanvasElement||this.fire(new o.B(new o.V(`sources.${I}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new o.B(new o.V(`sources.${I}`,null,'missing required property "canvas"'))),this.options=y,this.animate=y.animate===void 0||y.animate}load(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new o.B(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}getCanvas(){return this.canvas}onAdd(I){this.map=I,this.load(),this.canvas&&this.animate&&this.play()}onRemove(I){this.pause()}prepare(){let I=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,I=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,I=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const y=this.map.painter.context;this.texture?!I&&!this._playing||this.texture instanceof o.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(y,this.canvas,y.gl.RGBA8,{premultiply:!0}),this._prepareData(y)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const I of[this.canvas.width,this.canvas.height])if(isNaN(I)||I<=0)return!0;return!1}},custom:class extends o.E{constructor(I,y,C,R){super(),this.id=I,this.type="custom",this._dataType="raster",this._dispatcher=C,this._implementation=y,this.setEventedParent(R),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new o.B(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new o.B(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new uc(this._implementation.bounds,this.minzoom,this.maxzoom));const $=y;$.update=this._update.bind(this),$.clearTiles=this._clearTiles.bind(this),$.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aJ(y,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return o.aJ(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(I){this.map=I,this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(I),this.load()}onRemove(I){this._implementation.onRemove&&this._implementation.onRemove(I)}hasTile(I){if(this._implementation.hasTile){const{x:y,y:C,z:R}=I.canonical;return this._implementation.hasTile({x:y,y:C,z:R})}return!this.tileBounds||this.tileBounds.contains(I.canonical)}loadTile(I,y){const{x:C,y:R,z:$}=I.tileID.canonical,G=new AbortController,Z=Promise.resolve(this._implementation.loadTile({x:C,y:R,z:$},{signal:G.signal})).then((function(te){return delete I.request,I.aborted?(I.state="unloaded",y(null)):te===void 0?(I.state="errored",y(null)):te===null?(this.loadTileData(I,{width:this.tileSize,height:this.tileSize,data:null}),I.state="loaded",y(null)):function(ue){return ue instanceof ImageData||ue instanceof HTMLCanvasElement||ue instanceof ImageBitmap||ue instanceof HTMLImageElement}(te)?(this.loadTileData(I,te),I.state="loaded",void y(null)):(I.state="errored",y(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(te=>{te.name!=="AbortError"&&(I.state="errored",y(te))});Z.cancel=()=>G.abort(),I.request=Z}loadTileData(I,y){I.setTexture(y,this.map.painter)}unloadTile(I,y){if(I.texture&&I.texture instanceof o.T?(I.destroy(!1),I.texture&&I.texture instanceof o.T&&this.map.painter.saveTileTexture(I.texture)):I.destroy(),this._implementation.unloadTile){const{x:C,y:R,z:$}=I.tileID.canonical;this._implementation.unloadTile({x:C,y:R,z:$})}y&&y()}abortTile(I,y){I.request&&I.request.cancel&&(I.request.cancel(),delete I.request),y&&y()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(I=>({x:I.canonical.x,y:I.canonical.y,z:I.canonical.z}))}_clearTiles(){const I=o.F(this.id,this.scope);this.map.style.clearSource(I)}_update(){this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}}},Py=function(I,y,C,R){const $=new Iy[y.type](I,y,C,R);if($.id!==I)throw new Error(`Expected Source id to be ${I} instead of ${$.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],$),$};function Ef(I,y,C=""){return`${C}:${y.id||""}:${y.layer.id}:${function(R){if("layerId"in R)return`layer:${R.layerId}`;{const{featuresetId:$,importId:G}=R;return`featureset:${$}${G?`:import:${G}`:""}`}}(I.target)}`}function _h(I,y,C,R=""){if(I.uniqueFeatureID){const $=Ef(I,y,R);if(C.has($))return!0;C.add($)}return!1}function px(I,y,C,R,$=!1,G=void 0){const Z=y.sourceCache.transform,te=y.sourceCache.tilesIn(I,y.has3DLayers,$);te.sort(gm);const ue=[];for(const xe of te){const je=xe.tile.queryRenderedFeatures(y,xe,C,R,Z,$,G);Object.keys(je).length&&ue.push({wrappedTileID:xe.tile.tileID.wrapped().key,queryResults:je})}for(const xe in y.layers){const je=y.layers[xe];if(je.styleLayer){const Re=je.styleLayer.queryRenderedFeatures(I,y.sourceCache,R);Object.keys(Re).length&&ue.push({wrappedTileID:0,queryResults:Re})}}return ue.length===0?{}:function(xe){const je={},Re={};for(const Le of xe){const Ue=Le.queryResults,st=Le.wrappedTileID,Xe=Re[st]=Re[st]||{};for(const pt in Ue){const mt=Ue[pt],jt=Xe[pt]=Xe[pt]||{},Tt=je[pt]=je[pt]||[];for(const xt of mt)jt[xt.featureIndex]||(jt[xt.featureIndex]=!0,Tt.push(xt))}}return je}(ue)}function fo(I,y,C,R,$,G){const Z={},te=R.queryRenderedSymbols(I),ue=[];for(const xe of Object.keys(te).map(Number))ue.push($[xe]);ue.sort(gm);for(const xe of ue){const je=xe.featureIndex.lookupSymbolFeatures(te[xe.bucketInstanceId],xe.bucketIndex,xe.sourceLayerIndex,y,C,G);for(const Re in je){const Le=Z[Re]=Z[Re]||[],Ue=je[Re];Ue.sort((st,Xe)=>{const pt=xe.featureSortOrder;if(pt){const mt=pt.indexOf(st.featureIndex);return pt.indexOf(Xe.featureIndex)-mt}return Xe.featureIndex-st.featureIndex});for(const st of Ue)Le.push(st)}}return Z}function Vb(I,y){const C=I.getRenderableIds().map(G=>I.getTileByID(G)),R=[],$={};for(let G=0;G{if(G)C(G);else try{const ue=R.getHeaderLength(Z);if(ue>y)return void(this.request=this.fetchHeader(ue,C));R.parseHeader(Z),this._isHeaderLoaded=!0;let xe=0;for(const je of Object.values(R.layers))xe=Math.max(xe,je.dataIndex[je.dataIndex.length-1].lastByte);Z.byteLength>=xe&&(this.entireBuffer=Z),C(null,this.entireBuffer||Z,te)}catch(ue){C(ue)}}),this.request}fetchBandForRender(y,C,R,$){this.fetchBand(y,C,R,G=>{if(G)return void $(G);this.updateTextureDescriptor(y,C,R);const Z=this.textureDescriptorPerLayer.get(C);$(null,Z?Z.img:null)})}fetchBand(y,C,R,$,G=!0){const Z=this._mrt;if(!this._isHeaderLoaded||!Z)return void $(new Error("Tile header is not ready"));const te=this.actor;if(!te)return void $(new Error("Can't fetch tile band without an actor"));let ue;const xe=o.F(String(R),o.F(this.tileID.key,y));let je=this._taskQueue.get(xe);je?je.add($):(je=new Set,je.add($),this._taskQueue.set(xe,je));const Re=(Xe,pt)=>{ue.complete(Xe,pt),Xe?$(Xe):(je.forEach(mt=>mt(null,pt)),this._taskQueue.delete(xe))},Le=(Xe,pt)=>{if(Xe)return $(Xe);const mt=te.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:pt,task:ue},Re,void 0,!0);if(C!==null){const jt=this._workQueuePerLayer.get(C)||[];jt.push(()=>{mt&&mt.cancel(),ue.cancel()}),this._workQueuePerLayer.has(C)||this._workQueuePerLayer.set(C,jt)}};let Ue;try{Ue=Z.getLayer(y)}catch(Xe){if(this.state==="reloading")return;throw Xe}if(!Ue)return void $(new Error(`Unknown sourceLayer "${y}"`));if(Ue.hasDataForBand(R))return je.forEach(Xe=>Xe(null,null)),void this._taskQueue.delete(xe);const st=Ue.getDataRange([R]);if(ue=Z.createDecodingTask(st),!ue||ue.tasks.length)if(C!==null&&this.flushQueues(C),this.entireBuffer)Le(null,this.entireBuffer.slice(st.firstByte,st.lastByte+1));else{const Xe=Object.assign({},this.requestParams,{headers:{Range:`bytes=${st.firstByte}-${st.lastByte}`}}),pt=o.b1(Xe,Le);if(C!==null){const mt=this._fetchQueuePerLayer.get(C)||[];mt.push(()=>{pt.cancel(),ue.cancel()}),this._fetchQueuePerLayer.has(C)||this._fetchQueuePerLayer.set(C,mt)}}}updateNeeded(y,C){return(!this.textureDescriptorPerLayer.get(y)||this.textureDescriptorPerLayer.get(y).band!==C||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(y,C,R){if(!this._mrt)return;const $=this._mrt.getLayer(y);if(!$||!$.hasBand(R)||!$.hasDataForBand(R))return;const{bytes:G,tileSize:Z,buffer:te,offset:ue,scale:xe}=$.getBandView(R),je=Z+2*te,Re=new o.q({width:je,height:je},G),Le=this.texturePerLayer.get(C);Le&&Le instanceof o.T&&Le.update(Re,{premultiply:!1}),this.textureDescriptorPerLayer.set(C,{layer:y,band:R,img:Re,buffer:te,offset:ue,tileSize:Z,format:$.pixelFormat,mix:[xe,256*xe,65536*xe,16777216*xe]})}destroy(y=!1){if(super.destroy(y),delete this._mrt,!y)for(const C of this.texturePerLayer.values())C&&C instanceof o.T&&C.destroy();this.texturePerLayer.clear(),this.textureDescriptorPerLayer.clear(),this.fbo&&(this.fbo.destroy(),delete this.fbo),delete this.request,delete this.requestParams,this._isHeaderLoaded=!1}}class fx{constructor(y,C){this.max=y,this.onRemove=C,this.reset()}reset(){for(const y in this.data)for(const C of this.data[y])C.timeout&&clearTimeout(C.timeout),this.onRemove(C.value);return this.data={},this.order=[],this}add(y,C,R){const $=y.wrapped().key;this.data[$]===void 0&&(this.data[$]=[]);const G={value:C,timeout:void 0};if(R!==void 0&&(G.timeout=setTimeout(()=>{this.remove(y,G)},R)),this.data[$].push(G),this.order.push($),this.order.length>this.max){const Z=this._getAndRemoveByKey(this.order[0]);Z&&this.onRemove(Z)}return this}has(y){return y.wrapped().key in this.data}getAndRemove(y){return this.has(y)?this._getAndRemoveByKey(y.wrapped().key):null}_getAndRemoveByKey(y){const C=this.data[y].shift();return C.timeout&&clearTimeout(C.timeout),this.data[y].length===0&&delete this.data[y],this.order.splice(this.order.indexOf(y),1),C.value}getByKey(y){const C=this.data[y];return C?C[0].value:null}get(y){return this.has(y)?this.data[y.wrapped().key][0].value:null}remove(y,C){if(!this.has(y))return this;const R=y.wrapped().key,$=C===void 0?0:this.data[R].indexOf(C),G=this.data[R][$];return this.data[R].splice($,1),G.timeout&&clearTimeout(G.timeout),this.data[R].length===0&&delete this.data[R],this.onRemove(G.value),this.order.splice(this.order.indexOf(R),1),this}setMaxSize(y){for(this.max=y;this.order.length>this.max;){const C=this._getAndRemoveByKey(this.order[0]);C&&this.onRemove(C)}return this}filter(y){const C=[];for(const R in this.data)for(const $ of this.data[R])y($.value)||C.push($);for(const R of C)this.remove(R.value.tileID,R)}}class Yu{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(y,C,R){const $=String(C);if(this.stateChanges[y]=this.stateChanges[y]||{},this.stateChanges[y][$]=this.stateChanges[y][$]||{},Object.assign(this.stateChanges[y][$],R),this.deletedStates[y]===null){this.deletedStates[y]={};for(const G in this.state[y])G!==$&&(this.deletedStates[y][G]=null)}else if(this.deletedStates[y]&&this.deletedStates[y][$]===null){this.deletedStates[y][$]={};for(const G in this.state[y][$])R[G]||(this.deletedStates[y][$][G]=null)}else for(const G in R)this.deletedStates[y]&&this.deletedStates[y][$]&&this.deletedStates[y][$][G]===null&&delete this.deletedStates[y][$][G]}removeFeatureState(y,C,R){if(this.deletedStates[y]===null)return;const $=String(C);if(this.deletedStates[y]=this.deletedStates[y]||{},R&&C!==void 0)this.deletedStates[y][$]!==null&&(this.deletedStates[y][$]=this.deletedStates[y][$]||{},this.deletedStates[y][$][R]=null);else if(C!==void 0)if(this.stateChanges[y]&&this.stateChanges[y][$])for(R in this.deletedStates[y][$]={},this.stateChanges[y][$])this.deletedStates[y][$][R]=null;else this.deletedStates[y][$]=null;else this.deletedStates[y]=null}getState(y,C){const R=this.state[y]||{},$=this.stateChanges[y]||{},G=this.deletedStates[y];if(G===null)return{};if(C!==void 0){const te=String(C),ue=Object.assign({},R[te],$[te]);if(G){const xe=G[C];if(xe===null)return{};for(const je in xe)delete ue[je]}return ue}const Z=Object.assign({},R,$);if(G)for(const te in G)delete Z[te];return Z}initializeTileState(y,C){y.refreshFeatureState(C)}coalesceChanges(y,C){const R={};for(const $ in this.stateChanges){this.state[$]=this.state[$]||{};const G={};for(const Z in this.stateChanges[$])this.state[$][Z]||(this.state[$][Z]={}),Object.assign(this.state[$][Z],this.stateChanges[$][Z]),G[Z]=this.state[$][Z];R[$]=G}for(const $ in this.deletedStates){this.state[$]=this.state[$]||{};const G={};if(this.deletedStates[$]===null)for(const Z in this.state[$])G[Z]={},this.state[$][Z]={};else for(const Z in this.deletedStates[$]){if(this.deletedStates[$][Z]===null)this.state[$][Z]={};else if(this.state[$][Z])for(const te of Object.keys(this.deletedStates[$][Z]))delete this.state[$][Z][te];G[Z]=this.state[$][Z]}R[$]=R[$]||{},Object.assign(R[$],G)}if(this.stateChanges={},this.deletedStates={},Object.keys(R).length!==0)for(const $ in y)y[$].refreshFeatureState(C,R)}}class al extends o.E{constructor(y,C,R){super(),this.id=y,this._renderSourceType=R,this._maxzoomOverride=null,C.on("data",$=>{$.dataType==="source"&&$.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&$.dataType==="source"&&$.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),C.on("error",()=>{this._sourceErrored=!0}),this._source=C,this._tiles={},this._cache=new fx(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=C.minTileCacheSize,this._maxTileCacheSize=C.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new Yu,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(y){this.map=y,this._minTileCacheSize=this._minTileCacheSize===void 0&&y?y._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&y?y._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const y in this._tiles)if(!this._tiles[y].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const y=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,y&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(y){this._maxzoomOverride=y}_loadTile(y,C){return y.renderSourceType=this._renderSourceType,y.isExtraShadowCaster=this._shadowCasterTiles[y.tileID.key],this._source.loadTile(y,C)}_unloadTile(y){if(this._source.unloadTile)return this._source.unloadTile(y)}_abortTile(y){if(this._source.abortTile)return this._source.abortTile(y)}serialize(){return this._source.serialize()}prepare(y){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const C in this._tiles){const R=this._tiles[C];R.upload(y,this.map?this.map.painter:void 0),R.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(y=>y.tileID).sort(u0).map(y=>y.key)}getRenderableIds(y,C){const R=[];for(const $ in this._tiles)this._isIdRenderable(+$,y,C)&&R.push(this._tiles[$]);return y?R.sort(($,G)=>{const Z=$.tileID,te=G.tileID,ue=new o.P(Z.canonical.x,Z.canonical.y)._rotate(this.transform.angle),xe=new o.P(te.canonical.x,te.canonical.y)._rotate(this.transform.angle);return Z.overscaledZ-te.overscaledZ||xe.y-ue.y||xe.x-ue.x}).map($=>$.tileID.key):R.map($=>$.tileID).sort(u0).map($=>$.key)}hasRenderableParent(y){const C=this.findLoadedParent(y,0);return!!C&&this._isIdRenderable(C.tileID.key)}_isIdRenderable(y,C,R){return this._tiles[y]&&this._tiles[y].hasData()&&!this._coveredTiles[y]&&(C||!this._tiles[y].holdingForFade())&&(R||!this._shadowCasterTiles[y])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const y in this._tiles)this._tiles[y].state!=="errored"&&this._reloadTile(+y,"reloading")}}_reloadTile(y,C){const R=this._tiles[y];R&&(R.state!=="loading"&&(R.state=C),this._loadTile(R,this._tileLoaded.bind(this,R,y,C)))}_tileLoaded(y,C,R,$,G){if($){if(y.state="errored",o.b2($)){if(this._source.fire(new o.C("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:y})),!(y.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const te=this.map.painter.terrain;this.update(this.transform,te.getScaledDemTileSize(),!0),te.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B($,{tile:y}));return}y.timeAdded=o.o.now(),R==="expired"&&(y.refreshedUponExpiration=!0),this._setTileReloadTimer(C,y),this._source.type==="raster-dem"&&y.dem&&this._backfillDEM(y),this._state.initializeTileState(y,this.map?this.map.painter:null);let Z=new Map;G&&G.responseHeaders&&(Z=G.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:y,coord:y.tileID,sourceCacheId:this.id,responseHeaders:Z}))}_hasTunnelGeometry(){for(const y in this._tiles){const C=this._tiles[y];if(C&&C.hasTunnelGeometry)return!0}return!1}_backfillDEM(y){const C=this.getRenderableIds();for(let $=0;$1||(Math.abs(Z)>1&&(Math.abs(Z+ue)===1?Z+=ue:Math.abs(Z-ue)===1&&(Z-=ue)),G.dem&&$.dem&&($.dem.backfillBorder(G.dem,Z,te),$.neighboringTiles&&$.neighboringTiles[xe]&&($.neighboringTiles[xe].backfilled=!0)))}}getTile(y){return this.getTileByID(y.key)}getTileByID(y){return this._tiles[y]}_retainLoadedChildren(y,C,R,$){for(const G in this._tiles){let Z=this._tiles[G];if($[G]||!Z.hasData()||Z.tileID.overscaledZ<=C||Z.tileID.overscaledZ>R)continue;let te=Z.tileID;for(;Z&&Z.tileID.overscaledZ>C+1;){const xe=Z.tileID.scaledTo(Z.tileID.overscaledZ-1);Z=this._tiles[xe.key],Z&&Z.hasData()&&(te=xe)}let ue=te;for(;ue.overscaledZ>C;)if(ue=ue.scaledTo(ue.overscaledZ-1),y[ue.key]){$[te.key]=te;break}}}findLoadedParent(y,C){if(y.key in this._loadedParentTiles){const R=this._loadedParentTiles[y.key];return R&&R.tileID.overscaledZ>=C?R:null}for(let R=y.overscaledZ-1;R>=C;R--){const $=y.scaledTo(R),G=this._getLoadedTile($);if(G)return G}}_getLoadedTile(y){const C=this._tiles[y.key];return C&&C.hasData()?C:this._cache.getByKey(this._source.reparseOverscaled?y.wrapped().key:y.canonical.key)}updateCacheSize(y,C){C=C||this._source.tileSize;const R=Math.ceil(y.width/C)+1,$=Math.ceil(y.height/C)+1,G=Math.floor(R*$*5),Z=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,G):G,te=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,Z):Z;this._cache.setMaxSize(te)}handleWrapJump(y){const C=Math.round((y-(this._prevLng===void 0?y:this._prevLng))/360);if(this._prevLng=y,C){const R={};for(const $ in this._tiles){const G=this._tiles[$];G.tileID=G.tileID.unwrapTo(G.tileID.wrap+C),R[G.tileID.key]=G}this._tiles=R;for(const $ in this._timers)clearTimeout(this._timers[$]),delete this._timers[$];for(const $ in this._tiles)this._setTileReloadTimer(+$,this._tiles[$])}}update(y,C,R,$,G){if(this.transform=y,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!R)return;this.updateCacheSize(y,C),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const Z=this._source.type==="batched-model";let te,ue=this._source.maxzoom;this._maxzoomOverride!==null&&(ue=Math.min(ue,this._maxzoomOverride));const xe=this.map&&this.map.painter?this.map.painter._terrain:null;if(xe&&xe.sourceCache===this&&xe.attenuationRange()){const Ue=xe.attenuationRange()[0],st=Math.floor(Ue)-Math.log2(xe.getDemUpscale());ue>st&&(ue=st)}const je=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)te=y.getVisibleUnwrappedCoordinates(this._source.tileID).map(Ue=>new o.aR(Ue.canonical.z,Ue.wrap,Ue.canonical.z,Ue.canonical.x,Ue.canonical.y));else if(this.tileCoverLift!==0){const Ue=y.clone();Ue.tileCoverLift=this.tileCoverLift,te=Ue.coveringTiles({tileSize:C||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:ue,roundZoom:this._source.roundZoom&&!R,reparseOverscaled:je,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:Z}),this._source.minzoom<=1&&y.projection.name==="globe"&&(te.push(new o.aR(1,0,1,0,0)),te.push(new o.aR(1,0,1,1,0)),te.push(new o.aR(1,0,1,0,1)),te.push(new o.aR(1,0,1,1,1)))}else if(te=y.coveringTiles({tileSize:C||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:ue,roundZoom:this._source.roundZoom&&!R,reparseOverscaled:je,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:Z}),this._source.hasTile){const Ue=this._source.hasTile.bind(this._source);te=te.filter(st=>Ue(st))}}else te=[];if(te.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const Ue=y.coveringZoomLevel({tileSize:C||this._source.tileSize,roundZoom:this._source.roundZoom&&!R}),st=Math.min(Ue,ue);if(Z){const Xe=y.extendTileCover(te,st);for(const pt of Xe)te.push(pt)}else if(G){const Xe=this.transform.getFrustum(st),pt=y.extendTileCoverToNearPlane(te,Xe,st);for(const mt of pt)te.push(mt);if(st>=18&&this._hasTunnelGeometry()){const mt=y.extendTileCoverForTunnels(te,Xe,st,20);for(const jt of mt)te.push(jt)}}else if(this.castsShadows&&$){const Xe=y.extendTileCover(te,st,$,16);for(const pt of Xe)this._shadowCasterTiles[pt.key]=!0,te.push(pt)}}const Re=this._updateRetainedTiles(te);if(this._supportsFading&&te.length!==0){const Ue={},st={},Xe=o.o.now(),pt=Object.keys(Re);for(const jt of pt){const Tt=Re[jt],xt=this._tiles[jt];if(!xt||xt.fadeEndTime!==void 0&&xt.fadeEndTime<=Xe)continue;const es=this.findLoadedParent(Tt,Math.max(Tt.overscaledZ-al.maxOverzooming,this._source.minzoom));es&&(this._addTile(es.tileID),Ue[es.tileID.key]=es.tileID),st[jt]=Tt}const mt=te[te.length-1].overscaledZ;for(const jt in this._tiles){const Tt=this._tiles[jt];if(Re[jt]||!Tt.hasData())continue;let xt=Tt.tileID;for(;xt.overscaledZ>mt;){xt=xt.scaledTo(xt.overscaledZ-1);const es=this._tiles[xt.key];if(es&&es.hasData()&&st[xt.key]){Re[jt]=Tt.tileID;break}}}for(const jt in Ue)Re[jt]||(this._coveredTiles[jt]=!0,Re[jt]=Ue[jt])}for(const Ue in Re)this._tiles[Ue].clearFadeHold();const Le=o.b3(this._tiles,Re);for(const Ue of Le){const st=this._tiles[Ue];st.hasSymbolBuckets&&!st.holdingForFade()?st.setHoldDuration(this.map._fadeDuration):st.hasSymbolBuckets&&!st.symbolFadeFinished()||this._removeTile(+Ue)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const y in this._tiles)this._tiles[y].holdingForFade()&&this._removeTile(+y)}_updateRetainedTiles(y){const C={};if(y.length===0)return C;const R={},$=y.reduce((xe,je)=>Math.min(xe,je.overscaledZ),1/0),G=y[0].overscaledZ,Z=Math.max(G-al.maxOverzooming,this._source.minzoom),te=Math.max(G+al.maxUnderzooming,this._source.minzoom),ue={};for(const xe of y){const je=this._addTile(xe);C[xe.key]=xe,je.hasData()||$=this._source.maxzoom){const Le=xe.children(this._source.maxzoom)[0],Ue=this.getTile(Le);if(Ue&&Ue.hasData()){C[Le.key]=Le;continue}}else{const Le=xe.children(this._source.maxzoom);if(C[Le[0].key]&&C[Le[1].key]&&C[Le[2].key]&&C[Le[3].key])continue}let Re=je.wasRequested();for(let Le=xe.overscaledZ-1;Le>=Z;--Le){const Ue=xe.scaledTo(Le);if(R[Ue.key]||(R[Ue.key]=!0,je=this.getTile(Ue),!je&&Re&&(je=this._addTile(Ue)),je&&(C[Ue.key]=Ue,Re=je.wasRequested(),je.hasData())))break}}return C}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const y in this._tiles){const C=[];let R,$=this._tiles[y].tileID;for(;$.overscaledZ>0;){if($.key in this._loadedParentTiles){R=this._loadedParentTiles[$.key];break}C.push($.key);const G=$.scaledTo($.overscaledZ-1);if(R=this._getLoadedTile(G),R)break;$=G}for(const G of C)this._loadedParentTiles[G]=R}}_addTile(y){let C=this._tiles[y.key];if(C)return C.isExtraShadowCaster!==!0||this._shadowCasterTiles[y.key]||this._reloadTile(y.key,"reloading"),C;C=this._cache.getAndRemove(y),C&&(this._setTileReloadTimer(y.key,C),C.tileID=y,this._state.initializeTileState(C,this.map?this.map.painter:null),this._cacheTimers[y.key]&&(clearTimeout(this._cacheTimers[y.key]),delete this._cacheTimers[y.key],this._setTileReloadTimer(y.key,C)));const R=!!C;if(!R){const $=this.map?this.map.painter:null,G=this._source.tileSize*y.overscaleFactor();C=this._source.type==="raster-array"?new $h(y,G,this.transform.tileZoom,$,this._isRaster):new o.b0(y,G,this.transform.tileZoom,$,this._isRaster,this._source.worldview),this._loadTile(C,this._tileLoaded.bind(this,C,y.key,C.state))}return C.uses++,this._tiles[y.key]=C,R||this._source.fire(new o.C("dataloading",{tile:C,coord:C.tileID,dataType:"source"})),C}_setTileReloadTimer(y,C){y in this._timers&&(clearTimeout(this._timers[y]),delete this._timers[y]);const R=C.getExpiryTimeout();R&&(this._timers[y]=setTimeout(()=>{this._reloadTile(y,"expired"),delete this._timers[y]},R))}_removeTile(y){const C=this._tiles[y];C&&(C.uses--,delete this._tiles[y],this._timers[y]&&(clearTimeout(this._timers[y]),delete this._timers[y]),C.uses>0||(C.hasData()&&C.state!=="reloading"||C.state==="empty"?this._cache.add(C.tileID,C,C.getExpiryTimeout()):(C.aborted=!0,this._abortTile(C),this._unloadTile(C))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const y in this._tiles)this._removeTile(+y);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(y,C,R){const $=[],G=this.transform;if(!G)return $;const Z=G.projection.name==="globe",te=o.aH(G.center.lng);for(const ue in this._tiles){const xe=this._tiles[ue];if(R&&xe.clearQueryDebugViz(),xe.holdingForFade())continue;let je;if(Z){const Re=xe.tileID.canonical;if(Re.z===0){const Le=[Math.abs(o.aC(te,...vu(Re,-1))-te),Math.abs(o.aC(te,...vu(Re,1))-te)];je=[0,2*Le.indexOf(Math.min(...Le))-1]}else{const Le=[Math.abs(o.aC(te,...vu(Re,-1))-te),Math.abs(o.aC(te,...vu(Re,0))-te),Math.abs(o.aC(te,...vu(Re,1))-te)];je=[Le.indexOf(Math.min(...Le))-1]}}else je=[0];for(const Re of je){const Le=y.containsTile(xe,G,C,Re);Le&&$.push(Le)}}return $}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(y){return this._getRenderableCoordinates(y)}_getRenderableCoordinates(y,C){const R=this.getRenderableIds(y,C).map(G=>this._tiles[G].tileID),$=this.transform.projection.name==="globe";for(const G of R)G.projMatrix=this.transform.calculateProjMatrix(G.toUnwrapped()),G.expandedProjMatrix=$?this.transform.calculateProjMatrix(G.toUnwrapped(),!1,!0):G.projMatrix;return R}sortCoordinatesByDistance(y){const C=y.slice(),R=this.transform._camera.position,$=this.transform._camera.forward(),G={};for(const Z of C){const te=1/(1<G[Z.key]-G[te.key]),C}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const y=o.o.now();for(const C in this._tiles){const R=this._tiles[C];if(R.fadeEndTime!==void 0&&R.fadeEndTime>=y)return!0}}return!1}setFeatureState(y,C,R){this._state.updateState(y=y||"_geojsonTileLayer",C,R)}removeFeatureState(y,C,R){this._state.removeFeatureState(y=y||"_geojsonTileLayer",C,R)}getFeatureState(y,C){return this._state.getState(y=y||"_geojsonTileLayer",C)}setDependencies(y,C,R){const $=this._tiles[y];$&&$.setDependencies(C,R)}reloadTilesForDependencies(y,C){for(const R in this._tiles)this._tiles[R].hasDependency(y,C)&&this._reloadTile(+R,"reloading");this._cache.filter(R=>!R.hasDependency(y,C))}_preloadTiles(y,C){if(!this._sourceLoaded){const ue=()=>{this._sourceLoaded&&(this._source.off("data",ue),this._preloadTiles(y,C))};return void this._source.on("data",ue)}const R=new Map,$=Array.isArray(y)?y:[y],G=this.map.painter.terrain,Z=this.usedForTerrain&&G?G.getScaledDemTileSize():this._source.tileSize;for(const ue of $){const xe=ue.coveringTiles({tileSize:Z,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const je of xe)R.set(je.key,je);this.usedForTerrain&&ue.updateElevation(!1)}const te=Array.from(R.values());o.t(te,(ue,xe)=>{const je=new o.b0(ue,this._source.tileSize*ue.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(je,Re=>{this._source.type==="raster-dem"&&je.dem&&this._backfillDEM(je),xe(Re,je)})},C)}}function u0(I,y){const C=Math.abs(2*I.wrap)-+(I.wrap<0),R=Math.abs(2*y.wrap)-+(y.wrap<0);return I.overscaledZ-y.overscaledZ||R-C||y.canonical.y-I.canonical.y||y.canonical.x-I.canonical.x}function vu(I,y){const C=1<0:R.type==="building"?$=!R.isHidden(y)&&R.paint.get("building-opacity")>0:R.type==="model"&&($=!R.isHidden(y)&&R.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!$&&C.visible,C.visible=$}}updateZOffset(y,C){this.currentBuildingBuckets=[];for(const $ of this.layers){const G=$.layer,Z=this.style.getLayerSourceCache(G);let te=1;G.type==="fill-extrusion"?te=$.visible?G.paint.get("fill-extrusion-vertical-scale"):0:G.type==="building"&&(te=$.visible?G.paint.get("building-vertical-scale"):0);let ue=Z?Z.getTile(C):null;if(!ue&&Z)for(const xe in Z._tiles){const je=Z._tiles[xe];if(C.canonical.isChildOf(je.tileID.canonical)){ue=je;break}}this.currentBuildingBuckets.push({bucket:ue?ue.getBucket(G):null,tileID:ue?ue.tileID:C,verticalScale:te})}y.hasAnyZOffset=!1;let R=!1;for(let $=0;${R in y&&(C[R]=y[R])}),C}function Af(I){I=I.slice();const y=Object.create(null);for(const C of I)y[C.id]=C;for(let C=0;C0?($-Z)/te:0;return this.points[G].mult(1-ue).add(this.points[C].mult(ue))}}class Ry{constructor(y,C,R){const $=this.boxCells=[],G=this.circleCells=[];this.xCellCount=Math.ceil(y/R),this.yCellCount=Math.ceil(C/R);for(let Z=0;Zthis.width||$<0||C>this.height)return!G&&[];const te=[];if(y<=0&&C<=0&&this.width<=R&&this.height<=$){if(G)return!0;for(let ue=0;ue0:te}_queryCircle(y,C,R,$,G){const Z=y-R,te=y+R,ue=C-R,xe=C+R;if(te<0||Z>this.width||xe<0||ue>this.height)return!$&&[];const je=[];return this._forEachCell(Z,ue,te,xe,this._queryCellCircle,je,{hitTest:$,circle:{x:y,y:C,radius:R},seenUids:{box:{},circle:{}}},G),$?je.length>0:je}query(y,C,R,$,G){return this._query(y,C,R,$,!1,G)}hitTest(y,C,R,$,G){return this._query(y,C,R,$,!0,G)}hitTestCircle(y,C,R,$){return this._queryCircle(y,C,R,!0,$)}_queryCell(y,C,R,$,G,Z,te,ue){const xe=te.seenUids,je=this.boxCells[G];if(je!==null){const Le=this.bboxes;for(const Ue of je)if(!xe.box[Ue]){xe.box[Ue]=!0;const st=4*Ue;if(y<=Le[st+2]&&C<=Le[st+3]&&R>=Le[st+0]&&$>=Le[st+1]&&(!ue||ue(this.boxKeys[Ue]))){if(te.hitTest)return Z.push(!0),!0;Z.push({key:this.boxKeys[Ue],x1:Le[st],y1:Le[st+1],x2:Le[st+2],y2:Le[st+3]})}}}const Re=this.circleCells[G];if(Re!==null){const Le=this.circles;for(const Ue of Re)if(!xe.circle[Ue]){xe.circle[Ue]=!0;const st=3*Ue;if(this._circleAndRectCollide(Le[st],Le[st+1],Le[st+2],y,C,R,$)&&(!ue||ue(this.circleKeys[Ue]))){if(te.hitTest)return Z.push(!0),!0;{const Xe=Le[st],pt=Le[st+1],mt=Le[st+2];Z.push({key:this.circleKeys[Ue],x1:Xe-mt,y1:pt-mt,x2:Xe+mt,y2:pt+mt})}}}}}_queryCellCircle(y,C,R,$,G,Z,te,ue){const xe=te.circle,je=te.seenUids,Re=this.boxCells[G];if(Re!==null){const Ue=this.bboxes;for(const st of Re)if(!je.box[st]){je.box[st]=!0;const Xe=4*st;if(this._circleAndRectCollide(xe.x,xe.y,xe.radius,Ue[Xe+0],Ue[Xe+1],Ue[Xe+2],Ue[Xe+3])&&(!ue||ue(this.boxKeys[st])))return Z.push(!0),!0}}const Le=this.circleCells[G];if(Le!==null){const Ue=this.circles;for(const st of Le)if(!je.circle[st]){je.circle[st]=!0;const Xe=3*st;if(this._circlesCollide(Ue[Xe],Ue[Xe+1],Ue[Xe+2],xe.x,xe.y,xe.radius)&&(!ue||ue(this.circleKeys[st])))return Z.push(!0),!0}}}_forEachCell(y,C,R,$,G,Z,te,ue){const xe=this._convertToXCellCoord(y),je=this._convertToYCellCoord(C),Re=this._convertToXCellCoord(R),Le=this._convertToYCellCoord($);for(let Ue=xe;Ue<=Re;Ue++)for(let st=je;st<=Le;st++)if(G.call(this,y,C,R,$,this.xCellCount*st+Ue,Z,te,ue))return}_convertToXCellCoord(y){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(y*this.xScale)))}_convertToYCellCoord(y){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(y*this.yScale)))}_circlesCollide(y,C,R,$,G,Z){const te=$-y,ue=G-C,xe=R+Z;return xe*xe>te*te+ue*ue}_circleAndRectCollide(y,C,R,$,G,Z,te){const ue=(Z-$)/2,xe=Math.abs(y-($+ue));if(xe>ue+R)return!1;const je=(te-G)/2,Re=Math.abs(C-(G+je));if(Re>je+R)return!1;if(xe<=ue||Re<=je)return!0;const Le=xe-ue,Ue=Re-je;return Le*Le+Ue*Ue<=R*R}}const Gb=Math.tan(85*Math.PI/180);function Td(I,y,C,R,$,G,Z){const te=o.bb();if(C)if(G.name==="globe"){const ue=o.bc($,y);o.aD(te,te,ue)}else{const ue=o.bd([],Z);te[0]=ue[0],te[1]=ue[1],te[4]=ue[2],te[5]=ue[3],R||o.ba(te,te,$.angle)}else o.aD(te,$.labelPlaneMatrix,I);return te}function Bc(I,y,C,R,$,G,Z){const te=Td(I,y,C,R,$,G,Z);return G.name==="globe"&&C||(te[2]=te[6]=te[10]=te[14]=0),te}function sp(I,y,C,R,$,G,Z){if(C){if(G.name==="globe"){const te=Td(I,y,C,R,$,G,Z);return o.b7(te,te),o.aD(te,I,te),te}{const te=o.b8(I),ue=o.b9([]);return ue[0]=Z[0],ue[1]=Z[1],ue[4]=Z[2],ue[5]=Z[3],o.aD(te,te,ue),R||o.ba(te,te,-$.angle),te}}return $.glCoordMatrix}function Zc(I,y,C,R){const $=[I,y,C,1];C?o.aE($,$,R):Br($,$,R);const G=$[3];return $[0]/=G,$[1]/=G,$[2]/=G,$}function np(I,y){return Math.min(.5+I/y*.5,1.5)}function Op(I,y){const C=I[0]/I[3],R=I[1]/I[3];return C>=-y[0]&&C<=y[0]&&R>=-y[1]&&R<=y[1]}function Lt(I,y,C,R,$,G,Z,te,ue,xe,je=1){const Re=C.transform,Le=R?I.textSizeData:I.iconSizeData,Ue=o.bj(Le,C.transform.zoom,je),st=Re.projection.name==="globe",Xe=[256/C.width*2+1,256/C.height*2+1],pt=R?I.text.dynamicLayoutVertexArray:I.icon.dynamicLayoutVertexArray;pt.clear();let mt=null;st&&(mt=R?I.text.globeExtVertexArray:I.icon.globeExtVertexArray);const jt=I.lineVertexArray,Tt=R?I.text.placedSymbolArray:I.icon.placedSymbolArray,xt=C.transform.width/C.transform.height;let es,Ft=!1;for(let Jt=0;JtMath.abs(C)?{useVertical:!0}:I===o.bk.vertical?R>0?{needsFlipping:!0}:null:y!==0&&function($,G){return $===0||Math.abs(G/$)>Gb}(C,R)?y===1?{needsFlipping:!0}:null:C<0?{needsFlipping:!0}:null}function Or(I,y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue,st,Xe,pt,mt,jt,Tt){const xt=y/24,es=I.lineOffsetX*xt,Ft=I.lineOffsetY*xt,{lineStartIndex:Jt,glyphStartIndex:At,numGlyphs:Rt,segment:Wt,writingMode:ys,flipState:rs}=I,zs=Jt+I.lineLength,Is=an=>{if(je){const[Rs,qs,Qs]=an.up,Dn=xe.length;o.bm(je,Dn+0,Rs,qs,Qs),o.bm(je,Dn+1,Rs,qs,Qs),o.bm(je,Dn+2,Rs,qs,Qs),o.bm(je,Dn+3,Rs,qs,Qs)}const[mn,js,ms]=an.point;o.bn(xe,mn,js,ms,an.angle)};if(Rt>1){const an=hn(xt,te,es,Ft,C,Re,Le,I,ue,G,Ue,Xe,!1,pt,mt,jt,Tt);if(!an)return{notEnoughRoom:!0};if(R&&!C){let[mn,js,ms]=an.first.point,[Rs,qs,Qs]=an.last.point;[mn,js]=Zc(mn,js,ms,Z),[Rs,qs]=Zc(Rs,qs,Qs,Z);const Dn=zn(ys,rs,(Rs-mn)*st,qs-js);if(I.flipState=Dn&&Dn.needsFlipping?1:2,Dn)return Dn}Is(an.first);for(let mn=At+1;mn0?Rs:va(Le,ms,mn,1,$,void 0,pt,mt.canonical),Qs=zn(ys,rs,(qs[0]-mn[0])*st,qs[1]-mn[1]);if(I.flipState=Qs&&Qs.needsFlipping?1:2,Qs)return Qs}const an=Ja(xt*te.getoffsetX(At),es,Ft,C,Re,Le,Wt,Jt,zs,ue,G,Ue,Xe,!1,!1,pt,mt,jt,Tt);if(!an)return{notEnoughRoom:!0};Is(an)}return{}}function Wn(I,y,C,R,$){const{x:G,y:Z,z:te}=R.projectTilePoint(I.x,I.y,y);if(!$)return Zc(G,Z,te,C);const[ue,xe,je]=$.getElevation(I,$.elevation,$.elevationFeature);return Zc(G+ue,Z+xe,te+je,C)}function va(I,y,C,R,$,G,Z,te){const ue=Wn(I.sub(y)._unit()._add(I),te,$,Z,G);return o.ax(ue,C,ue),o.ay(ue,ue),o.bg(ue,C,ue,R)}function Ja(I,y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue,st,Xe,pt,mt,jt){const Tt=R?I-y:I+y;let xt=Tt>0?1:-1,es=0;R&&(xt*=-1,es=Math.PI),xt<0&&(es+=Math.PI);let Ft=te+Z+(xt>0?0:1)|0,Jt=$,At=$,Rt=0,Wt=0;const ys=Math.abs(Tt),rs=[],zs=[];let Is=G,an=Is,mn=o.be([]);const js=()=>va(an,Is,At,ys-Rt+1,je,Le,Xe,pt.canonical);for(;Rt+Wt<=ys;){if(Ft+=xt,Ft=ue)return null;if(At=Jt,an=Is,rs.push(At),Ue&&zs.push(an),Is=new o.P(xe.getx(Ft),xe.gety(Ft)),Jt=Re[Ft],!Jt){const Er=Wn(Is,pt.canonical,je,Xe,Le);Jt=Er[3]>0?Re[Ft]=Er:js()}Rt+=Wt;const dn=o.ax([],Jt,At),mr=o.bf(At,Jt);if(C&&mr>0&&Wt>0&&o.bi(mn,dn)/(Wt*mr)0,Tt),Jt=xe*Ft.perspectiveRatio,At=(R.x1*C+te.x-R.padding)*Jt+Ft.point.x,Rt=(R.y1*C+te.y-R.padding)*Jt+Ft.point.y,Wt=(R.x2*C+te.x+R.padding)*Jt+Ft.point.x,ys=(R.y2*C+te.y+R.padding)*Jt+Ft.point.y,rs=Ft.perspectiveRatio<=.55||Ft.occluded;return!this.isInsideGrid(At,Rt,Wt,ys)||!ue&&this.grid.hitTest(At,Rt,Wt,ys,Re)||rs?{box:[],offscreen:!1,occluded:Ft.occluded}:{box:[At,Rt,Wt,ys],offscreen:this.isOffscreen(At,Rt,Wt,ys),occluded:!1}}placeCollisionCircles(y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue,st,Xe,pt){const mt=[],jt=this.transform.elevation,Tt=y.getProjection(),xt=y.elevationType==="road",es=!!jt||xt,Ft=o.bu.getAtTileOffsetFunc(pt,this.transform.center.lat,this.transform.worldSize,Tt),Jt=new o.P(R.tileAnchorX,R.tileAnchorY),At=new o.P(R.tileAnchorX,R.tileAnchorY);let{x:Rt,y:Wt,z:ys}=Tt.projectTilePoint(At.x,At.y,pt.canonical),rs=null;if(es){const mr=xt?y.getElevationFeatureForText($):null;rs={getElevation:Ft,elevation:jt,elevationFeature:mr};const[Er,ar,hr]=Ft(Jt,jt,mr);Rt+=Er,Wt+=ar,ys+=hr}const zs=Tt.name==="globe",Is=this.projectAndGetPerspectiveRatio(ue,Rt,Wt,ys,pt,zs||!!jt||this.transform.pitch>0,Tt),{perspectiveRatio:an}=Is,mn=(Le?te/an:te*an)/o.by,js=Zc(Rt,Wt,ys,xe),ms=R.lineOffsetX*mn,Rs=R.lineOffsetY*mn,qs=o.ap(y.layers[0].layout.get("text-max-angle")),Qs=Math.cos(qs),Dn=Is.signedDistanceFromCamera>0?hn(mn,Z,ms,Rs,xt&&R.flipState===1,js,At,R,G,xe,{},es&&!Le?rs:null,Le&&es,Tt,pt,Le,Qs):null;let Cn=!1,Tn=!1,dn=!0;if(Dn&&!Is.occluded){const mr=.5*st*an+Xe,Er=new o.P(-100,-100),ar=new o.P(this.screenRightBoundary,this.screenBottomBoundary),hr=new Mf,{first:ra,last:Na}=Dn,ba=ra.path.length;let Ka=[];for(let _a=ba-1;_a>=1;_a--)Ka.push(ra.path[_a]);for(let _a=1;_a(es&&!zs&&(bo=Ft(bl_a[3]<=0)&&(Ka=[]));let Ya=[];if(Ka.length>0){let _a=1/0,Pi=-1/0,bo=1/0,bl=-1/0;for(const Lo of Ka)_a=Math.min(_a,Lo[0]),bo=Math.min(bo,Lo[1]),Pi=Math.max(Pi,Lo[0]),bl=Math.max(bl,Lo[1]);Pi>=Er.x&&_a<=ar.x&&bl>=Er.y&&bo<=ar.y&&(Ya=[Ka.map(Lo=>new o.P(Lo[0],Lo[1]))],(_aar.x||boar.y)&&(Ya=o.bv(Ya,Er.x,Er.y,ar.x,ar.y)))}for(const _a of Ya){hr.reset(_a,.25*mr);let Pi=0;Pi=hr.length<=.5*mr?1:Math.ceil(hr.paddedLength/Kr)+1;for(let bo=0;bo0?(o.aE(ue,ue,y),this.fogState&&G&&te.name!=="globe"&&(xe=function(Le,Ue,st,Xe,pt,mt){const jt=mt.calculateFogTileMatrix(pt),Tt=[Ue,st,Xe];return o.ah(Tt,Tt,jt),kr(Le,o.ai(Tt),mt.pitch,mt._fov)}(this.fogState,C,R,$,G.toUnwrapped(),this.transform)>.9)):Br(ue,ue,y);const je=ue[3];return{point:new o.P((ue[0]/je+1)/2*this.transform.width+Ed,(-ue[1]/je+1)/2*this.transform.height+Ed),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(te)/je*.5,1.5),signedDistanceFromCamera:je,occluded:Z&&ue[2]>je||xe}}isOffscreen(y,C,R,$){return R=this.screenRightBoundary||$this.screenBottomBoundary}isInsideGrid(y,C,R,$){return R>=0&&y=0&&CR.collisionGroupID===C}}return this.collisionGroups[y]}}function Uh(I,y,C,R,$){const{horizontalAlign:G,verticalAlign:Z}=o.bF(I),te=-(G-.5)*y,ue=-(Z-.5)*C,xe=o.bG(I,R);return new o.P(te+xe[0]*$,ue+xe[1]*$)}function gx(I,y,C,R,$){const G=new o.P(I,y);return C&&G._rotate(R?$:-$),G}class to{constructor(y,C,R,$,G,Z){this.transform=y.clone(),this.projection=y.projection.name,this.collisionIndex=new ym(this.transform,G),this.buildingIndex=Z,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=C,this.retainedQueryData={},this.collisionGroups=new Zi(R),this.collisionCircleArrays={},this.prevPlacement=$,$&&($.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(y,C,R,$,G=1){const Z=R.getBucket(C),te=R.latestFeatureIndex;if(!Z||!te||C.fqid!==Z.layerIds[0])return;const ue=Z.layers[0].layout,xe=Z.layers[0].paint,je=R.collisionBoxArray,Re=Math.pow(2,this.transform.zoom-R.tileID.overscaledZ),Le=R.tileSize/o.an,Ue=R.tileID.toUnwrapped();this.transform.setProjection(Z.projection);const st=(Xe=R.tileID,pt=Z.getProjection(),mt=this.transform,pt.name===this.projection?mt.calculateProjMatrix(Xe.toUnwrapped()):Hb(mt,pt,Xe));var Xe,pt,mt;const jt=ue.get("text-pitch-alignment")==="map",Tt=ue.get("text-rotation-alignment")==="map";C.compileFilter(C.options);const xt=C.dynamicFilter(),es=C.dynamicFilterNeedsFeature(),Ft=C.dynamicFilterNeedsGeometry(),Jt=this.transform.calculatePixelsToTileUnitsMatrix(R),At=Bc(st,R.tileID.canonical,jt,Tt,this.transform,Z.getProjection(),Jt);let Rt=null;const Wt=Z.getProjection().createInversionMatrix(this.transform,R.tileID.canonical);if(jt){const Rs=sp(st,R.tileID.canonical,jt,Tt,this.transform,Z.getProjection(),Jt);Rt=o.aD([],this.transform.labelPlaneMatrix,Rs)}let ys=null;xt&&R.latestFeatureIndex&&(ys={unwrappedTileID:Ue,dynamicFilter:xt,dynamicFilterNeedsFeature:es,needGeometry:Ft}),this.retainedQueryData[Z.bucketInstanceId]=new Ii(Z.bucketInstanceId,te,Z.sourceLayerIndex,Z.index,R.tileID);const[rs,zs]=Z.layers[0].layout.get("text-size-scale-range"),Is=o.aC(G,rs,zs),[an,mn]=ue.get("icon-size-scale-range"),js=o.aC(G,an,mn),ms={bucket:Z,layout:ue,paint:xe,posMatrix:st,invMatrix:Wt,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:At,labelToScreenMatrix:Rt,clippingData:ys,scale:Re,textPixelRatio:Le,holdingForFade:R.holdingForFade(),collisionBoxArray:je,partiallyEvaluatedTextSize:o.bj(Z.textSizeData,this.transform.zoom,Is),partiallyEvaluatedIconSize:o.bj(Z.iconSizeData,this.transform.zoom,js),collisionGroup:this.collisionGroups.get(Z.sourceID),latestFeatureIndex:R.latestFeatureIndex};if($)for(const Rs of Z.sortKeyRanges){const{sortKey:qs,symbolInstanceStart:Qs,symbolInstanceEnd:Dn}=Rs;y.push({sortKey:qs,symbolInstanceStart:Qs,symbolInstanceEnd:Dn,parameters:ms})}else y.push({symbolInstanceStart:0,symbolInstanceEnd:Z.symbolInstances.length,parameters:ms})}attemptAnchorPlacement(y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue,st,Xe,pt,mt,jt,Tt,xt,es){const{textOffset0:Ft,textOffset1:Jt,crossTileID:At}=Xe,Rt=[Ft,Jt],Wt=Uh(y,Z,te,Rt,ue),ys=this.collisionIndex.placeCollisionBox(mt,ue,C,R,$,G,gx(Wt.x,Wt.y,xe,je,this.transform.angle),st,Re,Le,Ue.predicate);if(Tt){const rs=mt.getSymbolInstanceIconSize(es,this.transform.zoom,Xe.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(mt,rs,Tt,R,$,G,gx(Wt.x,Wt.y,xe,je,this.transform.angle),st,Re,Le,Ue.predicate).box.length===0)return}if(ys.box.length>0){let rs;return this.prevPlacement&&this.prevPlacement.variableOffsets[At]&&this.prevPlacement.placements[At]&&this.prevPlacement.placements[At].text&&(rs=this.prevPlacement.variableOffsets[At].anchor),this.variableOffsets[At]={textOffset:Rt,width:Z,height:te,anchor:y,textScale:ue,prevAnchor:rs},this.markUsedJustification(mt,y,Xe,jt),mt.allowVerticalPlacement&&(this.markUsedOrientation(mt,jt,Xe),this.placedOrientations[At]=jt),{shift:Wt,placedGlyphBoxes:ys}}}placeLayerBucketPart(y,C,R,$,G=1){const{bucket:Z,layout:te,paint:ue,posMatrix:xe,textLabelPlaneMatrix:je,labelToScreenMatrix:Re,clippingData:Le,textPixelRatio:Ue,mercatorCenter:st,invMatrix:Xe,holdingForFade:pt,collisionBoxArray:mt,partiallyEvaluatedTextSize:jt,partiallyEvaluatedIconSize:Tt,collisionGroup:xt,latestFeatureIndex:es}=y.parameters,Ft=te.get("text-optional"),Jt=te.get("icon-optional"),At=te.get("text-allow-overlap"),Rt=te.get("icon-allow-overlap"),Wt=te.get("text-rotation-alignment")==="map",ys=te.get("icon-rotation-alignment")==="map",rs=te.get("text-pitch-alignment")==="map",zs=ue.get("symbol-z-offset"),Is=te.get("symbol-elevation-reference")==="sea",an=te.get("symbol-placement"),[mn,js]=te.get("text-size-scale-range"),[ms,Rs]=te.get("icon-size-scale-range"),qs=o.aC(G,mn,js),Qs=o.aC(G,ms,Rs),Dn=te.get("text-variable-anchor"),Cn=Wt&&an!=="point",Tn=ys&&an!=="point",dn=Dn&&Z.hasTextData(),mr=Z.hasIconTextFit()&&dn&&Z.hasIconData();this.transform.setProjection(Z.projection);const Er=dn||Cn,ar=Tn||mr;let hr=At&&(Rt||!Z.hasIconData()||Jt),ra=Rt&&(At||!Z.hasTextData()||Ft);const Na=!zs.isConstant();!Z.collisionArrays&&mt&&Z.deserializeCollisionBoxes(mt),R&&$&&Z.updateCollisionDebugBuffers(this.transform.zoom,mt,qs,Qs);const ba=(Kr,Ya,_a)=>{const{crossTileID:Pi,numVerticalGlyphVertices:bo}=Kr;let bl=null;if(Le&&Le.dynamicFilterNeedsFeature||Na){const $o=this.retainedQueryData[Z.bucketInstanceId],Qo=es.loadFeature({featureIndex:Kr.featureIndex,bucketIndex:$o.bucketIndex,sourceLayerIndex:$o.sourceLayerIndex,layoutVertexArrayOffset:0}),co=Qo.properties?Qo.properties.worldview:null;if(Z.localizable&&Z.worldview&&typeof co=="string")if(co==="all")Qo.properties.$localized=!0;else{if(!co.split(",").includes(Z.worldview))return;Qo.properties.$localized=!0,Qo.properties.worldview=Z.worldview}bl=Le&&Le.needGeometry?o.bD(Qo,!0):Qo}if(Le&&!(0,Le.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:Z.worldview},bl,this.retainedQueryData[Z.bucketInstanceId].tileID.canonical,new o.P(Kr.tileAnchorX,Kr.tileAnchorY),this.transform.calculateDistanceTileData(Le.unwrappedTileID)))return this.placements[Pi]=new If(!1,!1,!1,!0),void C.add(Pi);const Lo=zs.evaluate(bl,{});if((Kr.zOffset||0)+(Lo||0)>0&&this.frontCutoffStart>0){const $o=2*this.frontCutoffStart-1,Qo=[Kr.tileAnchorX,Kr.tileAnchorY,0,1],co=o.aE(o.bE(),Qo,xe);if(co[1]/co[3]<$o)return this.placements[Pi]=new If(!1,!1,!1,!0),void C.add(Pi)}if(C.has(Pi))return;if(pt)return void(this.placements[Pi]=new If(!1,!1,!1));let Vi=!1,Ba=!1,$a=!0,Do=!1,kl=!1,Hi=null,Ea={box:null,offscreen:null,occluded:null},ul={box:null},_o=null,Sc=null,li=null,ko=0,Xc=0,kh=0;_a.textFeatureIndex?ko=_a.textFeatureIndex:Kr.useRuntimeCollisionCircles&&(ko=Kr.featureIndex),_a.verticalTextFeatureIndex&&(Xc=_a.verticalTextFeatureIndex);const hd=Z.elevationFeatures?Z.elevationFeatures[Kr.elevationFeatureIndex]:void 0,_u=$o=>{$o.tileID=this.retainedQueryData[Z.bucketInstanceId].tileID;const Qo=this.transform.elevation;$o.elevation=Is?Lo:Lo+o.bu.getAtTileOffset($o.tileID,new o.P($o.tileAnchorX,$o.tileAnchorY),Qo,hd),$o.elevation+=Kr.zOffset},$f=_a.textBox;if($f){_u($f);const $o=co=>{let mc=o.bk.horizontal;if(Z.allowVerticalPlacement&&!co&&this.prevPlacement){const Kh=this.prevPlacement.placedOrientations[Pi];Kh&&(this.placedOrientations[Pi]=Kh,mc=Kh,this.markUsedOrientation(Z,mc,Kr))}return mc},Qo=(co,mc)=>{if(Z.allowVerticalPlacement&&bo>0&&_a.verticalTextBox){for(const Kh of Z.writingModes)if(Kh===o.bk.vertical?(Ea=mc(),ul=Ea):Ea=co(),Ea&&Ea.box&&Ea.box.length)break}else Ea=co()};if(Dn){let co=Dn;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Pi]){const Fl=this.prevPlacement.variableOffsets[Pi];co.indexOf(Fl.anchor)>0&&(co=co.filter(Uf=>Uf!==Fl.anchor),co.unshift(Fl.anchor))}const mc=(Fl,Uf,g_)=>{const Wj=Z.getSymbolInstanceTextSize(jt,Kr,this.transform.zoom,Ya),Kj=(Fl.x2-Fl.x1)*Wj+2*Fl.padding,ck=(Fl.y2-Fl.y1)*Wj+2*Fl.padding,E1=Kr.hasIconTextFit&&!Rt?Uf:null;E1&&_u(E1);let Jy={box:[],offscreen:!1,occluded:!1};const dk=At?2*co.length:co.length;for(let Yp=0;Yp=co.length,Kr,Ya,Z,g_,E1,jt,Tt);if(y_&&(Jy=y_.placedGlyphBoxes,Jy&&Jy.box&&Jy.box.length)){Vi=!0,Hi=y_.shift;break}}return Jy};Qo(()=>mc($f,_a.iconBox,o.bk.horizontal),()=>{const Fl=_a.verticalTextBox;return Fl&&_u(Fl),Z.allowVerticalPlacement&&!(Ea&&Ea.box&&Ea.box.length)&&bo>0&&Fl?mc(Fl,_a.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),Ea&&(Vi=Ea.box,$a=Ea.offscreen,Do=Ea.occluded);const Kh=$o(!(!Ea||!Ea.box));if(!Vi&&this.prevPlacement){const Fl=this.prevPlacement.variableOffsets[Pi];Fl&&(this.variableOffsets[Pi]=Fl,this.markUsedJustification(Z,Fl.anchor,Kr,Kh))}}else{const co=(mc,Kh)=>{const Fl=Z.getSymbolInstanceTextSize(jt,Kr,this.transform.zoom,Ya),Uf=this.collisionIndex.placeCollisionBox(Z,Fl,mc,st,Xe,Er,new o.P(0,0),At,Ue,xe,xt.predicate);return Uf&&Uf.box&&Uf.box.length&&(this.markUsedOrientation(Z,Kh,Kr),this.placedOrientations[Pi]=Kh),Uf};Qo(()=>co($f,o.bk.horizontal),()=>{const mc=_a.verticalTextBox;return Z.allowVerticalPlacement&&bo>0&&mc?(_u(mc),co(mc,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),$o(!!(Ea&&Ea.box&&Ea.box.length))}}if(_o=Ea,Vi=_o&&_o.box&&_o.box.length>0,$a=_o&&_o.offscreen,Do=_o&&_o.occluded,Kr.useRuntimeCollisionCircles){const $o=Kr.centerJustifiedTextSymbolIndex>=0?Kr.centerJustifiedTextSymbolIndex:Kr.verticalPlacedTextSymbolIndex,Qo=Z.text.placedSymbolArray.get($o),co=o.bl(Z.textSizeData,jt,Qo),mc=te.get("text-padding");Sc=this.collisionIndex.placeCollisionCircles(Z,At,Qo,$o,Z.lineVertexArray,Z.glyphOffsetArray,co,xe,je,Re,R,rs,xt.predicate,Kr.collisionCircleDiameter*co/o.by,mc,this.retainedQueryData[Z.bucketInstanceId].tileID),Vi=At||Sc.circles.length>0&&!Sc.collisionDetected,$a=$a&&Sc.offscreen,Do=Sc.occluded}if(_a.iconFeatureIndex&&(kh=_a.iconFeatureIndex),_a.iconBox){const $o=Qo=>{_u(Qo);const co=Kr.hasIconTextFit&&Hi?gx(Hi.x,Hi.y,Wt,rs,this.transform.angle):new o.P(0,0),mc=Z.getSymbolInstanceIconSize(Tt,this.transform.zoom,Kr.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(Z,mc,Qo,st,Xe,ar,co,Rt,Ue,xe,xt.predicate)};ul&&ul.box&&ul.box.length&&_a.verticalIconBox?(li=$o(_a.verticalIconBox),Ba=li.box.length>0):(li=$o(_a.iconBox),Ba=li.box.length>0),$a=$a&&li.offscreen,kl=li.occluded}const so=Ft||Kr.numHorizontalGlyphVertices===0&&bo===0,Tx=Jt||Kr.numIconVertices===0;if(so||Tx?Tx?so||(Ba=Ba&&Vi):Vi=Ba&&Vi:Ba=Vi=Ba&&Vi,Vi&&_o&&_o.box&&this.collisionIndex.insertCollisionBox(_o.box,te.get("text-ignore-placement"),Z.bucketInstanceId,ul&&ul.box&&Xc?Xc:ko,xt.ID),Ba&&li&&this.collisionIndex.insertCollisionBox(li.box,te.get("icon-ignore-placement"),Z.bucketInstanceId,kh,xt.ID),Sc&&(Vi&&this.collisionIndex.insertCollisionCircles(Sc.circles,te.get("text-ignore-placement"),Z.bucketInstanceId,ko,xt.ID),R)){const $o=Z.bucketInstanceId;let Qo=this.collisionCircleArrays[$o];Qo===void 0&&(Qo=this.collisionCircleArrays[$o]=new Mr);for(let co=0;co=0;--Ya){const _a=Kr[Ya];ba(Z.symbolInstances.get(_a),_a,Z.collisionArrays[_a])}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 Kr=Z.getSortedIndexesByZOffset();for(let Ya=0;Ya=0&&(y.text.placedSymbolArray.get(G).crossTileID=Re>=0&&G!==Re?0:xe),Z>=0&&(y.text.placedSymbolArray.get(Z).crossTileID=Re>=0&&Z!==Re?0:xe),te>=0&&(y.text.placedSymbolArray.get(te).crossTileID=Re>=0&&te!==Re?0:xe),ue>=0&&(y.text.placedSymbolArray.get(ue).crossTileID=Re>=0&&ue!==Re?0:xe)}markUsedOrientation(y,C,R){const $=C===o.bk.horizontal||C===o.bk.horizontalOnly?C:0,G=C===o.bk.vertical?C:0,{leftJustifiedTextSymbolIndex:Z,centerJustifiedTextSymbolIndex:te,rightJustifiedTextSymbolIndex:ue,verticalPlacedTextSymbolIndex:xe}=R,je=y.text.placedSymbolArray;Z>=0&&(je.get(Z).placedOrientation=$),te>=0&&(je.get(te).placedOrientation=$),ue>=0&&(je.get(ue).placedOrientation=$),xe>=0&&(je.get(xe).placedOrientation=G)}commit(y){this.commitTime=y,this.zoomAtLastRecencyCheck=this.transform.zoom;const C=this.prevPlacement;let R=!1;this.prevZoomAdjustment=C?C.zoomAdjustment(this.transform.zoom):0;const $=C?C.symbolFadeChange(y):1,G=C?C.opacities:{},Z=C?C.variableOffsets:{},te=C?C.placedOrientations:{};for(const ue in this.placements){const xe=this.placements[ue],je=G[ue];je?(this.opacities[ue]=new mg(je,$,xe.text,xe.icon,null,xe.clipped),R=R||xe.text!==je.text.placed||xe.icon!==je.icon.placed):(this.opacities[ue]=new mg(null,$,xe.text,xe.icon,xe.skipFade,xe.clipped),R=R||xe.text||xe.icon)}for(const ue in G){const xe=G[ue];if(!this.opacities[ue]){const je=new mg(xe,$,!1,!1);je.isHidden()||(this.opacities[ue]=je,R=R||xe.text.placed||xe.icon.placed)}}for(const ue in Z)this.variableOffsets[ue]||!this.opacities[ue]||this.opacities[ue].isHidden()||(this.variableOffsets[ue]=Z[ue]);for(const ue in te)this.placedOrientations[ue]||!this.opacities[ue]||this.opacities[ue].isHidden()||(this.placedOrientations[ue]=te[ue]);R?this.lastPlacementChangeTime=y:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=C?C.lastPlacementChangeTime:y)}updateLayerOpacities(y,C,R,$){$&&(this.lastReplacementSourceUpdateTime=$.updateTime);const G=new Set;for(const Z of C){const te=Z.getBucket(y);te&&Z.latestFeatureIndex&&y.fqid===te.layerIds[0]&&(this.updateBucketOpacities(te,G,Z,Z.collisionBoxArray,R,$,Z.tileID,y.scope),te.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(te,Z.tileID),te.elevationType==="road"&&te.updateRoadElevation(Z.tileID.canonical),te.updateZOffset())}}updateBucketOpacities(y,C,R,$,G,Z,te,ue){y.hasTextData()&&y.text.opacityVertexArray.clear(),y.hasIconData()&&y.icon.opacityVertexArray.clear(),y.hasIconCollisionBoxData()&&y.iconCollisionBox.collisionVertexArray.clear(),y.hasTextCollisionBoxData()&&y.textCollisionBox.collisionVertexArray.clear();const xe=y.layers[0].layout,je=y.layers[0].paint,Re=!!y.layers[0].dynamicFilter(),Le=new mg(null,0,!1,!1,!0),Ue=xe.get("text-allow-overlap"),st=xe.get("icon-allow-overlap"),Xe=xe.get("text-variable-anchor"),pt=xe.get("text-rotation-alignment")==="map",mt=xe.get("text-pitch-alignment")==="map",jt=je.get("symbol-z-offset"),Tt=xe.get("symbol-elevation-reference")==="sea",xt=!jt.isConstant(),es=new mg(null,0,Ue&&(st||!y.hasIconData()||xe.get("icon-optional")),st&&(Ue||!y.hasTextData()||xe.get("text-optional")),!0);!y.collisionArrays&&$&&(y.hasIconCollisionBoxData()||y.hasTextCollisionBoxData())&&y.deserializeCollisionBoxes($);const Ft=(At,Rt,Wt)=>{for(let ys=0;ys0||ys>0,Dn=zs>0,Cn=this.placedOrientations[rs],Tn=Cn===o.bk.vertical,dn=Cn===o.bk.horizontal||Cn===o.bk.horizontalOnly;!Qs&&!Dn||qs.isHidden()||Jt++;let mr=!1;if((Qs||Dn)&&Z)for(const Er of y.activeReplacements){if(o.bz(Er,G,o.bA.Symbol,ue)||Er.min.x>Is||Is>Er.max.x||Er.min.y>an||an>Er.max.y)continue;const ar=o.bB(Is,an,te.canonical,Er.footprintTileId.canonical);if(mr=o.bC(ar,Er.footprint),mr)break}if(mr&&this.collisionIndex.markSymbolAsClipped(y.bucketInstanceId,Rt.featureIndex),Qs){const Er=mr?bx:vx(qs.text);Ft(y.text,Wt,Tn?bx:Er),Ft(y.text,ys,dn?bx:Er);const ar=qs.text.isHidden(),{leftJustifiedTextSymbolIndex:hr,centerJustifiedTextSymbolIndex:ra,rightJustifiedTextSymbolIndex:Na,verticalPlacedTextSymbolIndex:ba}=Rt,Ka=y.text.placedSymbolArray,Kr=ar||Tn?1:0;hr>=0&&(Ka.get(hr).hidden=Kr),ra>=0&&(Ka.get(ra).hidden=Kr),Na>=0&&(Ka.get(Na).hidden=Kr),ba>=0&&(Ka.get(ba).hidden=ar||dn?1:0);const Ya=this.variableOffsets[rs];Ya&&this.markUsedJustification(y,Ya.anchor,Rt,Cn);const _a=this.placedOrientations[rs];_a&&(this.markUsedJustification(y,"left",Rt,_a),this.markUsedOrientation(y,_a,Rt))}if(Dn){const Er=mr?bx:vx(qs.icon),{placedIconSymbolIndex:ar,verticalPlacedIconSymbolIndex:hr}=Rt,ra=y.icon.placedSymbolArray,Na=qs.icon.isHidden()?1:0;ar>=0&&(Ft(y.icon,zs,Tn?bx:Er),ra.get(ar).hidden=Na),hr>=0&&(Ft(y.icon,Rt.numVerticalIconVertices,dn?bx:Er),ra.get(hr).hidden=Na)}if(y.hasIconCollisionBoxData()||y.hasTextCollisionBoxData()){const Er=y.collisionArrays[At];if(Er){let ar=new o.P(0,0),hr=!0;if(Er.textBox||Er.verticalTextBox){if(Xe){const Na=this.variableOffsets[rs];Na?(ar=Uh(Na.anchor,Na.width,Na.height,Na.textOffset,Na.textScale),pt&&ar._rotate(mt?this.transform.angle:-this.transform.angle)):hr=!1}Re&&(hr=!qs.clipped),Er.textBox&&yx(y.textCollisionBox.collisionVertexArray,qs.text.placed,!hr||Tn,ms,Tt,ar.x,ar.y),Er.verticalTextBox&&yx(y.textCollisionBox.collisionVertexArray,qs.text.placed,!hr||dn,ms,Tt,ar.x,ar.y)}const ra=hr&&!!(!dn&&Er.verticalIconBox);Er.iconBox&&yx(y.iconCollisionBox.collisionVertexArray,qs.icon.placed,ra,ms,Tt,Rt.hasIconTextFit?ar.x:0,Rt.hasIconTextFit?ar.y:0),Er.verticalIconBox&&yx(y.iconCollisionBox.collisionVertexArray,qs.icon.placed,!ra,ms,Tt,Rt.hasIconTextFit?ar.x:0,Rt.hasIconTextFit?ar.y:0)}}}if(y.fullyClipped=Jt===0,y.sortFeatures(this.transform.angle),this.retainedQueryData[y.bucketInstanceId]&&(this.retainedQueryData[y.bucketInstanceId].featureSortOrder=y.featureSortOrder),y.hasTextData()&&y.text.opacityVertexBuffer&&y.text.opacityVertexBuffer.updateData(y.text.opacityVertexArray),y.hasIconData()&&y.icon.opacityVertexBuffer&&y.icon.opacityVertexBuffer.updateData(y.icon.opacityVertexArray),y.hasIconCollisionBoxData()&&y.iconCollisionBox.collisionVertexBuffer&&y.iconCollisionBox.collisionVertexBuffer.updateData(y.iconCollisionBox.collisionVertexArray),y.hasTextCollisionBoxData()&&y.textCollisionBox.collisionVertexBuffer&&y.textCollisionBox.collisionVertexBuffer.updateData(y.textCollisionBox.collisionVertexArray),y.bucketInstanceId in this.collisionCircleArrays){const At=this.collisionCircleArrays[y.bucketInstanceId];y.placementInvProjMatrix=At.invProjMatrix,y.placementViewportMatrix=At.viewportMatrix,y.collisionCircleArray=At.circles,delete this.collisionCircleArrays[y.bucketInstanceId]}}symbolFadeChange(y){return this.fadeDuration===0?1:(y-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(y){return Math.max(0,(this.transform.zoom-y)/1.5)}hasTransitions(y){return y-this.lastPlacementChangeTimey}isStale(){return this.stale}setStale(){this.stale=!0}}function yx(I,y,C,R,$,G,Z){I.emplaceBack(y?1:0,C?1:0,G||0,Z||0,R,$?1:0),I.emplaceBack(y?1:0,C?1:0,G||0,Z||0,R,$?1:0),I.emplaceBack(y?1:0,C?1:0,G||0,Z||0,R,$?1:0),I.emplaceBack(y?1:0,C?1:0,G||0,Z||0,R,$?1:0)}const Oy=Math.pow(2,25),Wb=Math.pow(2,24),Qu=Math.pow(2,17),Ol=Math.pow(2,16),x6=Math.pow(2,9),Fy=Math.pow(2,8),Kb=Math.pow(2,1);function vx(I){if(I.opacity===0&&!I.placed)return 0;if(I.opacity===1&&I.placed)return 4294967295;const y=I.placed?1:0,C=Math.floor(127*I.opacity);return C*Oy+y*Wb+C*Qu+y*Ol+C*x6+y*Fy+C*Kb+y}const bx=0;class dj{constructor(y){this._sortAcrossTiles=y.layout.get("symbol-z-order")!=="viewport-y"&&y.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(y,C,R,$,G,Z){const te=this._bucketParts;for(;this._currentTileIndexue.sortKey-xe.sortKey));this._currentPartIndex{const ue=o.o.now()-Z;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&ue>2};for(;this._currentPlacementIndex>=0;){const ue=C[y[this._currentPlacementIndex]],xe=this.placement.collisionIndex.transform.zoom;if(ue.type==="symbol"&&ue.visibility!=="none"&&(!ue.minzoom||ue.minzoom<=xe)&&(!ue.maxzoom||ue.maxzoom>xe)){const je=ue,Re=je.layout.get("symbol-z-elevate"),Le=je.layout.get("symbol-sort-key").constantOr(1)!==void 0,Ue=je.layout.get("symbol-z-order"),st=Ue==="viewport-y"||Ue==="auto"&&!(Ue!=="viewport-y"&&Le),Xe=je.layout.get("text-allow-overlap")||je.layout.get("icon-allow-overlap")||je.layout.get("text-ignore-placement")||je.layout.get("icon-ignore-placement"),pt=st&&Xe,mt=this._inProgressLayer=this._inProgressLayer||new dj(je),jt=o.F(ue.source,ue.scope);if(mt.continuePlacement(Re||pt?$[jt]:R[jt],this.placement,this._showCollisionBoxes,ue,te,G))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(y){return this.placement.commit(y),this.placement}}const Wd=512/o.an/2;class rp{constructor(y,C,R){this.tileID=y,this.bucketInstanceId=R,this.index=new o.bI(C.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const $=y.canonical.x*o.an,G=y.canonical.y*o.an;for(let Z=0;Zpt-mt);for(const pt of Xe){const mt=this.crossTileIDs[pt];if(this.keys[pt]===je&&!R.has(mt)){R.add(mt),xe.crossTileID=mt;break}}}}}class Kd{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class Fp{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(y){const C=Math.round((y-this.lng)/360);if(C!==0)for(const R in this.indexes){const $=this.indexes[R],G={};for(const Z in $){const te=$[Z];te.tileID=te.tileID.unwrapTo(te.tileID.wrap+C),G[te.tileID.key]=te}this.indexes[R]=G}this.lng=y}addBucket(y,C,R){if(this.indexes[y.overscaledZ]&&this.indexes[y.overscaledZ][y.key]){if(this.indexes[y.overscaledZ][y.key].bucketInstanceId===C.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(y.overscaledZ,this.indexes[y.overscaledZ][y.key])}for(let G=0;Gy.overscaledZ)for(const te in Z){const ue=Z[te];ue.tileID.isChildOf(y)&&ue.findMatches(C.symbolInstances,y,$)}else{const te=Z[y.scaledTo(Number(G)).key];te&&te.findMatches(C.symbolInstances,y,$)}}for(let G=0;G{C[R]=!0});for(const R in this.layerIndexes)C[R]||delete this.layerIndexes[R]}}const Ml=771;class na{constructor(y,C,R,$){this.blendFunction=y,this.blendColor=C.toNonPremultipliedRenderColor(null),this.mask=R,this.blendEquation=$}}na.Replace=[1,0,1,0],na.disabled=new na(na.Replace,o.aq.transparent,[!1,!1,!1,!1]),na.unblended=new na(na.Replace,o.aq.transparent,[!0,!0,!0,!0]),na.alphaBlended=new na([1,Ml,1,Ml],o.aq.transparent,[!0,!0,!0,!0]),na.alphaBlendedNonPremultiplied=new na([770,Ml,770,Ml],o.aq.transparent,[!0,!0,!0,!0]),na.multiply=new na([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),na.multiplyAccumulateAlpha=new na([774,0,1,Ml],o.aq.transparent,[!0,!0,!0,!0]),na.additive=new na([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class rr{constructor(y,C,R){this.func=y,this.mask=C,this.range=R}}rr.ReadOnly=!1,rr.ReadWrite=!0,rr.disabled=new rr(519,rr.ReadOnly,[0,1]);const vl=7680;class la{constructor(y,C,R,$,G,Z){this.test=y,this.ref=C,this.mask=R,this.fail=$,this.depthFail=G,this.pass=Z}}la.disabled=new la({func:519,mask:0},0,0,vl,vl,vl);const ap=1029,vm=2305;class Fr{constructor(y,C,R){this.enable=y,this.mode=C,this.frontFace=R}}function zy(I,y){const C=o.bO(I,3);o.bR(I,y),o.bW(I,3,C)}function uj(I,y){const C=o.bL([]);return o.bM(C,C,-y),o.bN(C,C,-I),C}function o1(I,y){const C=[I[0],I[1],0],R=[y[0],y[1],0];if(o.ai(C)>=1e-15){const Z=o.ay([],C);o.bJ(R,Z,o.bi(R,Z)),y[0]=R[0],y[1]=R[1]}const $=o.bh([],y,I);if(o.bK($)<1e-15)return null;const G=Math.atan2(-$[1],$[0]);return uj(Math.atan2(Math.sqrt(I[0]*I[0]+I[1]*I[1]),-I[2]),G)}Fr.disabled=new Fr(!1,ap,vm),Fr.backCCW=new Fr(!0,ap,vm),Fr.backCW=new Fr(!0,ap,2304),Fr.frontCW=new Fr(!0,1028,2304),Fr.frontCCW=new Fr(!0,1028,vm);class Zb{constructor(y,C){this.position=y,this.orientation=C}get position(){return this._position}set position(y){if(y){const C=y instanceof o.ag?y:new o.ag(y[0],y[1],y[2]);this._renderWorldCopies&&(C.x=o.bs(C.x,0,1)),this._position=C}else this._position=null}lookAtPoint(y,C,R){if(this.orientation=null,!this.position)return;const $=this.position,G=R||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(y)):0),Z=o.ag.fromLngLat(y,G),te=[Z.x-$.x,Z.y-$.y,Z.z-$.z];C||(C=[0,0,1]),C[2]=Math.abs(C[2]),this.orientation=o1(te,C)}setPitchBearing(y,C){this.orientation=uj(o.ap(y),o.ap(-C))}}class m0{constructor(y,C){this._transform=o.b9([]),this.orientation=C,this.position=y}get mercatorPosition(){const y=this.position;return new o.ag(y[0],y[1],y[2])}get position(){const y=o.bO(this._transform,3);return[y[0],y[1],y[2]]}set position(y){var C;y&&o.bW(this._transform,3,[(C=y)[0],C[1],C[2],1])}get orientation(){return this._orientation}set orientation(y){this._orientation=y||o.bL([]),y&&zy(this._transform,this._orientation)}getPitchBearing(){const y=this.forward(),C=this.right();return{bearing:Math.atan2(-C[1],C[0]),pitch:Math.atan2(Math.sqrt(y[0]*y[0]+y[1]*y[1]),-y[2])}}setPitchBearing(y,C){this._orientation=uj(y,C),zy(this._transform,this._orientation)}forward(){const y=o.bO(this._transform,2);return[-y[0],-y[1],-y[2]]}up(){const y=o.bO(this._transform,1);return[-y[0],-y[1],-y[2]]}right(){const y=o.bO(this._transform,0);return[y[0],y[1],y[2]]}getCameraToWorld(y,C){const R=new Float64Array(16);return o.b7(R,this.getWorldToCamera(y,C)),R}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(y,C,R){const $=this.position;o.bJ($,$,-y);const G=new Float64Array(16);return o.bP(G,[R,R,R]),o.bx(G,G,$),G[10]*=C,G}getWorldToCamera(y,C){const R=new Float64Array(16),$=new Float64Array(4),G=this.position;return o.bQ($,this._orientation),o.bJ(G,G,-y),o.bR(R,$),o.bx(R,R,G),R[1]*=-1,R[5]*=-1,R[9]*=-1,R[13]*=-1,R[8]*=C,R[9]*=C,R[10]*=C,R[11]*=C,R}getCameraToClipPerspective(y,C,R,$){const G=new Float64Array(16);return o.bS(G,y,C,R,$),G}getCameraToClipOrthographic(y,C,R,$,G,Z){const te=new Float64Array(16);return o.bT(te,y,C,R,$,G,Z),te}getDistanceToElevation(y,C=!1){const R=y===0?0:o.bU(y,C?o.bV(this.position[1]):this.position[1]),$=this.forward();return(R-this.position[2])/$[2]}clone(){return new m0([...this.position],[...this.orientation])}}const Lf=(I,y)=>({u_matrix:I,u_ground_shadow_factor:y});class bm{constructor(y=0,C=0,R=0,$=0){if(isNaN(y)||y<0||isNaN(C)||C<0||isNaN(R)||R<0||isNaN($)||$<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=y,this.bottom=C,this.left=R,this.right=$}interpolate(y,C,R){return C.top!=null&&y.top!=null&&(this.top=o.am(y.top,C.top,R)),C.bottom!=null&&y.bottom!=null&&(this.bottom=o.am(y.bottom,C.bottom,R)),C.left!=null&&y.left!=null&&(this.left=o.am(y.left,C.left,R)),C.right!=null&&y.right!=null&&(this.right=o.am(y.right,C.right,R)),this}getCenter(y,C){const R=o.aC((this.left+y-this.right)/2,0,y),$=o.aC((this.top+C-this.bottom)/2,0,C);return new o.P(R,$)}equals(y){return this.top===y.top&&this.bottom===y.bottom&&this.left===y.left&&this.right===y.right}clone(){return new bm(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const Df=15;class ip{constructor(y,C,R,$,G,Z,te){this.tileSize=512,this._renderWorldCopies=G===void 0||G,this._minZoom=y||0,this._maxZoom=C||22,this._minPitch=R??0,this._maxPitch=$??60,this.setProjection(Z),this.setMaxBounds(te),this.width=0,this.height=0,this._center=new o.aU(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._nearZ=0,this._farZ=0,this._nearClipOffset=0,this._unmodified=!0,this._edgeInsets=new bm,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new m0,this._centerAltitude=0,this._averageElevation=0,this.cameraElevationReference="ground",this._pixelsPerMercatorPixel=1,this.globeRadius=0,this.globeCenterInViewSpace=[0,0,0],this._tileCoverLift=0,this.freezeTileCoverage=!1,this._horizonShift=.1,this._orthographicProjectionAtLowPitch=!1,this._allowWorldUnderZoom=!1}clone(){const y=new ip(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return y._elevation=this._elevation,y._centerAltitude=this._centerAltitude,y._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,y.tileSize=this.tileSize,y.mercatorFromTransition=this.mercatorFromTransition,y.width=this.width,y.height=this.height,y.cameraElevationReference=this.cameraElevationReference,y._center=this._center,y._setZoom(this.zoom),y._seaLevelZoom=this._seaLevelZoom,y.angle=this.angle,y._fov=this._fov,y._pitch=this._pitch,y._nearZ=this._nearZ,y._farZ=this._farZ,y._nearClipOffset=this._nearClipOffset,y._averageElevation=this._averageElevation,y._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,y._unmodified=this._unmodified,y._edgeInsets=this._edgeInsets.clone(),y._camera=this._camera.clone(),y._calcMatrices(),y.freezeTileCoverage=this.freezeTileCoverage,y.frustumCorners=this.frustumCorners,y._allowWorldUnderZoom=this._allowWorldUnderZoom,y}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||y===Number.NEGATIVE_INFINITY&&(!C||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const R=this._elevation;C||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&R.exaggeration()&&this._centerAltitudeValidForExaggeration!==R.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*R.exaggeration(),this._centerAltitudeValidForExaggeration=R.exaggeration()):(this._centerAltitude=y||0,this._centerAltitudeValidForExaggeration=R.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const y=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(y)}sampleAverageElevation(){if(!this._elevation)return 0;const y=this._elevation,C=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],R=this.horizonLineFromTop();let $=0,G=0;for(let Z=0;Z{const pt=o.ck(Le,Re,Ue,st,Xe);ue.has(pt)||(G.push(new o.aR(Re,Le,Ue,st,Xe)),ue.add(pt))};for(let Re=0;ReLe.canonical.z)continue;const Ue=Le.canonical,st=Le.overscaledZ,Xe=Le.wrap,pt=1<0,Tt=Ue.y+10,es=Le.wrap-(jt?0:1),Ft=Le.wrap+(mt?0:1),Jt=jt?Ue.x-1:pt-1,At=mt?Ue.x+1:0;if(Z)R[0]<0?(xe(st,Ft,Ue.z,At,Ue.y),R[1]<0&&Tt&&(xe(st,Xe,Ue.z,Ue.x,Ue.y+1),xe(st,Ft,Ue.z,At,Ue.y+1)),R[1]>0&&xt&&(xe(st,Xe,Ue.z,Ue.x,Ue.y-1),xe(st,Ft,Ue.z,At,Ue.y-1))):R[0]>0?(xe(st,es,Ue.z,Jt,Ue.y),R[1]<0&&Tt&&(xe(st,Xe,Ue.z,Ue.x,Ue.y+1),xe(st,es,Ue.z,Jt,Ue.y+1)),R[1]>0&&xt&&(xe(st,Xe,Ue.z,Ue.x,Ue.y-1),xe(st,es,Ue.z,Jt,Ue.y-1))):R[1]<0&&Tt?xe(st,Xe,Ue.z,Ue.x,Ue.y+1):xt&&xe(st,Xe,Ue.z,Ue.x,Ue.y-1);else{const Rt=Le.visibleQuadrants;1&Rt&&(xe(st,es,Ue.z,Jt,Ue.y),xt&&(xe(st,Xe,Ue.z,Ue.x,Ue.y-1),xe(st,es,Ue.z,Jt,Ue.y-1))),2&Rt&&(xe(st,Ft,Ue.z,At,Ue.y),xt&&(xe(st,Xe,Ue.z,Ue.x,Ue.y-1),xe(st,Ft,Ue.z,At,Ue.y-1))),4&Rt&&(xe(st,es,Ue.z,Jt,Ue.y),Tt&&(xe(st,Xe,Ue.z,Ue.x,Ue.y+1),xe(st,es,Ue.z,Jt,Ue.y+1))),8&Rt&&(xe(st,Ft,Ue.z,At,Ue.y),Tt&&(xe(st,Xe,Ue.z,Ue.x,Ue.y+1),xe(st,Ft,Ue.z,At,Ue.y+1)))}}const je=[];for(const Re of G)G.some(Le=>Re.isChildOf(Le))||je.push(Re);if(G=je.filter(Re=>!y.some(Le=>!!(Re.overscaledZ{const mt=pt.canonical.x+.5-Ue[0],jt=pt.canonical.y+.5-Ue[1];return mt*mt+jt*jt{const Jt=o.ck(Tt,jt,xt,es,Ft);G.has(Jt)||($.push(new o.aR(jt,Tt,xt,es,Ft)),G.add(Jt))},te=y.reduce((jt,Tt)=>Math.max(jt,Tt.overscaledZ),R),ue=1<{const xt=Math.floor(jt[0]),es=Math.floor(jt[1]),Ft=(jt[0]-xt)*o.an,Jt=(jt[1]-es)*o.an,At=Math.floor(Tt[0]),Rt=Math.floor(Tt[1]),Wt=(Tt[0]-At)*o.an,ys=(Tt[1]-Rt)*o.an;for(let rs=-1;rs<=1;rs++){const zs=xt+rs;if(!(zs<0||zs>=ue)){je.x=Ft-rs*o.an,Re.x=Wt-(zs-At)*o.an;for(let Is=-1;Is<=1;Is++){const an=es+Is;je.y=Jt-Is*o.an,Re.y=ys-(an-Rt)*o.an,o.cI(je,Re,xe)&&Z(te,0,R,zs,an)}}}},Ue=C.points,st=Ue[o.c9],Xe=Ue[o.ca],pt=this._projectToGround(st,Ue[o.cb]),mt=this._projectToGround(Xe,Ue[o.cc]);return Le(st,pt),Le(Xe,mt),$}_projectToGround(y,C){return o.cd(o.ce(),y,C,y[2]/(y[2]-C[2]))}_projectToZ(y,C,R){const $=y[2]-C[2];return Math.abs($)<1e-6?o.cf(y):o.cd(o.ce(),y,C,(y[2]-R)/$)}extendTileCoverForTunnels(y,C,R,$){if(R<18)return[];const G=C.points,Z=G[o.cg],te=G[o.ch],ue=G[o.ci],xe=G[o.cj];if(ue[2]>=0&&xe[2]>=0||Z[2]<=0||te[2]<=0)return[];const je=ue[2]<0?this._projectToZ(Z,ue,0):ue,Re=xe[2]<0?this._projectToZ(te,xe,0):xe,Le=-$,Ue=ue[2]3&&(Xe.length=3),Xe}_findExtensionTilesInQuad(y,C,R,$){const G=[],Z=new Set;for(const At of y)Z.add(At.key);const te=y.reduce((At,Rt)=>Math.max(At,Rt.overscaledZ),C),ue=1<{const Wt=At.canonical.x+.5-Ft,ys=At.canonical.y+.5-Jt,rs=Rt.canonical.x+.5-Ft,zs=Rt.canonical.y+.5-Jt;return Wt*Wt+ys*ys-(rs*rs+zs*zs)||At.canonical.x-Rt.canonical.x||At.canonical.y-Rt.canonical.y}),G}coveringTiles(y){let C=this.coveringZoomLevel(y);const R=C,$=this.elevation&&this.elevation.exaggeration(),G=$&&!y.isTerrainDEM,Z=this.projection.name==="mercator";if(y.minzoom!==void 0&&Cy.maxzoom&&(C=y.maxzoom);const te=this.locationCoordinate(this.center),ue=this.center.lat,xe=1<{const qs=new o.ag(ms.x+25e-6,ms.y,ms.z),Qs=new o.ag(ms.x,ms.y+25e-6,ms.z),Dn=ms.toLngLat(),Cn=qs.toLngLat(),Tn=Qs.toLngLat(),dn=this.locationCoordinate(Dn),mr=this.locationCoordinate(Cn),Er=this.locationCoordinate(Tn),ar=Math.hypot(mr.x-dn.x,mr.y-dn.y),hr=Math.hypot(Er.x-dn.x,Er.y-dn.y);return Math.sqrt(ar*hr)*Jt/25e-6},Rt=ms=>{const Rs=es,qs=Ft;return{aabb:o.cp(this,xe,0,0,0,ms,qs,Rs,this.projection),zoom:0,x:0,y:0,minZ:qs,maxZ:Rs,wrap:ms,fullyVisible:!1}},Wt=[];let ys=[];const rs=C,zs=y.reparseOverscaled?R:C,Is=(pt-this._centerAltitude)*Xe,an=ms=>{if(!this._elevation||!ms.tileID||!Z)return;const Rs=this._elevation.getMinMaxForTile(ms.tileID),qs=ms.aabb;Rs?(qs.min[2]=Rs.min,qs.max[2]=Rs.max,qs.center[2]=(qs.min[2]+qs.max[2])/2):(ms.shouldSplit=js(ms),ms.shouldSplit||(qs.min[2]=qs.max[2]=qs.center[2]=this._centerAltitude))},mn=(ms,Rs)=>{if(.707*Rs{if(ms.zoom=.9)return!0}else if(G&&(Qs=ms.aabb.distanceZ(mt)*Xe),this.projection.isReprojectedInTileSpace&&R<=5){const hr=Math.pow(2,ms.zoom),ra=At(new o.ag((ms.x+.5)/hr,(ms.y+.5)/hr));Dn=ra>.85?1:ra}if(!Z&&!Re){const hr=Math.sqrt(Rs*Rs+qs*qs+Qs*Qs);let ra=(1<0;){const ms=Wt.pop(),Rs=ms.x,qs=ms.y;let Qs=ms.fullyVisible;const Dn=()=>this.projection.name==="globe"&&(ms.y===0||ms.y===(1<Cn)continue;let Tn=0;if(!Qs){let ar=jt?ms.aabb.intersectsPrecise(Ue):ms.aabb.intersectsPreciseFlat(Ue);if(ar===0&&Dn()){const hr=new o.cn(ms.zoom,Rs,qs);ar=o.co(this,xe,hr,!0).intersectsPrecise(Ue)}if(ar===0)continue;if(y.calculateQuadrantVisibility)if(Ue.containsPoint(ms.aabb.center))Tn=15;else for(let hr=0;hr<4;hr++)ms.aabb.quadrant(hr).intersects(Ue)!==0&&(Tn|=1<>1),mr={aabb:Z?ms.aabb.quadrant(Cn):o.cp(this,xe,ms.zoom+1,Tn,dn,ms.wrap,ms.minZ,ms.maxZ,this.projection),zoom:ms.zoom+1,x:Tn,y:dn,wrap:ms.wrap,fullyVisible:Qs,tileID:void 0,shouldSplit:void 0,minZ:ms.minZ,maxZ:ms.maxZ};G&&!Re&&(mr.tileID=new o.aR(ms.zoom+1===rs?zs:ms.zoom+1,ms.wrap,ms.zoom+1,Tn,dn),an(mr)),Wt.push(mr)}}if(this.fogCullDistSq){const ms=this.fogCullDistSq,Rs=this.horizonLineFromTop();ys=ys.filter(qs=>{const Qs=[0,0,0,1],Dn=[o.an,o.an,0,1],Cn=this.calculateFogTileMatrix(qs.tileID.toUnwrapped());o.aE(Qs,Qs,Cn),o.aE(Dn,Dn,Cn);const Tn=o.cq([],Qs,Dn),dn=o.cr([],Qs,Dn),mr=o.cK(Tn,dn);if(mr===0)return!0;let Er=!1;const ar=this._elevation;if(ar&&mr>ms&&Rs!==0){const hr=this.calculateProjMatrix(qs.tileID.toUnwrapped());let ra;y.isTerrainDEM||(ra=ar.getMinMaxForTile(qs.tileID)),ra||(ra={min:Ft,max:es});const Na=o.cs(this.rotation),ba=[Na[0]*o.an,Na[1]*o.an,ra.max];o.ah(ba,ba,hr),Er=(1-ba[1])*this.height*.5ms.distanceSq-Rs.distanceSq).map(ms=>ms.tileID)}resize(y,C){this.width=y,this.height=C,this.pixelsToGLUnits=[2/y,-2/C],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(y){return Math.pow(2,y)}scaleZoom(y){return Math.log2(y)}project(y){const C=o.aC(y.lat,-o.ct,o.ct),R=this.projection.project(y.lng,C);return new o.P(R.x*this.worldSize,R.y*this.worldSize)}unproject(y){return this.projection.unproject(y.x/this.worldSize,y.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/o.bU(1,this.center.lat)/this.worldSize}setLocationAtPoint(y,C){let R,$;const G=this.centerPoint;if(this.projection.name==="globe"){const te=this.worldSize;R=(C.x-G.x)/te,$=(C.y-G.y)/te}else{const te=this.pointCoordinate(C),ue=this.pointCoordinate(G);R=te.x-ue.x,$=te.y-ue.y}const Z=this.locationCoordinate(y);this.setLocation(new o.ag(Z.x-R,Z.y-$))}setLocation(y){this.center=this.coordinateLocation(y),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(y,C){return this.projection.locationPoint(this,y,C)}locationPoint3D(y,C){return this.projection.locationPoint(this,y,C,!0)}pointLocation(y){return this.coordinateLocation(this.pointCoordinate(y))}pointLocation3D(y,C){return this.coordinateLocation(this.pointCoordinate3D(y,C))}locationCoordinate(y,C){const R=C?o.bU(C,y.lat):void 0,$=this.projection.project(y.lng,y.lat);return new o.ag($.x,$.y,R)}coordinateLocation(y){return this.projection.unproject(y.x,y.y)}pointRayIntersection(y,C){const R=C??this._centerAltitude,$=[y.x,y.y,0,1],G=[y.x,y.y,1,1];o.aE($,$,this.pixelMatrixInverse),o.aE(G,G,this.pixelMatrixInverse);const Z=G[3];o.cu($,$,1/$[3]),o.cu(G,G,1/Z);const te=$[2],ue=G[2];return{p0:$,p1:G,t:te===ue?0:(R-te)/(ue-te)}}screenPointToMercatorRay(y){const C=[y.x,y.y,0,1],R=[y.x,y.y,1,1];return o.aE(C,C,this.pixelMatrixInverse),o.aE(R,R,this.pixelMatrixInverse),o.cu(C,C,1/C[3]),o.cu(R,R,1/R[3]),C[2]=o.bU(C[2],this._center.lat)*this.worldSize,R[2]=o.bU(R[2],this._center.lat)*this.worldSize,o.cu(C,C,1/this.worldSize),o.cu(R,R,1/this.worldSize),new o.az([C[0],C[1],C[2]],o.ay([],o.ax([],R,C)))}rayIntersectionCoordinate(y){const{p0:C,p1:R,t:$}=y,G=o.bU(C[2],this._center.lat),Z=o.bU(R[2],this._center.lat);return new o.ag(o.am(C[0],R[0],$)/this.worldSize,o.am(C[1],R[1],$)/this.worldSize,o.am(G,Z,$))}pointCoordinate(y,C=this._centerAltitude){return this.projection.pointCoordinate(this,y.x,y.y,C)}pointCoordinate3D(y,C){if(!this.elevation)return this.pointCoordinate(y,C);let R=this.projection.pointCoordinate3D(this,y.x,y.y);if(R)return new o.ag(R[0],R[1],R[2]);let $=0,G=this.horizonLineFromTop();if(y.y>G)return this.pointCoordinate(y,C);const Z=.02*G,te=y.clone();for(let ue=0;ue<10&&G-$>Z;ue++){te.y=o.am($,G,.66);const xe=this.projection.pointCoordinate3D(this,te.x,te.y);xe?(G=te.y,R=xe):$=te.y}return R?new o.ag(R[0],R[1],R[2]):this.pointCoordinate(y)}isPointAboveHorizon(y){return this.projection.isPointAboveHorizon(this,y)}isPointOnSurface(y){if(y.y<0||y.y>this.height||y.x<0||y.x>this.width)return!1;if(this.elevation||this.zoom>=o.cv)return!this.isPointAboveHorizon(y);const C=this.pointCoordinate(y);return C.y>=0&&C.y<=1}_coordinatePoint(y,C){const R=C&&this.elevation?this.elevation.getAtPointOrZero(y,this._centerAltitude):this._centerAltitude,$=[y.x*this.worldSize,y.y*this.worldSize,R+y.toAltitude(),1];return o.aE($,$,this.pixelMatrix),$[3]>0?new o.P($[0]/$[3],$[1]/$[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:y,left:C}=this._edgeInsets,R=this.height-this._edgeInsets.bottom,$=this.width-this._edgeInsets.right,G=this.pointLocation3D(new o.P(C,y)),Z=this.pointLocation3D(new o.P($,y)),te=this.pointLocation3D(new o.P($,R)),ue=this.pointLocation3D(new o.P(C,R));let xe=Math.min(G.lng,Z.lng,te.lng,ue.lng),je=Math.max(G.lng,Z.lng,te.lng,ue.lng),Re=Math.min(G.lat,Z.lat,te.lat,ue.lat),Le=Math.max(G.lat,Z.lat,te.lat,ue.lat);const Ue=Math.pow(2,-this.zoom)/16*270,st=this.projection.name==="globe"?1:4,Xe=(pt,mt,jt,Tt,xt)=>{const es=(pt+jt)/2,Ft=(mt+Tt)/2,Jt=new o.P(es,Ft),{lng:At,lat:Rt}=this.pointLocation3D(Jt),Wt=Math.max(0,xe-At,Re-Rt,At-je,Rt-Le);xe=Math.min(xe,At),je=Math.max(je,At),Re=Math.min(Re,Rt),Le=Math.max(Le,Rt),(xtUe)&&(Xe(pt,mt,es,Ft,xt+1),Xe(es,Ft,jt,Tt,xt+1))};if(Xe(C,y,$,y,1),Xe($,y,$,R,1),Xe($,R,C,R,1),Xe(C,R,C,y,1),this.projection.name==="globe"){const[pt,mt]=o.cw(this);pt?(Le=90,je=180,xe=-180):mt&&(Re=-90,je=180,xe=-180)}return new o.aK(new o.aU(xe,Re),new o.aU(je,Le))}_getBoundsRectangular(y,C){const{top:R,left:$}=this._edgeInsets,G=this.height-this._edgeInsets.bottom,Z=this.width-this._edgeInsets.right,te=new o.P($,R),ue=new o.P(Z,R),xe=new o.P(Z,G),je=new o.P($,G);let Re=this.pointCoordinate(te,y),Le=this.pointCoordinate(ue,y);const Ue=this.pointCoordinate(xe,C),st=this.pointCoordinate(je,C),Xe=(pt,mt)=>(mt.y-pt.y)/(mt.x-pt.x);return Re.y>1&&Le.y>=0?Re=new o.ag((1-st.y)/Xe(st,Re)+st.x,1):Re.y<0&&Le.y<=1&&(Re=new o.ag(-st.y/Xe(st,Re)+st.x,0)),Le.y>1&&Re.y>=0?Le=new o.ag((1-Ue.y)/Xe(Ue,Le)+Ue.x,1):Le.y<0&&Re.y<=1&&(Le=new o.ag(-Ue.y/Xe(Ue,Le)+Ue.x,0)),new o.aK().extend(this.coordinateLocation(Re)).extend(this.coordinateLocation(Le)).extend(this.coordinateLocation(st)).extend(this.coordinateLocation(Ue))}_getBoundsRectangularTerrain(){const y=this.elevation;if(!y.visibleDemTiles.length||y.isUsingMockSource())return this._getBoundsRectangular(0,0);const C=y.visibleDemTiles.reduce((R,$)=>{if($.dem){const G=$.dem.tree;R.min=Math.min(R.min,G.minimums[0]),R.max=Math.max(R.max,G.maximums[0])}return R},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(C.min*y.exaggeration(),C.max*y.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(y=!0){const C=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,R=this.height/2-C*(1-this._horizonShift);return y?Math.max(0,R):R}getMaxBounds(){return this.maxBounds}setMaxBounds(y){this.maxBounds=y,this.minLat=-o.ct,this.maxLat=o.ct,this.minLng=-180,this.maxLng=180,y&&(this.minLat=y.getSouth(),this.maxLat=y.getNorth(),this.minLng=y.getWest(),this.maxLng=y.getEast(),this.maxLngRe&&(te=Re-xe),Re-jeUe&&(Z=Ue-ue),Ue-Le{for(let js=0;js<16;js++)zs[js]=o.am(Is[js],an[js],mn)})(te,te,ue,o.cL(this.pitch>=Df?1:this.pitch/Df))}else te=ue;const xe=o.cz([],ue,Z);let je=o.cz([],te,Z);if(this.projection.isReprojectedInTileSpace){const Rt=this.locationCoordinate(this.center),Wt=o.b9([]);o.bx(Wt,Wt,[Rt.x*this.worldSize,Rt.y*this.worldSize,0]),o.aD(Wt,Wt,o.cA(this)),o.bx(Wt,Wt,[-Rt.x*this.worldSize,-Rt.y*this.worldSize,0]),o.aD(je,je,Wt),o.aD(xe,xe,Wt),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],je,[this.worldSize,this.worldSize,this.worldSize/G,1]),this.projMatrix=je,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),C){const Rt=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);Rt[8]=2*-y.x/this.width,Rt[9]=2*y.y/this.height,this.expandedFarZProjMatrix=o.cz([],Rt,Z)}else this.expandedFarZProjMatrix=this.projMatrix;const Re=o.b7([],te);this.frustumCorners=o.cD.fromInvProjectionMatrix(Re,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!C);const Le=new Float32Array(16);o.b9(Le),o.cC(Le,Le,[1,-1,1]),o.cE(Le,Le,this._pitch),o.ba(Le,Le,this.angle);const Ue=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(Ue);const st=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;Ue[8]=2*-y.x/this.width,Ue[9]=2*(y.y+st)/this.height,this.skyboxMatrix=o.aD(Le,Ue,Le);const Xe=this.point,pt=Xe.x,mt=Xe.y,jt=this.width%2/2,Tt=this.height%2/2,xt=Math.cos(this.angle),es=Math.sin(this.angle),Ft=pt-Math.round(pt)+xt*jt+es*Tt,Jt=mt-Math.round(mt)+xt*Tt+es*jt,At=new Float64Array(je);if(o.bx(At,At,[Ft>.5?Ft-1:Ft,Jt>.5?Jt-1:Jt,0]),this.alignedProjMatrix=At,je=o.bb(),o.cC(je,je,[this.width/2,-this.height/2,1]),o.bx(je,je,[1,-1,0]),this.labelPlaneMatrix=je,je=o.bb(),o.cC(je,je,[1,-1,1]),o.bx(je,je,[-1,-1,0]),o.cC(je,je,[2/this.width,2/this.height,1]),this.glCoordMatrix=je,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,xe),this._calcFogMatrices(),this._distanceTileDataCache={},je=o.b7(new Float64Array(16),this.pixelMatrix),!je)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=je,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const Rt=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(Rt,Rt,Z),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=je;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const y=this.cameraWorldSizeForFog,C=this.cameraPixelsPerMeter,R=this._camera.position,$=1/this.height/this._pixelsPerMercatorPixel,G=[y,y,C];o.bJ(G,G,$),o.bJ(R,R,-1),o.cG(R,R,G);const Z=o.bb();o.bx(Z,Z,R),o.cC(Z,Z,G),this.mercatorFogMatrix=Z,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(y,C,$)}_computeCameraPosition(y){const C=(y=y||this.pixelsPerMeter)/this.pixelsPerMeter,R=this._camera.forward(),$=this.point,G=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*C-y/this.worldSize*this._centerAltitude;return[$.x/this.worldSize-R[0]*G,$.y/this.worldSize-R[1]*G,y/this.worldSize*this._centerAltitude-R[2]*G]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(y){const C=this._maxCameraBoundsDistance()*Math.cos(this._pitch),R=this._camera.position[2],$=y[2];let G=1;this.projection.wrap&&(this.center=this.center.wrap()),$>0&&(G=Math.min((C-R)/$,1)),this._camera.position=o.bg([],this._camera.position,y,G),this._updateStateFromCamera()}_updateStateFromCamera(){const y=this._camera.position,C=this._camera.forward(),{pitch:R,bearing:$}=this._camera.getPitchBearing(),G=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,Z=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),te=Math.max((y[2]-G)/Math.cos(R),Z),ue=this._zoomFromMercatorZ(te);o.bg(y,y,C,te),this._pitch=o.aC(R,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs($,-Math.PI,Math.PI),this._setZoom(o.aC(ue,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new o.ag(y[0],y[1],y[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(y){return Math.pow(2,y)*this.tileSize}_mercatorZfromZoom(y){return this.cameraToCenterDistance/this._worldSizeFromZoom(y)}_minimumHeightOverTerrain(){const y=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(y)}_zoomFromMercatorZ(y){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,y)*this.tileSize))}zoomFromMercatorZAdjusted(y){let C=0,R=o.cv,$=0,G=1/0;for(;R-C>1e-6&&R>C;){const Z=C+.5*(R-C),te=this.tileSize*Math.pow(2,Z),ue=this.getCameraToCenterDistance(this.projection,Z,te),xe=this.scaleZoom(ue/(Math.max(0,y)*this.tileSize)),je=Math.abs(Z-xe);jexe||Le.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+o.cH(this.fovAboveCenter)>88||this.anyCornerOffEdge(new o.P(0,0),new o.P(this.width,this.height))}zoomDeltaToMovement(y,C){const R=o.ai(o.ax([],this._camera.position,y)),$=this._zoomFromMercatorZ(R)+C;return R-this._mercatorZfromZoom($)}getCameraPoint(){if(this.projection.name==="globe"){const y=function([C,R,$],G){const Z=[C,R,$,1];o.aE(Z,Z,G);const te=Z[3]=Math.max(Z[3],1e-6);return Z[0]/=te,Z[1]/=te,Z[2]/=te,Z}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(y[0],y[1])}{const y=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,y))}}getCameraToCenterDistance(y,C=this.zoom,R=this.worldSize){const $=o.cy(y,C,this.width,this.height,1024),G=y.pixelSpaceConversion(this.center.lat,R,$);let Z=.5/Math.tan(.5*this._fov)*this.height*G;return this.isOrthographic&&(Z=o.am(1,Z,o.cL(this.pitch>=Df?1:this.pitch/Df))),Z}getWorldToCameraMatrix(){const y=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aD(y,y,this.globeMatrix),y}getFrustum(y){return o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,y,this.projection.zAxisUnit==="meters")}}const $c=(I,y)=>{if(y>0&&I.terrain&&o.w("Cutoff is currently disabled on terrain"),y<=0||I.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const C=I.transform,R=C.pitch,$=C.isLODDisabled(!1)?60:30;if(R<$-15)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const G=C._farZ-C._nearZ,Z=y*C.height*1.3,te=Math.pow(2,.85*Math.max(C._zoom-I.minCutoffZoom,0)),ue=1.4*C.cameraToCenterDistance*te,xe=o.aj($-15,$,R),je=(1-(Re=xe))*(C._farZ+Z)+Re*ue;var Re;const Le=Math.min(Z,je-C._nearZ);return{shouldRenderCutoff:xe>0,uniformValues:{u_cutoff_params:[C._nearZ,C._farZ,(je-C._nearZ)/G,(je-Le-C._nearZ)/G]}}},zp=2048;class hj{constructor(y,C){this.aabb=y,this.lastCascade=C}}class LN{add(y,C){const R=this.receivers[y.key];R!==void 0?(R.aabb.min[0]=Math.min(R.aabb.min[0],C.min[0]),R.aabb.min[1]=Math.min(R.aabb.min[1],C.min[1]),R.aabb.min[2]=Math.min(R.aabb.min[2],C.min[2]),R.aabb.max[0]=Math.max(R.aabb.max[0],C.max[0]),R.aabb.max[1]=Math.max(R.aabb.max[1],C.max[1]),R.aabb.max[2]=Math.max(R.aabb.max[2],C.max[2])):this.receivers[y.key]=new hj(C,null)}clear(){this.receivers={}}get(y){return this.receivers[y.key]}computeRequiredCascades(y,C,R){const $=o.cU.fromPoints(y.points);let G=0;for(const Z in this.receivers){const te=this.receivers[Z];if(!te||!$.intersectsAabb(te.aabb))continue;te.aabb.min=$.closestPoint(te.aabb.min),te.aabb.max=$.closestPoint(te.aabb.max);const ue=te.aabb.getCorners();for(let xe=0;xe1||Le[1]<-1||Le[1]>1){je=!1;break}}if(te.lastCascade=xe,G=Math.max(G,xe),je)break}}return G+1}}class ec{constructor(y){this.painter=y,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new LN,this._depthMode=new rr(y.context.gl.LEQUAL,rr.ReadWrite,[0,1]),this._uniformValues={u_light_matrix_0:new Float32Array(16),u_light_matrix_1:new Float32Array(16),u_shadow_intensity:0,u_fade_range:[0,0],u_shadow_normal_offset:[1,1,1],u_shadow_texel_size:1,u_shadow_map_resolution:1,u_shadow_direction:[0,0,1],u_shadow_bias:[36e-5,.0012,.012],u_shadowmap_0:0,u_shadowmap_1:0},this._forceDisable=!1,this.useNormalOffset=!1}destroy(){for(const y of this._cascades)y.texture.destroy(),y.framebuffer.destroy();this._cascades=[]}updateShadowParameters(y,C){const R=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!C||!C.properties)return;const $=C.properties.get("shadow-intensity"),G=C.properties.get("shadow-draw-before-layer");if(!C.shadowsEnabled()||$<=0)return;let Z=-1,te=0;for(const mt of R.style.order){const jt=R.style._mergedLayers[mt];jt.hasShadowPass()&&!jt.isHidden(y.zoom)&&(Z=te),!G||G!==mt&&G!==jt.slot||(this._drawShadowAfterLayer=te>0?te-1:0),te+=1}if(this._enabled=Z>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=Z);const ue=R.context,xe=zp,je=zp;if(this._cascades.length===0||zp!==this._cascades[0].texture.size[0]){this._cascades=[];for(let mt=0;mt<2;++mt){const jt=ue.gl,Tt=ue.createFramebuffer(xe,je,0,"texture"),xt=new o.T(ue,{width:xe,height:je,data:null},jt.DEPTH_COMPONENT16);Tt.depthAttachment.set(xt.texture),this._cascades.push({framebuffer:Tt,texture:xt,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=DN(C);let Re=0;if(y.elevation){const mt=y.elevation,jt=[1e4,-1e4];mt.visibleDemTiles.filter(Tt=>Tt.dem).forEach(Tt=>{const xt=Tt.dem.tree;jt[0]=Math.min(jt[0],xt.minimums[0]),jt[1]=Math.max(jt[1],xt.maximums[0])}),jt[0]!==1e4&&(Re=(jt[1]-jt[0])*mt.exaggeration())}const Le=1.5*y.cameraToCenterDistance,Ue=3*Le,st=new Float64Array(16);for(let mt=0;mt=0)return{};const G=function(ue,xe,je){const Re=je/(1<0&&(o.cT(G[1],G[1],[$[0]*Z,0,0]),o.cT(G[2],G[2],[$[0]*Z,0,0])),$[1]<0?(o.cT(G[0],G[0],[0,$[1]*Z,0]),o.cT(G[1],G[1],[0,$[1]*Z,0])):$[1]>0&&(o.cT(G[2],G[2],[0,$[1]*Z,0]),o.cT(G[3],G[3],[0,$[1]*Z,0]));const te={};return te.vertices=G,te.planes=[l1(G[1],G[0],G[4]),l1(G[2],G[1],G[5]),l1(G[3],G[2],G[6]),l1(G[0],G[3],G[7])],te}addShadowReceiver(y,C,R){this._receivers.add(y,o.cU.fromTileIdAndHeight(y,C,R))}getMaxCascadeForTile(y){const C=this._receivers.get(y);return C&&C.lastCascade?C.lastCascade:0}}function l1(I,y,C){const R=o.ax([],C,y),$=o.ax([],I,y),G=o.bh([],R,$),Z=o.ai(G);return Z===0?[0,0,1,0]:(o.bJ(G,G,1/Z),[G[0],G[1],G[2],-o.bi(G,y)])}function DN(I){const y=I.properties.get("direction"),C=o.cP(y.x,y.y,y.z);C[2]=o.aC(C[2],0,75);const R=o.cR([C[0],C[1],C[2]]);return o.cQ(R.x,R.y,R.z)}function Bp(I,y,C){const R=y.properties.get("color-use-theme")==="none",$=y.properties.get("color"),G=y.properties.get("intensity"),Z=y.properties.get("direction"),te=[Z.x,Z.y,Z.z],ue=C.properties.get("color-use-theme")==="none",xe=C.properties.get("color"),je=C.properties.get("intensity"),Re=Math.max(o.bi([0,0,1],te),0),Le=[0,0,0];o.bJ(Le,xe.toPremultipliedRenderColor(ue?null:I.getLut(y.scope)).toArray01Linear().slice(0,3),je);const Ue=[0,0,0];return o.bJ(Ue,$.toPremultipliedRenderColor(R?null:I.getLut(C.scope)).toArray01Linear().slice(0,3),Re*G),o.cW([Le[0]>0?Le[0]/(Le[0]+Ue[0]):0,Le[1]>0?Le[1]/(Le[1]+Ue[1]):0,Le[2]>0?Le[2]/(Le[2]+Ue[2]):0])}function By(I,y,C,R,$,G){const Z=I.zoom,te=I.scale,ue=I.worldSize,xe=1/ue,je=I.aspect,Re=Math.sqrt(1+je*je)*Math.tan(.5*I.fovX),Le=Re*Re,Ue=R-C,st=R+C;let Xe,pt;Le>Ue/st?(Xe=R,pt=R*Re):(Xe=.5*st*(1+Le),pt=.5*Math.sqrt(Ue*Ue+2*(R*R+C*C)*Le+st*st*Le*Le));const mt=I.projection.pixelsPerMeter(I.center.lat,ue),jt=I._camera.getCameraToWorldMercator(),Tt=[0,0,-Xe*xe];o.ah(Tt,Tt,jt);let xt=pt*xe;const es=function(Qs){return Qs[0]/=te,Qs[1]/=te,Qs[2]=o.bU(Qs[2],I._center.lat),Qs},Ft=I._edgeInsets;if(!(Ft.left===0&&Ft.top===0&&Ft.right===0&&Ft.bottom===0||Ft.left===Ft.right&&Ft.top===Ft.bottom)){const Qs=I._camera.getWorldToCamera(I.worldSize,I.projection.zAxisUnit==="meters"?mt:1),Dn=I._camera.getCameraToClipPerspective(I._fov,I.width/I.height,C,R);Dn[8]=2*-I.centerOffset.x/I.width,Dn[9]=2*I.centerOffset.y/I.height;const Cn=new Float64Array(16);o.cz(Cn,Dn,Qs);const Tn=new Float64Array(16);o.b7(Tn,Cn);const dn=o.cl.fromInvProjectionMatrix(Tn,ue,Z,!0);for(const mr of dn.points){const Er=es(mr);xt=Math.max(xt,o.bK(o.cV([],Tt,Er)))}}xt*=$/($-1);const Jt=Math.acos(y[2]),At=Math.atan2(-y[0],-y[1]),Rt=new m0;Rt.position=Tt,Rt.setPitchBearing(Jt,At);const Wt=Rt.getWorldToCamera(ue,mt),ys=xt*ue,rs=Math.min(I._mercatorZfromZoom(17)*ue*-2,-2*ys),zs=Rt.getCameraToClipOrthographic(-ys,ys,-ys,ys,rs,(ys+G*mt)/y[2]),Is=new Float64Array(16);o.aD(Is,zs,Wt);const an=o.cQ(Math.floor(1e6*Tt[0])/1e6*ue,Math.floor(1e6*Tt[1])/1e6*ue,0),mn=.5*$,js=[0,0,0];o.ah(js,an,Is),o.bJ(js,js,mn);const ms=[Math.floor(js[0]),Math.floor(js[1]),Math.floor(js[2])],Rs=[0,0,0];o.ax(Rs,js,ms),o.bJ(Rs,Rs,-1/mn);const qs=new Float64Array(16);return o.b9(qs),o.bx(qs,qs,Rs),o.aD(Is,qs,Is),[Is,ys]}class gC extends o.E{constructor(y){super(),this.requestManager=y,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(y,C){return o.cX(this.requestManager.transformRequest(C,o.R.Model).url).then(R=>{const $=o.cY(R),G=new o.cZ(y,C,void 0,void 0,$);return G.computeBoundsAndApplyParent(),G}).catch(R=>{if(R&&R.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${y} from ${C}: ${R.message}`)))})}load(y,C,R={forceReload:!1}){this.models[C]||(this.models[C]={});const $=Object.keys(y),G=[],Z=[];for(const te of $){const ue=y[te];this.hasURLBeenRequested(ue)&&!R.forceReload||(this.modelByURL[ue]={modelId:te,scope:C},G.push(this.loadModel(te,ue)),Z.push(te)),this.models[C][te]||(this.models[C][te]={model:null,numReferences:1})}this.numModelsLoading[C]=(this.numModelsLoading[C]||0)+Z.length,Promise.allSettled(G).then(te=>{for(let ue=0;ue{this.fire(new o.B(new Error(`Could not load models: ${te.message}`)))})}isLoaded(){for(const y in this.numModelsLoading)if(this.numModelsLoading[y]>0)return!1;return!0}hasModel(y,C,R={exactIdMatch:!1}){return!!(R.exactIdMatch?this.getModel(y,C):this.getModelByURL(this.modelUris[C][y]))}getModel(y,C){return this.models[C]||(this.models[C]={}),this.models[C][y]?this.models[C][y].model:void 0}getModelByURL(y){if(!y)return null;const C=this.modelByURL[y];return C?this.models[C.scope][C.modelId].model:null}hasModelBeenAdded(y,C){return this.models[C]&&this.models[C][y]!==void 0}getModelURIs(y){return this.modelUris[y]||{}}addModel(y,C,R){this.models[R]||(this.models[R]={}),this.modelUris[R]||(this.modelUris[R]={});const $=this.requestManager.normalizeModelURL(C);if((this.hasModel(y,R,{exactIdMatch:!0})||this.hasModelBeenAdded(y,R))&&this.modelUris[R][y]===$)this.models[R][y].numReferences++;else if(this.hasURLBeenRequested($)){const{scope:G,modelId:Z}=this.modelByURL[$];this.models[G][Z].numReferences++}else this.modelUris[R][y]=$,this.load({[y]:this.modelUris[R][y]},R)}addModelURLs(y,C){this.models[C]||(this.models[C]={}),this.modelUris[C]||(this.modelUris[C]={});const R=this.modelUris[C];for(const $ in y)R[$]=this.requestManager.normalizeModelURL(y[$])}reloadModels(y){this.load(this.modelUris[y],y,{forceReload:!0})}addModelsFromBucket(y,C){this.models[C]||(this.models[C]={}),this.modelUris[C]||(this.modelUris[C]={});const R={};for(const $ of y)this.hasModel($,C,{exactIdMatch:!0})||this.hasURLBeenRequested($)?this.models[C][$].numReferences++:this.modelUris[C][$]&&!this.hasURLBeenRequested($)?R[$]=this.modelUris[C][$]:!this.hasURLBeenRequested($)&&o.c_($,!1)&&(this.modelUris[C][$]=this.requestManager.normalizeModelURL($),R[$]=this.modelUris[C][$]);this.load(R,C)}hasURLBeenRequested(y){return this.modelByURL[y]!==void 0}removeModel(y,C,R=!1,$=!1){if(this.models[C]&&this.models[C][y]&&(this.models[C][y].numReferences--,this.models[C][y].numReferences===0||$)){const G=this.modelUris[C][y];R||delete this.modelUris[C][y],delete this.modelByURL[G];const Z=this.models[C][y].model;if(!Z)return;delete this.models[C][y],Z.destroy()}}destroy(){for(const y of Object.keys(this.models))for(const C of Object.keys(this.models[y])){const R=this.models[y][C].model;delete this.models[y][C],R&&R.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(y){return this.models[y]||(this.models[y]={}),Object.keys(this.models[y])}upload(y,C){this.models[C]||(this.models[C]={});for(const R in this.models[C])this.models[C][R].model&&this.models[C][R].model.upload(y.context)}}const p0=o.a8.colorTheme,Wl=new o.ab({data:new o.ac(p0.data)});function Yd(I){if(!I.metadata||!I.metadata.content_area)return;const y=o.o.devicePixelRatio,{left:C,top:R,width:$,height:G}=I.metadata.content_area,Z=C*y,te=R*y;return[Z,te,Z+$*y,te+G*y]}function ld(I){if(I)return I.map(([y,C])=>[y*o.o.devicePixelRatio,C*o.o.devicePixelRatio])}class Qb{constructor(y,C,R){this.id=y,this.scope=C,this.sourceCache=R,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(y){this.missingRequests.has(y.name)||this.pendingRequests.has(y.name)||this.pendingRequests.add(y.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const y=new Map;if(!this.sourceCache.loaded())return y;const C=this.sourceCache.getVisibleCoordinates();if(C.length===0)return y;const R=this.sourceCache.getSource();if(!(R instanceof xm))return y;const $=C.map(Z=>this.sourceCache.getTile(Z)),G=R.getImages($,Array.from(this.pendingRequests));for(const[Z,te]of G)y.set(o.I.from({name:Z,iconsetId:this.id}),te),this.pendingRequests.delete(Z);for(const Z of this.pendingRequests)this.missingRequests.add(Z);return this.pendingRequests.clear(),y}}class Rf{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(y,C,R,$,G){if(Rue*this._hysteresisRatio&&(Z=this._previousClosestBuildingId):xe&&!Z&&(Z=this._previousClosestBuildingId),this._previousClosestBuildingId=Z,Z}_calculateDistance(y,C){if(!C.center)return Number.MAX_VALUE;const R=y.lat-C.center[1],$=y.lng-C.center[0];return R*R+$*$}_isBuildingVisible(y,C,R){if(!R)return!1;for(const $ of y.floorIds){const G=y.floors[$];if(!G.geometry)continue;const Z=G.geometry;if(Z.type==="Polygon"){const te=this._convertRingToPoints(Z.coordinates[0]);if(o.bw(te,R))return!0}else if(Z.type==="MultiPolygon"){const te=this._convertMultiPolygonToPoints(Z.coordinates);if(o.d0(R,te))return!0}}return!1}_convertRingToPoints(y){return y.map(C=>new o.P(C[0],C[1]))}_convertMultiPolygonToPoints(y){return y.map(C=>C.length===0?[]:C[0].map(R=>new o.P(R[0],R[1])))}}class mj extends o.E{constructor(y){super(),this._style=y,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new Rf,this._initialLoadDone=!1,o.aZ(["_updateUI"],this),this._style.on("style.load",()=>{this._style.isIndoorEnabled()&&(this._style.map.on("load",()=>{this._initialLoadDone=!0,this._indoorState&&this._indoorState.needsUpdate&&(this._indoorState.needsUpdate=!1,this._style.updateIndoorDependentLayers()),this._updateUI()}),this._style.map.on("move",this._updateUI),this._style.map.on("idle",this._updateUI))})}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(y){y===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=y,this._recalculateActiveFloors())}setActiveFloorsVisibility(y){this._updateActiveFloors(y),this._updateIndoorSelector()}setIndoorData(y){let C=!1;for(const[R,$]of Object.entries(y.buildings))if(this._buildings[R])for(const G of $.floorIds)this._buildings[R].floorIds.add(G),this._buildings[R].floors[G]?this._mergeFloors(this._buildings[R].floors[G],$.floors[G]):(this._buildings[R].floors[G]=$.floors[G],C=!0);else this._buildings[R]=$,C=!0;C&&this._recalculateActiveFloors()}getIndoorTileOptions(y,C){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(y,C),indoorState:this._indoorState}:null}getControlState(){const y=this._buildings,C=this._closestBuildingId,R=C&&y?y[C]:void 0;if(!R)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let $=null;for(const Z of R.floorIds)if(this._activeFloors&&this._activeFloors.has(Z)){$=Z;break}const G=Array.from(R.floorIds).map(Z=>({id:Z,name:R.floors[Z].name,zIndex:R.floors[Z].zIndex})).sort((Z,te)=>te.zIndex-Z.zIndex).filter((Z,te,ue)=>te===0||Z.zIndex!==ue[te-1].zIndex);return{selectedFloorId:$,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:G}}_updateUI(){this._initialLoadDone=!0;const y=this._style.map.transform,C=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,y.center,y.zoom,y.getBounds(),this._makeViewportPolygon());if(C!==this._closestBuildingId){const R=this._closestBuildingId;this._closestBuildingId=C,this._onBuildingTransition(R,C),this._updateIndoorSelector()}}_onBuildingTransition(y,C){if(!this._indoorState)return;!C&&y?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!C&&!y&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.C("selector-update",this.getControlState()))}_updateActiveFloors(y){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:y,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const y=o.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(C,R){if(C===R)return!0;if(!C||!R||C.size!==R.size)return!1;for(const $ of C)if(!R.has($))return!1;return!0})(y,this._activeFloors)||(this._activeFloors=y,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(y,C){C.geometry&&(y.geometry?(y.geometry.type==="Polygon"&&(y.geometry={type:"MultiPolygon",coordinates:[y.geometry.coordinates]}),C.geometry.type==="Polygon"?y.geometry.coordinates.push(C.geometry.coordinates):C.geometry.type==="MultiPolygon"&&y.geometry.coordinates.push(...C.geometry.coordinates)):y.geometry=C.geometry)}_makeViewportPolygon(){const y=this._style.map.transform,C=y.width,R=y.height;return[y.pointLocation(new o.P(0,0)),y.pointLocation(new o.P(C,0)),y.pointLocation(new o.P(C,R)),y.pointLocation(new o.P(0,R))].map($=>new o.P($.lng,$.lat))}}const c1=(I,y)=>Un(I,y&&y.filter(C=>C.identifier!=="source.canvas")),qh=o.aJ(Xa,["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"]),RN=o.aJ(Xa,["setCenter","setZoom","setBearing","setPitch"]),pj=new Set(["background","sky","slot","custom"]),Xb={version:8,layers:[],sources:{}},Of={duration:300,delay:0};class Qc extends o.E{constructor(y,C={}){if(super(),this.map=y,this.scope=C.scope||"",this.globalId=null,this.fragments=[],this.importDepth=C.importDepth||0,this.importsCache=C.importsCache||new Map,this.resolvedImports=C.resolvedImports||new Set,this.transition=Object.assign({},Of),this._buildingIndex=new h0(this),this.crossTileSymbolIndex=new Pf,this._mergedOrder=[],this._drapedFirstOrder=[],this._mergedLayers={},this._mergedIndoor={},this._mergedSourceCaches={},this._mergedOtherSourceCaches={},this._mergedSymbolSourceCaches={},this._mergedFillExtrusionSourceCaches={},this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=C.styleChanges||new Ye,this._hasDataDrivenEmissive=!1,this.indoorManager=new mj(this),this.dispatcher=C.dispatcher?C.dispatcher:new dt(Qt(),this),this.map.painter&&this.map.painter.context){const $=this.map.painter.context.maxUniformBufferBindings,G=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:$,maxUniformBlockSizeDwords:G,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}C.imageManager?this.imageManager=C.imageManager:(this.imageManager=new ns(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=C.glyphManager?C.glyphManager:new o.d2(y._requestManager,C.localFontFamily?o.d3.all:C.localIdeographFontFamily?o.d3.ideographs:o.d3.none,C.localFontFamily||C.localIdeographFontFamily,C.useServerFontComposition),C.modelManager?this.modelManager=C.modelManager:(this.modelManager=new gC(y._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._fillExtrusionSourceCaches={},this._loaded=!1,this._precompileDone=!1,this._shouldPrecompile=!1,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=C.configOptions?C.configOptions:new Map,this._configDependentLayers=C.configDependentLayers?C.configDependentLayers:new Set,this._indoorDependentLayers=C.indoorDependentLayers?C.indoorDependentLayers:new Set,this._config=C.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:C.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=C.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const R=this;this._rtlTextPluginCallback=Qc.registerForPluginStateChange($=>{R.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:$.pluginStatus,pluginURL:$.pluginURL},(G,Z)=>{if(o.d6(G),Z&&Z.every(te=>te))for(const te in R._sourceCaches){const ue=R._sourceCaches[te],xe=ue.getSource().type;xe!=="vector"&&xe!=="geojson"||ue.reload()}})}),this.on("data",$=>{if($.dataType!=="source"||$.sourceDataType!=="metadata")return;const G=this.getOwnSource($.sourceId);if(G&&G.vectorLayerIds)for(const Z in this._layers){const te=this._layers[Z];te.source===G.id&&this._validateLayer(te)}})}load(y){return y?(typeof y=="string"?this.loadURL(y):this.loadJSON(y),this):this}_getGlobalId(y){if(!y)return null;if(typeof y=="string"){if(o.e(y))return y;const C=o.d7(y);if(!C.startsWith("http"))try{return new URL(C,location.href).toString()}catch{return C}return C}return`json://${o.d8(JSON.stringify(y))}`}_diffStyle(y,C,R){this.globalId=this._getGlobalId(y);const $=(G,Z)=>{try{Z(null,this.setState(G,R))}catch(te){Z(te,!1)}};if(typeof y=="string"){const G=this.map._requestManager.normalizeStyleURL(y),Z=this.map._requestManager.transformRequest(G,o.R.Style);o.m(Z,(te,ue)=>{te?this.fire(new o.B(te)):ue&&$(ue,C)})}else typeof y=="object"&&$(y,C)}loadURL(y,C={}){this.fire(new o.C("dataloading",{dataType:"style"}));const R=typeof C.validate=="boolean"?C.validate:!o.e(y);this.globalId=this._getGlobalId(y),y=this.map._requestManager.normalizeStyleURL(y,C.accessToken),this.resolvedImports.add(y);const $=this.importsCache.get(y);if($)return this._load($,R);const G=this.map._requestManager.transformRequest(y,o.R.Style);this._request=o.m(G,(Z,te)=>{if(this._request=null,Z)this.fire(new o.B(Z));else if(te)return this.importsCache.set(y,te),this._load(te,R)})}loadJSON(y,C={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(y),this._request=o.o.frame(()=>{this._request=null,this._load(y,C.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(Xb,!1)}_loadImports(y,C,R){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const $=[];for(const G of y){const Z=this._createFragmentStyle(G),te=new Promise(je=>{Z.once("style.import.load",je),Z.once("error",je)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if($.push(te),this.resolvedImports.has(G.url)){Z.loadEmpty();continue}const ue=G.data||this.importsCache.get(G.url);ue?(G.data?(Z.fire(new o.C("dataloading",{dataType:"style"})),Z.globalId=Z._getGlobalId(ue),queueMicrotask(()=>Z._load(ue,C))):Z.loadJSON(ue,{validate:C}),this._isInternalStyle(ue)&&(Z.globalId=null)):G.url?Z.loadURL(G.url,{validate:C}):Z.loadEmpty();const xe={style:Z,id:G.id,config:G.config};if(R){const je=this.fragments.findIndex(({id:Re})=>Re===R);this.fragments=this.fragments.slice(0,je).concat(xe).concat(this.fragments.slice(je))}else this.fragments.push(xe)}return Promise.allSettled($)}getImportGlobalIds(y=this,C=new Set){for(const R of y.fragments)R.style.globalId&&C.add(R.style.globalId),this.getImportGlobalIds(R.style,C);return[...C.values()]}_createFragmentStyle(y){const C=this.scope?o.F(y.id,this.scope):y.id;let R;const $=this._initialConfig&&this._initialConfig[C];(y.config||$)&&(R=Object.assign({},y.config,$));const G=new Qc(this.map,{scope:C,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:R,configOptions:this.options,colorThemeOverride:y["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return G.setEventedParent(this.map,{style:G}),G}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),this._shouldPrecompile=this.map._precompilePrograms&&this.isRootStyle()}_isInternalStyle(y){return this.isRootStyle()&&(y.fragment||!!y.schema&&y.fragment!==!1)}_load(y,C){if(this._isInternalStyle(y)){const G=Object.assign({},Xb,{imports:[{id:"basemap",data:y,url:""}]},y.center?{center:y.center}:{},y.bearing?{bearing:y.bearing}:{},y.pitch?{pitch:y.pitch}:{},y.zoom?{zoom:y.zoom}:{},y.light?{light:y.light}:{});return this._importedAsBasemap=!0,void this._load(G,C)}if(this.updateConfig(this._config,y.schema),C&&c1(this,$n(y)))return;this._loaded=!0;for(const G in y.sources)this.addSource(G,y.sources[G],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(y);const R=()=>{if(y.iconsets)for(const ue in y.iconsets)this.addIconset(ue,y.iconsets[ue]);y.sprite?this._loadIconset(y.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&y.glyphs&&this.glyphManager.setURL(y.glyphs);const G=Af(this.stylesheet.layers);if(this._order=G.map(ue=>ue.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 ue=this.stylesheet.lights[0];this.light=new sr(ue.properties,ue.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new sr(this.stylesheet.light)),this._layers={};for(const ue of G){const xe=o.de(ue,this.scope,this._styleColorTheme.lut,this.options);xe.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(xe.fqid),xe.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(xe.fqid),this._hasAppearances=this._hasAppearances||xe.getAppearances().length!==0,xe.setEventedParent(this,{layer:{id:xe.id}}),this._layers[xe.id]=xe;const je=this.getOwnLayerSourceCache(xe),Re=!!this.directionalLight&&this.directionalLight.shadowsEnabled();je&&xe.canCastShadows()&&Re&&(je.castsShadows=!0)}if(this.glyphManager.url){const ue=new Set;for(const xe in this._layers){const je=this._layers[xe];if(je.type==="symbol"&&je.layout){const Re=je.layout.get("text-font");Re&&Re.value&&Re.value.kind==="constant"&&ue.add(Re.value.value.join(","))}}for(const xe of ue)this.glyphManager.prefetchRange(xe,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const Z=this.stylesheet.terrain;Z&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(Z,1)),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new o.C("data",{dataType:"style"}));const te=this.isRootStyle();y.imports?this._loadImports(y.imports,C).then(()=>{this._reloadImports(),this.fire(new o.C(te?"style.load":"style.import.load"))}).catch(ue=>{this.fire(new o.B(new Error("Failed to load imports",ue))),this.fire(new o.C(te?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(te?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const $=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if($){const G=this._evaluateColorThemeData($);this._loadColorTheme(G).then(()=>{R()}).catch(Z=>{o.w(`Couldn't load color theme from the stylesheet: ${Z}`),R()})}else this._styleColorTheme.lut=null,R()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(y=>y.style.hasAppearances())}mergeAll(){let y,C,R,$,G,Z,te,ue,xe,je;const Re={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Le=>{if(Le.stylesheet){if(Le.light!=null&&(y=Le.light),Le.stylesheet.lights)for(const Ue of Le.stylesheet.lights)Ue.type==="ambient"&&Le.ambientLight!=null&&(C=Le.ambientLight),Ue.type==="directional"&&Le.directionalLight!=null&&(R=Le.directionalLight);$=this._prioritizeTerrain($,Le.terrain,Le.stylesheet.terrain),Le.stylesheet.fog&&Le.fog!=null&&(G=Le.fog),Le.stylesheet.snow&&Le.snow!=null&&(Z=Le.snow),Le.stylesheet.rain&&Le.rain!=null&&(te=Le.rain),Le.stylesheet.camera!=null&&(je=Le.stylesheet.camera),Le.stylesheet.projection!=null&&(ue=Le.stylesheet.projection),Le.stylesheet.transition!=null&&(xe=Le.stylesheet.transition),Re[Le.scope]=Le._styleColorTheme}}),this.light=y,this.ambientLight=C,this.directionalLight=R,this.fog=G,this.snow=Z,this.rain=te,this._styleColorThemeForScope=Re,$===null?delete this.terrain:this.terrain=$,this.camera=je||{"camera-projection":"perspective"},this.projection=ue||{name:"mercator"},this.transition=Object.assign({},Of,xe),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(y){const C=R=>{for(const $ of R.fragments)C($.style);y(R)};C(this)}_prioritizeTerrain(y,C,R){const $=y&&y.drapeRenderMode===0;return R===null?C&&C.drapeRenderMode===0?C:$?y:null:C!=null&&(!y||$||C&&C.drapeRenderMode===1)?C:y}mergeTerrain(){let y;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(C=>{y=this._prioritizeTerrain(y,C.terrain,C.stylesheet.terrain)}),y===null?delete this.terrain:this.terrain=y}mergeProjection(){let y;this.forEachFragmentStyle(C=>{C.stylesheet.projection!=null&&(y=C.stylesheet.projection)}),this.projection=y||{name:"mercator"}}mergeSources(){const y={},C={},R={},$={};this.forEachFragmentStyle(G=>{for(const Z in G._sourceCaches){const te=o.F(Z,G.scope);y[te]=G._sourceCaches[Z]}for(const Z in G._otherSourceCaches){const te=o.F(Z,G.scope);C[te]=G._otherSourceCaches[Z]}for(const Z in G._symbolSourceCaches){const te=o.F(Z,G.scope);R[te]=G._symbolSourceCaches[Z]}for(const Z in G._fillExtrusionSourceCaches){const te=o.F(Z,G.scope);$[te]=G._fillExtrusionSourceCaches[Z]}}),this._mergedSourceCaches=y,this._mergedOtherSourceCaches=C,this._mergedSymbolSourceCaches=R,this._mergedFillExtrusionSourceCaches=$}mergeIndoor(){this.forEachFragmentStyle(y=>{if(y.stylesheet&&y.stylesheet.indoor)for(const C of Object.values(y.stylesheet.indoor)){const R=C,$=o.F(R.sourceId,y.scope);this._mergedIndoor[$]=new Set(R.sourceLayers||[])}})}mergeLayers(){const y={},C=[],R={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(Z=>{for(const te of Z._order){const ue=Z._layers[te];if(ue.type==="slot"){const xe=o.da(te);if(y[xe])continue;y[xe]=[]}ue.slot&&y[ue.slot]?y[ue.slot].push(ue):C.push(ue)}}),this._mergedOrder=[];let $=-1;const G=(Z=[])=>{for(const te of Z)if(te.type==="slot"){const ue=o.da(te.id);y[ue]&&G(y[ue]),this._mergedSlots.push(ue)}else{const ue=o.F(te.id,te.scope);this._mergedOrder.push(ue),R[ue]=te,te.is3D(!!this.terrain)&&(this._has3DLayers=!0,$=this._mergedOrder.length-1),te.type==="circle"&&(this._hasCircleLayers=!0),te.type==="symbol"&&(this._hasSymbolLayers=!0),te.type==="clip"&&(this._clipLayerPresent=!0)}};if(G(C),this._has3DLayers){const Z={};for(let te=0;teZ[te]-Z[ue])}this._mergedLayers=R,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(y){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,y),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(y){return y.data?function(C,R,$){const G=Object.assign({},R);for(const te of Object.keys(p0))G[te]===void 0&&(G[te]=p0[te].default);const Z=new o.aa(Wl,C,new Map($));return Z.setTransitionOrValue(G,$),Z.untransitioned().possiblyEvaluate(new o.ae(0,{worldview:void 0}))}(this.scope,y,this.options).get("data"):null}_loadColorTheme(y){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const C=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((R,$)=>{const G="data:image/png;base64,";if(!y||y.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void R();let Z=y;Z.startsWith(G)||(Z=G+Z);const te=o.I.from("mapbox-reserved-lut"),ue=new Image;ue.src=Z,ue.onerror=()=>{this._styleColorTheme.lutLoading=!1,$(new Error("Failed to load image data"))},ue.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==C)return void R();this._styleColorTheme.lutLoading=!1;const{width:xe,height:je,data:Re}=o.o.getImageData(ue);if(je>32)return void $(new Error("The height of the image must be less than or equal to 32 pixels."));if(xe!==je*je)return void $(new Error("The width of the image must be equal to the height squared."));this.getImage(te)&&this.removeImage(te),this.addImage(te,{data:new o.q({width:xe,height:je},Re),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Le=this.imageManager.getImage(te,this.scope);Le?(this._styleColorTheme.lut={image:Le.data,data:y},R()):$(new Error("Missing LUT image."))}})}getLut(y){const C=this._styleColorThemeForScope[y];return C?C.lut:null}setProjection(y){y?this.stylesheet.projection=y:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this._loaded&&(this.dispatcher.broadcast("setProjection",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?(this.getTerrain()||this.stylesheet.terrain)&&!this.disableElevatedTerrain||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null,0))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(y){this._spriteRequest=function(C,R,$){let G,Z,te;const ue=o.o.devicePixelRatio>1?"@2x":"";let xe=o.m(R.transformRequest(R.normalizeSpriteURL(C,ue,".json"),o.R.SpriteJSON),(Le,Ue)=>{xe=null,te||(te=Le,G=Ue,Re())}),je=o.n(R.transformRequest(R.normalizeSpriteURL(C,ue,".png"),o.R.SpriteImage),(Le,Ue)=>{je=null,te||(te=Le,Z=Ue,Re())});function Re(){if(te)$(te);else if(G&&Z){const Le=o.o.getImageData(Z),Ue={};for(const st in G){const{width:Xe,height:pt,x:mt,y:jt,sdf:Tt,pixelRatio:xt,stretchX:es,stretchY:Ft,content:Jt}=G[st],At=new o.q({width:Xe,height:pt});o.q.copy(Le,At,{x:mt,y:jt},{x:0,y:0},{width:Xe,height:pt},null),Ue[st]={data:At,pixelRatio:xt!==void 0?xt:1,sdf:Tt!==void 0&&Tt,stretchX:es,stretchY:Ft,content:Jt,usvg:!1,version:0}}$(null,Ue)}}return{cancel(){xe&&(xe.cancel(),xe=null),je&&(je.cancel(),je=null)}}}(y,this.map._requestManager,(C,R)=>{if(this._spriteRequest=null,C)this.fire(new o.B(C));else if(R){const $=new Map;for(const G in R)$.set(o.I.from(G),R[G]);this.addImages($)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))})}addIconset(y,C){if(C.type==="sprite")return void this._loadSprite(C.url);const R=this.getOwnSourceCache(C.source);if(!R)return void this.fire(new o.B(new Error(`Source "${C.source}" as specified by iconset "${y}" does not exist and cannot be used as an iconset source`)));const $=R.getSource();if($.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${C.source}" as specified by iconset "${y}" is not a "raster-array" source and cannot be used as an iconset source`)));$.partial=!1;const G=new Qb(y,this.scope,R);this.imageManager.addImageProvider(G,this.scope)}removeIconset(y){this.imageManager.removeImageProvider(y,this.scope)}_loadIconset(y){if(!o.e(y)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(y);const C=this.map._spriteFormat==="auto";var R,$;this._spriteRequest=($=(G,Z)=>{if(this._spriteRequest=null,G)C?this._loadSprite(y):this.fire(new o.B(G));else if(Z){const te=new Map;for(const ue in Z)te.set(o.I.from(ue),Z[ue]);this.addImages(te)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))},o.b1((R=this.map._requestManager).transformRequest(R.normalizeIconsetURL(y),o.R.Iconset),(G,Z)=>{if(G)return void $(G);const te={},ue=o.c$(new o.a$(Z));for(const xe of ue.icons){const je={version:1,pixelRatio:o.o.devicePixelRatio,content:Yd(xe),stretchX:xe.metadata?ld(xe.metadata.stretch_x_areas):void 0,stretchY:xe.metadata?ld(xe.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:xe};te[xe.name]=je}$(null,te)}))}_validateLayer(y){const C=this.getOwnSource(y.source);if(!C)return;const R=y.sourceLayer;R&&(C.type==="geojson"||C.vectorLayerIds&&C.vectorLayerIds.indexOf(R)===-1)&&this.fire(new o.B(new Error(`Source layer "${R}" does not exist on source "${C.id}" as specified by style layer "${y.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const y in this._sourceCaches)if(!this._sourceCaches[y].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:y}of this.fragments)if(!y.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((y,C)=>{const R=this.fragments[C];return R&&R.style&&(y.data=R.style.serialize()),y})}_serializeSources(){const y={};for(const C in this._sourceCaches){const R=this._sourceCaches[C].getSource();y[R.id]||(y[R.id]=R.serialize())}return y}_serializeLayers(y){const C=[];for(const R of y){const $=this._layers[R];$&&$.type!=="custom"&&C.push($.serialize())}return C}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions()||this.hasFogTransition()||this.hasSnowTransition()||this.hasRainTransition())return!0;for(const y in this._sourceCaches)if(this._sourceCaches[y].hasTransition())return!0;for(const y in this._layers)if(this._layers[y].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const y in this._mergedLayers){const C=this._mergedLayers[y];if(C._transitionablePaint&&C._transitionablePaint._values){const R=C._transitionablePaint._values["line-emissive-strength"];if(R&&R.value&&R.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(y){return y?this.order:this._mergedOrder}isLayerDraped(y){return!!this.terrain&&y.isDraped(this.getLayerSourceCache(y))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(y){const C=this.getOwnLayer(y);if(C)return C;this.fire(new o.B(new Error(`The layer '${y}' does not exist in the map's style.`)))}_checkSource(y){const C=this.getOwnSource(y);if(C)return C;this.fire(new o.B(new Error(`The source '${y}' does not exist in the map's style.`)))}precompilePrograms(y,C){const R=this.map.painter;if(R)for(let $=y.minzoom||0;$<(y.maxzoom||25.5);$++){const G=y.getProgramIds();if(G)for(const Z of G){const te=y.getDefaultProgramParams(Z,C.zoom,this._styleColorTheme.lut);te&&(R.style=this,this.fog&&(R._fogVisible=!0,te.overrideFog=!0,R.getOrCreateProgram(Z,te)),R._fogVisible=!1,te.overrideFog=!1,R.getOrCreateProgram(Z,te),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(te.overrideRtt=!0,R.getOrCreateProgram(Z,te)))}}}update(y){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(y),this.directionalLight&&this.directionalLight.recalculate(y);const C=this.calculateLightsBrightness();y.brightness=C||0,C!==this._brightness&&(this._brightness=C,this.dispatcher.broadcast("setBrightness",C)),y.worldview!==this._worldview&&(this._worldview=y.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const R=this._changes.isDirty();let $=!1;if(this._changes.isDirty()){const ue=this._changes.getLayerUpdatesByScope();for(const xe in ue){const{updatedIds:je,removedIds:Re}=ue[xe];(je||Re)&&(this._updateWorkerLayers(xe,je,Re),$=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(y),this.light&&this.light.updateTransitions(y),this.ambientLight&&this.ambientLight.updateTransitions(y),this.directionalLight&&this.directionalLight.updateTransitions(y),this.fog&&this.fog.updateTransitions(y),this.snow&&this.snow.updateTransitions(y),this.rain&&this.rain.updateTransitions(y),this._changes.reset()}const G={};for(const ue in this._mergedSourceCaches){const xe=this._mergedSourceCaches[ue];G[ue]=xe.used,xe.used=!1,xe.tileCoverLift=0}const Z={};for(const ue of this._mergedOrder){const xe=this._mergedLayers[ue];if((xe.visibility!=="none"||xe.hasTransition())&&xe.recalculate(y,this._availableImages),!xe.isHidden(y.zoom)){const je=this.getLayerSourceCache(xe);je&&(je.used=!0,je.tileCoverLift=Math.max(je.tileCoverLift,xe.tileCoverLift()))}if(xe.type==="fill-extrusion"){const je=o.F(xe.source,xe.scope);if(je in this._mergedFillExtrusionSourceCaches){const Re=xe.layout&&xe.layout.get("source-max-zoom");if(Re!=null){const Le=Z[je];Z[je]=Le==null?Re:Math.min(Le,Re)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(xe,y)}):this.precompilePrograms(xe,y))}this._shouldPrecompile&&(this._precompileDone=!0);for(const ue in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[ue].setMaxzoomOverride(Z[ue]!=null?Z[ue]:null);this.terrain&&$&&this.mergeLayers();const te=this.imageManager.getPendingImageProviders();for(const ue of te)ue.sourceCache.used=!0;for(const ue in G){const xe=this._mergedSourceCaches[ue];G[ue]!==xe.used&&xe.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:xe.getSource().id}))}this.light&&this.light.recalculate(y),this.terrain&&this.terrain.recalculate(y),this.fog&&this.fog.recalculate(y),this.snow&&this.snow.recalculate(y),this.rain&&this.rain.recalculate(y),this.z=y.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),R&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const y=this.imageManager.getPendingImageProviders();for(const C of y){const R=C.resolvePendingRequests(),$=this.getFragmentStyle(C.scope);$&&$.addImages(R)}}_updateTilesForChangedImages(){const y={};for(const C in this._mergedSourceCaches){const R=this._mergedSourceCaches[C].getSource().scope;y[R]=y[R]||this._changes.getUpdatedImages(R),y[R].length!==0&&this._mergedSourceCaches[C].reloadTilesForDependencies(["icons","patterns"],y[R])}for(const C in y)this._changes.resetUpdatedImages(C)}_updateWorkerLayers(y,C,R){const $=this.getFragmentStyle(y);$&&this.dispatcher.broadcast("updateLayers",{layers:C?$._serializeLayers(C):[],scope:y,removedIds:R||[],options:$.options})}setState(y,C){if(this._checkLoaded(),c1(this,$n(y)))return!1;(y=o.d9(y)).layers=Af(y.layers);const R=function(Z,te){if(!Z)return[{command:Xa.setStyle,args:[te]}];let ue=[];try{if(!o.b6(Z.version,te.version))return[{command:Xa.setStyle,args:[te]}];if(o.b6(Z.center,te.center)||ue.push({command:Xa.setCenter,args:[te.center]}),o.b6(Z.zoom,te.zoom)||ue.push({command:Xa.setZoom,args:[te.zoom]}),o.b6(Z.bearing,te.bearing)||ue.push({command:Xa.setBearing,args:[te.bearing]}),o.b6(Z.pitch,te.pitch)||ue.push({command:Xa.setPitch,args:[te.pitch]}),o.b6(Z.sprite,te.sprite)||ue.push({command:Xa.setSprite,args:[te.sprite]}),o.b6(Z.glyphs,te.glyphs)||ue.push({command:Xa.setGlyphs,args:[te.glyphs]}),o.b6(Z.imports,te.imports)||function(Ue=[],st=[],Xe){st=st||[];const pt=(Ue=Ue||[]).map(xx),mt=st.map(xx),jt=Ue.reduce(hg,{}),Tt=st.reduce(hg,{}),xt=pt.slice();let es,Ft,Jt,At;for(es=0,Ft=0;es{Ue.source&&xe[Ue.source]?ue.push({command:Xa.removeLayer,args:[Ue.id]}):Re.push(Ue)});let Le=Z.terrain;Le&&xe[Le.source]&&(ue.push({command:Xa.setTerrain,args:[void 0]}),Le=void 0),ue=ue.concat(je),o.b6(Le,te.terrain)||ue.push({command:Xa.setTerrain,args:[te.terrain]}),function(Ue,st,Xe){st=st||[];const pt=(Ue=Ue||[]).map(xx),mt=st.map(xx),jt=Ue.reduce(hg,{}),Tt=st.reduce(hg,{}),xt=pt.slice(),es=Object.create(null);let Ft,Jt,At,Rt,Wt,ys,rs;for(Ft=0,Jt=0;Ft!(Z.command in RN));if(R.length===0)return!1;const $=R.filter(Z=>!(Z.command in qh));if($.length>0)throw new Error(`Unimplemented: ${$.map(Z=>Z.command).join(", ")}.`);const G=[];return R.forEach(Z=>{G.push(this[Z.command](...Z.args))}),C&&Promise.all(G).then(C).catch(C),this.stylesheet=y,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(){this._availableImages=this.imageManager.listImages(this.scope),this.dispatcher.broadcast("setImages",{scope:this.scope,images:this._availableImages})}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(y){if(y.size===0)return this;for(const[C,R]of y.entries()){if(this.getImage(C))return this.fire(new o.B(new Error(`An image with the name "${C.name}" already exists.`)));this.imageManager.addImage(C,this.scope,R),this._changes.updateImage(C,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(y,C){return this.getImage(y)?this.fire(new o.B(new Error(`An image with the name "${y.name}" already exists.`))):(this.imageManager.addImage(y,this.scope,C),this._changes.updateImage(y,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(y,C,R=!1){this.imageManager.updateImage(y,this.scope,C),R&&(this._changes.updateImage(y,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})))}getImage(y){return this.imageManager.getImage(y,this.scope)}removeImage(y){return this.getImage(y)?(this.imageManager.removeImage(y,this.scope),this._changes.updateImage(y,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this):this.fire(new o.B(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(y){return this.modelManager.addModelURLs(y,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.C("data",{dataType:"style"})),this}addModel(y,C,R={}){return this._checkLoaded(),this._validate(ln,`models.${y}`,C,null,R)||(this.modelManager.addModel(y,C,this.getActualScope()),this.fire(new o.C("data",{dataType:"style"}))),this}hasModel(y){return this.modelManager.hasModel(y,this.getActualScope())}removeModel(y){return this.hasModel(y)?(this.modelManager.removeModel(y,this.getActualScope(),!1,!0),this.fire(new o.C("data",{dataType:"style"})),this):this.fire(new o.B(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(y,C,R={}){if(this._checkLoaded(),this.getOwnSource(y)!==void 0)throw new Error(`There is already a source with ID "${y}".`);if(!C.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(C).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(C.type)>=0&&this._validate(Cr,`sources.${y}`,C,null,R))return;this.map&&this.map._collectResourceTiming&&(C.collectResourceTiming=!0);const $=Py(y,C,this.dispatcher,this);$.scope=this.scope,$.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded($.id),source:$.serialize(),sourceId:$.id}));const G=Z=>{const te=(Z===o.b4.Symbol?"symbol:":Z===o.b4.FillExtrusion?"fill-extrusion:":"other:")+$.id,ue=o.F(te,this.scope),xe=this._sourceCaches[te]=new al(ue,$,Z);Z===o.b4.Symbol?this._symbolSourceCaches[$.id]=xe:Z===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[$.id]=xe:this._otherSourceCaches[$.id]=xe,xe.onAdd(this.map)};G(o.b4.Other),C.type!=="vector"&&C.type!=="geojson"||(G(o.b4.Symbol),C.type==="vector"&&G(o.b4.FillExtrusion)),$.onAdd&&$.onAdd(this.map),R.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(y){this._checkLoaded();const C=this.getOwnSource(y);if(!C)throw new Error("There is no source with this ID");for(const $ in this._layers)if(this._layers[$].source===y)return this.fire(new o.B(new Error(`Source "${y}" cannot be removed while layer "${$}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===y)return this.fire(new o.B(new Error(`Source "${y}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const $=Object.entries(this.stylesheet.iconsets).find(([G,Z])=>Z.type==="source"&&Z.source===y);if($)return this.fire(new o.B(new Error(`Source "${y}" cannot be removed while iconset "${$[0]}" is using it.`)))}const R=this.getOwnSourceCaches(y);for(const $ of R){const G=o.da($.id);delete this._sourceCaches[G],this._changes.discardSourceCacheUpdate($.id),$.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:$.getSource().id})),$.setEventedParent(null),$.clearTiles()}return delete this._otherSourceCaches[y],delete this._symbolSourceCaches[y],delete this._fillExtrusionSourceCaches[y],this.mergeSources(),C.setEventedParent(null),C.onRemove&&C.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(y,C){this._checkLoaded(),this.getOwnSource(y).setData(C),this._changes.setDirty()}getOwnSource(y){const C=this.getOwnSourceCache(y);return C&&C.getSource()}getOwnSources(){const y=[];for(const C in this._otherSourceCaches){const R=this.getOwnSourceCache(C);R&&y.push(R.getSource())}return y}areTilesLoaded(){const y=this._mergedSourceCaches;for(const C in y){const R=y[C]._tiles;for(const $ in R){const G=R[$];if(G.state!=="loaded"&&G.state!=="errored")return!1}}return!0}setLights(y){if(this._checkLoaded(),!y)return delete this.ambientLight,void delete this.directionalLight;const C=this._getTransitionParameters();for(const G of y){if(this._validate(Oe,"lights",G))return;switch(G.type){case"ambient":if(this.ambientLight){const Z=this.ambientLight;Z.set(G),Z.updateTransitions(C)}else this.ambientLight=new jn(G,Aa(),this.scope,this.options);break;case"directional":if(this.directionalLight){const Z=this.directionalLight;Z.set(G),Z.updateTransitions(C)}else this.directionalLight=new jn(G,Bo(),this.scope,this.options)}}const R=Object.assign(C,{worldview:this.map.getWorldview()}),$=new o.ae(this.z||0,R);this.ambientLight&&this.ambientLight.recalculate($),this.directionalLight&&this.directionalLight.recalculate($),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const y=this.directionalLight,C=this.ambientLight;if(!y||!C)return;const R=Le=>.2126*(Le[0]<=.03928?Le[0]/12.92:Math.pow((Le[0]+.055)/1.055,2.4))+.7152*(Le[1]<=.03928?Le[1]/12.92:Math.pow((Le[1]+.055)/1.055,2.4))+.0722*(Le[2]<=.03928?Le[2]/12.92:Math.pow((Le[2]+.055)/1.055,2.4)),$=y.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),G=y.properties.get("intensity"),Z=y.properties.get("direction"),te=1-o.cP(Z.x,Z.y,Z.z)[2]/90,ue=R($)*G*te,xe=C.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),je=C.properties.get("intensity"),Re=R(xe)*je;return Number(((ue+Re)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const y=[];return this.directionalLight&&y.push(this.directionalLight.get()),this.ambientLight&&y.push(this.ambientLight.get()),y}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(y){if(y==null||y===""&&this.isRootStyle())return this;if(o.db(y)){const C=o.dc(y),R=this.fragments.find(({id:G})=>G===C);if(!R)return;const $=o.da(y);return R.style.getFragmentStyle($)}{const C=this.fragments.find(({id:R})=>R===y);return C?C.style:void 0}}setFeaturesetSelectors(y){if(!y)return;const C=(R,$="")=>`${R}::${$}`;this._featuresetSelectors={};for(const R in y){const $={},G=this._featuresetSelectors[R]=[];for(const Z of y[R].selectors){if(Z.featureNamespace){const ue=this.getOwnLayer(Z.layer);if(!ue){o.w(`Layer is undefined for selector: ${Z.layer}`);continue}const xe=C(ue.source,ue.sourceLayer);if(xe in $&&$[xe]!==Z.featureNamespace){o.w(`"featureNamespace ${Z.featureNamespace} of featureset ${R}'s selector is not associated to the same source, skip this selector`);continue}$[xe]=Z.featureNamespace}let te;if(Z.properties)for(const ue in Z.properties){const xe=o.X(Z.properties[ue]);xe.result==="success"&&(te=te||{},te[ue]=xe.value)}G.push({layerId:Z.layer,namespace:Z.featureNamespace,properties:te,uniqueFeatureID:Z._uniqueFeatureID})}}}getFeaturesetDescriptors(y){const C=this.getFragmentStyle(y);if(!C||!C.stylesheet.featuresets)return[];const R=[];for(const $ in C.stylesheet.featuresets)R.push({featuresetId:$,importId:C.scope?C.scope:void 0});return R}getFeaturesetLayers(y,C){const R=this.getFragmentStyle(C),$=R.stylesheet.featuresets;if(!$||!$[y])return this.fire(new o.B(new Error(`The featureset '${y}' does not exist in the map's style and cannot be queried.`))),[];const G=[];for(const Z of $[y].selectors){const te=R.getOwnLayer(Z.layer);te&&G.push(te)}return G}getConfigProperty(y,C){const R=this.getFragmentStyle(y);if(!R)return null;const $=o.F(C,R.scope),G=R.options.get($),Z=G?G.value||G.default:null;return Z?Z.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(y,C){const R=o.F(y,C);return this._mergedIndoor[R]}setIndoorData(y,C){this.indoorManager.setIndoorData(C)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(y,C,R){const $=this.getFragmentStyle(y);if(!$)return;const G=$.stylesheet.schema;if(!G||!G[C])return;const Z=o.X(R);if(Z.result!=="success")return void c1(this,Z.value);const te=Z.value.expression,ue=o.F(C,$.scope),xe=$.options.get(ue);if(!xe)return;let je;const{minValue:Re,maxValue:Le,stepValue:Ue,type:st,values:Xe}=G[C],pt=o.X(G[C].default);pt.result==="success"&&(je=pt.value.expression),je?(this.options.set(ue,Object.assign({},xe,{value:te,default:je,minValue:Re,maxValue:Le,stepValue:Ue,type:st,values:Xe})),this.updateConfigDependencies(C)):this.fire(new o.B(new Error(`No schema defined for the config option "${C}" in the "${y}" fragment.`)))}getConfig(y){const C=this.getFragmentStyle(y);if(!C)return null;const R=C.stylesheet.schema;if(!R)return null;const $={};for(const G in R){const Z=o.F(G,C.scope),te=C.options.get(Z),ue=te?te.value||te.default:null;$[G]=ue?ue.serialize():null}return $}setConfig(y,C){const R=this.getFragmentStyle(y);R&&(R.updateConfig(C,R.stylesheet.schema),this.updateConfigDependencies())}getSchema(y){const C=this.getFragmentStyle(y);return C?C.stylesheet.schema:null}setSchema(y,C){const R=this.getFragmentStyle(y);R&&(R.stylesheet.schema=C,R.updateConfig(R._config,C),this.updateConfigDependencies())}updateConfig(y,C){if(this._config=y,y||C)if(C)for(const R in C){let $,G;const Z=o.X(C[R].default);if(Z.result==="success"&&($=Z.value.expression),y&&y[R]!==void 0){const Le=o.X(y[R]);Le.result==="success"&&(G=Le.value.expression)}const{minValue:te,maxValue:ue,stepValue:xe,type:je,values:Re}=C[R];if($){const Le=o.F(R,this.scope);this.options.set(Le,{default:$,value:G,minValue:te,maxValue:ue,stepValue:xe,type:je,values:Re})}else this.fire(new o.B(new Error(`No schema defined for config option "${R}".`)))}else this.fire(new o.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(y,C=()=>!0){for(const R of y){const $=this.getLayer(R);$&&C($)&&($.possiblyEvaluateVisibility(),this._updateLayer($),this._changes.setDirty())}}updateConfigDependencies(y){this._updateLayers(this._configDependentLayers,C=>!y||C.expressionDependencies.configDependencies.has(y)),this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this.fog&&this.fog.updateConfig(this.options),this.snow&&this.snow.updateConfig(this.options),this.rain&&this.rain.updateConfig(this.options),this.forEachFragmentStyle(C=>{const R=C._styleColorTheme.colorThemeOverride?C._styleColorTheme.colorThemeOverride:C._styleColorTheme.colorTheme;if(R){const $=C._evaluateColorThemeData(R);(!C._styleColorTheme.lut&&$!==""||C._styleColorTheme.lut&&$!==C._styleColorTheme.lut.data)&&C.setColorTheme(R)}}),this._changes.setDirty()}addLayer(y,C,R={}){this._checkLoaded();const $=y.id;if(this._layers[$])return void this.fire(new o.B(new Error(`Layer with id "${$}" already exists on this map`)));let G;if(y.type==="custom"){if(c1(this,o.dd(y)))return;G=o.de(y,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof y.source=="object"&&(this.addSource($,y.source),y=o.d9(y),y=Object.assign(y,{source:$})),this._validate(qt,`layers.${$}`,y,{arrayIndex:-1},R))return;G=o.de(y,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(G),G.setEventedParent(this,{layer:{id:$}})}const Z=o.F(G.source,G.scope);G.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Z),G.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Z);let te=this._order.length;if(C){const Re=this._order.indexOf(C);if(Re===-1)return void this.fire(new o.B(new Error(`Layer with id "${C}" does not exist on this map.`)));G.slot&&G.slot!==this._layers[C].slot?o.w(`Layer with id "${C}" has a different slot. Layers can only be rearranged within the same slot.`):te=Re}this._order.splice(te,0,$),this._handleLayerOrderChange(),this._layers[$]=G;const ue=this.getOwnLayerSourceCache(G),xe=!!this.directionalLight&&this.directionalLight.shadowsEnabled();ue&&G.canCastShadows()&&xe&&(ue.castsShadows=!0);const je=this._changes.getRemovedLayer(G);if(je&&G.source&&ue&&G.type!=="custom"){this._changes.discardLayerRemoval(G);const Re=o.F(G.source,G.scope);je.type!==G.type?this._changes.updateSourceCache(Re,"clear"):(this._changes.updateSourceCache(Re,"reload"),ue.pause())}this._updateLayer(G),G.onAdd&&G.onAdd(this.map),G.scope=this.scope,this.mergeLayers()}moveLayer(y,C){this._checkLoaded();const R=this._checkLayer(y);if(!R||y===C)return;const $=this._order.indexOf(y);this._order.splice($,1);let G=this._order.length;if(C){const Z=this._order.indexOf(C);if(Z===-1)return void this.fire(new o.B(new Error(`Layer with id "${C}" does not exist on this map.`)));R.slot&&R.slot!==this._layers[C].slot?o.w(`Layer with id "${C}" has a different slot. Layers can only be rearranged within the same slot.`):G=Z}this._order.splice(G,0,y),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(y){this._checkLoaded();const C=this._checkLayer(y);if(!C)return;C.setEventedParent(null);const R=this._order.indexOf(y);this._order.splice(R,1),delete this._layers[y],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(C.fqid),this._indoorDependentLayers.delete(C.fqid),this._changes.removeLayer(C);const $=this.getOwnLayerSourceCache(C);if($&&$.castsShadows){let G=!1;for(const Z in this._layers)if(this._layers[Z].source===C.source&&this._layers[Z].canCastShadows()){G=!0;break}$.castsShadows=G}C.onRemove&&C.onRemove(this.map),this.mergeLayers()}getOwnLayer(y){return this._layers[y]}hasLayer(y){return y in this._mergedLayers}hasLayerType(y){for(const C in this._layers)if(this._layers[C].type===y)return!0;return!1}setLayerZoomRange(y,C,R){this._checkLoaded();const $=this._checkLayer(y);$&&($.minzoom===C&&$.maxzoom===R||(C!=null&&($.minzoom=C),R!=null&&($.maxzoom=R),this._updateLayer($)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(y,C){this._checkLoaded();const R=this._checkLayer(y);R&&R.slot!==C&&(R.slot=C,this._updateLayer(R))}setFilter(y,C,R={}){this._checkLoaded();const $=this._checkLayer(y);if($&&!o.b6($.filter,C))return C==null?($.filter=void 0,void this._updateLayer($)):void(this._validate(xs,`layers.${$.id}.filter`,C,{layerType:$.type},R)||($.filter=o.d9(C),this._updateLayer($)))}getFilter(y){const C=this._checkLayer(y);if(C)return o.d9(C.filter)}setLayoutProperty(y,C,R,$={}){this._checkLoaded();const G=this._checkLayer(y);if(G&&!o.b6(G.getLayoutProperty(C),R)){if(R!=null&&(!$||$.validate!==!1)&&c1(G,Ns.call($n,{key:`layers.${y}.layout.${C}`,layerType:G.type,objectKey:C,value:R,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;G.setLayoutProperty(C,R),G.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(G.fqid),G.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(G.fqid),this._updateLayer(G)}}setLayerProperty(y,C,R,$={}){this._checkLoaded();const G=this._checkLayer(y);G&&(C==="appearances"?(G.setAppearances(R),this._updateLayer(G)):G.isPaintProperty(C)?this.setPaintProperty(y,C,R,$):this.setLayoutProperty(y,C,R,$))}getLayoutProperty(y,C){const R=this._checkLayer(y);if(R)return R.getLayoutProperty(C)}setPaintProperty(y,C,R,$={}){this._checkLoaded();const G=this._checkLayer(y);if(!G||o.b6(G.getPaintProperty(C),R)||R!=null&&(!$||$.validate!==!1)&&c1(G,as.call($n,{key:`layers.${y}.paint.${C}`,layerType:G.type,objectKey:C,value:R,styleSpec:o.a8})))return;const Z=G.setPaintProperty(C,R);G.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(G.fqid),G.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(G.fqid),Z&&this._updateLayer(G),this._changes.updatePaintProperties(G)}getPaintProperty(y,C){const R=this._checkLayer(y);if(R)return R.getPaintProperty(C)}setFeatureState(y,C){if(this._checkLoaded(),"target"in y){if("featuresetId"in y.target){const{featuresetId:ue,importId:xe}=y.target,je=this.getFragmentStyle(xe),Re=je.getFeaturesetLayers(ue);for(const{source:Le,sourceLayer:Ue}of Re)je.setFeatureState({id:y.id,source:Le,sourceLayer:Ue},C)}else if("layerId"in y.target){const{layerId:ue}=y.target,xe=this.getLayer(ue);this.setFeatureState({id:y.id,source:xe.source,sourceLayer:xe.sourceLayer},C)}return}const R=y.source,$=y.sourceLayer,G=this._checkSource(R);if(!G)return;const Z=G.type;if(Z==="geojson"&&$)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(Z==="vector"&&!$)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));y.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided.")));const te=this.getOwnSourceCaches(R);for(const ue of te)ue.setFeatureState($,y.id,C)}removeFeatureState(y,C){if(this._checkLoaded(),"target"in y){if("featuresetId"in y.target){const{featuresetId:ue,importId:xe}=y.target,je=this.getFragmentStyle(xe),Re=je.getFeaturesetLayers(ue);for(const{source:Le,sourceLayer:Ue}of Re)je.removeFeatureState({id:y.id,source:Le,sourceLayer:Ue},C)}else if("layerId"in y.target){const{layerId:ue}=y.target,xe=this.getLayer(ue);this.removeFeatureState({id:y.id,source:xe.source,sourceLayer:xe.sourceLayer},C)}return}const R=y.source,$=this._checkSource(R);if(!$)return;const G=$.type,Z=G==="vector"?y.sourceLayer:void 0;if(G==="vector"&&!Z)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(C&&typeof y.id!="string"&&typeof y.id!="number")return void this.fire(new o.B(new Error("A feature id is required to remove its specific state property.")));const te=this.getOwnSourceCaches(R);for(const ue of te)ue.removeFeatureState(Z,y.id,C)}getFeatureState(y){if(this._checkLoaded(),"target"in y){let G;if("featuresetId"in y.target){const{featuresetId:Z,importId:te}=y.target,ue=this.getFragmentStyle(te),xe=ue.getFeaturesetLayers(Z);for(const{source:je,sourceLayer:Re}of xe){const Le=ue.getFeatureState({id:y.id,source:je,sourceLayer:Re});if(Le&&!G)G=Le;else if(!o.b6(G,Le))return void this.fire(new o.B(new Error("The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.")))}}else if("layerId"in y.target){const{layerId:Z}=y.target,te=this.getLayer(Z);G=this.getFeatureState({id:y.id,source:te.source,sourceLayer:te.sourceLayer})}return G}const C=y.source,R=y.sourceLayer,$=this._checkSource(C);if($){if($.type!=="vector"||R)return y.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(C)[0].getFeatureState(R,y.id);this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(y){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,y),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(y){y!==this._worldview&&(this._worldview=y,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const y=this.getTerrain(),C=y&&this.terrain&&this.terrain.scope===this.scope?y:this.stylesheet.terrain;return o.df({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,featuresets:this.stylesheet.featuresets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:C,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,indoor:this.stylesheet.indoor,center:this.stylesheet.center,"color-theme":this.stylesheet["color-theme"],zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},R=>R!==void 0)}_updateFilteredLayers(y){for(const C of Object.values(this._mergedLayers))y(C)&&this._updateLayer(C)}_updateLayer(y){this._changes.updateLayer(y);const C=this.getLayerSourceCache(y),R=o.F(y.source,y.scope),$=this._changes.getUpdatedSourceCaches();y.source&&!$[R]&&C&&C.getSource().type!=="raster"&&(this._changes.updateSourceCache(R,"reload"),C.pause()),y.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(y){const C=te=>this._mergedLayers[te].is3D(!!this.terrain),R=this.order,$={},G=[];for(let te=R.length-1;te>=0;te--){const ue=R[te];if(C(ue)){$[ue]=te;for(const xe of y){const je=xe[ue];if(je)for(const Re of je)G.push(Re)}}}G.sort((te,ue)=>ue.intersectionZ-te.intersectionZ);const Z=[];for(let te=R.length-1;te>=0;te--){const ue=R[te];if(C(ue))for(let xe=G.length-1;xe>=0;xe--){const je=G[xe].feature;if(je.layer&&$[je.layer.id]{if(pj.has(je.type))return;const Re=this.getOwnLayerSourceCache(je),Le=G[Re.id]=G[Re.id]||{sourceCache:Re,layers:{},has3DLayers:!1};je.is3D(!!this.terrain)&&(Le.has3DLayers=!0),Le.layers[je.fqid]=Le.layers[je.fqid]||{styleLayer:je,targets:[]},Le.layers[je.fqid].targets.push({filter:$})};if(C&&C.layers){if(!Array.isArray(C.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const je of C.layers){const Re=this._layers[je];if(!Re)return this.fire(new o.B(new Error(`The layer '${je}' does not exist in the map's style and cannot be queried for features.`))),[];Z(Re)}}else for(const je in this._layers)Z(this._layers[je]);const te=this._queryRenderedFeatures(y,G,R),ue=this._flattenAndSortRenderedFeatures(te),xe=[];for(const je of ue)o.dh(je.layer.id)===this.scope&&xe.push(je);return xe}queryRenderedFeatureset(y,C,R){let $;C&&!Array.isArray(C)&&C.filter&&(this._validate(xs,"queryRenderedFeatures.filter",C.filter,null,C),$=o.dg(C.filter));const G="mock",Z=[];if(C&&C.target)Z.push(Object.assign({},C,{targetId:G,filter:$}));else{const je=this.getFeaturesetDescriptors();for(const Re of je)Z.push({targetId:G,filter:$,target:Re});for(const{style:Re}of this.fragments){const Le=Re.getFeaturesetDescriptors();for(const Ue of Le)Z.push({targetId:G,filter:$,target:Ue})}}const te=this.queryRenderedTargets(y,Z,R),ue=[],xe=new Set;for(const je of te)for(const Re of je.variants[G])_h(Re,je,xe)||ue.push(new o.di(je,Re));return ue}queryRenderedTargets(y,C,R){const $={},G=(te,ue,xe,je)=>{const Re=$[ue.id]=$[ue.id]||{sourceCache:ue,layers:{},has3DLayers:!1};if(Re.layers[te.fqid]=Re.layers[te.fqid]||{styleLayer:te,targets:[]},te.is3D(!!this.terrain)&&(Re.has3DLayers=!0),!je)return xe.uniqueFeatureID=!1,void Re.layers[te.fqid].targets.push(xe);Re.layers[te.fqid].targets.push(Object.assign({},xe,{namespace:je.namespace,properties:je.properties,uniqueFeatureID:je.uniqueFeatureID}))};for(const te of C)if("featuresetId"in te.target){const{featuresetId:ue,importId:xe}=te.target,je=this.getFragmentStyle(xe);if(!je||!je._featuresetSelectors)continue;const Re=je._featuresetSelectors[ue];if(!Re){this.fire(new o.B(new Error(`The featureset '${ue}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const Le of Re){const Ue=je.getOwnLayer(Le.layerId);Ue&&!pj.has(Ue.type)&&G(Ue,je.getOwnLayerSourceCache(Ue),te,Le)}}else if("layerId"in te.target){const{layerId:ue}=te.target,xe=this.getLayer(ue);if(!xe||pj.has(xe.type))continue;G(xe,this.getLayerSourceCache(xe),te)}const Z=this._queryRenderedFeatures(y,$,R);return this._flattenAndSortRenderedFeatures(Z)}_queryRenderedFeatures(y,C,R){const $=[],G=!!this.map._showQueryGeometry,Z=rl.createFromScreenPoints(y,R);for(const te in C){const ue=px(Z,C[te],this._availableImages,R,G,this.getActualScope());Object.keys(ue).length&&$.push(ue)}if(this.placement)for(const te in C){if(C[te].sourceCache._renderSourceType!==o.b4.Symbol)continue;const ue=fo(Z.screenGeometry,C[te],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(ue).length&&$.push(ue)}return $}querySourceFeatures(y,C){const R=C&&C.filter;R&&this._validate(xs,"querySourceFeatures.filter",R,null,C);let $=[];const G=this.getOwnSourceCaches(y);for(const Z of G)$=$.concat(Vb(Z,C));return $}addSourceType(y,C,R){return Qc.getSourceType(y)?R(new Error(`A source type called "${y}" already exists.`)):(Qc.setSourceType(y,C),C.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:y,url:C.workerSourceURL},R):R(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(y,C,R={}){this._checkLoaded();const $=this.light.getLight();let G=!1;for(const te in y)if(!o.b6(y[te],$[te])){G=!0;break}if(!G)return;const Z=this._getTransitionParameters();this.light.setLight(y,C,R),this.light.updateTransitions(Z)}getTerrain(){return this.terrain&&this.terrain.drapeRenderMode===1?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=o.o.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&o.w("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(y,C=1){if(this._checkLoaded(),!y)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),C===0&&delete this.terrain,y===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let R=y;const $=!("source"in y)||y.source==null;if(C===1){if(this.disableElevatedTerrain)return;if("source"in R&&typeof R.source=="object"){const te="terrain-dem-src";this.addSource(te,R.source),R=o.d9(R),R=Object.assign(R,{source:te})}const G=Object.assign({},R),Z={};if(this.terrain&&$){G.source=this.terrain.get().source;const te=this.terrain?this.getFragmentStyle(this.terrain.scope):null;te&&(Z.style=te.serialize())}if(this._validate(Qe,"terrain",G,Z))return}if(!this.terrain||this.terrain.scope!==this.scope&&!$||this.terrain&&C!==this.terrain.drapeRenderMode){if(!R)return;this._createTerrain(R,C),this.fire(new o.C("data",{dataType:"style"}))}else{const G=this.terrain,Z=G.get();for(const te of Object.keys(o.a8.terrain))!R.hasOwnProperty(te)&&o.a8.terrain[te].default&&(R[te]=o.a8.terrain[te].default);for(const te in y)if(!o.b6(y[te],Z[te])){G.set(y,this.options),this.stylesheet.terrain=y;const ue=this._getTransitionParameters({duration:0});G.updateTransitions(ue),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(y){const C=this.fog=new wi(y,this.map.transform,this.scope,this.options);this.stylesheet.fog=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}_createSnow(y){const C=this.snow=new Mi(y,this.map.transform,this.scope,this.options);this.stylesheet.snow=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}_createRain(y){const C=this.rain=new da(y,this.map.transform,this.scope,this.options);this.stylesheet.rain=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const y of this.map._markers)y._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(y){if(this._checkLoaded(),!y)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const C=this.fog;if(!o.b6(C.get(),y)){C.set(y,this.options),this.stylesheet.fog=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}}else this._createFog(y);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(y){if(this._checkLoaded(),!y)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const C=this.snow;if(!o.b6(C.get(),y)){C.set(y,this.options),this.stylesheet.snow=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}}else this._createSnow(y);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(y){if(this._checkLoaded(),!y)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const C=this.rain;if(!o.b6(C.get(),y)){C.set(y,this.options),this.stylesheet.rain=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}}else this._createRain(y);this._markersNeedUpdate=!0}_reloadColorTheme(){const y=()=>{for(const $ in this._layers)this._layers[$].lut=this._styleColorTheme.lut;for(const $ in this._sourceCaches)this._sourceCaches[$].clearTiles()},C=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!C)return this._styleColorTheme.lut=null,void y();const R=this._evaluateColorThemeData(C);this._loadColorTheme(R).then(()=>{this.fire(new o.C("colorthemeset")),y()}).catch($=>{o.w(`Couldn't set color theme: ${$}`)})}setColorTheme(y){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=y,this._reloadColorTheme()}setImportColorTheme(y,C){const R=this.getFragmentStyle(y);R&&(R._styleColorTheme.colorThemeOverride=C,R._reloadColorTheme())}_getTransitionParameters(y){return{now:o.o.now(),transition:Object.assign(this.transition,y)}}updateDrapeFirstLayers(){if(!this.terrain)return;const y=[],C=[];for(const R of this._mergedOrder)this.isLayerDraped(this._mergedLayers[R])?y.push(R):C.push(R);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...y),this._drapedFirstOrder.push(...C)}_createTerrain(y,C){const R=this.terrain=new Ot(y,C,this.scope,this.options,this.map.getWorldview());C===1&&(this.stylesheet.terrain=y),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const $=this._getTransitionParameters({duration:0});R.updateTransitions($)}_force3DLayerUpdate(){for(const y in this._layers){const C=this._layers[y];C.type==="fill-extrusion"&&this._updateLayer(C)}}_forceSymbolLayerUpdate(){for(const y in this._layers){const C=this._layers[y];C.type==="symbol"&&this._updateLayer(C)}}_validate(y,C,R,$,G={}){if(G&&G.validate===!1)return!1;const Z=Object.assign({},this.serialize());return c1(this,y.call($n,Object.assign({key:C,style:Z,value:R,styleSpec:o.a8},$)))}_remove(){this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),o.dj.off("pluginStateChange",this._rtlTextPluginCallback);for(const y in this._mergedLayers)this._mergedLayers[y].setEventedParent(null);for(const y in this._mergedSourceCaches)this._mergedSourceCaches[y].clearTiles(),this._mergedSourceCaches[y].setEventedParent(null);this.imageManager.removeScope(this.scope),this.imageManager.imageAtlasCache.clear(),this.setEventedParent(null),delete this.fog,delete this.snow,delete this.rain,delete this.terrain,delete this.ambientLight,delete this.directionalLight,this.indoorManager.destroy(),this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.imageManager.destroy(),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(y){const C=this.getSourceCaches(y);for(const R of C)R.clearTiles()}clearSources(){for(const y in this._mergedSourceCaches)this._mergedSourceCaches[y].clearTiles()}clearLayers(){for(const y in this._mergedLayers){const C=this._mergedLayers[y];C._clear&&C._clear()}}reloadSource(y){const C=this.getSourceCaches(y);for(const R of C)R.resume(),R.reload()}reloadSources(){for(const y of this.getSources())y.reload&&y.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(y=>{y.modelManager.reloadModels(y.scope)})}updateSources(y){let C;this.directionalLight&&(C=DN(this.directionalLight));const R=new Set,$=new Set,G=new Set;for(const Z in this._mergedLayers){const te=this._mergedLayers[Z];te.type==="building"?R.add(te.source):te.type==="raster"&&te.paint&&te.paint.get("raster-elevation-reference")==="ground"&&G.add(te.source),te.hasElevation()&&!$.has(te.source)&&$.add(te.source)}for(const Z in this._mergedSourceCaches){const te=this._mergedSourceCaches[Z],ue=$.has(te._source.id);te._isRasterElevatedOverTerrain=G.has(te._source.id),R.has(te._source.id)&&(te._source.reparseOverscaled=!1),te.update(y,void 0,void 0,C,ue)}}_generateCollisionBoxes(){for(const y in this._sourceCaches){const C=this._sourceCaches[y];C.resume(),C.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new Yb),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(y,C,R,$,G){this.pauseablePlacement||(this.pauseablePlacement=new Yb);let Z=!1,te=!1;const ue={},xe={};for(const Xe of this._mergedOrder){const pt=this._mergedLayers[Xe];if(pt.type!=="symbol")continue;const mt=o.F(pt.source,pt.scope);let jt=ue[mt];if(!jt){const xt=this.getLayerSourceCache(pt);if(!xt)continue;const es=xt.getRenderableIds(!0).map(Ft=>xt.getTileByID(Ft));xe[mt]=es.slice(),jt=ue[mt]=es.sort((Ft,Jt)=>Jt.tileID.overscaledZ-Ft.tileID.overscaledZ||(Ft.tileID.isLessThan(Jt.tileID)?-1:1))}const Tt=this.crossTileSymbolIndex.addLayer(pt,jt,y.center.lng,y.projection);Z=Z||Tt}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const je=!!(this.placement&&!y.equals(this.placement.transform)),Re=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!G||this.placement.lastReplacementSourceUpdateTime!==G.updateTime)),Le=je||Re||Z,Ue=(Le||this.pauseablePlacement.isStale())&&R===0,st=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),y.zoom)&&R!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||Ue||st)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(y,this._mergedOrder,C,R,$,this.placement,this.fog&&y.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const Xe=this.map.painter.maxFrontCutoffRawStart;if(Xe>0){const pt=180*y.pitch/Math.PI;if(pt>=15){const mt=Math.min(1,Math.max(0,(pt-15)/5)),jt=mt*mt*(3-2*mt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-jt)+Xe*jt}}}if(this.pauseablePlacement.isDone()?Le&&R!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,ue,xe,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),te=!0),Z&&this.pauseablePlacement.setStale()),te||Z){this._buildingIndex.onNewFrame(y.zoom);for(let Xe=0;XeG===y.id)!==-1)return void this.fire(new o.B(new Error(`Import with id '${y.id}' already exists in the map's style.`)));if(!C)return R.push(y),this._loadImports([y],!0);const $=R.findIndex(({id:G})=>G===C);return $===-1&&this.fire(new o.B(new Error(`Import with id "${C}" does not exist on this map.`))),this.stylesheet.imports=R.slice(0,$).concat(y).concat(R.slice($)),this._loadImports([y],!0,C)}updateImport(y,C){this._checkLoaded();const R=this.stylesheet.imports||[],$=this.getImportIndex(y);return $===-1?this:typeof C=="string"?(this.setImportUrl(y,C),this):(C.url&&C.url!==R[$].url&&this.setImportUrl(y,C.url),o.b6(C.config,R[$].config)||this.setImportConfig(y,C.config,C.data.schema),o.b6(C.data,R[$].data)||this.setImportData(y,C.data),this)}moveImport(y,C){this._checkLoaded();let R=this.stylesheet.imports||[];const $=this.getImportIndex(y);if($===-1)return this;const G=this.getImportIndex(C);if(G===-1)return this;const Z=R[$],te=this.fragments[$];return R=R.filter(({id:ue})=>ue!==y),this.fragments=this.fragments.filter(({id:ue})=>ue!==y),this.stylesheet.imports=R.slice(0,G).concat(Z).concat(R.slice(G)),this.fragments=this.fragments.slice(0,G).concat(te).concat(this.fragments.slice(G)),this.mergeLayers(),this}setImportUrl(y,C){this._checkLoaded();const R=this.stylesheet.imports||[],$=this.getImportIndex(y);if($===-1)return this;R[$].url=C;const G=this.fragments[$];return G.style=this._createFragmentStyle(R[$]),G.style.on("style.import.load",()=>this.mergeAll()),G.style.loadURL(C),this}setImportData(y,C){this._checkLoaded();const R=this.getImportIndex(y),$=this.stylesheet.imports||[];return R===-1?this:C?(this.fragments[R].style.setState(C),this._reloadImports(),this):(delete $[R].data,this.setImportUrl(y,$[R].url))}setImportConfig(y,C,R){this._checkLoaded();const $=this.getImportIndex(y),G=this.stylesheet.imports||[];if($===-1)return this;C?G[$].config=C:delete G[$].config;const Z=this.fragments[$];R&&Z.style.stylesheet&&(Z.style.stylesheet.schema=R);const te=Z.style.stylesheet&&Z.style.stylesheet.schema;return Z.config=C,Z.style.updateConfig(C,te),this.updateConfigDependencies(),this}removeImport(y){this._checkLoaded();const C=this.stylesheet.imports||[],R=this.getImportIndex(y);R!==-1&&(C.splice(R,1),this.fragments[R].style._remove(),this.fragments.splice(R,1),this._reloadImports())}getImportIndex(y){const C=(this.stylesheet.imports||[]).findIndex(R=>R.id===y);return C===-1&&this.fire(new o.B(new Error(`Import '${y}' does not exist in the map's style and cannot be updated.`))),C}getLayer(y){return this._mergedLayers[y]}getSources(){const y=[];for(const C in this._mergedOtherSourceCaches){const R=this._mergedOtherSourceCaches[C];R&&y.push(R.getSource())}return y}getSource(y,C){const R=this.getSourceCache(y,C);return R&&R.getSource()}getLayerSource(y){const C=this.getLayerSourceCache(y);return C&&C.getSource()}getSourceCache(y,C){const R=o.F(y,C);return this._mergedOtherSourceCaches[R]}getLayerSourceCache(y){const C=o.F(y.source,y.scope);return y.type==="symbol"?this._mergedSymbolSourceCaches[C]:y.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[C]||this._mergedOtherSourceCaches[C]}getSourceCaches(y){if(y==null)return Object.values(this._mergedSourceCaches);const C=[];return this._mergedOtherSourceCaches[y]&&C.push(this._mergedOtherSourceCaches[y]),this._mergedSymbolSourceCaches[y]&&C.push(this._mergedSymbolSourceCaches[y]),this._mergedFillExtrusionSourceCaches[y]&&C.push(this._mergedFillExtrusionSourceCaches[y]),C}updateSourceCaches(){const y=this._changes.getUpdatedSourceCaches();for(const C in y){const R=y[C];R==="reload"?this.reloadSource(C):R==="clear"&&this.clearSource(C)}}updateLayers(y){const C=this._changes.getUpdatedPaintProperties();for(const R of C){const $=this.getLayer(R);$&&$.updateTransitions(y)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(y){this.stylesheet.glyphs=y,this.glyphManager.setURL(y)}getImages(y,C,R){this.imageManager.getImages(C.images,C.scope,R),this._updateTilesForChangedImages();const $=Z=>{if(Z){const te=C.images.map(ue=>o.I.toString(ue));Z.setDependencies(C.tileID.key,C.type,te)}},G=o.F(C.source,C.scope);$(this._mergedOtherSourceCaches[G]),$(this._mergedSymbolSourceCaches[G]),C.images.some(Z=>Z.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(y,C,R){this.imageManager.rasterizeImages(C,R)}checkAtlasCache(y,C,R){const $=this.imageManager.imageAtlasCache.findCachedAtlas(C.descriptor);R(null,$&&$.contentDescriptor?{iconPositions:$.iconPositions,patternPositions:$.patternPositions,sourceHash:$.contentDescriptor.hash}:null)}getGlyphs(y,C,R){this.glyphManager.getGlyphs(C.stacks,R)}getOwnSourceCache(y){return this._otherSourceCaches[y]}getOwnLayerSourceCache(y){return y.type==="symbol"?this._symbolSourceCaches[y.source]:y.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[y.source]||this._otherSourceCaches[y.source]}getOwnSourceCaches(y){const C=[];return this._otherSourceCaches[y]&&C.push(this._otherSourceCaches[y]),this._symbolSourceCaches[y]&&C.push(this._symbolSourceCaches[y]),this._fillExtrusionSourceCaches[y]&&C.push(this._fillExtrusionSourceCaches[y]),C}_isSourceCacheLoaded(y){const C=this.getOwnSourceCaches(y);return C.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${y}'`))),!1):C.every(R=>R.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(y,C){if(!this._clipLayerPresent&&y.type!=="fill-extrusion"&&y.type!=="building")return!1;const R=y.type==="fill-extrusion"&&(y.sourceLayer==="building"||y.sourceLayer==="procedural_buildings"),$=y.type==="building";if(y.is3D(!!this.terrain)){if(R||$||C&&C.type==="batched-model"||y.type==="model")return!0}else if(y.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(y=>{y.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}Qc.getSourceType=function(I){return Iy[I]},Qc.setSourceType=function(I,y){Iy[I]=y},Qc.registerForPluginStateChange=o.dk;var d1=` #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`,fj=` #ifdef DUAL_SOURCE_BLENDING layout(location=0,index=0) out vec4 glFragColor;layout(location=0,index=1) out vec4 glFragColorSrc1; #elif defined(FLOAT_RENDER_TARGET) layout(location=0) out highp vec4 glFragColor; #else layout(location=0) out vec4 glFragColor; #endif #ifdef USE_MRT1 layout(location=1) out vec4 out_Target1; #endif highp float unpack_depth(highp vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;}highp vec4 pack_depth(highp float ndc_z) {highp float depth=ndc_z*0.5+0.5;const highp vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const highp vec4 bit_mask =vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);highp vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} #ifdef INDICATOR_CUTOUT uniform vec3 u_indicator_cutout_centers;uniform vec4 u_indicator_cutout_params; #endif const float DITHER_THRESHOLDS[16]=float[16]( 1.0/17.0, 9.0/17.0, 3.0/17.0,11.0/17.0,13.0/17.0, 5.0/17.0,15.0/17.0, 7.0/17.0,4.0/17.0,12.0/17.0, 2.0/17.0,10.0/17.0,16.0/17.0, 8.0/17.0,14.0/17.0, 6.0/17.0 );vec4 applyCutout(vec4 color,float height) { #ifdef INDICATOR_CUTOUT float verticalFadeRange=u_indicator_cutout_centers.z*0.25;float holeMinOpacity=mix(1.0,u_indicator_cutout_params.x,smoothstep(u_indicator_cutout_centers.z,u_indicator_cutout_centers.z+verticalFadeRange,height));float holeRadius=max(u_indicator_cutout_params.y,0.0);float holeAspectRatio=u_indicator_cutout_params.z;float fadeStart=u_indicator_cutout_params.w;float distA=distance(vec2(gl_FragCoord.x,gl_FragCoord.y*holeAspectRatio),vec2(u_indicator_cutout_centers[0],u_indicator_cutout_centers[1]*holeAspectRatio));return color*min(smoothstep(fadeStart,holeRadius,distA)+holeMinOpacity,1.0); #else return color; #endif }float cutoutGroundRoofOpacity(vec4 groundRoof) { #ifdef INDICATOR_CUTOUT float fadeStartX=u_indicator_cutout_params.w;float holeRadius=u_indicator_cutout_params.y;float holeMinOpacity=mix(u_indicator_cutout_params.x,1.0,smoothstep(u_indicator_cutout_params.z,u_indicator_cutout_centers.z,groundRoof.y));float distX=abs(u_indicator_cutout_centers.x-groundRoof.x);float roofOpacity=mix(holeMinOpacity,1.0,smoothstep(fadeStartX,holeRadius,u_indicator_cutout_centers.y-groundRoof.w));float groundOpacity=min(smoothstep(fadeStartX,holeRadius,distX)+holeMinOpacity,1.0);return max(roofOpacity,groundOpacity); #else return 1.0; #endif } #ifdef DEBUG_WIREFRAME #define HANDLE_WIREFRAME_DEBUG \\ glFragColor=vec4(0.7,0.0,0.0,0.7); \\ gl_FragDepth=gl_FragCoord.z-0.0001; #else #define HANDLE_WIREFRAME_DEBUG #endif #ifdef RENDER_CUTOFF uniform highp vec4 u_cutoff_params;in float v_cutoff_opacity; #endif vec4 textureLodCustom(sampler2D image,highp vec2 pos,highp vec2 lod_coord) {highp vec2 size=vec2(textureSize(image,0));highp vec2 dx=dFdx(lod_coord.xy*size);highp vec2 dy=dFdy(lod_coord.xy*size);highp float delta_max_sqr=max(dot(dx,dx),dot(dy,dy));highp float lod=0.5*log2(delta_max_sqr);return textureLod(image,pos,lod);}vec4 applyLUT(highp sampler3D lut,vec4 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return vec4(texture(lut,uvw).rgb*col.a,col.a);}vec3 applyLUT(highp sampler3D lut,vec3 col) {return applyLUT(lut,vec4(col,1.0)).rgb;}`,pg=` #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`,Jb="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;}",ON=` #define ELEVATION_SCALE 7.0 #define ELEVATION_OFFSET 450.0 #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_tl_up;uniform vec3 u_tile_tr_up;uniform vec3 u_tile_br_up;uniform vec3 u_tile_bl_up;uniform float u_tile_up_scale;vec3 elevationVector(vec2 pos) {vec2 uv=pos/EXTENT;vec3 up=normalize(mix( mix(u_tile_tl_up,u_tile_tr_up,uv.xxx),mix(u_tile_bl_up,u_tile_br_up,uv.xxx),uv.yyy));return up*u_tile_up_scale;} #else vec3 elevationVector(vec2 pos) { return vec3(0,0,1); } #endif #ifdef TERRAIN uniform highp sampler2D u_dem;uniform highp sampler2D u_dem_prev;uniform vec2 u_dem_tl;uniform vec2 u_dem_tl_prev;uniform float u_dem_scale;uniform float u_dem_scale_prev;uniform float u_dem_size;uniform float u_dem_lerp;uniform float u_exaggeration;uniform float u_meter_to_dem;uniform mat4 u_label_plane_matrix_inv;vec4 tileUvToDemSample(vec2 uv,float dem_size,float dem_scale,vec2 dem_tl) {vec2 pos=dem_size*(uv*dem_scale+dem_tl)+1.0;vec2 f=fract(pos);return vec4((pos-f+0.5)/(dem_size+2.0),f);}float currentElevation(vec2 apos) { #ifdef TERRAIN_DEM_FLOAT_FORMAT vec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale+u_dem_tl)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem,pos).r; #else float dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale,u_dem_tl);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(dd,0)).r;float bl=texture(u_dem,pos+vec2(0,dd)).r;float br=texture(u_dem,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y); #endif }float prevElevation(vec2 apos) { #ifdef TERRAIN_DEM_FLOAT_FORMAT vec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale_prev+u_dem_tl_prev)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem_prev,pos).r; #else float dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale_prev,u_dem_tl_prev);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem_prev,pos).r;float tr=texture(u_dem_prev,pos+vec2(dd,0)).r;float bl=texture(u_dem_prev,pos+vec2(0,dd)).r;float br=texture(u_dem_prev,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y); #endif } #ifdef TERRAIN_VERTEX_MORPHING float elevation(vec2 apos) { #ifdef ZERO_EXAGGERATION return 0.0; #endif float nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp);} #else float elevation(vec2 apos) { #ifdef ZERO_EXAGGERATION return 0.0; #endif return currentElevation(apos);} #endif vec4 fourSample(vec2 pos,vec2 off) {float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(off.x,0.0)).r;float bl=texture(u_dem,pos+vec2(0.0,off.y)).r;float br=texture(u_dem,pos+off).r;return vec4(tl,tr,bl,br);}float flatElevation(vec2 pack) {vec2 apos=floor(pack/8.0);vec2 span=10.0*(pack-apos*8.0);vec2 uvTex=(apos-vec2(1.0,1.0))/8190.0;float size=u_dem_size+2.0;float dd=1.0/size;vec2 pos=u_dem_size*(uvTex*u_dem_scale+u_dem_tl)+1.0;vec2 f=fract(pos);pos=(pos-f+0.5)*dd;vec4 h=fourSample(pos,vec2(dd));float z=mix(mix(h.x,h.y,f.x),mix(h.z,h.w,f.x),f.y);vec2 w=floor(0.5*(span*u_meter_to_dem-1.0));vec2 d=dd*w;h=fourSample(pos-d,2.0*d+vec2(dd));vec4 diff=abs(h.xzxy-h.ywzw);vec2 slope=min(vec2(0.25),u_meter_to_dem*0.5*(diff.xz+diff.yw)/(2.0*w+vec2(1.0)));vec2 fix=slope*span;float base=z+max(fix.x,fix.y);return u_exaggeration*base;}float elevationFromUint16(float word) {return u_exaggeration*(word/ELEVATION_SCALE-ELEVATION_OFFSET);} #else float elevation(vec2 pos) { return 0.0; } #endif #ifdef DEPTH_OCCLUSION uniform highp sampler2D u_depth;uniform highp vec2 u_depth_size_inv;uniform highp vec2 u_depth_range_unpack;uniform highp float u_occluder_half_size;uniform highp float u_occlusion_depth_offset; #ifdef DEPTH_D24 float unpack_depth(float depth) {return depth*u_depth_range_unpack.x+u_depth_range_unpack.y;}vec4 unpack_depth4(vec4 depth) {return depth*u_depth_range_unpack.x+vec4(u_depth_range_unpack.y);} #else highp float unpack_depth_rgba(vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;} #endif bool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif #ifdef DEPTH_D24 float depth=unpack_depth(texture(u_depth,(coord.xy+1.0)*0.5).r); #else float depth=unpack_depth_rgba(texture(u_depth,(coord.xy+1.0)*0.5)); #endif return coord.z+u_occlusion_depth_offset > depth;}highp vec4 getCornerDepths(vec2 coord) {highp vec3 df=vec3(u_occluder_half_size*u_depth_size_inv,0.0);highp vec2 uv=0.5*coord.xy+0.5; #ifdef DEPTH_D24 highp vec4 depth=vec4( texture(u_depth,uv-df.xz).r,texture(u_depth,uv+df.xz).r,texture(u_depth,uv-df.zy).r,texture(u_depth,uv+df.zy).r );depth=unpack_depth4(depth); #else highp vec4 depth=vec4( unpack_depth_rgba(texture(u_depth,uv-df.xz)),unpack_depth_rgba(texture(u_depth,uv+df.xz)),unpack_depth_rgba(texture(u_depth,uv-df.zy)),unpack_depth_rgba(texture(u_depth,uv+df.zy)) ); #endif return depth;}highp float occlusionFadeMultiSample(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec2 uv=0.5*coord.xy+0.5; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif int NX=3;int NY=4;highp vec2 df=u_occluder_half_size*u_depth_size_inv;highp vec2 oneStep=2.0*u_occluder_half_size*u_depth_size_inv/vec2(NX-1,NY-1);highp float res=0.0;for (int y=0; y < NY;++y) {for (int x=0; x < NX;++x) { #ifdef DEPTH_D24 highp float depth=unpack_depth(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y)).r); #else highp float depth=unpack_depth_rgba(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y))); #endif res+=1.0-clamp(300.0*(coord.z+u_occlusion_depth_offset-depth),0.0,1.0);}}res=clamp(2.0*res/float(NX*NY)-0.5,0.0,1.0);return res;}highp float occlusionFade(vec4 frag) {highp vec3 coord=frag.xyz/frag.w; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif highp vec4 depth=getCornerDepths(coord.xy);return dot(vec4(0.25),vec4(1.0)-clamp(300.0*(vec4(coord.z+u_occlusion_depth_offset)-depth),0.0,1.0));} #else bool isOccluded(vec4 frag) { return false; }highp float occlusionFade(vec4 frag) { return 1.0; }highp float occlusionFadeMultiSample(vec4 frag) { return 1.0; } #endif`,FN=`#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`,u1=`#ifdef FOG uniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump vec2 u_fog_vertical_limit;uniform mediump float u_fog_temporal_offset;in vec3 v_fog_pos;uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform highp vec2 u_viewport;uniform float u_globe_transition;uniform int u_is_globe;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}float globe_glow_progress() {highp vec2 uv=gl_FragCoord.xy/u_viewport; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif highp vec3 ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float sdf=length(closest_point-u_globe_pos)/u_globe_radius;return sdf+PI*0.5;}float fog_opacity(vec3 pos) {float depth=length(pos);return fog_opacity(fog_range(depth));}vec3 fog_apply(vec3 color,vec3 pos,float opacity_limit) {float depth=length(pos);float opacity;if (u_is_globe==1) {float glow_progress=globe_glow_progress();float t=mix(glow_progress,depth,u_globe_transition);opacity=fog_opacity(fog_range(t));} else {opacity=fog_opacity(fog_range(depth));opacity*=fog_horizon_blending(pos/depth);}return mix(color,u_fog_color.rgb,min(opacity,opacity_limit));}vec3 fog_apply(vec3 color,vec3 pos) {return fog_apply(color,pos,1.0);}vec4 fog_apply_from_vert(vec4 color,float fog_opac) {float alpha=EPSILON+color.a;color.rgb=mix(color.rgb/alpha,u_fog_color.rgb,fog_opac)*alpha;return color;}vec3 fog_apply_sky_gradient(vec3 camera_ray,vec3 sky_color) {float horizon_blend=fog_horizon_blending(normalize(camera_ray));return mix(sky_color,u_fog_color.rgb,horizon_blend);}vec4 fog_apply_premultiplied(vec4 color,vec3 pos) {float alpha=EPSILON+color.a;color.rgb=fog_apply(color.rgb/alpha,pos)*alpha;return color;}vec4 fog_apply_premultiplied(vec4 color,vec3 pos,float heightMeters) {float verticalProgress=(u_fog_vertical_limit.x > 0.0 || u_fog_vertical_limit.y > 0.0) ? smoothstep(u_fog_vertical_limit.x,u_fog_vertical_limit.y,heightMeters) : 0.0;float opacityLimit=1.0-smoothstep(0.9,1.0,fog_opacity(pos));return mix(fog_apply_premultiplied(color,pos),color,min(verticalProgress,opacityLimit));}vec3 fog_dither(vec3 color) {return color;}vec4 fog_dither(vec4 color) {return vec4(fog_dither(color.rgb),color.a);} #endif`,h1=`#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`,zN=`#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;}`,xj=`#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`,op=`#ifdef RENDER_SHADOWS precision highp sampler2DShadow;uniform sampler2DShadow u_shadowmap_0;uniform sampler2DShadow u_shadowmap_1;uniform float u_shadow_intensity;uniform float u_shadow_map_resolution;uniform float u_shadow_texel_size;uniform highp vec3 u_shadow_normal_offset;uniform vec2 u_fade_range;uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_bias;float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) { #ifdef CLIP_ZERO_TO_ONE highp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z-bias); #else highp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z*0.5+0.5-bias); #endif return texture(shadowmap,coord);}float shadow_occlusion(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,highp float bias) {light_view_pos0.xyz/=light_view_pos0.w; #ifdef SHADOWS_SINGLE_CASCADE vec2 abs_bounds=abs(light_view_pos0.xy);if (abs_bounds.x >=1.0 || abs_bounds.y >=1.0) {return 0.0;}return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias); #else light_view_pos1.xyz/=light_view_pos1.w;vec4 abs_bounds=abs(vec4(light_view_pos0.xy,light_view_pos1.xy));if (abs_bounds.x < 1.0 && abs_bounds.y < 1.0) {return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias);}if (abs_bounds.z >=1.0 || abs_bounds.w >=1.0) {return 0.0;}float occlusion1=shadow_sample(u_shadowmap_1,light_view_pos1.xyz,bias);return clamp(mix(occlusion1,0.0,smoothstep(u_fade_range.x,u_fade_range.y,view_depth)),0.0,1.0); #endif }highp float calculate_shadow_bias(float NDotL) { #ifdef NORMAL_OFFSET return 0.5*u_shadow_bias.x; #else return 0.5*(u_shadow_bias.x+clamp(u_shadow_bias.y*tan(acos(NDotL)),0.0,u_shadow_bias.z)); #endif }float shadowed_light_factor_normal(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_opacity(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,float shadow_opacity) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias)*shadow_opacity;return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_unbiased(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}highp vec2 compute_receiver_plane_depth_bias(highp vec3 pos_dx,highp vec3 pos_dy) {highp vec2 biasUV=vec2( pos_dy.y*pos_dx.z-pos_dx.y*pos_dy.z,pos_dx.x*pos_dy.z-pos_dy.x*pos_dx.z);biasUV*=1.0/((pos_dx.x*pos_dy.y)-(pos_dx.y*pos_dy.x));return biasUV;}float shadowed_light_factor_plane_bias(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {highp vec3 light_view_pos0_xyz=light_view_pos0.xyz/light_view_pos0.w*0.5+0.5;highp vec3 light_view_pos0_ddx=dFdx(light_view_pos0_xyz);highp vec3 light_view_pos0_ddy=dFdy(light_view_pos0_xyz);highp vec2 plane_depth_bias=compute_receiver_plane_depth_bias(light_view_pos0_ddx,light_view_pos0_ddy);highp float bias=dot(vec2(u_shadow_texel_size,u_shadow_texel_size),plane_depth_bias)+0.0001;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadowed_light_factor(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadow_occlusion(float ndotl,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=calculate_shadow_bias(ndotl);return shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);} #endif`;const f0=/#include\s+"([^"]+)"/g,Bn=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,gj=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,yj=new Set(["ifdef","ifndef","elif","if","defined"]),$y=new Set;fg(d1,$y),fg(pg,$y),fg(fj,$y);const $p={"_prelude_fog.vertex.glsl":FN,"_prelude_terrain.vertex.glsl":ON,"_prelude_shadow.vertex.glsl":xj,"_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":u1,"_prelude_shadow.fragment.glsl":op,"_prelude_lighting.glsl":` #ifdef LIGHTING_3D_MODE uniform mediump vec3 u_lighting_ambient_color;uniform mediump vec3 u_lighting_directional_dir;uniform mediump vec3 u_lighting_directional_color;uniform mediump vec3 u_ground_radiance;float calculate_ambient_directional_factor(vec3 normal) {float NdotL=dot(normal,u_lighting_directional_dir);const float factor_reduction_max=0.3;float dir_luminance=dot(u_lighting_directional_color,vec3(0.2126,0.7152,0.0722));float directional_factor_min=1.0-factor_reduction_max*min(dir_luminance,1.0);float ambient_directional_factor=mix(directional_factor_min,1.0,min((NdotL+1.0),1.0));const float vertical_factor_min=0.92;float vertical_factor=mix(vertical_factor_min,1.0,normal.z*0.5+0.5);return vertical_factor*ambient_directional_factor;}vec3 linearProduct(vec3 srgbIn,vec3 k) {return srgbIn*pow(k,vec3(1./2.2));}vec3 apply_lighting(vec3 color,vec3 normal,float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return linearProduct(color,ambient_contrib+directional_contrib);}vec4 apply_lighting(vec4 color,vec3 normal,float dir_factor) {return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting(vec3 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return apply_lighting(color.rgb,normal,dir_factor);}vec4 apply_lighting(vec4 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting_ground(vec3 color) {return color*u_ground_radiance;}vec4 apply_lighting_ground(vec4 color) {return vec4(apply_lighting_ground(color.rgb),color.a);}float calculate_NdotL(vec3 normal) {const float ext=0.70710678118;return (clamp(dot(normal,u_lighting_directional_dir),-ext,1.0)+ext)/(1.0+ext);}vec4 apply_lighting_with_emission_ground(vec4 color,float emissive_strength) {return mix(apply_lighting_ground(color),color,emissive_strength);}vec3 compute_flood_lighting(vec3 flood_light_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=flood_light_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);float occlusion_ramp=smoothstep(0.0,0.2,1.0-occlusion);return mix(fully_occluded_color,flood_light_color,occlusion_ramp);}vec3 compute_emissive_draped(vec3 unlit_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=unlit_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);return mix(fully_occluded_color,unlit_color,1.0-occlusion);} #endif`,"_prelude_raster_array.glsl":h1,"_prelude_raster_particle.glsl":zN},m1={};gi("",ON),gi(u1,FN),gi(op,xj),gi(h1,""),gi(zN,"");const x0=gi(fj,pg),e_=d1,p1=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",e_,x0.fragmentSource].join(` `),yC=["precision highp float;",e_,x0.vertexSource].join(` `);var vC={background:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec4 u_color;uniform float u_opacity;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE in vec4 v_color; #endif void main() {vec4 out_color; #ifdef FEATURE_CUTOUT vec2 uv=gl_FragCoord.xy*u_inv_viewport_size.xy; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif float factorTex=min(texture(u_cutout_factor_image,uv).r,1.0);float cutoutFactor=(1.0-u_feature_cutout_params.x)*factorTex;out_color=u_color*(1.0-cutoutFactor); #else #ifdef LIGHTING_3D_MODE out_color=v_color; #else out_color=u_color; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #endif glFragColor=out_color*u_opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_lighting.glsl" in ivec2 a_pos;uniform mat4 u_matrix;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE uniform mediump vec4 u_color;out vec4 v_color; #endif void main() {gl_Position=u_matrix*vec4(a_pos,0,1); #ifndef FEATURE_CUTOUT #ifdef LIGHTING_3D_MODE v_color=apply_lighting_with_emission_ground(u_color,u_emissive_strength); #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #endif }`),backgroundPattern:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec2 u_pattern_tl;uniform vec2 u_pattern_br;uniform vec2 u_texsize;uniform float u_opacity;uniform float u_emissive_strength;uniform sampler2D u_image;in highp vec2 v_pos;void main() {highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(u_pattern_tl/u_texsize,u_pattern_br/u_texsize,imagecoord);vec4 out_color=textureLodCustom(u_image,pos,v_pos); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*u_opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pattern_size;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec2 u_pattern_units_to_pixels;in ivec2 a_pos;out highp vec2 v_pos;void main() {vec2 pos=vec2(a_pos);gl_Position=u_matrix*vec4(pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_pattern_units_to_pixels,pos); #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),building:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" const float window_depth=0.5;const float ao_radius=0.2;in vec4 v_color;in highp vec3 v_normal;in highp vec3 v_pos; #ifdef RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #endif #ifdef BUILDING_FAUX_FACADE in lowp float v_faux_facade;in highp float v_faux_facade_ed;in highp vec2 v_faux_facade_window;in highp vec2 v_faux_facade_floor;in highp vec2 v_faux_facade_range;in highp float v_aspect;in highp vec3 v_tbn_0;in highp vec3 v_tbn_1;in highp vec3 v_tbn_2;in highp vec4 v_faux_color_emissive;uniform float u_faux_facade_ao_intensity; #endif #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT in highp float v_flood_radius;in float v_has_flood_light; #endif uniform lowp float u_opacity;uniform vec3 u_camera_pos;uniform highp float u_tile_to_meter;uniform float u_facade_emissive_chance;uniform vec3 u_flood_light_color;uniform float u_flood_light_intensity;vec3 linearTosRGB(in vec3 color) {return pow(color,vec3(1./2.2));} #ifdef BUILDING_FAUX_FACADE highp float hash12(in highp vec2 p) {highp vec3 p3 =fract(vec3(p.xyx)*0.1031);p3+=dot(p3,p3.yzx+33.33);return fract((p3.x+p3.y)*p3.z);}float min3(in vec3 v) {return min(min(v.x,v.y),v.z);}highp vec2 get_uv_mask_id(in highp vec2 q,out highp float mask,out highp vec2 id) {highp vec2 p=q;mask=step(v_faux_facade_range.x,p.y)*step(p.y,v_faux_facade_range.y);p.y=p.y-v_faux_facade_range.x;highp vec2 uv=modf(p/v_faux_facade_floor,id);highp vec4 d=(v_faux_facade_floor.xyxy+vec4(-v_faux_facade_window,v_faux_facade_window))*0.5;highp vec4 edge=d/v_faux_facade_floor.xyxy;highp vec2 m=step(edge.xy,uv)*step(uv,edge.zw);mask*=m.x*m.y;uv-=vec2(0.5);uv*=vec2(0.5)/(vec2(0.5)-edge.xy);uv+=vec2(0.5);return uv;}highp float ray_unit_box(in highp vec3 ray_o,in highp vec3 ray_d,in highp vec3 bmin,in highp vec3 bmax) {highp vec3 planes=mix(bmin,bmax,step(0.0,ray_d));highp vec3 t=(planes-ray_o)/ray_d;return min3(t);}float get_emissive(in vec2 id) {if (u_facade_emissive_chance > 0.0) {return (step(hash12(id),u_facade_emissive_chance)+0.05)*v_faux_color_emissive.a;}return 0.0;}vec3 get_shade_info(in highp vec3 v,in highp vec3 v_normalized,in vec3 color,in vec2 id,in mat3 tbn,inout vec3 out_normal,inout float out_emissive) {vec3 out_color=color;highp vec3 abs_v=abs(v_normalized);bool x_major=abs_v.x >=abs_v.y && abs_v.x >=abs_v.z;bool y_major=abs_v.y >=abs_v.x && abs_v.y >=abs_v.z;bool z_major=abs_v.z >=abs_v.x && abs_v.z >=abs_v.y; #if 0 if (x_major) {out_color=v.x > 0.0 ? vec3(1.0,0.0,0.0) : vec3(0.0,1.0,1.0);} else if (y_major) {out_color=v.y > 0.0 ? vec3(0.0,1.0,0.0) : vec3(1.0,0.0,1.0);} else if (z_major) {out_color=v.z > 0.0 ? vec3(0.0,0.0,1.0) : vec3(1.0,1.0,0.0);}out_emissive=1.0; #else if (x_major) {out_normal=-sign(v.x)*tbn[0];} else if (y_major) {out_normal=vec3(0.0,0.0,-sign(v.y));} else if (z_major) {out_color=v_faux_color_emissive.rgb;out_emissive=v.z <=0.0 ? get_emissive(id) : out_emissive;}float ao=1.0;if (u_faux_facade_ao_intensity > 0.0) {vec4 ao_range=v_faux_facade_window.xxyy*0.5-vec4(0,ao_radius,0,ao_radius);vec2 ao_range_z=vec2(window_depth*0.5)-vec2(0.0,ao_radius);if (x_major || y_major) {ao*=smoothstep(-ao_range_z.x,-ao_range_z.y,v.z);} else if (z_major) {ao*=smoothstep(-ao_range.x,-ao_range.y,v.x)*(1.0-smoothstep(ao_range.y,ao_range.x,v.x));ao*=smoothstep(-ao_range.z,-ao_range.w,v.y)*(1.0-smoothstep(ao_range.w,ao_range.z,v.y));}ao=mix(1.0,min(1.0,ao+0.25),u_faux_facade_ao_intensity);}out_color*=ao; #endif return out_color;} #endif vec3 apply_lighting_linear(in vec3 color,in vec3 normal,in float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return color*(ambient_contrib+directional_contrib);}void main() {vec3 normal=normalize(v_normal);vec3 base_color=v_color.rgb;float emissive=v_color.a; #ifdef BUILDING_FAUX_FACADE if (v_faux_facade > 0.0) {highp mat3 tbn=mat3(v_tbn_0,v_tbn_1,v_tbn_2);highp vec3 v=vec3(v_pos.xy,v_pos.z/u_tile_to_meter)-u_camera_pos;highp vec3 view_tangent=transpose(tbn)*v;highp vec2 q=vec2(v_faux_facade_ed,v_pos.z);float mask=0.0;vec2 id=vec2(0.0);highp vec2 uv=get_uv_mask_id(q,mask,id);uv*=v_faux_facade_window;highp vec3 bmin=vec3(0.0,0.0,-window_depth);highp vec3 bmax=bmin+vec3(v_faux_facade_window,window_depth);highp vec3 ray_o=vec3(uv,0.0);highp vec3 ray_d=normalize(view_tangent);highp float t_min=ray_unit_box(ray_o,ray_d,bmin,bmax);highp vec3 hit=ray_o+t_min*ray_d;highp vec3 r=vec3(v_faux_facade_window,-window_depth);hit-=r*0.5;highp vec3 normalized=hit/r;vec3 out_normal=normal;float out_emissive=emissive;vec3 room_color=get_shade_info(hit,normalized,base_color,id,tbn,out_normal,out_emissive);base_color=mix(base_color,room_color,mask);normal=mix(normal,out_normal,mask);emissive=mix(emissive,out_emissive,mask);} #endif vec4 color=vec4(base_color,1.0);vec3 xy_flipped_normal=vec3(-normal.xy,normal.z);float shadowed_lighting_factor=0.0; #ifdef RENDER_SHADOWS #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif #else shadowed_lighting_factor=max(0.0,dot(xy_flipped_normal,u_lighting_directional_dir)); #endif color.rgb=apply_lighting_linear(color.rgb,xy_flipped_normal,shadowed_lighting_factor);color.rgb=linearTosRGB(color.rgb); #ifdef FLOOD_LIGHT float flood_radiance=(1.0-min(v_pos.z/v_flood_radius,1.0))*u_flood_light_intensity*v_has_flood_light;color.rgb=mix(color.rgb,u_flood_light_color,flood_radiance); #endif color.rgb=mix(color.rgb,linearTosRGB(base_color.rgb),emissive); #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,v_pos.z)); #endif color*=u_opacity; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (ditherOpacity < DITHER_THRESHOLDS[index]) {discard;}}} #else color=applyCutout(color,v_pos.z); #endif #endif #ifdef RENDER_FRONT_CUTOFF if (v_front_cutoff_opacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (v_front_cutoff_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif glFragColor=color; #ifdef DEBUG_SHOW_NORMALS color.rgb=xy_flipped_normal*0.5+vec3(0.5,0.5,0.5);color.a=1.0;glFragColor=color; #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec3 a_pos_3f;in ivec4 a_normal_3;in ivec4 a_centroid_3; #ifdef FLOOD_LIGHT in int a_flood_light_wall_radius_1i16; #endif #ifdef BUILDING_FAUX_FACADE in uvec4 a_faux_facade_data;in uvec2 a_faux_facade_vertical_range; #endif uniform mat4 u_matrix;uniform mat4 u_normal_matrix;uniform highp float u_tile_to_meter; #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params;out float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT out vec4 v_ground_roof; #endif #endif out vec4 v_color;out vec3 v_normal;out highp vec3 v_pos; #ifdef BUILDING_FAUX_FACADE out lowp float v_faux_facade;out highp float v_faux_facade_ed;out highp vec2 v_faux_facade_window;out highp vec2 v_faux_facade_floor;out highp vec2 v_faux_facade_range;out highp float v_aspect;out highp vec3 v_tbn_0;out highp vec3 v_tbn_1;out highp vec3 v_tbn_2;out highp vec4 v_faux_color_emissive; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT out highp float v_flood_radius;out float v_has_flood_light; #endif const float MAX_UINT_16=65535.0;const float MAX_INT_16=32767.0;const float MAX_UINT_8=255.0;const float TWO_POW_8=256.0;const float FLOOD_LIGHT_MAX_RADIUS_METER=2048.0;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #ifdef BUILDING_FAUX_FACADE mat3 get_tbn(in vec3 normal) {const vec3 bitangent=vec3(0.0,0.0,1.0);vec3 tangent=normalize(vec3(normal.y,-normal.x,0.0));return mat3(tangent,bitangent,normal);} #endif #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 part_color_emissive #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 faux_facade_color_emissive void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute-custom highp uvec2 faux_facade_color_emissive #ifdef FLOOD_LIGHT v_flood_radius=(float(a_flood_light_wall_radius_1i16)/MAX_INT_16*FLOOD_LIGHT_MAX_RADIUS_METER);v_has_flood_light=step(0.0,v_flood_radius); #endif vec4 color_emissive=decode_color(vec2(part_color_emissive));v_color=vec4(sRGBToLinear(color_emissive.rgb),color_emissive.a);vec3 a_normal_3f=vec3(a_normal_3)/MAX_INT_16;v_normal=vec3(u_normal_matrix*vec4(a_normal_3f,0.0));float hidden=0.0;float depth_offset=0.0;vec2 centroid_xy=vec2(a_centroid_3.xy >> 2);vec2 spanBits=vec2(a_centroid_3.xy & 3); #ifdef BUILDING_FAUX_FACADE vec4 faux_facade_data=vec4(a_faux_facade_data);v_faux_facade=faux_facade_data.x;if (v_faux_facade > 0.0) {v_faux_facade_ed=faux_facade_data.x *u_tile_to_meter;float window_x_perc=floor(faux_facade_data.y/TWO_POW_8);float window_y_perc=faux_facade_data.y-TWO_POW_8*window_x_perc;vec2 window_perc=vec2(window_x_perc,window_y_perc)/MAX_UINT_8;v_faux_facade_floor=(faux_facade_data.zw/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_faux_facade_window=window_perc*v_faux_facade_floor;v_faux_facade_range=(vec2(a_faux_facade_vertical_range)/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_aspect=v_faux_facade_window.x/v_faux_facade_window.y;mat3 tbn=get_tbn(normalize(v_normal));v_tbn_0=tbn[0];v_tbn_1=tbn[1];v_tbn_2=tbn[2];v_faux_color_emissive=decode_color(vec2(faux_facade_color_emissive));v_faux_color_emissive.rgb=sRGBToLinear(v_faux_color_emissive.rgb);depth_offset=min(1000.0,float(a_centroid_3.z))*0.0000002;} #endif v_pos=a_pos_3f; #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) float halfSpanX=spanBits.x*10.0/u_tile_to_meter;float halfSpanY=spanBits.y*10.0/u_tile_to_meter;vec2 screenUpInTile=vec2(u_matrix[0][1],u_matrix[1][1]);vec2 spanOffset=vec2(halfSpanX,halfSpanY)*sign(screenUpInTile);vec2 cutoff_highestCorner=centroid_xy+spanOffset;vec2 cutoff_lowestCorner=centroid_xy-spanOffset; #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_xy,0.0,1.0); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,ground.z);hidden=float(v_cutoff_opacity==0.0);v_pos.z*=v_cutoff_opacity; #endif #ifdef RENDER_SHADOWS vec3 shadow_pos=v_pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset_model(v_normal);shadow_pos+=offset*shadow_normal_offset_multiplier0(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shadow_pos,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(shadow_pos,1.0); #endif #ifdef FOG v_fog_pos=fog_position(v_pos); #endif #ifdef RENDER_FRONT_CUTOFF v_front_cutoff_opacity=1.0;{hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;hidden=max(hidden,float(ndc_y < threshold-range_ndc));float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);v_front_cutoff_opacity=mix(u_front_cutoff_params.z,1.0,t);} #endif gl_Position=mix(u_matrix*vec4(v_pos,1),AWAY,hidden);gl_Position.z-=depth_offset*gl_Position.w; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT vec4 ic_ground=u_matrix*vec4(v_pos.xy,0.0,1.0);vec4 ic_roof=u_matrix*vec4(v_pos.xy,v_pos.z,1.0);v_ground_roof=vec4(ic_ground.xy/ic_ground.w,ic_roof.xy/ic_roof.w); #endif #endif }`),buildingBloom:gi(`in vec4 v_color_emissive; #pragma mapbox: define-attribute highp vec4 bloom_attenuation #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation float saturate(float val) {return clamp(val,0.0,1.0);}void main() {float emission=v_color_emissive.a;float opacity=1.0; #ifdef HAS_ATTRIBUTE_a_bloom_attenuation float distance=length(vec2(1.3*max(0.0,abs(bloom_attenuation.x)-bloom_attenuation.z),bloom_attenuation.y));distance+= mix(0.5,0.0,clamp(emission-1.0,0.0,1.0));opacity*=saturate(1.0-distance*distance); #endif #ifdef RENDER_CUTOFF opacity*=v_cutoff_opacity; #endif glFragColor=vec4(v_color_emissive.rgb,1.0)*opacity;}`,`in vec3 a_pos_3f; #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 part_color_emissive #pragma mapbox: define-attribute highp vec4 bloom_attenuation out vec4 v_color_emissive;uniform mat4 u_matrix;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation #ifdef HAS_ATTRIBUTE_a_part_color_emissive vec4 color_emissive=decode_color(vec2(part_color_emissive));float part_emissive=color_emissive.a*5.0;v_color_emissive=vec4(sRGBToLinear(color_emissive.rgb),part_emissive); #else v_color_emissive=vec4(1.0); #endif gl_Position=u_matrix*vec4(a_pos_3f,1.0); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif }`),buildingDepth:gi("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:gi(`#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:gi("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:gi(`#include "_prelude_fog.fragment.glsl" uniform highp float u_intensity;in vec2 v_extrude; #pragma mapbox: define highp float weight #define GAUSS_COEF 0.3989422804014327 void main() { #pragma mapbox: initialize highp float weight float d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);glFragColor=vec4(val,1.0,1.0,1.0); #ifdef FOG if (u_is_globe==0) {glFragColor.r*=pow(1.0-fog_opacity(v_fog_pos),2.0);} #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;in ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir; #endif out vec2 v_extrude; #pragma mapbox: define highp float weight #pragma mapbox: define mediump float radius const highp float ZERO=1.0/255.0/16.0; #define GAUSS_COEF 0.3989422804014327 void main() { #pragma mapbox: initialize highp float weight #pragma mapbox: initialize mediump float radius vec2 unscaled_extrude=vec2(mod(vec2(a_pos),2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 tilePos=floor(vec2(a_pos)*0.5);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 pos_normal_3=vec3(a_pos_normal_3)/16384.0;mat3 surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(tilePos)*elevation(tilePos);vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*elevation(tilePos);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,tilePos,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #else pos=vec3(tilePos+extrude,elevation(tilePos)); #endif gl_Position=u_matrix*vec4(pos,1); #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),heatmapTexture:gi(`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:gi("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:gi("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:gi("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);glFragColor=mix(u_color,overlay_color,overlay_color.a);}",`#include "_prelude_terrain.vertex.glsl" in ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3; #endif out vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {vec2 pos=vec2(a_pos);float h=elevation(pos);v_uv=pos/8192.0; #ifdef PROJECTION_GLOBE_VIEW gl_Position=u_matrix*vec4(vec3(a_pos_3)+elevationVector(pos)*h,1); #else gl_Position=u_matrix*vec4(pos*u_overlay_scale,h,1); #endif }`),elevatedStructuresDepth:gi("void main() {}","in ivec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform float u_depth_bias;void main() {gl_Position=u_matrix*vec4(a_pos,a_height,1);gl_Position.z=gl_Position.z+u_depth_bias;}"),elevatedStructuresDepthReconstruct:gi(`#ifdef DEPTH_RECONSTRUCTION in float v_height; #endif void main() { #ifdef DEPTH_RECONSTRUCTION if (v_height >=0.0) discard; #else #ifdef FEATURE_CUTOUT apply_feature_cutout(vec4(0.0,0.0,0.0,1.0),gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif #endif glFragColor=vec4(1.0,0.0,0.0,1.0);}`,`in ivec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform vec3 u_camera_pos;uniform highp float u_depth_bias;uniform lowp float u_height_scale;uniform lowp float u_reset_depth; #ifdef DEPTH_RECONSTRUCTION out float v_height; #endif void main() {vec3 vpos=vec3(a_pos,a_height*u_height_scale); #ifdef DEPTH_RECONSTRUCTION if (u_camera_pos.z > vpos.z) {vpos-=(u_camera_pos-vpos)*(vpos.z/(u_camera_pos.z-vpos.z));}v_height=a_height; #endif gl_Position=u_matrix*vec4(vpos,1);gl_Position.z=u_reset_depth==1.0 ? gl_Position.w : gl_Position.z+u_depth_bias;}`),elevatedStructures:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" in vec3 v_normal;in float v_height; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth; #endif vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}vec3 compute_view_dependent_emissive_color(float ndotl,float emissive_strength,vec3 color) {color=sRGBToLinear(color);color=color*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);color=linearTosRGB(color.rgb);return color;}uniform float u_emissive_strength; #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color vec3 color=structure_color.xyz;vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE vec3 normal=normalize(v_normal);vec3 transformed_normal=vec3(-normal.xy,normal.z);float ndotl=calculate_NdotL(transformed_normal);float emissive_strength=u_emissive_strength;emissive_strength=0.0;vec3 emissive_color=compute_view_dependent_emissive_color(ndotl,emissive_strength,color.xyz); #ifdef RENDER_SHADOWS float light=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);color.rgb=apply_lighting(color.rgb,transformed_normal,light); #else color=apply_lighting(color,transformed_normal); #endif color=mix(color,emissive_color,emissive_strength);if (v_height < 0.0) {float penetration=max(v_height+7.5,0.0);float occlusion=1.0-1.0/PI*acos(1.0-penetration/4.0);color=color*(1.0-pow(occlusion,2.0)*0.3);} #endif #ifdef FOG color=fog_apply(color,v_fog_pos); #endif vec4 out_color=vec4(color,1.0); #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_height); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color;HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos;in float a_height;in ivec4 a_pos_normal_3;uniform mat4 u_matrix;out vec3 v_normal;out float v_height; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth; #endif #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color v_normal=vec3(a_pos_normal_3)/16384.0;v_height=a_height;vec3 pos=vec3(vec2(a_pos),a_height);gl_Position=u_matrix*vec4(pos,1); #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(-v_normal.xy,v_normal.z));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),fill:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif vec4 out_color=color; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif out_color*=opacity; #ifdef INDICATOR_CUTOUT if (v_z_offset >=0.0) {out_color=applyCutout(out_color,v_z_offset);} #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif uniform mat4 u_matrix; #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp float z_offset #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #ifdef INDICATOR_CUTOUT v_z_offset=z_offset; #endif }`),fillOutline:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" in highp vec2 v_pos;uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #pragma mapbox: define highp vec4 outline_color #pragma mapbox: define lowp float opacity void main() { #pragma mapbox: initialize highp vec4 outline_color #pragma mapbox: initialize lowp float opacity float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=outline_color;vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color*(alpha*opacity); #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif uniform mat4 u_matrix;uniform vec2 u_world;out highp vec2 v_pos; #pragma mapbox: define highp vec4 outline_color #pragma mapbox: define lowp float opacity #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize highp vec4 outline_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp float z_offset #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden); #ifdef FLIP_Y v_pos=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world; #else v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #endif #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),fillOutlinePattern:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_PATTERN_TRANSITION uniform float u_pattern_transition; #endif uniform float u_emissive_strength; #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif in highp vec2 v_pos;in highp vec2 v_pos_world; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);float dist=length(v_pos_world-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_PATTERN_TRANSITION vec2 pattern_b_tl=pattern_b.xy;vec2 pattern_b_br=pattern_b.zw;highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(alpha*opacity); #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif out highp vec2 v_pos;out highp vec2 v_pos_world; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define lowp float pixel_ratio #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw); #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset; #endif float hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos); #ifdef FLIP_Y v_pos_world=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world; #else v_pos_world=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #endif #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),fillPattern:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_PATTERN_TRANSITION uniform float u_pattern_transition; #endif in highp vec2 v_pos;uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y); #ifdef ELEVATED_ROADS out_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif out highp vec2 v_pos; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define lowp float pixel_ratio #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio; #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),lineBlendComposite:gi(`uniform sampler2D u_image;uniform float u_opacity;uniform int u_blend_mode;in vec2 v_pos; #define ADDITIVE 1 void main() {vec4 color=texture(u_image,v_pos);if (u_blend_mode==ADDITIVE) {if (color.a <=0.0) {discard;}float density=color.a;vec3 avgColor=color.rgb/max(density,0.001);float t=density/(1.0+density);glFragColor=vec4(avgColor*t*u_opacity,t*u_opacity);} else {vec3 multiplyFactor=color.rgb*u_opacity+(1.0-u_opacity);glFragColor=vec4(multiplyFactor,1.0);} #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(0.0); #endif HANDLE_WIREFRAME_DEBUG;}`,"in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),fillExtrusion:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" in vec4 v_color;in vec4 v_flat; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif uniform lowp float u_opacity; #ifdef RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec2 v_ao; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) in vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) in highp vec3 v_normal; #endif uniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor; #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) in float v_flood_radius;in float v_has_floodlight; #endif in float v_height; #pragma mapbox: define highp float emissive_strength void main() { #pragma mapbox: initialize highp float emissive_strength #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) vec3 normal=normalize(v_normal); #endif float z;vec4 color=v_color; #ifdef ZERO_ROOF_RADIUS z=float(normal.z > 0.00001); #ifdef LIGHTING_3D_MODE normal=mix(normal,vec3(0.0,0.0,1.0),z); #else color=mix(v_color,v_roof_color,z); #endif #endif float h=max(0.0,v_height);float ao_shade=1.0; #ifdef FAUX_AO float intensity=u_ao[0];float h_floors=h/(u_ao[1]*u_vertical_scale);float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);ao_shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x; #ifdef ZERO_ROOF_RADIUS concave*=(1.0-z); #endif float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);ao_shade*=mix(1.0,x_shade*x_shade*x_shade,concave); #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT color.rgb*=mix(ao_shade,1.0,v_has_floodlight); #else color.rgb*=ao_shade; #endif #else color.rgb*=ao_shade; #endif #endif #ifdef LIGHTING_3D_MODE float flood_radiance=0.0; #ifdef FLOOD_LIGHT flood_radiance=(1.0-min(h/v_flood_radius,1.0))*u_flood_light_intensity*v_has_floodlight; #endif #ifdef RENDER_SHADOWS #ifdef FLOOD_LIGHT float ndotl_unclamped=dot(normal,u_shadow_direction);float ndotl=max(0.0,ndotl_unclamped);float occlusion=ndotl_unclamped < 0.0 ? 1.0 : shadow_occlusion(ndotl,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 litColor=apply_lighting(color.rgb,normal,(1.0-u_shadow_intensity*occlusion)*ndotl);vec3 floodLitColor=compute_flood_lighting(u_flood_light_color*u_opacity,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=mix(litColor,floodLitColor,flood_radiance); #else float shadowed_lighting_factor; #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif color.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor); #endif #else color.rgb=apply_lighting(color.rgb,normal); #ifdef FLOOD_LIGHT color.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance); #endif #endif color.rgb=mix(color.rgb,v_flat.rgb,emissive_strength);color*=u_opacity; #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h)); #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (ditherOpacity < DITHER_THRESHOLDS[index]) {discard;}}} #else color=applyCutout(color,h); #endif #endif #ifdef RENDER_FRONT_CUTOFF if (v_front_cutoff_opacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (v_front_cutoff_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_lighting.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_edge_radius;uniform float u_width_scale;in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift; #endif #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif uniform highp float u_vertical_scale; #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params;out float v_front_cutoff_opacity; #endif out vec4 v_color;out vec4 v_flat; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) out vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) out highp vec3 v_normal; #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;out vec2 v_ao; #endif #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) out float v_flood_radius;out float v_has_floodlight; #endif out float v_height; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT out vec4 v_ground_roof; #endif #endif vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp vec4 color #pragma mapbox: define highp float flood_light_wall_radius #pragma mapbox: define highp float line_width #pragma mapbox: define highp float emissive_strength void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize highp float flood_light_wall_radius #pragma mapbox: initialize highp float line_width #pragma mapbox: initialize highp float emissive_strength base*=u_vertical_scale;height*=u_vertical_scale;vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0)); #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) v_normal=normal; #endif base=max(0.0,base);float attr_height=height;height=max(0.0,top_up_ny_start.y==0.0 && top_up_ny_start.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny_start.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif float ele=0.0;float h=0.0;float c_ele=0.0;vec3 pos; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && (int(centroid_pos.y) & 7)==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base; #else h=t > 0.0 ? height : base; #endif pos=vec3(pos_nx.xy,h); #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*h);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,pos.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*pos.z;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #endif float cutoff=1.0;vec3 scaled_pos=pos; #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec2 centroid_decoded=pos.xy;bool isBorderCentroid=false;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {int iy=int(centroid_pos.y);int spanYbits=iy & 7;if (spanYbits==7) {isBorderCentroid=true;int borderID=(iy >> 3) & 3;float coordAlongBorder=float(iy >> 5)*4.0;if (borderID==0) centroid_decoded=vec2(0.0,coordAlongBorder);else if (borderID==1) centroid_decoded=vec2(EXTENT,coordAlongBorder);else if (borderID==2) centroid_decoded=vec2(coordAlongBorder,0.0);else centroid_decoded=vec2(coordAlongBorder,EXTENT);} else {centroid_decoded=floor(centroid_pos/8.0);}} #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_decoded,ele,1.0); #endif #ifdef RENDER_CUTOFF #ifdef CLIP_ZERO_TO_ONE cutoff=cutoff_opacity(u_cutoff_params,ground.z*2.0-ground.w); #else cutoff=cutoff_opacity(u_cutoff_params,ground.z); #endif if (centroid_pos.y !=0.0 && centroid_pos.x !=0.0) {vec3 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_random/8.0;vec3 g=floor(ground_pos);vec3 mod_=centroid_random-g*8.0;float seed=min(1.0,0.1*(min(3.5,max(mod_.x+mod_.y,0.2*attr_height))*0.35+mod_.z));if (cutoff < 0.8-seed) {cutoff=0.0;}}float cutoff_scale=cutoff;v_cutoff_opacity=cutoff;scaled_pos.z=mix(c_ele,h,cutoff_scale); #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (cutoff==0.0 && centroid_pos.x !=0.0) || (color.a==0.0)); #ifdef RENDER_FRONT_CUTOFF v_front_cutoff_opacity=1.0;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;if (!isBorderCentroid) {hidden=max(hidden,float(ndc_y < threshold-range_ndc));}float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);v_front_cutoff_opacity=mix(u_front_cutoff_params.z,1.0,t);} #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);scaled_pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;scaled_pos.xy-=join_normal_inside.z*wall_offset*0.5; #endif gl_Position=mix(u_matrix*vec4(scaled_pos,1),AWAY,hidden);h=h-ele;v_height=h; #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(normal);shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1); #endif float NdotL=0.0;float colorvalue=0.0; #ifndef LIGHTING_3D_MODE colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),NdotL);if (normal.y !=0.0) {float r=0.84;r=mix(0.7,0.98,1.0-u_lightintensity);NdotL*=( (1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));} #endif #ifdef FAUX_AO float concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height; #ifdef TERRAIN top_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height); #endif v_ao=vec2(mix(concave,-concave,start),y_ground);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]); #ifdef PROJECTION_GLOBE_VIEW top_height+=u_height_lift; #endif gl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w; #endif #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT float is_wall=1.0-float(t > 0.0 && top_up_ny_start.y > 0.0);v_has_floodlight=float(flood_light_wall_radius > 0.0 && is_wall > 0.0);v_flood_radius=flood_light_wall_radius*u_vertical_scale; #endif v_color=vec4(color.rgb,1.0);float ndotl=calculate_NdotL(normal);v_flat.rgb=sRGBToLinear(color.rgb);v_flat.rgb=v_flat.rgb*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);v_flat=vec4(linearTosRGB(v_flat.rgb),1.0); #else v_color=vec4(0.0,0.0,0.0,1.0);v_color.rgb+=clamp(color.rgb*NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_color*=u_opacity; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) float roofNdotL=clamp(u_lightpos.z,0.0,1.0);roofNdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),roofNdotL);v_roof_color=vec4(0.0,0.0,0.0,1.0);v_roof_color.rgb+=clamp(color.rgb*roofNdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_roof_color*=u_opacity; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT vec4 pos_ground=u_matrix*vec4(pos.xy,ele,1.0);vec4 pos_roof=u_matrix*vec4(pos.xy,ele+height,1.0);v_ground_roof=vec4(pos_ground.xy/pos_ground.w,pos_roof.xy/pos_roof.w); #endif #endif }`),fillExtrusionDepth:gi("void main() {}",`#include "_prelude_terrain.vertex.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform float u_edge_radius;uniform float u_width_scale;uniform float u_vertical_scale; #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp float line_width #pragma mapbox: define highp vec4 color void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp float line_width #pragma mapbox: initialize highp vec4 color base*=u_vertical_scale;height*=u_vertical_scale;vec3 top_up_ny=vec3(a_pos_normal_ed.xyz & 1);vec3 pos_nx=vec3(a_pos_normal_ed.xyz >> 1);base=max(0.0,base);height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif vec3 pos; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;float ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);float c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);float h=t > 0.0 ? max(h_base,h_height) : h_base;pos=vec3(pos_nx.xy,h); #else pos=vec3(pos_nx.xy,t > 0.0 ? height : base); #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;pos.xy-=join_normal_inside.z*wall_offset*0.5; #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(pos,1),AWAY,hidden);}`),fillExtrusionPattern:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_EXTRUSION_PATTERN_TRANSITION uniform float u_pattern_transition; #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec3 v_ao; #endif #ifdef LIGHTING_3D_MODE in vec3 v_normal; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif in highp vec2 v_pos;in vec4 v_lighting;uniform lowp float u_opacity; #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define highp float pixel_ratio void main() { #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_EXTRUSION_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting(out_color,normalize(v_normal))*u_opacity; #else out_color=out_color*v_lighting; #endif #ifdef FAUX_AO float intensity=u_ao[0];float h=max(0.0,v_ao.z);float h_floors=h/u_ao[1];float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);float shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);shade*=mix(1.0,x_shade*x_shade*x_shade,concave);out_color.rgb=out_color.rgb*shade; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,height); #endif glFragColor=out_color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_lighting.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform float u_tile_units_to_pixels;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_width_scale;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift; #endif #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif out highp vec2 v_pos;out vec4 v_lighting; #ifdef FAUX_AO uniform lowp vec2 u_ao;out vec3 v_ao; #endif #ifdef LIGHTING_3D_MODE out vec3 v_normal; #endif #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define highp float pixel_ratio #pragma mapbox: define highp float line_width void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio #pragma mapbox: initialize highp float line_width vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=float(a_pos_normal_ed.w);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;base=max(0.0,base);height=max(0.0,height);float t=top_up_ny_start.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif float ele=0.0;float h=z;vec3 p;float c_ele; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;p=vec3(pos_nx.xy,h); #else p=vec3(pos_nx.xy,z); #endif #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*(p.z+lift));vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,p.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*p.z;p=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);p.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;p.xy-=join_normal_inside.z*wall_offset*0.5; #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(p,1),AWAY,hidden);vec2 pos=normal.z==1.0 ? pos_nx.xy : vec2(edgedistance,z*u_height_factor);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float NdotL=0.0; #ifdef LIGHTING_3D_MODE NdotL=calculate_NdotL(normal); #else NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),NdotL); #endif if (normal.y !=0.0) {float r=0.84; #ifndef LIGHTING_3D_MODE r=mix(0.7,0.98,1.0-u_lightintensity); #endif NdotL*=( (1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));} #ifdef FAUX_AO float concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height; #ifdef TERRAIN top_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height); #endif v_ao=vec3(mix(concave,-concave,start),y_ground,h-ele);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]); #ifdef PROJECTION_GLOBE_VIEW top_height+=u_height_lift; #endif gl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w; #endif #ifdef LIGHTING_3D_MODE v_normal=normal; #else v_lighting.rgb+=clamp(NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity; #endif #ifdef FOG v_fog_pos=fog_position(p); #endif }`),groundShadow:gi(`#include "_prelude_shadow.fragment.glsl" precision highp float;uniform vec3 u_ground_shadow_factor;in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1; #ifdef FOG in float v_fog_opacity; #endif void main() {float light=shadowed_light_factor_plane_bias(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 shadow=mix(u_ground_shadow_factor,vec3(1.0),light); #ifdef RENDER_CUTOFF shadow=mix(vec3(1.0),shadow,cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w)); #endif #ifdef FOG shadow=mix(shadow,vec3(1.0),v_fog_opacity); #endif #ifdef INDICATOR_CUTOUT shadow=mix(shadow,vec3(1.0),1.0-applyCutout(vec4(1.0),0.0).r); #endif #ifdef FEATURE_CUTOUT shadow=mix(shadow,vec3(1.0),get_cutout_factors(gl_FragCoord).y); #endif glFragColor=vec4(shadow,1.0);}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;in ivec2 a_pos;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1; #ifdef FOG out float v_fog_opacity; #endif void main() {gl_Position=u_matrix*vec4(a_pos,0.0,1.0);v_pos_light_view_0=u_light_matrix_0*vec4(a_pos,0.0,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(a_pos,0.0,1.0); #ifdef FOG v_fog_pos=fog_position(vec2(a_pos));v_fog_opacity=fog(v_fog_pos); #endif }`),fillExtrusionGroundEffect:gi(`uniform highp float u_ao_pass;uniform highp float u_opacity;uniform highp float u_flood_light_intensity;uniform highp vec3 u_flood_light_color;uniform highp float u_attenuation;uniform sampler2D u_fb;uniform float u_fb_size; #ifdef SDF_SUBPASS in highp vec2 v_pos;in highp vec4 v_line_segment;in highp float v_flood_light_radius_tile;in highp vec2 v_ao;float line_df(highp vec2 a,highp vec2 b,highp vec2 p) {highp vec2 ba=b-a;highp vec2 pa=p-a;highp float r=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);return length(pa-r*ba);} #ifdef FOG in highp float v_fog; #endif #endif void main() { #ifdef CLEAR_SUBPASS vec4 color=vec4(1.0); #ifdef CLEAR_FROM_TEXTURE color=texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)); #endif glFragColor=color; #else #ifdef SDF_SUBPASS highp float d=line_df(v_line_segment.xy,v_line_segment.zw,v_pos);highp float effect_radius=mix(v_flood_light_radius_tile,v_ao.y,u_ao_pass);d/=effect_radius;d=min(d,1.0);d=1.0-pow(1.0-d,u_attenuation);highp float effect_intensity=mix(u_flood_light_intensity,v_ao.x,u_ao_pass);highp float fog=1.0; #ifdef FOG fog=v_fog; #endif #ifdef RENDER_CUTOFF fog*=v_cutoff_opacity; #endif glFragColor=vec4(vec3(0.0),mix(1.0,d,effect_intensity*u_opacity*fog)); #else #ifdef USE_MRT1 out_Target1=vec4(1.0-texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)).a,0.0,0.0,0.0); #else vec4 color=mix(vec4(u_flood_light_color,1.0),vec4(vec3(0.0),1.0),u_ao_pass); #ifdef OVERDRAW_INSPECTOR color=vec4(1.0); #endif glFragColor=color; #endif #endif HANDLE_WIREFRAME_DEBUG; #endif }`,`#include "_prelude_fog.vertex.glsl" in highp ivec4 a_pos_end;in highp int a_angular_offset_factor;in highp uint a_hidden_by_landmark; #ifdef SDF_SUBPASS out highp vec2 v_pos;out highp vec4 v_line_segment;out highp float v_flood_light_radius_tile;out highp vec2 v_ao; #ifdef FOG out highp float v_fog; #endif #endif uniform highp float u_flood_light_intensity;uniform highp mat4 u_matrix;uniform highp float u_ao_pass;uniform highp float u_meter_to_tile;uniform highp float u_edge_radius;uniform highp float u_dynamic_offset;uniform highp vec2 u_ao; #pragma mapbox: define highp float flood_light_ground_radius const float TANGENT_CUTOFF=4.0;const float NORM=32767.0;void main() { #pragma mapbox: initialize highp float flood_light_ground_radius vec4 pos_end=vec4(a_pos_end);vec2 p=pos_end.xy;vec2 q=floor(pos_end.zw*0.5);vec2 start_bottom=pos_end.zw-q*2.0;float fl_ground_radius=abs(flood_light_ground_radius);float direction=flood_light_ground_radius < 0.0 ?-1.0 : 1.0;float flood_radius_tile=fl_ground_radius*u_meter_to_tile;vec2 v=normalize(q-p);float ao_radius=u_ao.y/3.5;float effect_radius=mix(flood_radius_tile,ao_radius,u_ao_pass)+u_edge_radius;float angular_offset_factor=float(a_angular_offset_factor)/NORM*TANGENT_CUTOFF;float angular_offset=direction*angular_offset_factor*effect_radius;float top=1.0-start_bottom.y;float side=(0.5-start_bottom.x)*2.0;vec2 extrusion_parallel=v*side*mix(u_dynamic_offset,angular_offset,top);vec2 perp=vec2(v.y,-v.x);vec2 extrusion_perp=direction*perp*effect_radius*top;vec3 pos=vec3(mix(q,p,start_bottom.x),0.0);pos.xy+=extrusion_parallel+extrusion_perp; #ifdef SDF_SUBPASS v_pos=pos.xy;v_line_segment=vec4(p,q)+perp.xyxy*u_edge_radius;v_flood_light_radius_tile=flood_radius_tile;v_ao=vec2(u_ao.x,ao_radius); #ifdef FOG v_fog_pos=fog_position(pos);v_fog=1.0-fog(v_fog_pos); #endif #endif float hidden_by_landmark=0.0; #ifdef HAS_CENTROID hidden_by_landmark=float(a_hidden_by_landmark); #endif float isFloodlit=float(fl_ground_radius > 0.0 && u_flood_light_intensity > 0.0);float hidden=mix(1.0-isFloodlit,isFloodlit,u_ao_pass);hidden+=hidden_by_landmark;gl_Position=mix(u_matrix*vec4(pos,1.0),AWAY,float(hidden > 0.0)); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif }`),hillshadePrepare:gi(`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:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;uniform float u_emissive_strength;void main() {vec4 pixel=texture(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);glFragColor=accent_color*(1.0-shade_color.a)+shade_color; #ifdef LIGHTING_3D_MODE glFragColor=apply_lighting_with_emission_ground(glFragColor,u_emissive_strength); #endif #ifdef FOG glFragColor=fog_dither(fog_apply_premultiplied(glFragColor,v_fog_pos)); #endif #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=vec2(a_texture_pos)/8192.0; #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),line:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_floor_width_scale;uniform float u_alpha_discard_threshold;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform highp vec2 u_trim_gradient_mix_range;uniform lowp vec4 u_trim_color;uniform bool u_emissive_in_shadows;in vec4 v_width2_dilute;in vec2 v_normal;in float v_gamma_scale;in highp vec3 v_uv; #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH in float stub_side; #endif #ifdef RENDER_LINE_DASH uniform sampler2D u_dash_image;in vec2 v_tex; #endif #ifdef RENDER_LINE_GRADIENT uniform sampler2D u_gradient_image; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif float luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;} #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float floorwidth #pragma mapbox: define mediump uvec4 dash #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define mediump float side_z_offset #pragma mapbox: define lowp float border_width #pragma mapbox: define lowp vec4 border_color #pragma mapbox: define lowp float emissive_strength float linearstep(float edge0,float edge1,float x) {return clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize mediump uvec4 dash #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump float side_z_offset #pragma mapbox: initialize lowp float border_width #pragma mapbox: initialize lowp vec4 border_color #pragma mapbox: initialize lowp float emissive_strength float dist=length(v_normal)*v_width2_dilute.x; #ifdef VARIABLE_LINE_WIDTH blur=mix(blur,0.0,stub_side); #endif float diluted_opacity=opacity*v_width2_dilute.z;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2_dilute.y-blur2),v_width2_dilute.x-dist)/blur2,0.0,1.0); #ifdef VARIABLE_LINE_WIDTH alpha=mix(alpha,1.0,stub_side); #endif alpha=side_z_offset > 0.0 ? 1.0-alpha : alpha; #ifdef RENDER_LINE_DASH float sdfdist=texture(u_dash_image,v_tex).r;float sdfgamma=1.0/(2.0*u_device_pixel_ratio)/(float(dash.z)+float(dash.w)/65535.0);float scaled_floorwidth=(floorwidth*u_floor_width_scale);alpha*=linearstep(0.5-sdfgamma/scaled_floorwidth,0.5+sdfgamma/scaled_floorwidth,sdfdist); #endif highp vec4 out_color; #ifdef RENDER_LINE_GRADIENT out_color=texture(u_gradient_image,v_uv.xy); #else out_color=color; #endif float trim_alpha=1.0; #ifdef RENDER_LINE_TRIM_OFFSET highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);highp float gradient_trim_color_mix_factor=0.0; #ifdef RENDER_LINE_GRADIENT gradient_trim_color_mix_factor=smoothstep(u_trim_gradient_mix_range.x,u_trim_gradient_mix_range.y,line_progress); #endif highp vec4 trim_color=mix(u_trim_color,out_color,gradient_trim_color_mix_factor);out_color=mix(u_trim_gradient_mix_range.x < 1.0 ? color : out_color,trim_color,transition_factor);trim_alpha=1.0-transition_factor;} #endif if (u_alpha_discard_threshold !=0.0) {if (alpha < u_alpha_discard_threshold) {discard;}} #ifdef RENDER_LINE_BORDER #ifndef VARIABLE_LINE_WIDTH float edgeBlur=((border_width*u_width_scale)+1.0/u_device_pixel_ratio);float alpha2=clamp(min(dist-(v_width2_dilute.y-edgeBlur),v_width2_dilute.x-dist)/edgeBlur,0.0,1.0);if (alpha2 < 1.) {float smoothAlpha=smoothstep(0.6,1.0,alpha2);if (border_color.a==0.0) {float Y=(out_color.a > 0.01) ? luminance(out_color.rgb/out_color.a) : 1.;float adjustment=(Y > 0.) ? 0.5/Y : 0.45;if (out_color.a > 0.25 && Y < 0.25) {vec3 borderColor=(Y > 0.) ? out_color.rgb : vec3(1,1,1)*out_color.a;out_color.rgb=out_color.rgb+borderColor*(adjustment*(1.0-smoothAlpha));} else {out_color.rgb*=(0.6 +0.4*smoothAlpha);}} else {out_color=mix(border_color*trim_alpha,out_color,smoothAlpha);}out_color*=v_width2_dilute.w;} #endif #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);light=u_emissive_in_shadows ? mix(light,1.0,emissive_strength) : light; #ifdef ELEVATED_ROADS out_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif out_color*=(alpha*diluted_opacity); #ifdef LINE_BLEND_MULTIPLY glFragColor=vec4(out_color.rgb+(1.0-out_color.a),1.0);HANDLE_WIREFRAME_DEBUG;return; #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissive_strength); #else #ifdef USE_MRT1 out_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define EXTRUDE_SCALE 0.015873016 in ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH) in vec3 a_z_offset_width; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) in highp vec3 a_packed; #endif #ifdef RENDER_LINE_DASH in float a_linesofar; #endif uniform mat4 u_matrix;uniform mat2 u_pixels_to_tile_units;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;uniform float u_width_scale;uniform highp float u_floor_width_scale; #ifdef RENDER_LINE_CURVE uniform mat3 u_curve_points_x;uniform mat3 u_curve_points_y;uniform mat3 u_curve_points_z;uniform float u_curve_point_count; #endif #ifdef ELEVATED uniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) { #ifdef ELEVATION_REFERENCE_SEA return 0.0; #else return elevation(apos); #endif } #endif out vec2 v_normal;out vec4 v_width2_dilute;out float v_gamma_scale;out highp vec3 v_uv; #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH out float stub_side; #endif #ifdef RENDER_LINE_DASH uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out vec2 v_tex; #endif #ifdef RENDER_LINE_GRADIENT uniform float u_image_height; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float floorwidth #pragma mapbox: define mediump uvec4 dash #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define mediump float gapwidth #pragma mapbox: define lowp float offset #pragma mapbox: define mediump float width #pragma mapbox: define mediump float side_z_offset #pragma mapbox: define lowp float border_width #pragma mapbox: define lowp vec4 border_color #pragma mapbox: define lowp float emissive_strength #ifdef RENDER_LINE_CURVE vec3 getCurvePoint(int index) {int row=index/3;int col=index-row*3;float x=u_curve_points_x[row][col];float y=u_curve_points_y[row][col];float z=u_curve_points_z[row][col];return vec3(x,y,z);}vec3 catmullRom(vec3 p0,vec3 p1,vec3 p2,vec3 p3,float t) {float t2=t*t;float t3=t2*t;return 0.5*( 2.0*p1+(-p0+p2)*t+(2.0*p0-5.0*p1+4.0*p2-p3)*t2+(-p0+3.0*p1-3.0*p2+p3)*t3 );}vec2 catmullRomTangent(vec2 p0,vec2 p1,vec2 p2,vec2 p3,float t) {float t2=t*t;return 0.5*( (-p0+p2)+(2.0*p0-5.0*p1+4.0*p2-p3)*2.0*t+(-p0+3.0*p1-3.0*p2+p3)*3.0*t2 );}struct CurveResult {vec3 point;vec2 tangent;};CurveResult calculateCurve(float line_progress) {float curve_progress=line_progress*(u_curve_point_count-1.0);float curve_progress_local=fract(curve_progress);float curve_segment=floor(curve_progress);int seg=int(curve_segment);vec3 p1=getCurvePoint(seg);vec3 p2=getCurvePoint(seg+1);float is_first_seg=step(curve_segment,0.5);vec3 p0_extrapolated=p1-(p2-p1);vec3 p0_fetched=getCurvePoint(max(seg-1,0));vec3 p0=mix(p0_fetched,p0_extrapolated,is_first_seg);int last_seg=int(u_curve_point_count)-2;float is_last_seg=step(float(last_seg)-0.5,curve_segment);vec3 p3_extrapolated=p2+(p2-p1);vec3 p3_fetched=getCurvePoint(min(seg+2,int(u_curve_point_count)-1));vec3 p3=mix(p3_fetched,p3_extrapolated,is_last_seg);vec3 point=catmullRom(p0,p1,p2,p3,curve_progress_local);vec2 tangent=catmullRomTangent(p0.xy,p1.xy,p2.xy,p3.xy,curve_progress_local)*(u_curve_point_count-1.0);CurveResult result;result.point=point;result.tangent=tangent;return result;} #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize mediump uvec4 dash #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump float gapwidth #pragma mapbox: initialize lowp float offset #pragma mapbox: initialize mediump float width #pragma mapbox: initialize mediump float side_z_offset #pragma mapbox: initialize lowp float border_width #pragma mapbox: initialize lowp vec4 border_color #pragma mapbox: initialize lowp float emissive_strength float a_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset=a_z_offset_width.x; #endif highp float line_progress=0.0; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) line_progress=a_packed[2]; #endif float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);mediump vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;offset=-1.0*offset*u_width_scale;bool left=normal.y==1.0; #ifdef RENDER_LINE_CURVE CurveResult curve=calculateCurve(line_progress);pos=curve.point.xy*8192.0;a_extrude=length(a_extrude)*normalize(curve.tangent);a_extrude=left ? vec2(-a_extrude.y,a_extrude.x) : vec2(a_extrude.y,-a_extrude.x);a_z_offset+=curve.point.z; #endif gapwidth=gapwidth/2.0;float halfwidth;float dilute_scale=1.0;float dilute_border_scale=1.0; #ifdef VARIABLE_LINE_WIDTH float left_width=a_z_offset_width.y;float right_width=a_z_offset_width.z;halfwidth=(u_width_scale*(left ? left_width : right_width))/2.0;if (side_z_offset !=0.0) {float left_f=step(1.0,normal.y);float is_negative=step(side_z_offset,0.0);float apply=mix(1.0-left_f,left_f,is_negative);a_extrude*=apply;a_z_offset+=abs(side_z_offset)*apply;v_normal*=left_f;}offset=border_width > 0.0 ? (left_width+right_width)*u_width_scale*0.5 : offset;halfwidth=border_width > 0.0 ? border_width*u_width_scale*0.5 : halfwidth;bool zero_right_width=border_width==0.0 && right_width==0.0;stub_side=zero_right_width ?-normal.y : 0.0;v_normal=!left && zero_right_width ? vec2(0.0) : v_normal;ANTIALIASING=!left && zero_right_width ? 0.0 : ANTIALIASING; #else halfwidth=(u_width_scale*width)/2.0; #endif float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*EXTRUDE_SCALE;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*EXTRUDE_SCALE*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy; #ifdef ELEVATED_ROADS v_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0); #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset; #ifdef ELEVATION_GROUND_SCALE scaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale); #endif #ifdef CROSS_SLOPE_VERTICAL float top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0); #else #ifdef CROSS_SLOPE_HORIZONTAL float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset; #else float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset; #endif #endif gl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden); #else gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0); #endif #endif #ifndef ELEVATED #ifndef VARIABLE_LINE_WIDTH #ifndef RENDER_TO_TEXTURE float base_w=gl_Position.w;vec2 screen_width=abs(projected_extrude.xy/base_w*u_units_to_pixels);float max_extrude_component=max(screen_width.x,screen_width.y);if (width >=1.0 && base_w > 0.0 && max_extrude_component > 0.0001) {float min_pixel=1.05;if (max_extrude_component < min_pixel) {vec2 abs_pos=abs(gl_Position.xy);float is_out=max(abs_pos.x,abs_pos.y)/base_w;dilute_scale=mix(max_extrude_component/min_pixel,1.0,smoothstep(2.5,4.5,is_out));projected_extrude/=dilute_scale;}else { #ifdef RENDER_LINE_BORDER float border_ratio=(border_width*u_width_scale+ANTIALIASING)/outset;screen_width*=border_ratio;float max_border_component=max(screen_width.x,screen_width.y);dilute_border_scale=min(1.0,max_border_component/min_pixel); #endif }} #endif #endif #ifdef ELEVATED_ROADS gl_Position=gl_Position+projected_extrude; #else gl_Position=mix(gl_Position+projected_extrude,AWAY,hidden); #endif #endif #ifdef ELEVATED_ROADS #ifdef RENDER_SHADOWS vec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #endif #ifndef RENDER_TO_TEXTURE float epsilon=0.0001;float extrude_length_without_perspective=max(length(dist),epsilon);float extrude_length_with_perspective=max(length(projected_extrude_xy/gl_Position.w*u_units_to_pixels),epsilon);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur)); #else v_gamma_scale=1.0; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) highp float a_uv_x=a_packed[0];float a_split_index=a_packed[1]; #ifdef RENDER_LINE_GRADIENT highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec3(a_uv_x,a_split_index*texel_height-half_texel_height,line_progress); #else v_uv=vec3(a_uv_x,0.0,line_progress); #endif #endif #ifdef RENDER_LINE_DASH vec4 dashf=vec4(dash);float totalLength=dashf.z+dashf.w/65535.0;float scale=totalLength==0.0 ? 0.0 : u_tile_units_to_pixels/totalLength;v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*dashf.y+dashf.x+0.5)/u_texsize.y); #endif v_width2_dilute=vec4(outset,inset,dilute_scale,dilute_border_scale); #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),linePattern:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;uniform highp vec2 u_texsize;uniform highp float u_tile_units_to_pixels;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;uniform sampler2D u_image; #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef LINE_PATTERN_TRANSITION uniform float u_pattern_transition; #endif in vec2 v_normal;in vec2 v_width2;in highp float v_linesofar;in float v_gamma_scale;in float v_width; #ifdef RENDER_LINE_TRIM_OFFSET in highp vec3 v_uv; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef LINE_JOIN_NONE in vec2 v_pattern_data; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #pragma mapbox: define mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define mediump float pixel_ratio #pragma mapbox: define mediump float blur #pragma mapbox: define mediump float opacity #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize mediump float pixel_ratio #pragma mapbox: initialize mediump float blur #pragma mapbox: initialize mediump float opacity #pragma mapbox: initialize lowp float emissive_strength vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;highp float pattern_size=display_size.x/u_tile_units_to_pixels;float aspect=display_size.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);highp float pattern_x=v_linesofar/pattern_size*aspect;highp float x=mod(pattern_x,1.0);highp float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;highp vec2 pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(x,y));highp vec2 lod_pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(pattern_x,y));vec4 color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU color=applyLUT(u_lutTexture,color); #endif #ifdef LINE_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl*texel_size-texel_size,pattern_b_br*texel_size+texel_size,vec2(x,y));vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);color=color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef RENDER_LINE_TRIM_OFFSET highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);color=mix(color,color.a*u_trim_color,transition_factor);} #endif #ifdef LINE_JOIN_NONE highp float pattern_len=pattern_size/aspect;highp float segment_phase=pattern_len-mod(v_linesofar-v_pattern_data.x+pattern_len,pattern_len);highp float visible_start=segment_phase-step(pattern_len*0.5,segment_phase)*pattern_len;highp float visible_end=floor((v_pattern_data.y-segment_phase)/pattern_len)*pattern_len+segment_phase;visible_end+=step(pattern_len*0.5,v_pattern_data.y-visible_end)*pattern_len;if (v_pattern_data.x < visible_start || v_pattern_data.x >=visible_end) {color=vec4(0.0);} #endif #ifdef LIGHTING_3D_MODE color=apply_lighting_with_emission_ground(color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth); #ifdef ELEVATED_ROADS color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #endif color*=(alpha*opacity);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}} #ifdef INDICATOR_CUTOUT color=applyCutout(color,v_z_offset); #endif glFragColor=color; #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissive_strength); #else #ifdef USE_MRT1 out_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define scale 0.015873016 in ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) in vec3 a_z_offset_width; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #ifdef RENDER_LINE_TRIM_OFFSET in highp vec3 a_packed; #endif in highp float a_linesofar; #ifdef LINE_JOIN_NONE in highp vec3 a_pattern_data;out vec2 v_pattern_data; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif uniform mat4 u_matrix;uniform float u_tile_units_to_pixels;uniform vec2 u_units_to_pixels;uniform mat2 u_pixels_to_tile_units;uniform float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_floor_width_scale; #ifdef ELEVATED uniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) { #ifdef ELEVATION_REFERENCE_SEA return 0.0; #else return elevation(apos); #endif } #endif out vec2 v_normal;out vec2 v_width2;out highp float v_linesofar;out float v_gamma_scale;out float v_width; #ifdef RENDER_LINE_TRIM_OFFSET out highp vec3 v_uv; #endif #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #pragma mapbox: define mediump float blur #pragma mapbox: define mediump float opacity #pragma mapbox: define mediump float offset #pragma mapbox: define mediump float gapwidth #pragma mapbox: define mediump float width #pragma mapbox: define mediump float floorwidth #pragma mapbox: define mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define mediump float pixel_ratio #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize mediump float blur #pragma mapbox: initialize mediump float opacity #pragma mapbox: initialize mediump float offset #pragma mapbox: initialize mediump float gapwidth #pragma mapbox: initialize mediump float width #pragma mapbox: initialize mediump float floorwidth #pragma mapbox: initialize mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize mediump float pixel_ratio #pragma mapbox: initialize lowp float emissive_strength float a_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset=a_z_offset_width.x; #endif float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=(u_width_scale*width)/2.0;offset=-1.0*offset*u_width_scale;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);vec2 dist=outset*a_extrude*scale;float u=0.5*a_direction;float t=1.0-abs(u);vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy; #ifdef ELEVATED_ROADS v_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0)+projected_extrude; #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset; #ifdef ELEVATION_GROUND_SCALE scaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale); #endif #ifdef CROSS_SLOPE_VERTICAL float top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0); #else #ifdef CROSS_SLOPE_HORIZONTAL float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset; #else float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset; #endif #endif gl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden); #else gl_Position=mix(u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude,AWAY,hidden); #endif #endif #ifdef ELEVATED_ROADS #ifdef RENDER_SHADOWS vec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #endif #ifndef RENDER_TO_TEXTURE float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude_xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur)); #else v_gamma_scale=1.0; #endif #ifdef RENDER_LINE_TRIM_OFFSET highp float a_uv_x=a_packed[0];highp float line_progress=a_packed[2];v_uv=vec3(a_uv_x,0.0,line_progress); #endif v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=(floorwidth*u_floor_width_scale); #ifdef LINE_JOIN_NONE v_width=(floorwidth*u_floor_width_scale)+ANTIALIASING;mediump float pixels_to_tile_units=1.0/u_tile_units_to_pixels;mediump float pixel_ratio_inverse=1.0/pixel_ratio;mediump float aspect=v_width/(float(pattern.w-pattern.y)*pixel_ratio_inverse);highp float subt_multiple=float(pattern.z-pattern.x)*pixel_ratio_inverse*pixels_to_tile_units*aspect*32.0;highp float subt=floor(a_pattern_data.z/subt_multiple)*subt_multiple;float offset_sign=(fract(a_pattern_data.x)-0.5)*4.0;float line_progress_offset=offset_sign*v_width*0.5*pixels_to_tile_units;v_linesofar=(a_pattern_data.z-subt)+a_linesofar+line_progress_offset;v_pattern_data=vec2(a_pattern_data.x+line_progress_offset,a_pattern_data.y); #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),raster:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_raster_array.glsl" uniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;uniform highp float u_zoom_transition;in vec2 v_pos0;in vec2 v_pos1;in float v_depth; #ifdef PROJECTION_GLOBE_VIEW in float v_split_fade; #endif uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;uniform float u_emissive_strength; #ifndef RASTER_ARRAY uniform highp sampler2D u_image0;uniform sampler2D u_image1; #endif #ifdef RASTER_COLOR uniform sampler2D u_color_ramp;uniform highp vec4 u_colorization_mix;uniform highp float u_colorization_offset;uniform vec2 u_texture_res; #endif void main() {vec4 color0,color1,color;vec2 value; #ifdef RASTER_COLOR #ifdef RASTER_ARRAY #ifdef RASTER_ARRAY_LINEAR value=mix( raTexture2D_image0_linear(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_linear(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t ); #else value=mix( raTexture2D_image0_nearest(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_nearest(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t ); #endif if (value.y > 0.0) value.x/=value.y; #else color=mix(texture(u_image0,v_pos0),texture(u_image1,v_pos1),u_fade_t);value=vec2(u_colorization_offset+dot(color.rgb,u_colorization_mix.rgb),color.a); #endif color=texture(u_color_ramp,vec2(value.x,0.5));if (color.a > 0.0) color.rgb/=color.a;color.a*=value.y; #else color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t); #endif color.a*=u_opacity; #ifdef GLOBE_POLES color.a*=1.0-smoothstep(0.0,0.05,u_zoom_transition); #endif vec3 rgb=color.rgb;rgb=vec3( dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);vec3 out_color=mix(u_high_vec,u_low_vec,rgb); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),u_emissive_strength).rgb; #endif #ifdef FOG highp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit)); #endif glFragColor=vec4(out_color*color.a,color.a); #ifdef PROJECTION_GLOBE_VIEW glFragColor*=mix(1.0,1.0-smoothstep(0.0,0.05,u_zoom_transition),smoothstep(0.8,0.9,v_split_fade)); #endif #ifdef RENDER_CUTOFF glFragColor=glFragColor*cutoff_opacity(u_cutoff_params,v_depth); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform vec2 u_perspective_transform;uniform vec2 u_texture_offset;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center; #ifdef ELEVATED uniform lowp float u_zbias_factor; #endif #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in ivec2 a_pos;in uvec2 a_texture_pos; #endif out vec2 v_pos0;out vec2 v_pos1;out float v_depth; #ifdef PROJECTION_GLOBE_VIEW out float v_split_fade; #endif void main() {vec2 uv; #ifdef GLOBE_POLES vec3 globe_pos=a_globe_pos;uv=a_uv;float ele=u_raster_elevation; #ifdef ELEVATION_REFERENCE_GROUND ele+=elevation(uv*EXTENT); #endif globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos,1.0); #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz); #endif #else vec4 world_pos; #ifdef PROJECTION_GLOBE_VIEW vec2 texture_pos=vec2(a_texture_pos);uv=texture_pos/8192.0;vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]); float tiles=u_grid_matrix[0][2];if (tiles > 0.0) {float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvY=mercatorY*tiles-idy;float uvX=mercatorX*tiles-idx;uv=vec2(uvX,uvY);}float ele=u_raster_elevation; #ifdef ELEVATION_REFERENCE_GROUND ele+=elevation(uv*EXTENT)-decomposed_pos_and_skirt.z; #endif vec4 merc_world_pos=vec4(0.0); v_split_fade=0.0;if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,ele,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;float opposite_merc_center=mod(u_merc_center.x+0.5,1.0);float dist_from_poles=(abs(mercatorY-0.5)*2.0);float range=0.1;v_split_fade=abs(opposite_merc_center-mercatorX);v_split_fade=clamp(1.0-v_split_fade,0.0,1.0);v_split_fade=max(smoothstep(1.0-range,1.0,dist_from_poles),max(smoothstep(1.0-range,1.0,v_split_fade),smoothstep(1.0-range,1.0,1.0-v_split_fade)));}vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);world_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0); #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else float ele=0.0;vec2 decodedPos=vec2(a_pos); #ifdef ELEVATION_REFERENCE_GROUND vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;decodedPos=decomposedPosAndSkirt.xy;uv=decodedPos/8192.0;ele=elevation(decodedPos)-skirt; #else uv=vec2(a_texture_pos)/8192.0; #endif world_pos=vec4(decodedPos,(u_raster_elevation+ele),1.0); #ifdef FOG v_fog_pos=fog_position(decodedPos); #endif #endif float w=1.0+dot(uv*EXTENT,u_perspective_transform);gl_Position=u_matrix*world_pos*w; #endif v_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;v_pos0=u_texture_offset.x+u_texture_offset.y*v_pos0;v_pos1=u_texture_offset.x+u_texture_offset.y*v_pos1; #ifdef ELEVATED float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor);gl_Position.z-=(gl_Position.w*zbias); #endif #ifdef RENDER_CUTOFF v_depth=gl_Position.z; #endif }`),rasterParticle:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;in vec2 v_pos0;in vec2 v_pos1;uniform sampler2D u_image0;uniform sampler2D u_image1;void main() {vec4 color0,color1,color;color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 out_color=color.rgb; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),1.0).rgb; #endif #ifdef FOG highp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit)); #endif glFragColor=vec4(out_color*color.a,color.a); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center; #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {float w=1.0;vec2 uv; #ifdef PROJECTION_GLOBE_VIEW vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvX=mercatorX*tiles-idx;float uvY=mercatorY*tiles-idy;uv=vec2(uvX,uvY);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else uv=vec2(a_texture_pos)/8192.0;gl_Position=u_matrix*vec4(vec2(a_pos)*w,u_raster_elevation*w,w); #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #endif v_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}`),rasterParticleDraw:gi("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:gi("uniform sampler2D u_texture;uniform float u_opacity;in vec2 v_tex_pos;void main() {vec4 color=texture(u_texture,v_tex_pos);glFragColor=vec4(floor(255.0*color*u_opacity)/255.0);}","in ivec2 a_pos;out vec2 v_tex_pos;void main() {vec2 uv=0.5*vec2(a_pos)+vec2(0.5);v_tex_pos=uv;gl_Position=vec4(a_pos,0.0,1.0);}"),rasterParticleUpdate:gi(`#include "_prelude_raster_particle.glsl" uniform sampler2D u_particle_texture;uniform mediump float u_particle_texture_side_len;uniform mediump float u_speed_factor;uniform highp float u_reset_rate;uniform highp float u_rand_seed;in highp vec2 v_tex_coord;vec2 linearstep(vec2 edge0,vec2 edge1,vec2 x) {return clamp((x-edge0)/(edge1-edge0),vec2(0),vec2(1));}const highp vec3 rand_constants=vec3(12.9898,78.233,4375.85453);highp float rand(const highp vec2 co) {highp float t=dot(rand_constants.xy,co);return fract(sin(t)*(rand_constants.z+t));}void main() {ivec2 pixel_coord=ivec2(v_tex_coord*u_particle_texture_side_len);highp vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);highp vec2 pos=unpack_pos_from_rgba(pixel);highp vec2 velocity=lookup_velocity(clamp(pos,0.0,1.0));highp vec2 dp=velocity==INVALID_VELOCITY ? vec2(0) : velocity*u_speed_factor;pos=pos+dp;highp vec2 seed=(pos+v_tex_coord)*u_rand_seed;highp vec2 random_pos=vec2(rand(seed+1.3),rand(seed+2.1));highp vec2 persist_rate=pow( linearstep(vec2(-u_particle_pos_offset),vec2(0),pos)*linearstep(vec2(1.0+u_particle_pos_offset),vec2(1),pos),vec2(4) );highp vec2 per_frame_persist=pow(persist_rate,abs(dp)/u_particle_pos_offset);highp float drop_rate=1.0-per_frame_persist.x*per_frame_persist.y;drop_rate=any(greaterThanEqual(abs(pos-0.5),vec2(0.5+u_particle_pos_offset))) ? 1.0 : drop_rate;highp float drop=step(1.0-drop_rate-u_reset_rate,rand(seed));highp vec2 next_pos=mix(pos,random_pos,drop);glFragColor=pack_pos_to_rgba(next_pos);}`,"in ivec2 a_pos;out vec2 v_tex_coord;void main() {v_tex_coord=0.5*vec2(a_pos+ivec2(1));gl_Position=vec4(a_pos,0.0,1.0);}"),symbol:gi(`#include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #define SDF_PX 8.0 #define SDF 1.0 #define ICON 0.0 uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_halo;uniform lowp float u_scale_factor; #ifdef ICON_TRANSITION uniform float u_icon_transition; #endif #ifdef COLOR_ADJUSTMENT uniform mat4 u_color_adj_mat; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #else #ifdef RENDER_SHADOWS in highp float v_z_offset; #endif #endif in vec2 v_tex_a; #ifdef ICON_TRANSITION in vec2 v_tex_b; #endif in float v_draw_halo;in vec3 v_gamma_scale_size_fade_opacity; #ifdef RENDER_TEXT_AND_SYMBOL in float is_sdf;in vec2 v_tex_a_icon; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef USE_PAINT_PROPERTIES_UBO in lowp float v_opacity; #ifdef RENDER_SDF in lowp vec4 v_fill_np_color;in lowp vec4 v_halo_np_color;in lowp float v_halo_width;in lowp float v_halo_blur; #endif #ifdef LIGHTING_3D_MODE in lowp float v_emissive_strength; #endif #else #pragma mapbox: define highp vec4 fill_color #pragma mapbox: define highp vec4 halo_color #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp float halo_width #pragma mapbox: define lowp float halo_blur #pragma mapbox: define lowp float emissive_strength #endif void main() { #ifdef USE_PAINT_PROPERTIES_UBO lowp float opacity=v_opacity;lowp vec4 fill_color=vec4(0.0);lowp vec4 halo_color=vec4(0.0);lowp float halo_width=0.0;lowp float halo_blur=0.0; #ifdef RENDER_SDF fill_color=vec4(v_fill_np_color.rgb*v_fill_np_color.a,v_fill_np_color.a);halo_color=vec4(v_halo_np_color.rgb*v_halo_np_color.a,v_halo_np_color.a);halo_width=v_halo_width;halo_blur=v_halo_blur; #endif lowp float emissive_strength=0.0; #ifdef LIGHTING_3D_MODE emissive_strength=v_emissive_strength; #endif #else #pragma mapbox: initialize highp vec4 fill_color #pragma mapbox: initialize highp vec4 halo_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize lowp float halo_width #pragma mapbox: initialize lowp float halo_blur #pragma mapbox: initialize lowp float emissive_strength #endif vec4 out_color;float fade_opacity=v_gamma_scale_size_fade_opacity[2]; #ifdef RENDER_TEXT_AND_SYMBOL if (is_sdf==ICON) {vec2 tex_icon=v_tex_a_icon;lowp float alpha=opacity*fade_opacity;glFragColor=texture(u_texture_icon,tex_icon)*alpha; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif return;} #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef RENDER_SDF float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_gamma_scale_size_fade_opacity.x;float size=v_gamma_scale_size_fade_opacity.y;float fontScale=u_is_text ? size/24.0 : size;out_color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo=v_draw_halo > 0.0;if (draw_halo) {out_color=halo_color;gamma=(halo_blur*u_scale_factor*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width*u_scale_factor/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,v_tex_a).r;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);out_color*=alpha; #else #ifdef ICON_TRANSITION vec4 a=texture(u_texture,v_tex_a)*(1.0-u_icon_transition);vec4 b=texture(u_texture,v_tex_b)*u_icon_transition;out_color=(a+b); #else out_color=texture(u_texture,v_tex_a); #endif #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef COLOR_ADJUSTMENT out_color=u_color_adj_mat*out_color; #endif #endif out_color*=opacity*fade_opacity; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y); #ifdef TERRAIN out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #else out_color.rgb*=mix(v_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #endif #endif #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #define USING_APPEARANCE 1.0 in ivec4 a_pos_offset;in uvec4 a_tex_size;in ivec4 a_pixeloffset;in vec4 a_projected_pos;in uint a_fade_opacity; #ifdef Z_OFFSET in float a_auto_z_offset; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_globe_anchor;in vec3 a_globe_normal; #endif #ifdef ICON_TRANSITION in uvec2 a_texb; #endif #ifdef OCCLUSION_QUERIES in float a_occlusion_query_opacity; #endif #ifdef ELEVATED_ROADS in vec3 a_x_axis;in vec3 a_y_axis;uniform float u_normal_scale; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #else #ifdef RENDER_SHADOWS out highp float v_z_offset; #endif #endif uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_elevation_from_sea;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform vec2 u_texsize_icon;uniform bool u_is_halo; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix; #endif out vec2 v_tex_a; #ifdef ICON_TRANSITION out vec2 v_tex_b; #endif out float v_draw_halo;out vec3 v_gamma_scale_size_fade_opacity; #ifdef RENDER_TEXT_AND_SYMBOL out float is_sdf;out vec2 v_tex_a_icon; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #ifdef USE_PAINT_PROPERTIES_UBO #ifndef MAX_UBO_SIZE_VEC4 #define MAX_UBO_SIZE_VEC4 1024u #endif #define SPP_HEADER_SIZE_VEC4 3u #define DWORDS_PER_VEC4 4u struct SymbolPaintProperties {vec4 fill_np_color;vec4 halo_np_color;float opacity;float halo_width;float halo_blur;float emissive_strength;float occlusion_opacity;float z_offset;vec2 translate;};struct PropertyType {bool isDataDriven;bool isZoomDependent;uint offsetDwords;};struct SymbolPropertyHeader {uint dataDrivenBlockSizeVec4;PropertyType fill_np_color;PropertyType halo_np_color;PropertyType opacity;PropertyType halo_width;PropertyType halo_blur;PropertyType emissive_strength;PropertyType occlusion_opacity;PropertyType z_offset;PropertyType translate;};uniform float u_zoom;uniform lowp vec4 u_spp_fill_np_color;uniform lowp vec4 u_spp_halo_np_color;uniform lowp float u_spp_opacity;uniform lowp float u_spp_halo_width;uniform lowp float u_spp_halo_blur;uniform lowp float u_spp_emissive_strength;uniform lowp float u_spp_occlusion_opacity;uniform lowp float u_spp_z_offset;uniform lowp vec2 u_spp_translate_rotation;in float a_feature_index;layout(std140) uniform SymbolPaintPropertiesHeaderUniform {uvec4 header[SPP_HEADER_SIZE_VEC4];} u_spp_header;layout(std140) uniform SymbolPaintPropertiesUniform {vec4 properties[MAX_UBO_SIZE_VEC4];} u_spp_properties;layout(std140) uniform SymbolPaintPropertiesIndexUniform {uvec4 block_indices[MAX_UBO_SIZE_VEC4];} u_spp_index;out lowp float v_opacity; #ifdef RENDER_SDF out lowp vec4 v_fill_np_color;out lowp vec4 v_halo_np_color;out lowp float v_halo_width;out lowp float v_halo_blur; #endif #ifdef LIGHTING_3D_MODE out lowp float v_emissive_strength; #endif PropertyType getPropertyType(uint propertyIndex,uint dataDrivenMask,uint zoomDependentMask,uint offsetDwords) {PropertyType type;type.isDataDriven=(dataDrivenMask & (1u << propertyIndex)) !=0u;type.isZoomDependent=(zoomDependentMask & (1u << propertyIndex)) !=0u;type.offsetDwords=offsetDwords;return type;}SymbolPropertyHeader readSymbolPropertiesHeader() {SymbolPropertyHeader header;uint dataDrivenMask=u_spp_header.header[0][0];uint zoomDependentMask=u_spp_header.header[0][1];header.dataDrivenBlockSizeVec4=u_spp_header.header[0][2];header.fill_np_color =getPropertyType(0u,dataDrivenMask,zoomDependentMask,u_spp_header.header[0][3]);header.halo_np_color =getPropertyType(1u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][0]);header.opacity =getPropertyType(2u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][1]);header.halo_width =getPropertyType(3u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][2]);header.halo_blur =getPropertyType(4u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][3]);header.emissive_strength =getPropertyType(5u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][0]);header.occlusion_opacity =getPropertyType(6u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][1]);header.z_offset =getPropertyType(7u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][2]);header.translate =getPropertyType(8u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][3]);return header;}uint uvec4At(uvec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}float vec4At(vec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}vec4 readVec4(uint baseOffsetVec4,uint propertyOffsetDwords) {return u_spp_properties.properties[baseOffsetVec4+propertyOffsetDwords/DWORDS_PER_VEC4];}float readFloat(vec4 slot,uint propertyOffsetDwords) {return slot[propertyOffsetDwords % DWORDS_PER_VEC4];}uint readUint(uvec4 slot,uint offset) {return slot[offset % DWORDS_PER_VEC4];}vec2 readVec2(vec4 slot,uint propertyOffsetDwords) {float x=vec4At(slot,propertyOffsetDwords % DWORDS_PER_VEC4);float y=vec4At(slot,propertyOffsetDwords % DWORDS_PER_VEC4+1u);return vec2(x,y);}uint getDataDrivenBlockOffsetVec4(uint dataDrivenBlockSizeVec4) {uint featureIndex=uint(a_feature_index);uvec4 slot=u_spp_index.block_indices[featureIndex/DWORDS_PER_VEC4];uint blockIndex=uvec4At(slot,featureIndex % DWORDS_PER_VEC4);return blockIndex*dataDrivenBlockSizeVec4;}vec4 readColorProperty(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 color=readVec4(blockOffsetVec4,propertyType.offsetDwords);if (propertyType.isZoomDependent) {color=unpack_mix_color(color,u_zoom);} else {vec2 packedColor=readVec2(color,propertyType.offsetDwords);color=decode_color(packedColor);}return color;}vec2 readVec2Property(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 slot=readVec4(blockOffsetVec4,propertyType.offsetDwords);if (propertyType.isZoomDependent) {vec2 minVal=slot.xy;vec2 maxVal=slot.zw;return mix(minVal,maxVal,u_zoom);}return readVec2(slot,propertyType.offsetDwords);}float readFloatProperty(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 slot=readVec4(blockOffsetVec4,propertyType.offsetDwords);float value;if (propertyType.isZoomDependent) {vec2 packedValues=readVec2(slot,propertyType.offsetDwords);value=unpack_mix_vec2(packedValues,u_zoom);} else {value=readFloat(slot,propertyType.offsetDwords);}return value;}SymbolPaintProperties readSymbolPaintProperties() {SymbolPropertyHeader header=readSymbolPropertiesHeader();uint sizeVec4=header.dataDrivenBlockSizeVec4;SymbolPaintProperties props;props.fill_np_color =header.fill_np_color.isDataDriven ? readColorProperty(header.fill_np_color,sizeVec4) : u_spp_fill_np_color;props.halo_np_color =header.halo_np_color.isDataDriven ? readColorProperty(header.halo_np_color,sizeVec4) : u_spp_halo_np_color;props.opacity =header.opacity.isDataDriven ? readFloatProperty(header.opacity,sizeVec4) : u_spp_opacity;props.halo_width =header.halo_width.isDataDriven ? readFloatProperty(header.halo_width,sizeVec4) : u_spp_halo_width;props.halo_blur =header.halo_blur.isDataDriven ? readFloatProperty(header.halo_blur,sizeVec4) : u_spp_halo_blur;props.emissive_strength =header.emissive_strength.isDataDriven ? readFloatProperty(header.emissive_strength,sizeVec4) : u_spp_emissive_strength;props.occlusion_opacity =header.occlusion_opacity.isDataDriven ? readFloatProperty(header.occlusion_opacity,sizeVec4) : u_spp_occlusion_opacity;props.z_offset =header.z_offset.isDataDriven ? readFloatProperty(header.z_offset,sizeVec4) : u_spp_z_offset;props.translate =header.translate.isDataDriven ? readVec2Property(header.translate,sizeVec4) : vec2(0.0);return props;} #else #pragma mapbox: define highp vec4 fill_color #pragma mapbox: define highp vec4 halo_color #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp float halo_width #pragma mapbox: define lowp float halo_blur #pragma mapbox: define lowp float emissive_strength #pragma mapbox: define lowp float occlusion_opacity #pragma mapbox: define lowp float z_offset #endif vec2 unpack_opacity(uint packedOpacity) {return vec2(float(packedOpacity/2u)/127.0,float(packedOpacity & 1u));}void main() { #ifdef USE_PAINT_PROPERTIES_UBO SymbolPaintProperties paint_properties=readSymbolPaintProperties();lowp float opacity=paint_properties.opacity;v_opacity=opacity; #ifdef RENDER_SDF v_fill_np_color=paint_properties.fill_np_color;v_halo_np_color=paint_properties.halo_np_color;v_halo_width=paint_properties.halo_width;v_halo_blur=paint_properties.halo_blur; #endif #ifdef LIGHTING_3D_MODE v_emissive_strength=paint_properties.emissive_strength; #endif lowp float occlusion_opacity=paint_properties.occlusion_opacity;lowp float z_offset=paint_properties.z_offset; #else #pragma mapbox: initialize highp vec4 fill_color #pragma mapbox: initialize highp vec4 halo_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize lowp float halo_width #pragma mapbox: initialize lowp float halo_blur #pragma mapbox: initialize lowp float emissive_strength #pragma mapbox: initialize lowp float occlusion_opacity #pragma mapbox: initialize lowp float z_offset #endif vec2 a_pos=vec2(a_pos_offset.xy);vec2 a_offset=vec2(a_pos_offset.zw);vec2 a_tex=vec2(a_tex_size.xy);vec2 a_size=vec2(a_tex_size.zw);float a_size_min=floor(a_size[0]*0.5);float a_size_max= floor(a_size[1]*0.5);float a_apperance=a_size[1]-2.0*a_size_max;vec2 a_pxoffset=vec2(a_pixeloffset.xy);vec2 a_min_font_scale=vec2(a_pixeloffset.zw)/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (a_apperance==USING_APPEARANCE) {size=a_size_max/128.0;} else if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size_max,u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=u_elevation_from_sea ? z_offset : z_offset+elevation(tile_anchor); #ifdef Z_OFFSET e+=a_auto_z_offset; #endif vec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;vec3 world_pos_globe; #ifdef PROJECTION_GLOBE_VIEW mercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos_globe=vec3(a_globe_anchor)+h;world_pos=mix_globe_mercator(world_pos_globe,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0; #else world_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0; #endif vec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ? camera_to_anchor_distance/u_camera_to_center_distance : u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp( 0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetprojected_point;vec2 a; #ifdef PROJECTION_GLOBE_VIEW vec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetprojected_point=u_matrix*vec4(vec3(a_globe_anchor)+displacement,1);vec4 projected_point_globe=u_matrix*vec4(world_pos_globe,1);a=projected_point_globe.xy/projected_point_globe.w; #else offsetprojected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);a=projected_point.xy/projected_point.w; #endif vec2 b=offsetprojected_point.xy/offsetprojected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos; #ifdef PROJECTION_GLOBE_VIEW #ifdef PROJECTED_POS_ON_VIEWPORT projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xyz+h,1.0); #else vec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz,mercator_pos,u_zoom_transition)+h;projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0); #endif #else projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0); #endif highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*max(a_min_font_scale,font_scale)+a_pxoffset/16.0); #ifdef TERRAIN #ifdef PITCH_WITH_MAP_TERRAIN vec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy); #endif #endif #ifdef Z_OFFSET z+=u_pitch_with_map ? a_auto_z_offset+z_offset : 0.0; #else z+=u_pitch_with_map ? z_offset : 0.0; #endif float occlusion_fade=globe_occlusion_fade;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change)); #ifdef DEPTH_OCCLUSION float depth_occlusion=occlusionFadeMultiSample(projected_point);float depth_occlusion_multplier=mix(occlusion_opacity,1.0,depth_occlusion);out_fade_opacity*=depth_occlusion_multplier; #endif #ifdef OCCLUSION_QUERIES float occludedFadeMultiplier=mix(occlusion_opacity,1.0,a_occlusion_query_opacity);out_fade_opacity*=occludedFadeMultiplier; #endif #ifdef Z_TEST_OCCLUSION out_fade_opacity*=occlusion_opacity; #endif float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y; #else #ifdef ELEVATED_ROADS vec3 xAxis=vec3(a_x_axis.xy,a_x_axis.z*u_normal_scale);vec3 yAxis=vec3(a_y_axis.xy,a_y_axis.z*u_normal_scale);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y; #else pos=vec3(projected_pos.xy/projected_pos.w+offset,z); #endif #endif gl_Position=mix(u_coord_matrix*vec4(pos,1.0),AWAY,hidden); #ifdef USE_PAINT_PROPERTIES_UBO {vec2 tr=paint_properties.translate;vec2 rotated_tr=vec2( u_spp_translate_rotation.x*tr.x-u_spp_translate_rotation.y*tr.y,u_spp_translate_rotation.y*tr.x+u_spp_translate_rotation.x*tr.y );gl_Position.xy+=(u_coord_matrix*vec4(rotated_tr,0.0,0.0)).xy;} #endif float gamma_scale=gl_Position.w;v_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;v_gamma_scale_size_fade_opacity=vec3(gamma_scale,size,out_fade_opacity);v_tex_a=a_tex/u_texsize; #ifdef RENDER_TEXT_AND_SYMBOL is_sdf=a_size[0]-2.0*a_size_min;v_tex_a_icon=a_tex/u_texsize_icon; #endif #ifdef ICON_TRANSITION v_tex_b=vec2(a_texb)/u_texsize; #endif #ifdef RENDER_SHADOWS vec4 shd_pos=u_inv_matrix*vec4(pos,1.0);vec3 shd_pos0=shd_pos.xyz;vec3 shd_pos1=shd_pos.xyz; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef INDICATOR_CUTOUT v_z_offset=e; #else #ifdef RENDER_SHADOWS v_z_offset=e; #endif #endif }`),terrainRaster:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image0; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS uniform sampler2D u_image1;uniform float u_emissive_texture_available; #endif in vec2 v_pos0; #ifdef FOG in float v_fog_opacity; #endif #ifdef RENDER_SHADOWS in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1; #endif uniform vec3 u_ground_shadow_factor;void main() {vec4 image_color=texture(u_image0,v_pos0);vec4 color; #ifdef LIGHTING_3D_MODE const vec3 normal=vec3(0.0,0.0,1.0); #ifdef RENDER_SHADOWS float cutoffOpacity=1.0; #ifdef RENDER_CUTOFF cutoffOpacity=cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w); #endif #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;vec3 unlit_base=image_color.rgb*(1.0-emissive_strength);vec3 emissive_base=image_color.rgb*emissive_strength;float ndotl=u_shadow_direction.z;float occlusion=ndotl < 0.0 ? 1.0 : shadow_occlusion(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,0.0);ndotl=max(0.0,ndotl);vec3 lit=apply_lighting(unlit_base,normal,mix(1.0,(1.0-(u_shadow_intensity*occlusion))*ndotl,cutoffOpacity));vec3 emissive=compute_emissive_draped(emissive_base,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=lit+emissive;color.a=1.0; #else float lighting_factor=shadowed_light_factor_normal_unbiased(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);color=apply_lighting(image_color,normal,mix(1.0,lighting_factor,cutoffOpacity)); #endif #else float lighting_factor=u_lighting_directional_dir.z;color=apply_lighting(image_color,normal,lighting_factor); #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;color.rgb=mix(color.rgb,image_color.rgb,emissive_strength);color.a=1.0; #endif #endif #else color=image_color; #endif #ifdef FOG #ifdef ZERO_EXAGGERATION color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #else color=fog_dither(fog_apply_from_vert(color,v_fog_opacity)); #endif #endif glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;uniform float u_skirt_height;in ivec2 a_pos;out vec2 v_pos0; #ifdef FOG out float v_fog_opacity; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1; #endif void main() {vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;vec2 decodedPos=decomposedPosAndSkirt.xy;float elevation=elevation(decodedPos)-skirt*u_skirt_height;v_pos0=decodedPos/8192.0;gl_Position=u_matrix*vec4(decodedPos,elevation,1.0); #ifdef FOG #ifdef ZERO_EXAGGERATION v_fog_pos=fog_position(decodedPos); #else v_fog_opacity=fog(fog_position(vec3(decodedPos,elevation))); #endif #endif #ifdef RENDER_SHADOWS vec3 pos=vec3(decodedPos,elevation);v_pos_light_view_0=u_light_matrix_0*vec4(pos,1.);v_pos_light_view_1=u_light_matrix_1*vec4(pos,1.); #endif }`),terrainDepth:gi("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:gi(`#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 }`,Jb),skyboxGradient:gi(`#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 }`,Jb),skyboxCapture:gi(` in highp vec3 v_position;uniform highp float u_sun_intensity;uniform highp float u_luminance;uniform lowp vec3 u_sun_direction;uniform highp vec4 u_color_tint_r;uniform highp vec4 u_color_tint_m;precision highp float; #define BETA_R vec3(5.5e-6,13.0e-6,22.4e-6) #define BETA_M vec3(21e-6,21e-6,21e-6) #define MIE_G 0.76 #define DENSITY_HEIGHT_SCALE_R 8000.0 #define DENSITY_HEIGHT_SCALE_M 1200.0 #define PLANET_RADIUS 6360e3 #define ATMOSPHERE_RADIUS 6420e3 #define SAMPLE_STEPS 10 #define DENSITY_STEPS 4 float ray_sphere_exit(vec3 orig,vec3 dir,float radius) {float a=dot(dir,dir);float b=2.0*dot(dir,orig);float c=dot(orig,orig)-radius*radius;float d=sqrt(b*b-4.0*a*c);return (-b+d)/(2.0*a);}vec3 extinction(vec2 density) {return exp(-vec3(BETA_R*u_color_tint_r.a*density.x+BETA_M*u_color_tint_m.a*density.y));}vec2 local_density(vec3 point) {float height=max(length(point)-PLANET_RADIUS,0.0);float exp_r=exp(-height/DENSITY_HEIGHT_SCALE_R);float exp_m=exp(-height/DENSITY_HEIGHT_SCALE_M);return vec2(exp_r,exp_m);}float phase_ray(float cos_angle) {return (3.0/(16.0*PI))*(1.0+cos_angle*cos_angle);}float phase_mie(float cos_angle) {return (3.0/(8.0*PI))*((1.0-MIE_G*MIE_G)*(1.0+cos_angle*cos_angle))/((2.0+MIE_G*MIE_G)*pow(1.0+MIE_G*MIE_G-2.0*MIE_G*cos_angle,1.5));}vec2 density_to_atmosphere(vec3 point,vec3 light_dir) {float ray_len=ray_sphere_exit(point,light_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(DENSITY_STEPS);vec2 density_point_to_atmosphere=vec2(0.0);for (int i=0; i < DENSITY_STEPS;++i) {vec3 point_on_ray=point+light_dir*((float(i)+0.5)*step_len);density_point_to_atmosphere+=local_density(point_on_ray)*step_len;;}return density_point_to_atmosphere;}vec3 atmosphere(vec3 ray_dir,vec3 sun_direction,float sun_intensity) {vec2 density_orig_to_point=vec2(0.0);vec3 scatter_r=vec3(0.0);vec3 scatter_m=vec3(0.0);vec3 origin=vec3(0.0,PLANET_RADIUS,0.0);float ray_len=ray_sphere_exit(origin,ray_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(SAMPLE_STEPS);for (int i=0; i < SAMPLE_STEPS;++i) {vec3 point_on_ray=origin+ray_dir*((float(i)+0.5)*step_len);vec2 density=local_density(point_on_ray)*step_len;density_orig_to_point+=density;vec2 density_point_to_atmosphere=density_to_atmosphere(point_on_ray,sun_direction);vec2 density_orig_to_atmosphere=density_orig_to_point+density_point_to_atmosphere;vec3 extinction=extinction(density_orig_to_atmosphere);scatter_r+=density.x*extinction;scatter_m+=density.y*extinction;}float cos_angle=dot(ray_dir,sun_direction);float phase_r=phase_ray(cos_angle);float phase_m=phase_mie(cos_angle);vec3 beta_r=BETA_R*u_color_tint_r.rgb*u_color_tint_r.a;vec3 beta_m=BETA_M*u_color_tint_m.rgb*u_color_tint_m.a;return (scatter_r*phase_r*beta_r+scatter_m*phase_m*beta_m)*sun_intensity;}const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;vec3 uncharted2_tonemap(vec3 x) {return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}void main() {vec3 ray_direction=v_position;ray_direction.y=pow(ray_direction.y,5.0);const float y_bias=0.015;ray_direction.y+=y_bias;vec3 color=atmosphere(normalize(ray_direction),u_sun_direction,u_sun_intensity);float white_scale=1.0748724675633854;color=uncharted2_tonemap((log2(2.0/pow(u_luminance,4.0)))*color)*white_scale;glFragColor=vec4(color,1.0);}`,"in highp vec3 a_pos_3f;uniform mat3 u_matrix_3f;out highp vec3 v_position;float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec4 pos=vec4(u_matrix_3f*a_pos_3f,1.0);v_position=pos.xyz;v_position.y*=-1.0;v_position.y=map(v_position.y,-1.0,1.0,0.0,1.0);gl_Position=vec4(a_pos_3f.xy,0.0,1.0);}"),globeRaster:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image0; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS uniform sampler2D u_image1;uniform float u_emissive_texture_available; #endif uniform float u_far_z_cutoff;in vec2 v_pos0; #ifndef FOG uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform vec2 u_viewport; #endif void main() {vec4 color; #ifdef CUSTOM_ANTIALIASING highp vec2 uv=gl_FragCoord.xy/u_viewport; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif highp vec3 ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float norm_dist_from_center=1.0-length(closest_point-u_globe_pos)/u_globe_radius;const float antialias_pixel=2.0;highp float antialias_factor=antialias_pixel*fwidth(norm_dist_from_center);highp float antialias=smoothstep(0.0,antialias_factor,norm_dist_from_center);vec4 raster=texture(u_image0,v_pos0); #ifdef LIGHTING_3D_MODE #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : raster.a;raster=apply_lighting_with_emission_ground(raster,emissive_strength);color=vec4(clamp(raster.rgb,vec3(0),vec3(1))*antialias,antialias); #else raster=apply_lighting_ground(raster);color=vec4(raster.rgb*antialias,raster.a*antialias); #endif #else color=vec4(raster.rgb*antialias,raster.a*antialias); #endif #else color=texture(u_image0,v_pos0); #ifdef LIGHTING_3D_MODE #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : color.a;color=apply_lighting_with_emission_ground(color,emissive_strength);color.a=1.0; #else color=apply_lighting_ground(color); #endif #endif #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #endif color*=1.0-step(u_far_z_cutoff,1.0/gl_FragCoord.w);glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_proj_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform float u_zoom_transition;uniform vec2 u_merc_center;uniform mat3 u_grid_matrix;uniform float u_skirt_height; #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in ivec2 a_pos; #endif out vec2 v_pos0;void main() { #ifdef GLOBE_POLES vec3 globe_pos=a_globe_pos;vec2 uv=a_uv; #else float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float uvY=mercatorY*tiles-idy;float mercatorX=mercatorXfromLng(latLng[1]);float uvX=mercatorX*tiles-idx;vec3 globe_pos=latLngToECEF(latLng.xy);vec2 merc_pos=vec2(mercatorX,mercatorY);vec2 uv=vec2(uvX,uvY); #endif v_pos0=uv;vec2 tile_pos=uv*EXTENT;vec3 globe_derived_up_vector=normalize(globe_pos)*u_tile_up_scale; #ifdef GLOBE_POLES vec3 up_vector=globe_derived_up_vector; #else vec3 up_vector=elevationVector(tile_pos); #endif float height=elevation(tile_pos);globe_pos+=up_vector*height; #ifndef GLOBE_POLES globe_pos-=globe_derived_up_vector*u_skirt_height*decomposed_pos_and_skirt.z; #endif #ifdef GLOBE_POLES vec4 interpolated_pos=u_globe_matrix*vec4(globe_pos,1.0); #else vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {merc_world_pos=vec4(merc_pos,height-u_skirt_height*decomposed_pos_and_skirt.z,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0); #endif gl_Position=u_proj_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif }`),globeAtmosphere:gi(`#include "_prelude_fog.fragment.glsl" uniform float u_transition;uniform highp float u_fadeout_range;uniform highp float u_temporal_offset;uniform vec4 u_atmosphere_fog_color;uniform vec4 u_high_color;uniform vec4 u_space_color;uniform float u_horizon_angle;in highp vec3 v_ray_dir;in highp vec3 v_horizon_dir;void main() {highp vec3 dir=normalize(v_ray_dir);float globe_pos_dot_dir; #ifdef PROJECTION_GLOBE_VIEW globe_pos_dot_dir=dot(u_globe_pos,dir);highp vec3 closest_point_forward=abs(globe_pos_dot_dir)*dir;float norm_dist_from_center=length(closest_point_forward-u_globe_pos)/u_globe_radius;if (norm_dist_from_center < 0.98) { #ifdef ALPHA_PASS glFragColor=vec4(0,0,0,0);return; #else #ifdef NATIVE glFragColor=vec4(1,1,1,1); #else glFragColor=vec4(0,0,0,1); #endif return; #endif } #endif highp vec3 horizon_dir=normalize(v_horizon_dir);float horizon_angle_mercator=dir.y < horizon_dir.y ? 0.0 : max(acos(clamp(dot(dir,horizon_dir),-1.0,1.0)),0.0);float horizon_angle; #ifdef PROJECTION_GLOBE_VIEW highp vec3 closest_point=globe_pos_dot_dir*dir;highp float closest_point_to_center=length(closest_point-u_globe_pos);highp float theta=asin(clamp(closest_point_to_center/length(u_globe_pos),-1.0,1.0));horizon_angle=globe_pos_dot_dir < 0.0 ? PI-theta-u_horizon_angle : theta-u_horizon_angle;float angle_t=pow(u_transition,10.0);horizon_angle=mix(horizon_angle,horizon_angle_mercator,angle_t); #else horizon_angle=horizon_angle_mercator; #endif horizon_angle/=PI;float t=exp(-horizon_angle/u_fadeout_range);float alpha_0=u_atmosphere_fog_color.a;float alpha_1=u_high_color.a;float alpha_2=u_space_color.a;vec3 color_stop_0=u_atmosphere_fog_color.rgb;vec3 color_stop_1=u_high_color.rgb;vec3 color_stop_2=u_space_color.rgb; #ifdef ALPHA_PASS float a0=mix(alpha_2,1.0,alpha_1);float a1=mix(a0,1.0,alpha_0);float a2=mix(a0,a1,t);float a =mix(alpha_2,a2,t);glFragColor=vec4(1.0,1.0,1.0,a); #else vec3 c0=mix(color_stop_2,color_stop_1,alpha_1);vec3 c1=mix(c0,color_stop_0,alpha_0);vec3 c2=mix(c0,c1,t);vec3 c=c2;glFragColor=vec4(c*t,t); #endif }`,`in vec3 a_pos;in vec2 a_uv;uniform vec3 u_frustum_tl;uniform vec3 u_frustum_tr;uniform vec3 u_frustum_br;uniform vec3 u_frustum_bl;uniform float u_horizon;out highp vec3 v_ray_dir;out highp vec3 v_horizon_dir;void main() {v_ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,a_uv.x),mix(u_frustum_bl,u_frustum_br,a_uv.x),a_uv.y);v_horizon_dir=mix( mix(u_frustum_tl,u_frustum_bl,u_horizon),mix(u_frustum_tr,u_frustum_br,u_horizon),a_uv.x);gl_Position=vec4(a_pos,1.0);}`),model:gi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_opacity; #ifdef DITHERED_DISCARD uniform float u_dithered_discard_threshold; #endif uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity;uniform vec4 u_baseColorFactor;uniform vec4 u_emissiveFactor;uniform float u_metallicFactor;uniform float u_roughnessFactor;uniform float u_emissive_strength;in highp vec4 v_position_height;in lowp vec4 v_color_mix; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth_shadows; #endif #ifdef OCCLUSION_TEXTURE_TRANSFORM uniform vec4 u_occlusionTextureTransform; #endif #pragma mapbox: define-attribute highp vec3 normal_3f #pragma mapbox: define-attribute highp vec3 color_3f #pragma mapbox: define-attribute highp vec4 color_4f #pragma mapbox: define-attribute highp vec2 uv_2f #pragma mapbox: initialize-attribute highp vec3 normal_3f #pragma mapbox: initialize-attribute highp vec3 color_3f #pragma mapbox: initialize-attribute highp vec4 color_4f #pragma mapbox: initialize-attribute highp vec2 uv_2f #ifdef HAS_ATTRIBUTE_a_pbr in lowp vec4 v_roughness_metallic_emissive_alpha;in mediump vec4 v_height_based_emission_params; #endif #ifdef HAS_TEXTURE_u_baseColorTexture uniform sampler2D u_baseColorTexture;uniform bool u_baseTextureIsAlpha;uniform bool u_alphaMask;uniform float u_alphaCutoff; #endif #ifdef HAS_TEXTURE_u_metallicRoughnessTexture uniform sampler2D u_metallicRoughnessTexture; #endif #ifdef HAS_TEXTURE_u_occlusionTexture uniform sampler2D u_occlusionTexture;uniform float u_aoIntensity; #endif #ifdef HAS_TEXTURE_u_normalTexture uniform sampler2D u_normalTexture; #endif #ifdef HAS_TEXTURE_u_emissionTexture uniform sampler2D u_emissionTexture; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef TERRAIN_FRAGMENT_OCCLUSION in highp float v_depth;uniform highp sampler2D u_depthTexture;uniform highp vec2 u_inv_depth_size;uniform highp vec2 u_depth_range_unpack; #ifdef DEPTH_D24 highp float unpack_depth(highp float depth) {return depth*u_depth_range_unpack.x+u_depth_range_unpack.y;} #else highp float unpack_depth_rgba(highp vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;} #endif bool isOccluded() {highp vec2 coord=gl_FragCoord.xy*u_inv_depth_size; #ifdef FLIP_Y coord.y=1.0-coord.y; #endif #ifdef DEPTH_D24 highp float depth=unpack_depth(texture(u_depthTexture,coord).r); #else highp float depth=unpack_depth_rgba(texture(u_depthTexture,coord)); #endif return v_depth > depth+0.0005;} #endif #define saturate(_x) clamp(_x,0.,1.) vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}float calculate_NdotL(vec3 normal,vec3 lightDir) {const float ext=0.70710678118;return (clamp(dot(normal,lightDir),-ext,1.0)+ext)/(1.0+ext);}vec3 getDiffuseShadedColor(vec3 albedo,vec3 normal,vec3 lightDir,vec3 lightColor) { #ifdef LIGHTING_3D_MODE vec3 transformed_normal=vec3(-normal.xy,normal.z);float lighting_factor; #ifdef RENDER_SHADOWS lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows); #else lighting_factor=saturate(dot(transformed_normal,u_lighting_directional_dir)); #endif return apply_lighting(albedo,transformed_normal,lighting_factor); #else vec3 n=normal;float colorvalue=((albedo.x*0.2126)+(albedo.y*0.7152))+(albedo.z*0.0722);vec3 c=vec3(0.03,0.03,0.03);float directional=clamp(dot(n,vec3(lightDir)),0.0,1.0);directional=mix(1.0-u_lightintensity,max((1.0-colorvalue)+u_lightintensity,1.0),directional);vec3 c3=c+clamp((albedo*directional)*lightColor,mix(vec3(0.0),vec3(0.3),vec3(1.0)-lightColor),vec3(1.0));return c3; #endif }vec4 getBaseColor() {vec4 albedo=u_baseColorFactor; #ifdef HAS_ATTRIBUTE_a_color_3f albedo*=vec4(color_3f,1.0); #endif #ifdef HAS_ATTRIBUTE_a_pbr #else #ifdef HAS_ATTRIBUTE_a_color_4f albedo*=color_4f; #endif #endif #if defined (HAS_TEXTURE_u_baseColorTexture) && defined (HAS_ATTRIBUTE_a_uv_2f) vec4 texColor=texture(u_baseColorTexture,uv_2f);if(u_alphaMask) {if (texColor.w < u_alphaCutoff) {discard;}} #ifdef UNPREMULT_TEXTURE_IN_SHADER if(texColor.w > 0.0) {texColor.rgb/=texColor.w;}texColor.w=1.0; #endif if(u_baseTextureIsAlpha) {if (texColor.r < 0.5) {discard;}} else {texColor.rgb=sRGBToLinear(texColor.rgb);albedo*=texColor;} #endif vec4 color=vec4(mix(albedo.rgb,v_color_mix.rgb,v_color_mix.a),albedo.a); #ifdef APPLY_LUT_ON_GPU color=applyLUT(u_lutTexture,color); #endif return color;}highp mat3 cotangentFrame(highp vec3 N,highp vec3 p,highp vec2 uv ) { #ifdef HAS_TEXTURE_u_normalTexture highp vec3 dp1=vec3(dFdx(p.x),dFdx(p.y),dFdx(p.z));highp vec3 dp2=vec3(dFdy(p.x),dFdy(p.y),dFdy(p.z));highp vec2 duv1=vec2(dFdx(uv.x),dFdx(uv.y));highp vec2 duv2=vec2(dFdy(uv.x),dFdy(uv.y));highp vec3 dp2perp=cross( dp2,N );highp vec3 dp1perp=cross( N,dp1 );highp vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;highp vec3 B=dp2perp*duv1.y+dp1perp*duv2.y; #ifdef FLIP_Y T=-T;B=-B; #endif highp float lengthT=dot(T,T);highp float lengthB=dot(B,B);highp float maxLength=max(lengthT,lengthB);highp float invmax=inversesqrt( maxLength );highp mat3 res=mat3( T*invmax,B*invmax,N );return res; #else return mat3(1.0); #endif }highp vec3 getNormal(){highp vec3 n; #ifdef HAS_ATTRIBUTE_a_normal_3f n=normalize(normal_3f); #else highp vec3 fdx=vec3(dFdx(v_position_height.x),dFdx(v_position_height.y),dFdx(v_position_height.z));highp vec3 fdy=vec3(dFdy(v_position_height.x),dFdy(v_position_height.y),dFdy(v_position_height.z)); #ifdef FLIP_Y n=normalize(cross(fdx,fdy)); #else n=normalize(cross(fdx,fdy))*-1.0; #endif #endif #if defined(HAS_TEXTURE_u_normalTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) vec3 nMap=texture( u_normalTexture,uv_2f).xyz;nMap=normalize(2.0*nMap-vec3(1.0));highp vec3 v=normalize(-v_position_height.xyz);highp mat3 TBN=cotangentFrame(n,v,uv_2f);n=normalize(TBN*nMap); #endif return n;}struct Material {float perceptualRoughness;float alphaRoughness;float metallic;vec3 f90;vec4 baseColor;vec3 diffuseColor;vec3 specularColor;highp vec3 normal;};Material getPBRMaterial() {Material mat;mat.baseColor=getBaseColor();mat.perceptualRoughness=u_roughnessFactor;mat.metallic=u_metallicFactor; #ifdef HAS_ATTRIBUTE_a_pbr mat.perceptualRoughness=v_roughness_metallic_emissive_alpha.x;mat.metallic=v_roughness_metallic_emissive_alpha.y;mat.baseColor.w*=v_roughness_metallic_emissive_alpha.w; #endif #if defined(HAS_TEXTURE_u_metallicRoughnessTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) vec4 mrSample=texture(u_metallicRoughnessTexture,uv_2f);mat.perceptualRoughness*=mrSample.g;mat.metallic*=mrSample.b; #endif const float c_minRoughness=0.04;mat.perceptualRoughness=clamp(mat.perceptualRoughness,c_minRoughness,1.0);mat.metallic=saturate(mat.metallic);mat.alphaRoughness=mat.perceptualRoughness*mat.perceptualRoughness;const vec3 f0=vec3(0.04);mat.diffuseColor=mat.baseColor.rgb*(vec3(1.0)-f0);mat.diffuseColor*=1.0-mat.metallic;mat.specularColor=mix(f0,mat.baseColor.rgb,mat.metallic);highp float reflectance=max(max(mat.specularColor.r,mat.specularColor.g),mat.specularColor.b);highp float reflectance90=saturate(reflectance*25.0);mat.f90=vec3(reflectance90);mat.normal=getNormal();return mat;}float V_GGX(float NdotL,float NdotV,float roughness) {float a2=roughness*roughness;float GGXV=NdotL*sqrt(NdotV*NdotV*(1.0-a2)+a2);float GGXL=NdotV*sqrt(NdotL*NdotL*(1.0-a2)+a2);return 0.5/(GGXV+GGXL);}float V_GGXFast(float NdotL,float NdotV,float roughness) {float a=roughness;float GGXV=NdotL*(NdotV*(1.0-a)+a);float GGXL=NdotV*(NdotL*(1.0-a)+a);return 0.5/(GGXV+GGXL);}vec3 F_Schlick(vec3 specularColor,vec3 f90,float VdotH) {return specularColor+(f90-specularColor)*pow(clamp(1.0-VdotH,0.0,1.0),5.0);}vec3 F_SchlickFast(vec3 specularColor,float VdotH) {float x=1.0-VdotH;float x4=x*x*x*x;return specularColor+(1.0-specularColor)*x4*x;}float D_GGX(highp float NdotH,float alphaRoughness) {highp float a4=alphaRoughness*alphaRoughness;highp float f=(NdotH*a4-NdotH)*NdotH+1.0;return a4/(PI*f*f);}vec3 diffuseBurley(Material mat,float LdotH,float NdotL,float NdotV) {float f90=2.0*LdotH*LdotH*mat.alphaRoughness-0.5;return (mat.diffuseColor/PI)*(1.0+f90*pow((1.0-NdotL),5.0))*(1.0+f90*pow((1.0-NdotV),5.0));}vec3 diffuseLambertian(Material mat) { #ifdef LIGHTING_3D_MODE return mat.diffuseColor; #else return mat.diffuseColor/PI; #endif }vec3 EnvBRDFApprox(vec3 specularColor,float roughness,highp float NdotV) {vec4 c0=vec4(-1,-0.0275,-0.572,0.022);vec4 c1=vec4(1,0.0425,1.04,-0.04);highp vec4 r=roughness*c0+c1;highp float a004=min(r.x*r.x,exp2(-9.28*NdotV))*r.x+r.y;vec2 AB=vec2(-1.04,1.04)*a004+r.zw;return specularColor*AB.x+AB.y;}vec3 computeIndirectLightContribution(Material mat,float NdotV,vec3 normal) {vec3 env_light=vec3(0.65,0.65,0.65); #ifdef LIGHTING_3D_MODE float ambient_factor=calculate_ambient_directional_factor(normal);env_light=u_lighting_ambient_color*ambient_factor; #endif vec3 envBRDF=EnvBRDFApprox(mat.specularColor,mat.perceptualRoughness,NdotV);vec3 indirectSpecular= envBRDF*env_light;vec3 indirectDiffuse=mat.diffuseColor*env_light;return indirectSpecular+indirectDiffuse;}vec3 computeLightContribution(Material mat,vec3 lightPosition,vec3 lightColor) {highp vec3 n=mat.normal;highp vec3 v=normalize(-v_position_height.xyz);highp vec3 l=normalize(lightPosition);highp vec3 h=normalize(v+l);float NdotV=clamp(abs(dot(n,v)),0.001,1.0);float NdotL=saturate(dot(n,l));highp float NdotH=saturate(dot(n,h));float VdotH=saturate(dot(v,h));vec3 f=F_SchlickFast(mat.specularColor,VdotH);float g=V_GGXFast(NdotL,NdotV,mat.alphaRoughness);float d=D_GGX(NdotH,mat.alphaRoughness);vec3 diffuseTerm=(1.0-f)*diffuseLambertian(mat);vec3 specularTerm=f*g*d;vec3 transformed_normal=vec3(-n.xy,n.z);float lighting_factor; #ifdef RENDER_SHADOWS lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows); #else lighting_factor=NdotL; #endif vec3 directLightColor=(specularTerm+diffuseTerm)*lighting_factor*lightColor;vec3 indirectLightColor=computeIndirectLightContribution(mat,NdotV,transformed_normal);vec3 color=(saturate(directLightColor)+indirectLightColor);float intensityFactor=1.0; #if !defined(LIGHTING_3D_MODE) const vec3 luminosityFactor=vec3(0.2126,0.7152,0.0722);float luminance=dot(diffuseTerm,luminosityFactor);intensityFactor=mix((1.0-u_lightintensity),max((1.0-luminance+u_lightintensity),1.0),NdotL); #endif color*=intensityFactor;return color;}void main() { #ifdef TERRAIN_FRAGMENT_OCCLUSION if (isOccluded()) {discard;} #endif vec3 lightDir=u_lightpos;vec3 lightColor=u_lightcolor; #ifdef LIGHTING_3D_MODE lightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color; #endif vec4 finalColor; #ifdef DIFFUSE_SHADED vec3 N=getNormal();vec3 baseColor=getBaseColor().rgb;vec3 diffuse=getDiffuseShadedColor(baseColor,N,lightDir,lightColor); #ifdef HAS_TEXTURE_u_occlusionTexture float ao=(texture(u_occlusionTexture,uv_2f).r-1.0)*u_aoIntensity+1.0;diffuse*=ao; #endif finalColor=vec4(mix(diffuse,baseColor,u_emissive_strength),1.0)*u_opacity; #else Material mat=getPBRMaterial();vec3 color=computeLightContribution(mat,lightDir,lightColor);float ao=1.0; #if defined (HAS_TEXTURE_u_occlusionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) #ifdef OCCLUSION_TEXTURE_TRANSFORM vec2 uv=uv_2f.xy*u_occlusionTextureTransform.zw+u_occlusionTextureTransform.xy; #else vec2 uv=uv_2f; #endif ao=(texture(u_occlusionTexture,uv).x-1.0)*u_aoIntensity+1.0;color*=ao; #endif vec4 emissive=u_emissiveFactor; #if defined(HAS_TEXTURE_u_emissionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) emissive.rgb*=sRGBToLinear(texture(u_emissionTexture,uv_2f).rgb); #endif #ifdef APPLY_LUT_ON_GPU float emissiveFactorLength=max(length(u_emissiveFactor.rgb),0.001);emissive.rgb=sRGBToLinear(applyLUT(u_lutTexture,linearTosRGB(emissive.rgb/emissiveFactorLength).rbg))*emissiveFactorLength; #endif color+=emissive.rgb;float opacity=mat.baseColor.w*u_opacity; #ifdef HAS_ATTRIBUTE_a_pbr float resEmission=v_roughness_metallic_emissive_alpha.z;resEmission*=v_height_based_emission_params.z+v_height_based_emission_params.w*pow(clamp(v_height_based_emission_params.x,0.0,1.0),v_height_based_emission_params.y);vec3 color_mix=v_color_mix.rgb; #ifdef APPLY_LUT_ON_GPU color_mix=applyLUT(u_lutTexture,color_mix); #endif color=mix(color,color_mix,min(1.0,resEmission)); #ifdef HAS_ATTRIBUTE_a_color_4f float distance=length(vec2(1.3*max(0.0,abs(color_4f.x)-color_4f.z),color_4f.y));distance+= mix(0.5,0.0,clamp(resEmission-1.0,0.0,1.0));opacity*=v_roughness_metallic_emissive_alpha.w*saturate(1.0-distance*distance); #endif #endif vec3 unlitColor=mat.baseColor.rgb*ao+emissive.rgb;color=mix(color,unlitColor,u_emissive_strength);color=linearTosRGB(color);color*=opacity;finalColor=vec4(color,opacity); #endif #ifdef DITHERED_DISCARD if (abs(u_dithered_discard_threshold) < 1.0) {float ditherValue=fract(52.9829189*fract(0.06711056*gl_FragCoord.x+0.00583715*gl_FragCoord.y));float compareValue=mix(1.0-ditherValue,ditherValue,step(0.0,u_dithered_discard_threshold));if (abs(u_dithered_discard_threshold) < compareValue) {discard;}} #endif #ifdef FOG finalColor=fog_dither(fog_apply_premultiplied(finalColor,v_fog_pos,v_position_height.w)); #endif #ifdef RENDER_CUTOFF finalColor*=v_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT finalColor=applyCutout(finalColor,v_position_height.w); #endif #ifdef FEATURE_CUTOUT finalColor=apply_feature_cutout(finalColor,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif glFragColor=finalColor; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec3 a_pos_3f; #pragma mapbox: define-attribute highp vec3 normal_3f #pragma mapbox: define-attribute highp vec2 uv_2f #pragma mapbox: define-attribute highp vec3 color_3f #pragma mapbox: define-attribute highp vec4 color_4f #pragma mapbox: define-attribute-vertex-shader-only highp uvec4 pbr #pragma mapbox: define-attribute-vertex-shader-only highp vec3 heightBasedEmissiveStrength uniform mat4 u_matrix;uniform mat4 u_node_matrix;uniform mat4 u_lighting_matrix;uniform vec3 u_camera_pos;uniform vec4 u_color_mix; #ifdef INSTANCED_ARRAYS in vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3; #else uniform highp mat4 u_normal_matrix; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth_shadows; #endif out vec4 v_position_height;out lowp vec4 v_color_mix; #ifdef TERRAIN_FRAGMENT_OCCLUSION out highp float v_depth; #endif #ifdef HAS_ATTRIBUTE_a_pbr out lowp vec4 v_roughness_metallic_emissive_alpha;out mediump vec4 v_height_based_emission_params; #endif vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() { #pragma mapbox: initialize-attribute highp vec3 normal_3f #pragma mapbox: initialize-attribute highp vec2 uv_2f #pragma mapbox: initialize-attribute highp vec3 color_3f #pragma mapbox: initialize-attribute highp vec4 color_4f #pragma mapbox: initialize-attribute-custom highp uvec4 pbr #pragma mapbox: initialize-attribute-custom highp vec3 heightBasedEmissiveStrength highp mat4 normal_matrix; #ifdef INSTANCED_ARRAYS normal_matrix=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3); #else normal_matrix=u_normal_matrix; #endif vec3 local_pos;mat3 rs; #ifdef MODEL_POSITION_ON_GPU vec3 pos_color=normal_matrix[0].xyz;vec4 translate=normal_matrix[1];vec3 pos_a=floor(pos_color);vec3 rgb=1.05*(pos_color-pos_a);float hidden=float(pos_a.x > EXTENT);float color_mix=pos_a.z/100.0;v_color_mix=vec4(sRGBToLinear(rgb),color_mix);float meter_to_tile=normal_matrix[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);rs[0].x=normal_matrix[1].w;rs[0].yz=normal_matrix[2].xy;rs[1].xy=normal_matrix[2].zw;rs[1].z=normal_matrix[3].x;rs[2].xyz=normal_matrix[3].yzw;vec4 pos_node=u_lighting_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;local_pos=pos.xyz;gl_Position=mix(u_matrix*pos,AWAY,hidden);pos.z*=meter_to_tile;v_position_height.xyz=pos.xyz-u_camera_pos; #else local_pos=a_pos_3f;gl_Position=u_matrix*vec4(a_pos_3f,1);v_position_height.xyz=vec3(u_lighting_matrix*vec4(a_pos_3f,1));v_color_mix=vec4(sRGBToLinear(u_color_mix.rgb),u_color_mix.a); #endif v_position_height.w=a_pos_3f.z; #ifdef HAS_ATTRIBUTE_a_pbr vec4 albedo_c=decode_color(vec2(pbr.xy));vec2 e_r_m=unpack_float(float(pbr.z));vec2 r_m= unpack_float(e_r_m.y*16.0);r_m.r=r_m.r*16.0;v_color_mix=vec4(albedo_c.rgb,1.0);v_roughness_metallic_emissive_alpha=vec4(vec3(r_m,e_r_m.x)/255.0,albedo_c.a);v_roughness_metallic_emissive_alpha.z*=2.0;float heightBasedRelativeIntepolation=a_pos_3f.z*heightBasedEmissiveStrength.x+heightBasedEmissiveStrength.y;v_height_based_emission_params.x=heightBasedRelativeIntepolation;v_height_based_emission_params.y=heightBasedEmissiveStrength.z;vec2 emissionMultiplierValues=unpack_float(float(pbr.w))/256.0;v_height_based_emission_params.z=emissionMultiplierValues.x;v_height_based_emission_params.w=emissionMultiplierValues.y-emissionMultiplierValues.x; #endif #ifdef FOG v_fog_pos=fog_position(local_pos); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif #ifdef TERRAIN_FRAGMENT_OCCLUSION v_depth=gl_Position.z/gl_Position.w; #ifdef CLIP_ZERO_TO_ONE v_depth=-1.0+2.0*v_depth; #endif #endif #ifdef HAS_ATTRIBUTE_a_normal_3f #ifdef MODEL_POSITION_ON_GPU float x_squared_scale=dot(rs[0],rs[0]);float y_squared_scale=dot(rs[1],rs[1]);float z_squared_scale=dot(rs[2],rs[2]);vec3 squared_scale=vec3(x_squared_scale,y_squared_scale,z_squared_scale);normal_3f=rs*((u_lighting_matrix*vec4(normal_3f,0.0)).xyz/squared_scale);normal_3f=normalize(normal_3f); #else normal_3f=vec3(normal_matrix*vec4(normal_3f,0)); #endif #endif #ifdef HAS_ATTRIBUTE_a_pbr #ifdef HAS_ATTRIBUTE_a_color_4f v_roughness_metallic_emissive_alpha.w=clamp(color_4f.a*v_roughness_metallic_emissive_alpha.w*(v_roughness_metallic_emissive_alpha.z-1.0),0.0,1.0); #endif #endif #ifdef RENDER_SHADOWS vec4 shadow_pos=u_node_matrix*vec4(local_pos,1.0); #ifdef NORMAL_OFFSET #ifdef HAS_ATTRIBUTE_a_normal_3f #ifdef MODEL_POSITION_ON_GPU vec3 offset=shadow_normal_offset(vec3(-normal_3f.xy,normal_3f.z));shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #else vec3 offset=shadow_normal_offset_model(normal_3f);shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #endif #endif #endif v_pos_light_view_0=u_light_matrix_0*shadow_pos;v_pos_light_view_1=u_light_matrix_1*shadow_pos;v_depth_shadows=gl_Position.w; #endif }`),modelDepth:gi("void main() {}",`in vec3 a_pos_3f;uniform mat4 u_matrix; #ifdef MODEL_POSITION_ON_GPU #ifdef INSTANCED_ARRAYS in vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3; #else uniform highp mat4 u_instance; #endif uniform highp mat4 u_node_matrix; #endif void main() { #ifdef MODEL_POSITION_ON_GPU highp mat4 instance; #ifdef INSTANCED_ARRAYS instance=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3); #else instance=u_instance; #endif vec3 pos_color=instance[0].xyz;vec4 translate=instance[1];vec3 pos_a=floor(pos_color);float hidden=float(pos_a.x > EXTENT);float meter_to_tile=instance[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);mat3 rs;rs[0].x=instance[1].w;rs[0].yz=instance[2].xy;rs[1].xy=instance[2].zw;rs[1].z=instance[3].x;rs[2].xyz=instance[3].yzw;vec4 pos_node=u_node_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;gl_Position=mix(u_matrix*pos,AWAY,hidden); #else gl_Position=u_matrix*vec4(a_pos_3f,1); #endif }`),stars:gi(`in highp vec2 v_uv;in mediump float v_intensity;float shapeCircle(in vec2 uv) {float beginFade=0.6;float lengthFromCenter=length(v_uv);return 1.0-clamp((lengthFromCenter-beginFade)/(1.0-beginFade),0.0,1.0);}void main() {float alpha=shapeCircle(v_uv);vec3 color=vec3(1.0,1.0,1.0);alpha*=v_intensity;glFragColor=vec4(color*alpha,alpha);HANDLE_WIREFRAME_DEBUG;}`,` in vec3 a_pos_3f;in vec2 a_uv;in float a_size_scale;in float a_opacity;uniform mat4 u_matrix;uniform vec3 u_up;uniform vec3 u_right;uniform float u_intensity_multiplier;out highp vec2 v_uv;out mediump float v_intensity;void main() {v_uv=a_uv;v_intensity=a_opacity*u_intensity_multiplier;vec3 pos=a_pos_3f;pos+=a_uv.x*u_right*a_size_scale;pos+=a_uv.y*u_up*a_size_scale;gl_Position=u_matrix*vec4(pos,1.0);}`),snowParticle:gi("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:gi("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:gi("uniform vec3 u_vignetteShape;uniform vec4 u_vignetteColor;in vec2 st;void main() {float screenDist=length(st);float alpha=clamp((screenDist-u_vignetteShape.x)/u_vignetteShape.y,0.0,1.0);alpha=pow(alpha,u_vignetteShape.z)*u_vignetteColor.a;vec3 color=u_vignetteColor.rgb;glFragColor=vec4(color*alpha,alpha) ;}","in vec2 a_pos_2f;out vec2 st;void main() {st=a_pos_2f;gl_Position=vec4(a_pos_2f,0,1);}"),occlusion:gi("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 fg(I,y){const C=I.split(` `);for(let R of C){if(R=R.trimStart(),R[0]!=="#"||!R.includes("if")||R.startsWith("#endif"))continue;const $=R.match(gj);if($)for(const G of $)yj.has(G)||y.add(G)}}function bC(I){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(I)}function gi(I,y){const C=new Set,R=[],$=[];I=I.replace(f0,(Z,te)=>($.push(te),"")),y=y.replace(f0,(Z,te)=>(R.push(te),""));let G=new Set($y);fg(I,G),fg(y,G);for(const Z of[...R,...$])m1[Z]||(m1[Z]=new Set,fg($p[Z],m1[Z])),G=new Set([...G,...m1[Z]]);return{fragmentSource:I=I.replace(Bn,(Z,te,ue,xe,je)=>(C.add(je),te==="define"?` #ifndef HAS_UNIFORM_u_${je} ${bC(xe)?"flat ":""}in ${ue} ${xe} ${je}; #else uniform ${ue} ${xe} u_${je}; #endif `:te==="initialize"?` #ifdef HAS_UNIFORM_u_${je} ${ue} ${xe} ${je} = u_${je}; #endif `:te==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${je} in ${ue} ${xe} ${je}; #endif `:te==="initialize-attribute"?"":void 0)),vertexSource:y=y.replace(Bn,(Z,te,ue,xe,je)=>{const Re=`MATERIAL_ATTRIBUTE_OFFSET_${je}`,Le=xe==="float"?"vec2":xe,Ue=`GET_ATTRIBUTE_${Le}(a_${je}, materialInfo, ${Re})`,st=je.match(/color/)?"color":Le;return te==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${je} in ${ue} ${xe} a_${je}; #endif `:C.has(je)?te==="define"?` #ifndef HAS_UNIFORM_u_${je} uniform lowp float u_${je}_t; #if !defined(${Re}) in ${ue} ${Le} a_${je}; #endif ${bC(xe)?"flat ":""}out ${ue} ${xe} ${je}; #else uniform ${ue} ${xe} u_${je}; #endif `:te==="initialize"?st==="vec4"||st==="uvec4"?` #ifndef HAS_UNIFORM_u_${je} ${je} = a_${je}; #else ${ue} ${xe} ${je} = u_${je}; #endif `:` #if !defined(HAS_UNIFORM_u_${je}) #ifdef ${Re} ${je} = unpack_mix_${st}(${Ue}, u_${je}_t); #else ${je} = unpack_mix_${st}(a_${je}, u_${je}_t); #endif #else ${ue} ${xe} ${je} = u_${je}; #endif `:te==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${je} in ${ue} ${xe} a_${je}; out ${ue} ${xe} ${je}; #endif `:te==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${je} ${je} = a_${je}; #endif `:void 0:te==="define"?` #ifndef HAS_UNIFORM_u_${je} uniform lowp float u_${je}_t; #if !defined(${Re}) in ${ue} ${Le} a_${je}; #endif #else uniform ${ue} ${xe} u_${je}; #endif `:te==="define-instanced"?st==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${je}0; in vec4 a_${je}1; in vec4 a_${je}2; in vec4 a_${je}3; #else uniform ${ue} ${xe} u_${je}; #endif `:` #ifdef INSTANCED_ARRAYS in ${ue} ${Le} a_${je}; #else uniform ${ue} ${xe} u_${je}; #endif `:te==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${je} ${ue} ${xe} ${je} = a_${je}; #endif `:st==="vec4"||st==="uvec4"?` #ifndef HAS_UNIFORM_u_${je} #ifdef ${Re} ${ue} ${xe} ${je} = ${Ue}; #else ${ue} ${xe} ${je} = a_${je}; #endif #else ${ue} ${xe} ${je} = u_${je}; #endif `:` #ifndef HAS_UNIFORM_u_${je} #ifdef ${Re} ${ue} ${xe} ${je} = unpack_mix_${st}(${Ue}, u_${je}_t); #else ${ue} ${xe} ${je} = unpack_mix_${st}(a_${je}, u_${je}_t); #endif #else ${ue} ${xe} ${je} = u_${je}; #endif `}),usedDefines:G,vertexIncludes:R,fragmentIncludes:$}}class _C{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(y,C,R,$,G,Z,te,ue){this.context=y;let xe=this.boundPaintVertexBuffers.length!==$.length;for(let Re=0;!xe&&Re<$.length;Re++)this.boundPaintVertexBuffers[Re]!==$[Re]&&(xe=!0);let je=this.boundDynamicVertexBuffers.length!==te.length;for(let Re=0;!je&&Re{const es=Tt.paint.get("hillshade-shadow-color"),Ft=Tt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Jt=Tt.paint.get("hillshade-highlight-color"),At=Tt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Rt=Tt.paint.get("hillshade-accent-color"),Wt=Tt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",ys=Tt.paint.get("hillshade-emissive-strength");let rs=o.ap(Tt.paint.get("hillshade-illumination-direction"));if(Tt.paint.get("hillshade-illumination-anchor")==="viewport")rs-=mt.transform.angle;else if(mt.style&&mt.style.enable3dLights()&&mt.style.directionalLight){const Is=mt.style.directionalLight.properties.get("direction"),an=o.cP(Is.x,Is.y,Is.z);rs=o.ap(an[1])}const zs=!mt.options.moving;return{u_matrix:xt||mt.transform.calculateProjMatrix(jt.tileID.toUnwrapped(),zs),u_image:0,u_latrange:wC(0,jt.tileID),u_light:[Tt.paint.get("hillshade-exaggeration"),rs],u_shadow:es.toPremultipliedRenderColor(Ft?null:Tt.lut),u_highlight:Jt.toPremultipliedRenderColor(At?null:Tt.lut),u_emissive_strength:ys,u_accent:Rt.toPremultipliedRenderColor(Wt?null:Tt.lut)}})(I,C,R,I.terrain?y.projMatrix:null);I.uploadCommonUniforms(te,Le,y.toUnwrapped());const{tileBoundsBuffer:st,tileBoundsIndexBuffer:Xe,tileBoundsSegments:pt}=I.getTileBoundsBuffers(C);Le.draw(I,ue.TRIANGLES,$,G,Z,Fr.disabled,Ue,R.id,st,Xe,pt)}function jC(I,y,C){if(!y.needsDEMTextureUpload)return;const R=I.context,$=R.gl;R.pixelStoreUnpackPremultiplyAlpha.set(!1),y.demTexture=y.demTexture||I.getTileTexture(C.stride);const G=C.getPixels();y.demTexture?y.demTexture.update(G,{premultiply:!1}):y.demTexture=new o.T(R,G,$.R32F,{premultiply:!1}),y.needsDEMTextureUpload=!1}function g6(I,y,C){const R=I.context,$=R.gl;if(!y.dem)return;const G=y.dem;if(R.activeTexture.set($.TEXTURE1),jC(I,y,G),!y.demTexture)return;y.demTexture.bind($.NEAREST,$.CLAMP_TO_EDGE);const Z=G.dim;R.activeTexture.set($.TEXTURE0);let te=y.hillshadeFBO;if(!te){const Le=new o.T(R,{width:Z,height:Z,data:null},$.RGBA8);Le.bind($.LINEAR,$.CLAMP_TO_EDGE),te=y.hillshadeFBO=R.createFramebuffer(Z,Z,1,"renderbuffer"),te.colorAttachment0.set(Le.texture)}R.bindFramebuffer.set(te.framebuffer),R.viewport.set([0,0,Z,Z]);const{tileBoundsBuffer:ue,tileBoundsIndexBuffer:xe,tileBoundsSegments:je}=I.getMercatorTileBoundsBuffers(),Re=[];I.linearFloatFilteringSupported()&&Re.push("TERRAIN_DEM_FLOAT_FORMAT"),I.terrain&&I.terrain.renderingToTexture&&I.emissiveMode==="mrt-fallback"&&Re.push("USE_MRT1"),I.getOrCreateProgram("hillshadePrepare",{defines:Re}).draw(I,$.TRIANGLES,rr.disabled,la.disabled,na.unblended,Fr.disabled,((Le,Ue)=>{const st=Ue.stride,Xe=o.bb();return o.bT(Xe,0,o.an,-o.an,0,0,1),o.bx(Xe,Xe,[0,-o.an,0]),{u_matrix:Xe,u_image:1,u_dimension:[st,st],u_zoom:Le.overscaledZ}})(y.tileID,G),C.id,ue,xe,je),y.needsHillshadePrepare=!1}class dl{constructor(y){this.gl=y.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(y){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class vj extends dl{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(y){const C=this.current;(y.r!==C.r||y.g!==C.g||y.b!==C.b||y.a!==C.a||this.dirty)&&(this.gl.clearColor(y.r,y.g,y.b,y.a),this.current=y,this.dirty=!1)}}class qR extends dl{getDefault(){return 1}set(y){(y!==this.current||this.dirty)&&(this.gl.clearDepth(y),this.current=y,this.dirty=!1)}}class BN extends dl{getDefault(){return 0}set(y){(y!==this.current||this.dirty)&&(this.gl.clearStencil(y),this.current=y,this.dirty=!1)}}class VR extends dl{getDefault(){return[!0,!0,!0,!0]}set(y){const C=this.current;(y[0]!==C[0]||y[1]!==C[1]||y[2]!==C[2]||y[3]!==C[3]||this.dirty)&&(this.gl.colorMask(y[0],y[1],y[2],y[3]),this.current=y,this.dirty=!1)}}class Ff extends dl{getDefault(){return!0}set(y){(y!==this.current||this.dirty)&&(this.gl.depthMask(y),this.current=y,this.dirty=!1)}}class bj extends dl{getDefault(){return 255}set(y){(y!==this.current||this.dirty)&&(this.gl.stencilMask(y),this.current=y,this.dirty=!1)}}class f1 extends dl{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(y){const C=this.current;(y.func!==C.func||y.ref!==C.ref||y.mask!==C.mask||this.dirty)&&(this.gl.stencilFunc(y.func,y.ref,y.mask),this.current=y,this.dirty=!1)}}class $N extends dl{getDefault(){const y=this.gl;return[y.KEEP,y.KEEP,y.KEEP]}set(y){const C=this.current;(y[0]!==C[0]||y[1]!==C[1]||y[2]!==C[2]||this.dirty)&&(this.gl.stencilOp(y[0],y[1],y[2]),this.current=y,this.dirty=!1)}}class Uy extends dl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;y?C.enable(C.STENCIL_TEST):C.disable(C.STENCIL_TEST),this.current=y,this.dirty=!1}}class qy extends dl{getDefault(){return[0,1]}set(y){const C=this.current;(y[0]!==C[0]||y[1]!==C[1]||this.dirty)&&(this.gl.depthRange(y[0],y[1]),this.current=y,this.dirty=!1)}}class Vy extends dl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;y?C.enable(C.DEPTH_TEST):C.disable(C.DEPTH_TEST),this.current=y,this.dirty=!1}}class _m extends dl{getDefault(){return this.gl.LESS}set(y){(y!==this.current||this.dirty)&&(this.gl.depthFunc(y),this.current=y,this.dirty=!1)}}class UN extends dl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;y?C.enable(C.BLEND):C.disable(C.BLEND),this.current=y,this.dirty=!1}}class _j extends dl{getDefault(){const y=this.gl;return[y.ONE,y.ZERO,y.ONE,y.ZERO]}set(y){const C=this.current;(y[0]!==C[0]||y[1]!==C[1]||y[2]!==C[2]||y[3]!==C[3]||this.dirty)&&(this.gl.blendFuncSeparate(y[0],y[1],y[2],y[3]),this.current=y,this.dirty=!1)}}class y6 extends dl{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(y){const C=this.current;(y.r!==C.r||y.g!==C.g||y.b!==C.b||y.a!==C.a||this.dirty)&&(this.gl.blendColor(y.r,y.g,y.b,y.a),this.current=y,this.dirty=!1)}}class x1 extends dl{getDefault(){return this.gl.FUNC_ADD}set(y){(y!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(y,y),this.current=y,this.dirty=!1)}}class wj extends dl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;y?C.enable(C.CULL_FACE):C.disable(C.CULL_FACE),this.current=y,this.dirty=!1}}class jj extends dl{getDefault(){return this.gl.BACK}set(y){(y!==this.current||this.dirty)&&(this.gl.cullFace(y),this.current=y,this.dirty=!1)}}class qN extends dl{getDefault(){return this.gl.CCW}set(y){(y!==this.current||this.dirty)&&(this.gl.frontFace(y),this.current=y,this.dirty=!1)}}let Nj=class extends dl{getDefault(){return null}set(I){(I!==this.current||this.dirty)&&(this.gl.useProgram(I),this.current=I,this.dirty=!1)}};class kj extends dl{getDefault(){return this.gl.TEXTURE0}set(y){(y!==this.current||this.dirty)&&(this.gl.activeTexture(y),this.current=y,this.dirty=!1)}}class wm extends dl{getDefault(){const y=this.gl;return[0,0,y.drawingBufferWidth,y.drawingBufferHeight]}set(y){const C=this.current;(y[0]!==C[0]||y[1]!==C[1]||y[2]!==C[2]||y[3]!==C[3]||this.dirty)&&(this.gl.viewport(y[0],y[1],y[2],y[3]),this.current=y,this.dirty=!1)}}class Vh extends dl{getDefault(){return null}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.bindFramebuffer(C.FRAMEBUFFER,y),this.current=y,this.dirty=!1}}class NC extends dl{getDefault(){return null}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.bindRenderbuffer(C.RENDERBUFFER,y),this.current=y,this.dirty=!1}}class g1 extends dl{getDefault(){return null}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.bindTexture(C.TEXTURE_2D,y),this.current=y,this.dirty=!1}}class kC extends dl{getDefault(){return null}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.bindBuffer(C.ARRAY_BUFFER,y),this.current=y,this.dirty=!1}}class v6 extends dl{getDefault(){return null}set(y){const C=this.gl;C.bindBuffer(C.ELEMENT_ARRAY_BUFFER,y),this.current=y,this.dirty=!1}}class b6 extends dl{getDefault(){return null}set(y){this.gl&&(y!==this.current||this.dirty)&&(this.gl.bindVertexArray(y),this.current=y,this.dirty=!1)}}class SC extends dl{getDefault(){return 4}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_ALIGNMENT,y),this.current=y,this.dirty=!1}}class VN extends dl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_PREMULTIPLY_ALPHA_WEBGL,y),this.current=y,this.dirty=!1}}class Sj extends dl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_FLIP_Y_WEBGL,y),this.current=y,this.dirty=!1}}class t_ extends dl{constructor(y,C){super(y),this.context=y,this.parent=C}getDefault(){return null}}class y1 extends t_{constructor(y,C,R=0){super(y,C),this.attachmentPoint=y.gl.COLOR_ATTACHMENT0+R}setDirty(){this.dirty=!0}set(y){if(y===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferTexture2D(C.FRAMEBUFFER,this.attachmentPoint,C.TEXTURE_2D,y,0),this.current=y,this.dirty=!1}}class Cj extends t_{attachment(){return this.gl.DEPTH_ATTACHMENT}set(y){if(y===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferRenderbuffer(C.FRAMEBUFFER,this.attachment(),C.RENDERBUFFER,y),this.current=y,this.dirty=!1}}class HN extends t_{attachment(){return this.gl.DEPTH_ATTACHMENT}set(y){if(y===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferTexture2D(C.FRAMEBUFFER,this.attachment(),C.TEXTURE_2D,y,0),this.current=y,this.dirty=!1}}class _6 extends Cj{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const v1=(I,y,C,R)=>({u_matrix:I,u_image0:0,u_image1:1,u_skirt_height:y,u_ground_shadow_factor:C,u_emissive_texture_available:R}),g0=(I,y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue,st,Xe,pt)=>({u_proj_matrix:Float32Array.from(I),u_globe_matrix:y,u_normalize_matrix:Float32Array.from(R),u_merc_matrix:C,u_zoom_transition:$,u_merc_center:G,u_image0:0,u_image1:1,u_frustum_tl:Z,u_frustum_tr:te,u_frustum_br:ue,u_frustum_bl:xe,u_globe_pos:je,u_globe_radius:Re,u_viewport:Le,u_grid_matrix:pt?Float32Array.from(pt):new Float32Array(9),u_skirt_height:Ue,u_far_z_cutoff:st,u_emissive_texture_available:Xe});function CC(I,y){return I!=null&&y!=null&&!(!I.hasData()||!y.hasData())&&I.demTexture!=null&&y.demTexture!=null&&I.tileID.key!==y.tileID.key}const bu=new class{constructor(){this.operations={}}newMorphing(I,y,C,R,$){if(I in this.operations){const G=this.operations[I];G.to.tileID.key!==C.tileID.key&&(G.queued=C)}else this.operations[I]={startTime:R,phase:0,duration:$,from:y,to:C,queued:null}}getMorphValuesForProxy(I){if(!(I in this.operations))return null;const y=this.operations[I];return{from:y.from,to:y.to,phase:y.phase}}update(I){for(const y in this.operations){const C=this.operations[y];for(C.phase=(I-C.startTime)/C.duration;C.phase>=1||!this._validOp(C);)if(!this._nextOp(C,I)){delete this.operations[y];break}}}_nextOp(I,y){return!!I.queued&&(I.from=I.to,I.to=I.queued,I.queued=null,I.phase=0,I.startTime=y,!0)}_validOp(I){return I.from.hasData()&&I.to.hasData()}},s_={0:null,1:"TERRAIN_VERTEX_MORPHING"};function n_(I,y,C){if(y===0)return 0;const R=y<1&&C===514?.25/y:1;return 6*Math.pow(1.5,22-I)*Math.max(y,1)*R}function b1(I,y){const C=1<({u_matrix:I});function lp(I,y,C,R,$){if($>0){const G=o.o.now(),Z=(G-I.timeAdded)/$,te=y?(G-y.timeAdded)/$:-1,ue=C.getSource(),xe=R.coveringZoomLevel({tileSize:ue.tileSize,roundZoom:ue.roundZoom}),je=!y||Math.abs(y.tileID.overscaledZ-xe)>Math.abs(I.tileID.overscaledZ-xe),Re=je&&I.refreshedUponExpiration?1:o.aC(je?Z:1-te,0,1);return y?{opacity:1,mix:1-Re,isFading:Z<1}:{opacity:Re,mix:0,isFading:Z<1}}return{opacity:1,mix:0,isFading:!1}}class Ej extends al{constructor(y){const C={type:"raster-dem",maxzoom:Math.ceil(y.transform.maxZoom)},R=Py("mock-dem",C,y.style.dispatcher,y.style);super("mock-dem",R,null),R.setEventedParent(this),this._sourceLoaded=!0}_loadTile(y,C){y.state="loaded",C(null)}}class _1 extends al{constructor(y){const C=Py("proxy",{type:"geojson",maxzoom:Math.ceil(y.transform.maxZoom)},y.style.dispatcher,y.style);super("proxy",C,null),C.setEventedParent(this),this.map=this.getSource().map=y,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(y,C,R){if(y.freezeTileCoverage)return;this.transform=y;const $=y.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((G,Z)=>{if(G[Z.key]="",!this._tiles[Z.key]){const te=new o.b0(Z,this._source.tileSize*Z.overscaleFactor(),y.tileZoom,void 0,void 0,this._source.worldview);te.state="loaded",this._tiles[Z.key]=te}return G},{});for(const G in this._tiles)G in $||(this.freeFBO(G),this._tiles[G].unloadVectorData(),delete this._tiles[G])}freeFBO(y){const C=this.proxyCachedFBO[y];if(C!==void 0){const R=Object.values(C);this.renderCachePool.push(...R),delete this.proxyCachedFBO[y]}}deallocRenderCache(){this.renderCache.forEach(y=>y.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class Hy extends o.aR{constructor(y,C,R){super(y.overscaledZ,y.wrap,y.canonical.z,y.canonical.x,y.canonical.y),this.proxyTileKey=C,this.projMatrix=R}}class Gy extends o.bu{constructor(y,C){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=y,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[R,$,G]=function(){const ue=new o.dB,xe=new o.dC,je=131;ue.reserve(17161),xe.reserve(33800);const Re=o.an/128,Le=o.an+Re/2,Ue=Le+Re;for(let Xe=-Re;XeLe||Xe<0||Xe>Le?24575:0,jt=o.aC(Math.round(pt),0,o.an),Tt=o.aC(Math.round(Xe),0,o.an);ue.emplaceBack(jt+mt,Tt)}const st=(Xe,pt)=>{const mt=pt*je+Xe;xe.emplaceBack(mt+1,mt,mt+je),xe.emplaceBack(mt+je,mt+je+1,mt+1)};for(let Xe=1;Xe<129;Xe++)for(let pt=1;pt<129;pt++)st(pt,Xe);return[0,129].forEach(Xe=>{for(let pt=0;pt<130;pt++)st(pt,Xe),st(Xe,pt)}),[ue,xe,32768]}(),Z=y.context;this.gridBuffer=Z.createVertexBuffer(R,o.dx.members),this.gridIndexBuffer=Z.createIndexBuffer($),this.gridSegments=o.dy.simpleSegment(0,0,R.length,$.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,R.length,G),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new _1(C.map),this.orthoMatrix=o.bb(),o.bT(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,o.an,0,o.an,0,1);const te=Z.gl;this._overlapStencilMode=new la({func:te.GEQUAL,mask:255},0,255,te.KEEP,te.KEEP,te.REPLACE),this._previousZoom=y.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=C,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Ej(C.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(y){y.on("data",this._onStyleDataEvent.bind(this)),this._style=y,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(y,C,R){if(y&&y.terrain){this._style!==y&&(this.style=y,this._evaluationZoom=void 0);const $=y.terrain.properties,G=y.terrain.drapeRenderMode===0,Z=y.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const te=y.terrain&&y.terrain.scope,ue=$.get("source"),xe=G?this._mockSourceCache:y.getSourceCache(ue,te);if(!xe)return void o.w(`Couldn't find terrain source "${ue}".`);if(this.sourceCache=xe,this._attenuationRange=y.terrain.getAttenuationRange(),this._exaggeration=Z?this.calculateExaggeration(C):$.get("exaggeration"),!C.projection.requiresDraping&&Z&&this._exaggeration===0)return void this._disable();this.enabled=!0;const je=()=>{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 Re=this.getScaledDemTileSize();this.sourceCache.update(C,Re,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,je(),this._initializing=!0),je(),C.updateElevation(!0,R),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(C),this._emptyDEMTextureDirty=!0,this._previousZoom=C.zoom}else this._disable()}calculateExaggeration(y){if(this._attenuationRange&&y.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(y.zoom);const C=this._previousCameraAltitude,R=y.getFreeCameraOptions().position.z/y.pixelsPerMeter*y.worldSize;this._previousCameraAltitude=R;const $=C!=null?R-C:Number.MAX_VALUE;if(Math.abs($)<2)return this._exaggeration;const G=y.zoom,Z=this._style.terrain;if(!this._previousUpdateTimestamp)return Z.getExaggeration(G);let te=G-this._previousZoom;const ue=this._previousUpdateTimestamp;let xe=G;this._evaluationZoom!=null&&(xe=this._evaluationZoom,Math.abs(G-xe)>.5&&(te=.5*(G-xe+te)),te*$<0&&(xe+=te)),this._evaluationZoom=xe;const je=Z.getExaggeration(xe),Re=je===Z.getExaggeration(Math.max(0,xe-.1));if(Re&&Math.abs(je-this._exaggeration)<.01)return je;let Le=Math.min(.1,.00375*(this._updateTimestamp-ue));return(Re||je<.1||Math.abs(te)<1e-4)&&(Le=Math.min(.2,4*Le)),o.am(this._exaggeration,je,Le)}resetTileLookupCache(y){this._findCoveringTileCache[y]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(y){y.dataType==="source"&&y.coord?this._clearRenderCacheForTile(y.sourceCacheId,y.coord):y.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 y in this._style._mergedSourceCaches)this._style._mergedSourceCaches[y].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(y=>y.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 y=2*this.proxySourceCache.getSource().tileSize;return[y,y]}set useVertexMorphing(y){this._useVertexMorphing=y}updateTileBinding(y){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const C=this.proxySourceCache,R=this.painter.transform;this._initializing&&(this._initializing=R._centerAltitude===0&&this.getAtPointOrZero(o.ag.fromLngLat(R.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const $=this.proxyCoords=C.getIds().map(ue=>{const xe=C.getTileByID(ue).tileID;return xe.projMatrix=R.calculateProjMatrix(xe.toUnwrapped()),xe});(function(ue,xe){const je=xe.transform.pointCoordinate(xe.transform.getCameraPoint()),Re=new o.P(je.x,je.y);ue.sort((Le,Ue)=>{if(Ue.overscaledZ-Le.overscaledZ)return Ue.overscaledZ-Le.overscaledZ;const st=new o.P(Le.canonical.x+(1<{this.proxyToSource[ue.key]={}}),this.terrainTileForTile={};const Z=this._style._mergedSourceCaches;for(const ue in Z){const xe=Z[ue];if(!xe.used||(xe!==this.sourceCache&&this.resetTileLookupCache(xe.id),this._setupProxiedCoordsForOrtho(xe,y[ue],G),xe.usedForTerrain))continue;const je=y[ue];(xe.getSource().reparseOverscaled||xe._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(je)}this.proxiedCoords[C.id]=$.map(ue=>new Hy(ue,ue.key,this.orthoMatrix)),this._assignTerrainTiles($),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(G),this.renderingToTexture=!1;const te={};this._visibleDemTiles=[];for(const ue of this.proxyCoords){const xe=this.terrainTileForTile[ue.key];if(!xe)continue;const je=xe.tileID.key;je in te||(this._visibleDemTiles.push(xe),te[je]=je)}}_assignTerrainTiles(y){this._initializing||y.forEach(C=>{if(this.terrainTileForTile[C.key])return;const R=this._findTileCoveringTileID(C,this.sourceCache);R&&(this.terrainTileForTile[C.key]=R)})}_prepareDEMTextures(){const y=this.painter.context,C=y.gl;for(const R in this.terrainTileForTile){const $=this.terrainTileForTile[R],G=$.dem;!G||$.demTexture&&!$.needsDEMTextureUpload||(y.activeTexture.set(C.TEXTURE1),jC(this.painter,$,G))}}_prepareDemTileUniforms(y,C,R,$){if(!C||C.demTexture==null)return!1;const G=y.tileID.canonical,Z=Math.pow(2,C.tileID.canonical.z-G.z),te=$||"";return R[`u_dem_tl${te}`]=[G.x*Z%1,G.y*Z%1],R[`u_dem_scale${te}`]=Z,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let y=0;const C=this._visibleDemTiles.reduce((R,$)=>{if(!$.dem)return R;const G=$.dem.tree.minimums[0];return G>0&&y++,R+G},0);return y?C/y:0}_updateEmptyDEMTexture(){const y=this.painter.context,C=y.gl;y.activeTexture.set(C.TEXTURE2);const R=this._getLoadedAreaMinimum(),$=new o.dz({width:1,height:1},new Float32Array([R]));this._emptyDEMTextureDirty=!1;let G=this._emptyDEMTexture;return G?G.update($,{premultiply:!1}):G=this._emptyDEMTexture=new o.T(y,$,C.R32F,{premultiply:!1}),G}setupElevationDraw(y,C,R){const $=this.painter.context,G=$.gl,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};Z.u_exaggeration=this.exaggeration();let te=null,ue=null,xe=1;if(R&&R.morphing&&this._useVertexMorphing){const Ue=R.morphing.srcDemTile,st=R.morphing.dstDemTile;xe=R.morphing.phase,Ue&&st&&(this._prepareDemTileUniforms(y,Ue,Z,"_prev")&&(ue=Ue),this._prepareDemTileUniforms(y,st,Z)&&(te=st))}const je=Ue=>Ue&&Ue.demTexture&&this.painter.linearFloatFilteringSupported()?G.LINEAR:G.NEAREST;let Re=null;var Le;if(this.enabled?ue&&te?(Re=te.demTexture,$.activeTexture.set(G.TEXTURE4),ue.demTexture.bind(je(ue),G.CLAMP_TO_EDGE),Z.u_dem_lerp=xe):(te=this.terrainTileForTile[y.tileID.key],Re=this._prepareDemTileUniforms(y,te,Z)?te.demTexture:this.emptyDEMTexture):Re=this.emptyDEMTexture,$.activeTexture.set(G.TEXTURE2),Re&&(Z.u_dem_size=(Le=Re).size[0]===1?1:Le.size[0]-2,Re.bind(je(te),G.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(R&&R.useDepthForOcclusion,C,Z),R&&R.useMeterToDem&&te){const Ue=(1<{if(mt===Is)return;const an=[s_[Is],"PROJECTION_GLOBE_VIEW"];Tt&&an.push("CUSTOM_ANTIALIASING");const mn=xe.isTileAffectedByFog(zs);pt=xe.getOrCreateProgram("globeRaster",{defines:an,overrideFog:mn}),mt=Is},es=xe.colorModeForRenderPass(),Ft=new rr(Xe.LEQUAL,rr.ReadWrite,xe.depthRangeFor3D);bu.update(Ue);const Jt=o.dq(jt),At=[o.aH(jt.center.lng),o.aL(jt.center.lat)],Rt=xe.globeSharedBuffers,Wt=[jt.width*o.o.devicePixelRatio,jt.height*o.o.devicePixelRatio],ys=Float32Array.from(jt.globeMatrix),rs={useDenormalizedUpVectorScale:!0};{const zs=xe.transform,Is=n_(zs.zoom,je.exaggeration(),je.sourceCache._source.tileSize);mt=-1;const an=Xe.TRIANGLES;for(const mn of Le){const js=Re.getTile(mn),ms=la.disabled,Rs=je.prevTerrainTileForTile[mn.key],qs=je.terrainTileForTile[mn.key];CC(Rs,qs)&&bu.newMorphing(mn.key,Rs,qs,Ue,250),Up(xe,js.emissiveTexture),st.activeTexture.set(Xe.TEXTURE0),js.texture&&js.texture.bind(Xe.LINEAR,Xe.CLAMP_TO_EDGE);const Qs=bu.getMorphValuesForProxy(mn.key),Dn=Qs?1:0;Qs&&Object.assign(rs,{morphing:{srcDemTile:Qs.from,dstDemTile:Qs.to,phase:o.dn(Qs.phase)}});const Cn=o.dr(mn.canonical),Tn=o.ds(Cn.getCenter().lat),dn=o.dt(mn.canonical,Cn,Tn,zs.worldSize/zs._pixelsPerMercatorPixel),mr=o.du(o.dv(mn.canonical)),Er=xe.emissiveMode==="mrt-fallback"?1:0,ar=g0(zs.expandedFarZProjMatrix,ys,Jt,mr,o.al(zs.zoom),At,zs.frustumCorners.TL,zs.frustumCorners.TR,zs.frustumCorners.BR,zs.frustumCorners.BL,zs.globeCenterInViewSpace,zs.globeRadius,Wt,Is,zs._farZ,Er,dn);if(xt(mn,Dn),pt&&(je.setupElevationDraw(js,pt,rs),xe.uploadCommonUniforms(st,pt,mn.toUnwrapped()),Rt)){const[hr,ra,Na]=Rt.getGridBuffers(Tn,Is!==0);pt.draw(xe,an,Ft,ms,es,Fr.backCCW,ar,"globe_raster",hr,ra,Na)}}}if(Rt&&(xe.renderDefaultNorthPole||xe.renderDefaultSouthPole)){const zs=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Tt&&zs.push("CUSTOM_ANTIALIASING"),pt=xe.getOrCreateProgram("globeRaster",{defines:zs});for(const Is of Le){const{x:an,y:mn,z:js}=Is.canonical,ms=mn===0,Rs=mn===(1<hr.draw(xe,Xe.TRIANGLES,Ft,la.disabled,es,Fr.disabled,g0(jt.expandedFarZProjMatrix,dn,dn,mr,0,At,jt.frustumCorners.TL,jt.frustumCorners.TR,jt.frustumCorners.BR,jt.frustumCorners.BL,jt.globeCenterInViewSpace,jt.globeRadius,Wt,0,jt._farZ,Er),"globe_pole_raster",ra,Dn,Cn);je.setupElevationDraw(Tn,pt,rs),xe.uploadCommonUniforms(st,pt,Is.toUnwrapped()),ms&&xe.renderDefaultNorthPole&&ar(pt,qs),Rs&&xe.renderDefaultSouthPole&&(dn=o.cC(o.bb(),dn,[1,-1,1]),ar(pt,Qs))}}}})($,G,Z,te,ue);else{const xe=$.context,je=xe.gl;let Re,Le;const Ue=$.shadowRenderer,st=$c($,$.longestCutoffRange),Xe=es=>{if(Le===es)return;const Ft=[];Ft.push(s_[es]),st.shouldRenderCutoff&&Ft.push("RENDER_CUTOFF"),Ue&&(Ft.push("RENDER_SHADOWS"),Ue.useNormalOffset&&Ft.push("NORMAL_OFFSET")),Re=$.getOrCreateProgram("terrainRaster",{defines:Ft}),Le=es},pt=$.colorModeForRenderPass(),mt=new rr(je.LEQUAL,rr.ReadWrite,$.depthRangeFor3D);bu.update(ue);const jt=$.transform,Tt=n_(jt.zoom,G.exaggeration(),G.sourceCache._source.tileSize);let xt=[0,0,0];if(Ue){const es=$.style.directionalLight,Ft=$.style.ambientLight;es&&Ft&&(xt=Bp($.style,es,Ft))}{Le=-1;const es=je.TRIANGLES,[Ft,Jt]=[G.gridIndexBuffer,G.gridSegments];for(const At of te){const Rt=Z.getTile(At),Wt=la.disabled,ys=G.prevTerrainTileForTile[At.key],rs=G.terrainTileForTile[At.key];CC(ys,rs)&&bu.newMorphing(At.key,ys,rs,ue,250),Up($,Rt.emissiveTexture),xe.activeTexture.set(je.TEXTURE0),Rt.texture&&Rt.texture.bind(je.LINEAR,je.CLAMP_TO_EDGE);const zs=bu.getMorphValuesForProxy(At.key),Is=zs?1:0;let an;zs&&(an={morphing:{srcDemTile:zs.from,dstDemTile:zs.to,phase:o.dn(zs.phase)}});const mn=$.emissiveMode==="mrt-fallback"?1:0,js=v1(At.projMatrix,b1(At.canonical,jt.renderWorldCopies)?Tt/10:Tt,xt,mn);if(Xe(Is),!Re)continue;G.setupElevationDraw(Rt,Re,an);const ms=At.toUnwrapped();Ue&&Ue.setupShadows(ms,Re),$.uploadCommonUniforms(xe,Re,ms,null,st),Re.draw($,es,mt,Wt,pt,Fr.backCCW,js,"terrain_raster",G.gridBuffer,Ft,Jt)}}}}(C,this,this.proxySourceCache,y,this._updateTimestamp),this.renderingToTexture=!0,C.gpuTimingDeferredRenderEnd(),y.splice(0,y.length))}renderBatch(y){if(this._drapedRenderBatches.length===0)return y+1;this.renderingToTexture=!0;const C=this.painter,R=this.painter.context,$=this.proxySourceCache,G=this.proxiedCoords[$.id],Z=this._drapedRenderBatches.shift(),te=C.style.order,ue=[];this._updateFBOs(C.emissiveMode==="mrt-fallback");let xe=0;for(const je of G){const Re=$.getTileByID(je.proxyTileKey),Le=$.proxyCachedFBO[je.key]?$.proxyCachedFBO[je.key][y]:void 0,Ue=Le!==void 0?$.renderCache[Le]:this.pool[xe++],st=Le!==void 0;if(Re.texture=Ue.tex,Re.emissiveTexture=Ue.emissiveTex,st&&!Ue.dirty){ue.push(Re.tileID);continue}R.bindFramebuffer.set(Ue.fb.framebuffer);const Xe=R.gl;let pt;Xe.drawBuffers(C.emissiveMode==="mrt-fallback"?[Xe.COLOR_ATTACHMENT0,Xe.COLOR_ATTACHMENT1]:[Xe.COLOR_ATTACHMENT0]),this.renderedToTile=!1,Ue.dirty&&(R.clear({color:o.aq.transparent,stencil:0}),Ue.dirty=!1);for(let mt=Z.start;mt<=Z.end;++mt){const jt=C.style._mergedLayers[te[mt]];if(jt.isHidden(C.transform.zoom))continue;const Tt=C.style.getLayerSourceCache(jt),xt=Tt?this.proxyToSource[je.key][Tt.id]:[je];if(!xt)continue;const es=xt;R.viewport.set([0,0,Ue.fb.width,Ue.fb.height]),pt!==(Tt?Tt.id:null)&&(this._setupStencil(Ue,xt,jt,Tt),pt=Tt?Tt.id:null),C.renderLayer(C,Tt,jt,es)}if(Xe.drawBuffers([Xe.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const mt of this._pendingGroundEffectLayers){const jt=C.style._mergedLayers[te[mt]];if(jt.isHidden(C.transform.zoom))continue;const Tt=C.style.getLayerSourceCache(jt),xt=Tt?this.proxyToSource[je.key][Tt.id]:[je];if(!xt)continue;const es=xt;R.viewport.set([0,0,Ue.fb.width,Ue.fb.height]),pt!==(Tt?Tt.id:null)&&(this._setupStencil(Ue,xt,jt,Tt),pt=Tt?Tt.id:null),C.renderLayer(C,Tt,jt,es)}this.renderedToTile?(Ue.dirty=!0,ue.push(Re.tileID)):st||--xe,xe===5&&(xe=0,this.renderToBackBuffer(ue))}return this.renderToBackBuffer(ue),this.renderingToTexture=!1,R.bindFramebuffer.set(null),R.viewport.set([0,0,C.width,C.height]),Z.end+1}postRender(){}isLayerOrderingCorrect(y){const C=y.order.length;let R=-1,$=C;for(let G=0;GR}getMinElevationBelowMSL(){let y=0;return this._visibleDemTiles.filter(C=>C.dem).forEach(C=>{y=Math.min(y,C.dem.tree.minimums[0])}),y===0?y:(y-30)*this._exaggeration}raycast(y,C,R){if(!this._visibleDemTiles)return null;const $=this._visibleDemTiles.filter(G=>G.dem).map(G=>{const Z=G.tileID,te=1<(G.t!==null?G.t:Number.MAX_VALUE)-(Z.t!==null?Z.t:Number.MAX_VALUE));for(const G of $){if(G.t==null)return null;const Z=G.tile.dem.tree.raycast(G.minx,G.miny,G.maxx,G.maxy,y,C,R);if(Z!=null)return Z}return null}_createFBO(){const y=this.painter.context,C=y.gl,R=this.drapeBufferSize;y.activeTexture.set(C.TEXTURE0);const $=new o.T(y,{width:R[0],height:R[1],data:null},C.RGBA8);$.bind(C.LINEAR,C.CLAMP_TO_EDGE);const G=y.createFramebuffer(R[0],R[1],1,null);let Z;return G.colorAttachment0.set($.texture),this._emissiveTexture&&(Z=new o.T(y,{width:R[0],height:R[1],data:null},C.R8),Z.bind(C.LINEAR,C.CLAMP_TO_EDGE),G.createColorAttachment(y,1),G.colorAttachment1.set(Z.texture)),G.depthAttachment=new _6(y,G.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=y.createRenderbuffer(y.gl.DEPTH_STENCIL,R[0],R[1]),this._stencilRef=0,G.depthAttachment.set(this._sharedDepthStencil),y.clear({stencil:0})):G.depthAttachment.set(this._sharedDepthStencil),y.extTextureFilterAnisotropic&&C.texParameterf(C.TEXTURE_2D,y.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,y.extTextureFilterAnisotropicMax),{fb:G,tex:$,emissiveTex:Z,dirty:!1}}_updateFBOs(y){if(this._emissiveTexture!==y){for(const C of this.pool)this._updateFBO(C,y);for(const C of this.proxySourceCache.renderCache)this._updateFBO(C,y);this._emissiveTexture=y}}_updateFBO(y,C){const R=y.fb,$=this.painter.context,G=$.gl,Z=this.drapeBufferSize;if(C){const te=new o.T($,{width:Z[0],height:Z[1],data:null},G.R8);te.bind(G.LINEAR,G.CLAMP_TO_EDGE),y.emissiveTex=te,R.createColorAttachment($,1),R.colorAttachment1.set(te.texture)}else y.emissiveTex=void 0,R.removeColorAttachment($,1);y.dirty=!0}_initFBOPool(){for(;this.pool.length{const C=this._style._mergedLayers[y],R=C.isHidden(this.painter.transform.zoom);return C.type==="hillshade"||C.type==="custom"?!R&&C.shouldRedrape():!R&&C.hasTransition()})}_clearLineLayersFromRenderCache(){let y=!1;for(const R of this._style.getSources())if(R instanceof Gd){y=!0;break}if(!y)return;const C={};for(let R=0;Rue>te.end)||o.w("fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.")}this._drapedRenderBatches=R}_setupRenderCache(y){const C=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,C.renderCache.length>C.renderCachePool.length){const Z=Object.values(C.proxyCachedFBO);C.proxyCachedFBO={};for(let te=0;te=0;Z--){const te=R[Z];if(C.getTileByID(te.key),C.proxyCachedFBO[te.key]!==void 0){const ue=y[te.key],xe=this.proxyToSource[te.key];let je=0;for(const Re in xe){const Le=xe[Re],Ue=ue[Re];if(!Ue||Ue.length!==Le.length||Le.some((st,Xe)=>st!==Ue[Xe]||$[Re]&&$[Re].hasOwnProperty(st.key))){je=-1;break}++je}for(const Re in C.proxyCachedFBO[te.key])C.renderCache[C.proxyCachedFBO[te.key][Re]].dirty=je<0||je!==Object.values(ue).length}}const G=[...this._drapedRenderBatches];G.sort((Z,te)=>te.end-te.start-(Z.end-Z.start));for(const Z of G)for(const te of R){if(C.proxyCachedFBO[te.key])continue;let ue=C.renderCachePool.pop();ue===void 0&&C.renderCache.length<50&&(ue=C.renderCache.length,C.renderCache.push(this._createFBO())),ue!==void 0&&(C.proxyCachedFBO[te.key]={},C.proxyCachedFBO[te.key][Z.start]=ue,C.renderCache[ue].dirty=!0)}this._tilesDirty={}}_setupStencil(y,C,R,$){if(!$||!this._sourceTilesOverlap[$.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const G=this.painter.context,Z=G.gl;if(C.length<=1)return void(this._overlapStencilType=!1);let te;if(R.isTileClipped())te=C.length,this._overlapStencilMode.test={func:Z.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(C[0].overscaledZ>C[C.length-1].overscaledZ))return void(this._overlapStencilType=!1);te=1,this._overlapStencilMode.test={func:Z.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+te>255&&(G.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=te,this._overlapStencilMode.ref=this._stencilRef,R.isTileClipped()&&this._renderTileClippingMasks(C,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(y){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[y.key]),this._overlapStencilMode):la.disabled}_renderTileClippingMasks(y,C){const R=this.painter,$=this.painter.context,G=$.gl;R._tileClippingMaskIDs={},$.setColorMode(na.disabled),$.setDepthMode(rr.disabled);const Z=R.getOrCreateProgram("clippingMask");for(const te of y){const ue=R._tileClippingMaskIDs[te.key]=--C;Z.draw(R,G.TRIANGLES,rr.disabled,new la({func:G.ALWAYS,mask:0},ue,255,G.KEEP,G.KEEP,G.REPLACE),na.disabled,Fr.disabled,Tj(te.projMatrix),"$clipping",R.tileExtentBuffer,R.quadTriangleIndexBuffer,R.tileExtentSegments)}}pointCoordinate(y){const C=this.painter.transform;if(y.x<0||y.x>C.width||y.y<0||y.y>C.height)return null;const R=[y.x,y.y,1,1];o.aE(R,R,C.pixelMatrixInverse),o.cu(R,R,1/R[3]),R[0]/=C.worldSize,R[1]/=C.worldSize;const $=C._camera.position,G=o.bU(1,C.center.lat),Z=[$[0],$[1],$[2]/G,0],te=o.cV([],R.slice(0,3),Z);o.ay(te,te);const ue=this.raycast(Z,te,this._exaggeration);return ue!==null&&ue?(o.bg(Z,Z,te,ue),Z[3]=Z[2],Z[2]*=G,Z):null}_setupProxiedCoordsForOrtho(y,C,R){if(y.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(y,C,R);this._findCoveringTileCache[y.id]=this._findCoveringTileCache[y.id]||{};const $=this.proxiedCoords[y.id]=[],G=this.proxyCoords;for(let ue=0;ueje.overscaledZ-xe.overscaledZ)}_setupProxiedCoordsForImageSource(y,C,R){if(!y.getSource().loaded())return;const $=this.proxiedCoords[y.id]=[],G=this.proxyCoords,Z=y.getSource(),te=Z.tileID;if(!te)return;const ue=new o.P(te.x,te.y)._div(1<(Re.min.x=Math.min(Re.min.x,Le.x-ue.x),Re.min.y=Math.min(Re.min.y,Le.y-ue.y),Re.max.x=Math.max(Re.max.x,Le.x-ue.x),Re.max.y=Math.max(Re.max.y,Le.y-ue.y),Re),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),je=(Re,Le)=>{const Ue=Re.wrap+Re.canonical.x/(1<pt+xe.max.x||st+Xemt+xe.max.y};for(let Re=0;ReZ.key===C.tileID.key);if(G)return G}if(C.tileID.key!==y.key){const G=y.canonical.z-C.tileID.canonical.z;let Z,te,ue;$=o.bb();const xe=C.tileID.wrap-y.wrap<0?(Z=o.an>>G,te=Z*((C.tileID.canonical.x<=Re){const Le=y.canonical.z-Re;C.getSource().reparseOverscaled?(te=Math.max(y.canonical.z+2,C.transform.tileZoom),Z=new o.aR(te,y.wrap,Re,y.canonical.x>>Le,y.canonical.y>>Le)):Le!==0&&(te=Re,Z=new o.aR(te,y.wrap,Re,y.canonical.x>>Le,y.canonical.y>>Le))}Z.key!==y.key&&(xe.push(Z.key),R=C.getTile(Z))}const je=Re=>{xe.forEach(Le=>{$[Le]=Re}),xe.length=0};for(te-=1;te>=ue&&(!R||!R.hasData());te--){R&&je(R.tileID.key);const Re=Z.calculateScaledKey(te);if(R=C.getTileByID(Re),R&&R.hasData())break;const Le=$[Re];if(Le===null)break;Le===void 0?xe.push(Re):R=C.getTileByID(Le)}return je(R?R.tileID.key:null),R&&R.hasData()?R:null}findDEMTileFor(y){return this.enabled?this._findTileCoveringTileID(y,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(y,C){let R=this._tilesDirty[y];R||(R=this._tilesDirty[y]={}),R[C.key]=!0}}function r_(I,y,C){const R=function(te,ue,xe){const je=o.bi(ue,te),Re=o.bi(xe,[.2126,.7152,.0722]),Le=(st,Xe,pt)=>(1-pt)*st+pt*Xe,Ue=Le(1-.3*Math.min(Re,1),1,Math.min(je+1,1));return Le(.92,1,Math.asin(o.aC(ue[2],-1,1))/Math.PI+.5)*Ue}(I,[0,0,1],y),$=[0,0,0];o.bJ($,C.slice(0,3),R);const G=[0,0,0];o.bJ(G,y.slice(0,3),I[2]);const Z=[0,0,0];return o.cT(Z,$,G),o.cW(Z)}const TC=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],a_=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class cd{static cacheKey(y,C,R,$){const G=[C];$&&G.push($.cacheKey);for(const Z of R)(typeof Z=="string"&&Z.includes(" ")||y.usedDefines.has(Z))&&G.push(Z);return G.join("/")}constructor(y,C,R,$,G,Z){const te=y.gl;this.program=te.createProgram(),this.configuration=$,this.name=C,this.fixedDefines=[...Z];const ue=`#version 300 es ${($?$.defines():[]).concat(Z.map(Xe=>`#define ${Xe}`)).join(` `)}`,xe=[ue,p1];for(const Xe of R.fragmentIncludes)xe.push($p[Xe]);xe.push(R.fragmentSource);const je=xe.join(` `),Re=[ue,yC];for(const Xe of R.vertexIncludes)Re.push($p[Xe]);this.forceManualRenderingForInstanceIDShaders=y.forceManualRenderingForInstanceIDShaders&&R.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Re.push("uniform int u_instanceID;"),Re.push(R.vertexSource);let Le=Re.join(` `);this.forceManualRenderingForInstanceIDShaders&&(Le=Le.replaceAll("gl_InstanceID","u_instanceID"));const Ue=te.createShader(te.FRAGMENT_SHADER);if(te.isContextLost())return void(this.failedToCreate=!0);te.shaderSource(Ue,je),te.compileShader(Ue),te.attachShader(this.program,Ue);const st=te.createShader(te.VERTEX_SHADER);te.isContextLost()?this.failedToCreate=!0:(te.shaderSource(st,Le),te.compileShader(st),te.attachShader(this.program,st),this.attributes={},te.linkProgram(this.program),te.deleteShader(st),te.deleteShader(Ue),this.fixedUniforms=G(y),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=$?$.getUniforms(y):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(Xe=>({u_instanceID:new o.bX(Xe)}))(y)),(Z.includes("TERRAIN")||Z.includes("ELEVATED")||C.includes("symbol")||C.includes("circle"))&&(this.terrainUniforms=(Xe=>({u_dem:new o.bX(Xe),u_dem_prev:new o.bX(Xe),u_dem_tl:new o.b_(Xe),u_dem_scale:new o.bZ(Xe),u_dem_tl_prev:new o.b_(Xe),u_dem_scale_prev:new o.bZ(Xe),u_dem_size:new o.bZ(Xe),u_dem_lerp:new o.bZ(Xe),u_exaggeration:new o.bZ(Xe),u_depth:new o.bX(Xe),u_depth_size_inv:new o.b_(Xe),u_depth_range_unpack:new o.b_(Xe),u_occluder_half_size:new o.bZ(Xe),u_occlusion_depth_offset:new o.bZ(Xe),u_meter_to_dem:new o.bZ(Xe),u_label_plane_matrix_inv:new o.b$(Xe)}))(y)),Z.includes("GLOBE")&&(this.globeUniforms=(Xe=>({u_tile_tl_up:new o.bY(Xe),u_tile_tr_up:new o.bY(Xe),u_tile_br_up:new o.bY(Xe),u_tile_bl_up:new o.bY(Xe),u_tile_up_scale:new o.bZ(Xe)}))(y)),Z.includes("FOG")&&(this.fogUniforms=(Xe=>({u_fog_matrix:new o.b$(Xe),u_fog_range:new o.b_(Xe),u_fog_color:new o.cO(Xe),u_fog_horizon_blend:new o.bZ(Xe),u_fog_vertical_limit:new o.b_(Xe),u_fog_temporal_offset:new o.bZ(Xe),u_frustum_tl:new o.bY(Xe),u_frustum_tr:new o.bY(Xe),u_frustum_br:new o.bY(Xe),u_frustum_bl:new o.bY(Xe),u_globe_pos:new o.bY(Xe),u_globe_radius:new o.bZ(Xe),u_globe_transition:new o.bZ(Xe),u_is_globe:new o.bX(Xe),u_viewport:new o.b_(Xe)}))(y)),Z.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(Xe=>({u_cutoff_params:new o.cO(Xe)}))(y)),Z.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(Xe=>({u_lighting_ambient_color:new o.bY(Xe),u_lighting_directional_dir:new o.bY(Xe),u_lighting_directional_color:new o.bY(Xe),u_ground_radiance:new o.bY(Xe)}))(y)),Z.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(Xe=>({u_light_matrix_0:new o.b$(Xe),u_light_matrix_1:new o.b$(Xe),u_fade_range:new o.b_(Xe),u_shadow_normal_offset:new o.bY(Xe),u_shadow_intensity:new o.bZ(Xe),u_shadow_texel_size:new o.bZ(Xe),u_shadow_map_resolution:new o.bZ(Xe),u_shadow_direction:new o.bY(Xe),u_shadow_bias:new o.bY(Xe),u_shadowmap_0:new o.bX(Xe),u_shadowmap_1:new o.bX(Xe)}))(y)))}getAttributeLocation(y,C){let R=this.attributes[C];return R===void 0&&(R=this.attributes[C]=y.getAttribLocation(this.program,C)),R}setTerrainUniformValues(y,C){if(!this.terrainUniforms)return;const R=this.terrainUniforms;if(!this.failedToCreate){y.program.set(this.program);for(const $ in C)R[$]&&R[$].set(this.program,$,C[$])}}setGlobeUniformValues(y,C){if(!this.globeUniforms)return;const R=this.globeUniforms;if(!this.failedToCreate){y.program.set(this.program);for(const $ in C)R[$]&&R[$].set(this.program,$,C[$])}}setFogUniformValues(y,C){if(!this.fogUniforms)return;const R=this.fogUniforms;if(!this.failedToCreate){y.program.set(this.program);for(const $ in C)R[$].set(this.program,$,C[$])}}setCutoffUniformValues(y,C){if(!this.cutoffUniforms)return;const R=this.cutoffUniforms;if(!this.failedToCreate){y.program.set(this.program);for(const $ in C)R[$].set(this.program,$,C[$])}}setLightsUniformValues(y,C){if(!this.lightsUniforms)return;const R=this.lightsUniforms;if(!this.failedToCreate){y.program.set(this.program);for(const $ in C)R[$].set(this.program,$,C[$])}}setShadowUniformValues(y,C){if(this.failedToCreate||!this.shadowUniforms)return;const R=this.shadowUniforms;y.program.set(this.program);for(const $ in C)R[$].set(this.program,$,C[$])}_drawDebugWireframe(y,C,R,$,G,Z,te,ue,xe,je){const Re=y.options.wireframe;if(Re.terrain===!1&&Re.layers2D===!1&&Re.layers3D===!1)return;const Le=y.context;if(!(!(!Re.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Re.layers2D||y._terrain&&y._terrain.renderingToTexture||!TC.includes(this.name))||!(!Re.layers3D||!a_.includes(this.name))))return;const Ue=Le.gl,st=y.wireframeDebugCache.getLinesFromTrianglesBuffer(y.frameCounter,G,Le);if(!st)return;const Xe=[...this.fixedDefines,"DEBUG_WIREFRAME"],pt=y.getOrCreateProgram(this.name,{config:this.configuration,defines:Xe});Le.program.set(pt.program);const mt=(xt,es,Ft)=>{if(es[xt]&&Ft[xt])for(const Jt in es[xt])Ft[xt][Jt]&&Ft[xt][Jt].set(Ft.program,Jt,es[xt][Jt].current)};xe&&xe.setUniforms(pt.program,Le,pt.binderUniforms,te,{zoom:ue}),mt("fixedUniforms",this,pt),mt("terrainUniforms",this,pt),mt("globeUniforms",this,pt),mt("fogUniforms",this,pt),mt("lightsUniforms",this,pt),mt("shadowUniforms",this,pt),st.bind(),Le.setColorMode(new na([Ue.ONE,Ue.ONE_MINUS_SRC_ALPHA,Ue.ZERO,Ue.ONE],o.aq.transparent,[!0,!0,!0,!1])),Le.setDepthMode(new rr(C.func===Ue.LESS?Ue.LEQUAL:C.func,rr.ReadOnly,C.range)),Le.setStencilMode(la.disabled);const jt=3*Z.primitiveLength*2,Tt=3*Z.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const xt=je||1;for(let es=0;es1?Ue.drawElementsInstanced(Ue.LINES,jt,Ue.UNSIGNED_SHORT,Tt,je):Ue.drawElements(Ue.LINES,jt,Ue.UNSIGNED_SHORT,Tt);G.bind(),Le.program.set(this.program),Le.setDepthMode(C),Le.setStencilMode(R),Le.setColorMode($)}checkUniforms(y,C,R){if(this.fixedDefines.includes(C)){for(const $ of Object.keys(R))if(!R[$].initialized)throw new Error(`Program '${this.name}', from draw '${y}': uniform ${$} not set but required by ${C} being defined`)}}draw(y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue,st,Xe,pt){const mt=y.context,jt=mt.gl;if(this.failedToCreate)return;mt.program.set(this.program),mt.setDepthMode(R),mt.setStencilMode($),mt.setColorMode(G),mt.setCullFace(Z);for(const[At,Rt]of this.fixedUniformsEntries)Rt.set(this.program,At,te[At]);st&&st.setUniforms(this.program,mt,this.binderUniforms,Le,{zoom:Ue});const Tt={[jt.POINTS]:1,[jt.LINES]:2,[jt.TRIANGLES]:3,[jt.LINE_STRIP]:1}[C];this.checkUniforms(ue,"RENDER_SHADOWS",this.shadowUniforms);const xt=Xe||[],es=st?st.getPaintVertexBuffers():[],Ft=C===jt.TRIANGLES&&je,Jt=pt&&pt>0?1:void 0;for(const At of Re.get()){const Rt=At.vaos||(At.vaos={});if((Rt[ue]||(Rt[ue]=new _C)).bind(mt,this,xe,es,je,At.vertexOffset,xt,Jt),this.forceManualRenderingForInstanceIDShaders){const Wt=pt||1;for(let ys=0;ys1?jt.drawElementsInstanced(C,At.primitiveLength*Tt,jt.UNSIGNED_SHORT,At.primitiveOffset*Tt*2,pt):je?jt.drawElements(C,At.primitiveLength*Tt,jt.UNSIGNED_SHORT,At.primitiveOffset*Tt*2):jt.drawArrays(C,At.vertexOffset,At.vertexLength);Ft&&this._drawDebugWireframe(y,R,$,G,je,At,Le,Ue,st,pt)}}}function w6(I,y,C=0){const R=Math.pow(2,y.tileID.overscaledZ),$=y.tileSize*Math.pow(2,I.transform.tileZoom)/R,G=$*(y.tileID.canonical.x+y.tileID.wrap*R),Z=$*y.tileID.canonical.y;return{u_image:0,u_texsize:y.imageAtlasTexture?y.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.aA(y,1,I.transform.tileZoom),u_pixel_coord_upper:[G>>16,Z>>16],u_pixel_coord_lower:[65535&G,65535&Z],u_pattern_transition:C}}const GN={terrain:0,flat:1},WN=o.bb(),wh=(I,y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue,st,Xe,pt,mt,jt=[0,0,1])=>{const Tt=y.style.light,xt=Tt.properties.get("position"),es=[xt.x,xt.y,xt.z],Ft=o.dE();Tt.properties.get("anchor")==="viewport"&&(o.dF(Ft,-y.transform.angle),o.dG(es,es,Ft));const Jt=Tt.properties.get("color").toPremultipliedRenderColor(null),At=y.transform,Rt={u_matrix:I,u_lightpos:es,u_lightintensity:Tt.properties.get("intensity"),u_lightcolor:[Jt.r,Jt.g,Jt.b],u_vertical_gradient:+C,u_opacity:R,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:WN,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:GN[xe],u_base_type:GN[je],u_ao:$,u_edge_radius:G,u_width_scale:Z,u_flood_light_color:st,u_vertical_scale:Xe,u_flood_light_intensity:pt,u_ground_shadow_factor:mt,u_front_cutoff_params:jt};return At.projection.name==="globe"&&(Rt.u_tile_id=[te.canonical.x,te.canonical.y,1<({u_matrix:I,u_edge_radius:y,u_width_scale:C,u_vertical_scale:R,u_height_type:GN[$],u_base_type:GN[G]}),qa=(I,y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue,st,Xe,pt,mt)=>{const jt=wh(I,y,C,R,$,G,Z,te,xe,je,Re,Le,Ue,st,Xe,pt,1,[0,0,0]),Tt={u_height_factor:-Math.pow(2,te.overscaledZ)/ue.tileSize/8};return Object.assign(jt,w6(y,ue,mt),Tt)},y0=(I,y,C)=>({u_matrix:I,u_emissive_strength:y,u_ground_shadow_factor:C}),i_=(I,y,C,R,$,G=0)=>Object.assign(y0(I,y,$),w6(C,R,G)),EC=(I,y,C,R)=>({u_matrix:I,u_world:C,u_emissive_strength:y,u_ground_shadow_factor:R}),o_=(I,y,C,R,$,G,Z=0)=>Object.assign(i_(I,y,C,R,G,Z),{u_world:$}),l_=(I,y)=>({u_matrix:I,u_depth_bias:y}),Aj=(I,y)=>({u_matrix:I,u_ground_shadow_factor:y}),w1=(I,y,C,R,$)=>({u_matrix:I,u_camera_pos:[y[0],y[1],y[2]],u_depth_bias:C,u_height_scale:R,u_reset_depth:$}),Mj=(I,y,C)=>({u_image:I,u_opacity:y,u_blend_mode:C}),v0=(I,y,C,R,$,G,Z,te,ue,xe=[0,0,1])=>({u_matrix:I,u_normal_matrix:y,u_opacity:C,u_faux_facade_ao_intensity:R,u_camera_pos:$,u_tile_to_meter:G,u_facade_emissive_chance:Z,u_flood_light_color:te,u_flood_light_intensity:ue,u_front_cutoff_params:xe}),Ij=I=>({u_matrix:I}),c_=I=>({u_matrix:I}),KN=(I,y,C,R,$,G,Z,te)=>{const ue=o.an/G.tileSize;return{u_matrix:I,u_inv_rot_matrix:y,u_camera_to_center_distance:C.getCameraToCenterDistance(te),u_extrude_scale:[C.pixelsToGLUnits[0]/ue,C.pixelsToGLUnits[1]/ue],u_zoom_transition:R,u_tile_id:Z,u_merc_center:$}},Uc=(I,y,C,R)=>({u_matrix:I,u_inv_matrix:y,u_camera_to_center_distance:C.getCameraToCenterDistance(R),u_viewport_size:[C.width,C.height]}),jm=(I,y,C=1)=>({u_matrix:I,u_color:y,u_overlay:0,u_overlay_scale:C}),qp=o.bb(),YN=(I,y,C,R,$,G,Z)=>{const te=I.transform,ue=te.projection.name==="globe",xe=ue?o.dH(te.zoom,y.canonical)*te._pixelsPerMercatorPixel:o.aA(C,1,G),je={u_matrix:y.projMatrix,u_extrude_scale:xe,u_intensity:Z,u_inv_rot_matrix:qp,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(ue){je.u_inv_rot_matrix=R,je.u_merc_center=$,je.u_tile_id=[y.canonical.x,y.canonical.y,1<({u_matrix:y,u_normalize_matrix:C,u_globe_matrix:R,u_merc_matrix:$,u_grid_matrix:G,u_tl_parent:Z,u_scale_parent:je,u_fade_t:Re.mix,u_opacity:Re.opacity*Le.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Le.paint.get("raster-brightness-min"),u_brightness_high:Le.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(Le.paint.get("raster-saturation")),u_contrast_factor:o.dI(Le.paint.get("raster-contrast")),u_spin_weights:j6(Le.paint.get("raster-hue-rotate")),u_perspective_transform:Ue,u_raster_elevation:st,u_zoom_transition:te,u_merc_center:ue,u_cutoff_params:xe,u_colorization_mix:ZN(o.dK,pt,jt),u_colorization_offset:cp(o.dK,mt,jt),u_color_ramp:Xe,u_texture_offset:[xt/(Tt+2*xt),Tt/(Tt+2*xt)],u_texture_res:[Tt+2*xt,Tt+2*xt],u_emissive_strength:es,u_zbias_factor:QN(I)});function j6(I){I*=Math.PI/180;const y=Math.sin(I),C=Math.cos(I);return[(2*C+1)/3,(-Math.sqrt(3)*y-C+1)/3,(Math.sqrt(3)*y-C+1)/3]}const wx=.05,N6=(I,y,C,R,$,G,Z,te,ue,xe,je,Re)=>({u_matrix:I,u_normalize_matrix:y,u_globe_matrix:C,u_merc_matrix:R,u_grid_matrix:$,u_tl_parent:G,u_scale_parent:xe,u_fade_t:je.mix,u_opacity:je.opacity,u_image0:0,u_image1:1,u_raster_elevation:Re,u_zoom_transition:Z,u_merc_center:te,u_cutoff_params:ue}),k6=(I,y,C,R,$,G,Z,te,ue,xe)=>({u_particle_texture:I,u_particle_texture_side_len:y,u_tile_offset:C,u_velocity:R,u_color_ramp:G,u_velocity_res:$,u_max_speed:Z,u_uv_offset:te,u_data_scale:[255*ue[0],255*ue[1]],u_data_offset:xe,u_particle_pos_scale:1.1,u_particle_pos_offset:[wx,wx]}),AC=(I,y,C,R,$,G,Z,te,ue,xe)=>({u_particle_texture:I,u_particle_texture_side_len:y,u_velocity:C,u_velocity_res:R,u_max_speed:$,u_speed_factor:G,u_reset_rate:Z,u_rand_seed:Math.random(),u_uv_offset:te,u_data_scale:[255*ue[0],255*ue[1]],u_data_offset:xe,u_particle_pos_scale:1.1,u_particle_pos_offset:[wx,wx]}),Pj=o.bb(),j1=(I,y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue,st,Xe,pt,mt,jt,Tt,xt,es,Ft,Jt)=>{const At=$.transform,Rt={u_is_size_zoom_constant:+(I==="constant"||I==="source"),u_is_size_feature_constant:+(I==="constant"||I==="camera"),u_size_t:y?y.uSizeT:0,u_size:y?y.uSize:0,u_camera_to_center_distance:At.getCameraToCenterDistance(jt),u_rotate_symbol:+C,u_aspect_ratio:At.width/At.height,u_fade_change:$.options.fadeDuration?$.symbolFadeChange:1,u_matrix:G,u_label_plane_matrix:Z,u_coord_matrix:te,u_is_text:+xe,u_elevation_from_sea:ue?1:0,u_pitch_with_map:+R,u_texsize:je,u_texsize_icon:Re,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Pj,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Pj,u_up_vector:[0,-1,0],u_color_adj_mat:es,u_icon_transition:Ft||0,u_gamma_scale:R?$.transform.getCameraToCenterDistance(jt)*Math.cos($.terrain?0:$.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Jt||1,u_ground_shadow_factor:Tt,u_inv_matrix:o.b7(o.bb(),Z),u_normal_scale:xt,u_lutTexture:10,u_zoom:At.zoom-Math.floor(At.zoom),u_spp_fill_np_color:[0,0,0,1],u_spp_halo_np_color:[0,0,0,0],u_spp_opacity:1,u_spp_halo_width:0,u_spp_halo_blur:0,u_spp_emissive_strength:0,u_spp_occlusion_opacity:1,u_spp_z_offset:0,u_spp_translate_rotation:[1,0]};return jt.name==="globe"&&(Rt.u_tile_id=[Ue.canonical.x,Ue.canonical.y,1<({u_matrix:I,u_emissive_strength:y,u_opacity:C,u_color:R}),jx=(I,y,C,R,$,G,Z,te,ue)=>Object.assign(function(xe,je,Re,Le,Ue,st){const{width:Xe,height:pt}=Le.imageManager.getPixelSize(je),mt=Math.pow(2,st.tileID.overscaledZ),jt=st.tileSize*Math.pow(2,Le.transform.tileZoom)/mt,Tt=jt*(st.tileID.canonical.x+st.tileID.wrap*mt),xt=jt*st.tileID.canonical.y;return{u_image:0,u_pattern_tl:Re.tl,u_pattern_br:Re.br,u_texsize:[Xe,pt],u_pattern_size:Re.displaySize,u_pattern_units_to_pixels:Ue?[Le.transform.width,-1*Le.transform.height]:[1/o.aA(st,1,Le.transform.tileZoom),1/o.aA(st,1,Le.transform.tileZoom)],u_pixel_coord_upper:[Tt>>16,xt>>16],u_pixel_coord_lower:[65535&Tt,65535&xt]}}(0,G,Z,R,te,ue),{u_matrix:I,u_emissive_strength:y,u_opacity:C}),b0=new Float32Array(o.b9([])),Nx=(I,y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue=[0,0,0],st,Xe,pt)=>{const mt=$.style.light,jt=mt.properties.get("position"),Tt=[-jt.x,-jt.y,jt.z],xt=o.dE();mt.properties.get("anchor")==="viewport"&&(o.dF(xt,-$.transform.angle),o.dG(Tt,Tt,xt));const es=je.alphaMode==="MASK",Ft=mt.properties.get("color").toNonPremultipliedRenderColor(null),Jt=Le.paint.get("model-ambient-occlusion-intensity"),At=Le.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return At.a=Le.paint.get("model-color-mix-intensity").constantOr(0),pt&&(At.r=pt[0],At.g=pt[1],At.b=pt[2],At.a=pt[3]),Xe&&(At.r=Xe.color.r,At.g=Xe.color.g,At.b=Xe.color.b,At.a=Xe.colorMix,Re=Xe.emissionStrength,G*=Xe.opacity),{u_matrix:I,u_lighting_matrix:y,u_normal_matrix:C,u_node_matrix:R||b0,u_lightpos:Tt,u_lightintensity:mt.properties.get("intensity"),u_lightcolor:[Ft.r,Ft.g,Ft.b],u_camera_pos:Ue,u_opacity:G,u_baseTextureIsAlpha:0,u_alphaMask:+es,u_alphaCutoff:je.alphaCutoff,u_baseColorFactor:Z.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:te.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:ue,u_roughnessFactor:xe,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:At.toArray01(),u_aoIntensity:Jt,u_emissive_strength:Re,u_occlusionTextureTransform:st||[0,0,0,0]}},Lj=(I,y=b0,C=b0)=>({u_matrix:I,u_instance:y,u_node_matrix:C}),d_={fillExtrusion:I=>({u_matrix:new o.b$(I),u_lightpos:new o.bY(I),u_lightintensity:new o.bZ(I),u_lightcolor:new o.bY(I),u_vertical_gradient:new o.bZ(I),u_opacity:new o.bZ(I),u_edge_radius:new o.bZ(I),u_width_scale:new o.bZ(I),u_ao:new o.b_(I),u_height_type:new o.bX(I),u_base_type:new o.bX(I),u_tile_id:new o.bY(I),u_zoom_transition:new o.bZ(I),u_inv_rot_matrix:new o.b$(I),u_merc_center:new o.b_(I),u_up_dir:new o.bY(I),u_height_lift:new o.bZ(I),u_flood_light_color:new o.bY(I),u_vertical_scale:new o.bZ(I),u_flood_light_intensity:new o.bZ(I),u_ground_shadow_factor:new o.bY(I),u_front_cutoff_params:new o.bY(I)}),fillExtrusionDepth:I=>({u_matrix:new o.b$(I),u_edge_radius:new o.bZ(I),u_width_scale:new o.bZ(I),u_vertical_scale:new o.bZ(I),u_height_type:new o.bX(I),u_base_type:new o.bX(I)}),fillExtrusionPattern:I=>({u_matrix:new o.b$(I),u_lightpos:new o.bY(I),u_lightintensity:new o.bZ(I),u_lightcolor:new o.bY(I),u_vertical_gradient:new o.bZ(I),u_height_factor:new o.bZ(I),u_edge_radius:new o.bZ(I),u_width_scale:new o.bZ(I),u_ao:new o.b_(I),u_height_type:new o.bX(I),u_base_type:new o.bX(I),u_tile_id:new o.bY(I),u_zoom_transition:new o.bZ(I),u_inv_rot_matrix:new o.b$(I),u_merc_center:new o.b_(I),u_up_dir:new o.bY(I),u_height_lift:new o.bZ(I),u_image:new o.bX(I),u_texsize:new o.b_(I),u_pixel_coord_upper:new o.b_(I),u_pixel_coord_lower:new o.b_(I),u_tile_units_to_pixels:new o.bZ(I),u_opacity:new o.bZ(I),u_pattern_transition:new o.bZ(I)}),fillExtrusionGroundEffect:I=>({u_matrix:new o.b$(I),u_opacity:new o.bZ(I),u_ao_pass:new o.bZ(I),u_meter_to_tile:new o.bZ(I),u_ao:new o.b_(I),u_flood_light_intensity:new o.bZ(I),u_flood_light_color:new o.bY(I),u_attenuation:new o.bZ(I),u_edge_radius:new o.bZ(I),u_fb:new o.bX(I),u_fb_size:new o.bZ(I),u_dynamic_offset:new o.bZ(I)}),fill:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_ground_shadow_factor:new o.bY(I)}),fillPattern:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_image:new o.bX(I),u_texsize:new o.b_(I),u_pixel_coord_upper:new o.b_(I),u_pixel_coord_lower:new o.b_(I),u_tile_units_to_pixels:new o.bZ(I),u_ground_shadow_factor:new o.bY(I),u_pattern_transition:new o.bZ(I)}),fillOutline:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_world:new o.b_(I),u_ground_shadow_factor:new o.bY(I)}),fillOutlinePattern:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_world:new o.b_(I),u_image:new o.bX(I),u_texsize:new o.b_(I),u_pixel_coord_upper:new o.b_(I),u_pixel_coord_lower:new o.b_(I),u_tile_units_to_pixels:new o.bZ(I),u_ground_shadow_factor:new o.bY(I),u_pattern_transition:new o.bZ(I)}),lineBlendComposite:I=>({u_image:new o.bX(I),u_opacity:new o.bZ(I),u_blend_mode:new o.bX(I)}),building:I=>({u_matrix:new o.b$(I),u_normal_matrix:new o.b$(I),u_opacity:new o.bZ(I),u_faux_facade_ao_intensity:new o.bZ(I),u_camera_pos:new o.bY(I),u_tile_to_meter:new o.bZ(I),u_facade_emissive_chance:new o.bZ(I),u_flood_light_color:new o.bY(I),u_flood_light_intensity:new o.bZ(I),u_front_cutoff_params:new o.bY(I)}),buildingBloom:I=>({u_matrix:new o.b$(I)}),buildingDepth:I=>({u_matrix:new o.b$(I)}),elevatedStructuresDepth:I=>({u_matrix:new o.b$(I),u_depth_bias:new o.bZ(I)}),elevatedStructures:I=>({u_matrix:new o.b$(I),u_ground_shadow_factor:new o.bY(I)}),elevatedStructuresDepthReconstruct:I=>({u_matrix:new o.b$(I),u_camera_pos:new o.bY(I),u_depth_bias:new o.bZ(I),u_height_scale:new o.bZ(I),u_reset_depth:new o.bZ(I)}),circle:o.dO,collisionBox:I=>({u_matrix:new o.b$(I),u_inv_rot_matrix:new o.b$(I),u_camera_to_center_distance:new o.bZ(I),u_extrude_scale:new o.b_(I),u_zoom_transition:new o.bZ(I),u_merc_center:new o.b_(I),u_tile_id:new o.bY(I)}),collisionCircle:I=>({u_matrix:new o.b$(I),u_inv_matrix:new o.b$(I),u_camera_to_center_distance:new o.bZ(I),u_viewport_size:new o.b_(I)}),debug:I=>({u_color:new o.dl(I),u_matrix:new o.b$(I),u_overlay:new o.bX(I),u_overlay_scale:new o.bZ(I)}),clippingMask:I=>({u_matrix:new o.b$(I)}),heatmap:I=>({u_extrude_scale:new o.bZ(I),u_intensity:new o.bZ(I),u_matrix:new o.b$(I),u_inv_rot_matrix:new o.b$(I),u_merc_center:new o.b_(I),u_tile_id:new o.bY(I),u_zoom_transition:new o.bZ(I),u_up_dir:new o.bY(I)}),heatmapTexture:I=>({u_image:new o.bX(I),u_color_ramp:new o.bX(I),u_opacity:new o.bZ(I)}),hillshade:I=>({u_matrix:new o.b$(I),u_image:new o.bX(I),u_latrange:new o.b_(I),u_light:new o.b_(I),u_shadow:new o.dl(I),u_highlight:new o.dl(I),u_emissive_strength:new o.bZ(I),u_accent:new o.dl(I)}),hillshadePrepare:I=>({u_matrix:new o.b$(I),u_image:new o.bX(I),u_dimension:new o.b_(I),u_zoom:new o.bZ(I)}),line:o.dN,linePattern:o.dM,raster:I=>({u_matrix:new o.b$(I),u_normalize_matrix:new o.b$(I),u_globe_matrix:new o.b$(I),u_merc_matrix:new o.b$(I),u_grid_matrix:new o.dm(I),u_tl_parent:new o.b_(I),u_scale_parent:new o.bZ(I),u_fade_t:new o.bZ(I),u_opacity:new o.bZ(I),u_image0:new o.bX(I),u_image1:new o.bX(I),u_brightness_low:new o.bZ(I),u_brightness_high:new o.bZ(I),u_saturation_factor:new o.bZ(I),u_contrast_factor:new o.bZ(I),u_spin_weights:new o.bY(I),u_perspective_transform:new o.b_(I),u_raster_elevation:new o.bZ(I),u_zoom_transition:new o.bZ(I),u_merc_center:new o.b_(I),u_cutoff_params:new o.cO(I),u_colorization_mix:new o.cO(I),u_colorization_offset:new o.bZ(I),u_color_ramp:new o.bX(I),u_texture_offset:new o.b_(I),u_texture_res:new o.b_(I),u_emissive_strength:new o.bZ(I),u_zbias_factor:new o.bZ(I)}),rasterParticle:I=>({u_matrix:new o.b$(I),u_normalize_matrix:new o.b$(I),u_globe_matrix:new o.b$(I),u_merc_matrix:new o.b$(I),u_grid_matrix:new o.dm(I),u_tl_parent:new o.b_(I),u_scale_parent:new o.bZ(I),u_fade_t:new o.bZ(I),u_opacity:new o.bZ(I),u_image0:new o.bX(I),u_image1:new o.bX(I),u_raster_elevation:new o.bZ(I),u_zoom_transition:new o.bZ(I),u_merc_center:new o.b_(I),u_cutoff_params:new o.cO(I)}),rasterParticleTexture:I=>({u_texture:new o.bX(I),u_opacity:new o.bZ(I)}),rasterParticleDraw:I=>({u_particle_texture:new o.bX(I),u_particle_texture_side_len:new o.bZ(I),u_tile_offset:new o.b_(I),u_velocity:new o.bX(I),u_color_ramp:new o.bX(I),u_velocity_res:new o.b_(I),u_max_speed:new o.bZ(I),u_uv_offset:new o.b_(I),u_data_scale:new o.b_(I),u_data_offset:new o.bZ(I),u_particle_pos_scale:new o.bZ(I),u_particle_pos_offset:new o.b_(I)}),rasterParticleUpdate:I=>({u_particle_texture:new o.bX(I),u_particle_texture_side_len:new o.bZ(I),u_velocity:new o.bX(I),u_velocity_res:new o.b_(I),u_max_speed:new o.bZ(I),u_speed_factor:new o.bZ(I),u_reset_rate:new o.bZ(I),u_rand_seed:new o.bZ(I),u_uv_offset:new o.b_(I),u_data_scale:new o.b_(I),u_data_offset:new o.bZ(I),u_particle_pos_scale:new o.bZ(I),u_particle_pos_offset:new o.b_(I)}),symbol:I=>({u_is_size_zoom_constant:new o.bX(I),u_is_size_feature_constant:new o.bX(I),u_size_t:new o.bZ(I),u_size:new o.bZ(I),u_camera_to_center_distance:new o.bZ(I),u_rotate_symbol:new o.bX(I),u_aspect_ratio:new o.bZ(I),u_fade_change:new o.bZ(I),u_matrix:new o.b$(I),u_label_plane_matrix:new o.b$(I),u_coord_matrix:new o.b$(I),u_is_text:new o.bX(I),u_elevation_from_sea:new o.bX(I),u_pitch_with_map:new o.bX(I),u_texsize:new o.b_(I),u_texsize_icon:new o.b_(I),u_texture:new o.bX(I),u_texture_icon:new o.bX(I),u_gamma_scale:new o.bZ(I),u_device_pixel_ratio:new o.bZ(I),u_tile_id:new o.bY(I),u_zoom_transition:new o.bZ(I),u_inv_rot_matrix:new o.b$(I),u_merc_center:new o.b_(I),u_camera_forward:new o.bY(I),u_tile_matrix:new o.b$(I),u_up_vector:new o.bY(I),u_ecef_origin:new o.bY(I),u_is_halo:new o.bX(I),u_icon_transition:new o.bZ(I),u_color_adj_mat:new o.b$(I),u_scale_factor:new o.bZ(I),u_ground_shadow_factor:new o.bY(I),u_inv_matrix:new o.b$(I),u_normal_scale:new o.bZ(I),u_lutTexture:new o.bX(I),u_zoom:new o.bZ(I),u_spp_fill_np_color:new o.cO(I),u_spp_halo_np_color:new o.cO(I),u_spp_opacity:new o.bZ(I),u_spp_halo_width:new o.bZ(I),u_spp_halo_blur:new o.bZ(I),u_spp_emissive_strength:new o.bZ(I),u_spp_occlusion_opacity:new o.bZ(I),u_spp_z_offset:new o.bZ(I),u_spp_translate_rotation:new o.b_(I)}),background:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_opacity:new o.bZ(I),u_color:new o.dl(I)}),backgroundPattern:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_opacity:new o.bZ(I),u_image:new o.bX(I),u_pattern_tl:new o.b_(I),u_pattern_br:new o.b_(I),u_texsize:new o.b_(I),u_pattern_size:new o.b_(I),u_pixel_coord_upper:new o.b_(I),u_pixel_coord_lower:new o.b_(I),u_pattern_units_to_pixels:new o.b_(I)}),terrainRaster:I=>({u_matrix:new o.b$(I),u_image0:new o.bX(I),u_image1:new o.bX(I),u_skirt_height:new o.bZ(I),u_ground_shadow_factor:new o.bY(I),u_emissive_texture_available:new o.bZ(I)}),skybox:I=>({u_matrix:new o.b$(I),u_sun_direction:new o.bY(I),u_cubemap:new o.bX(I),u_opacity:new o.bZ(I),u_temporal_offset:new o.bZ(I)}),skyboxGradient:I=>({u_matrix:new o.b$(I),u_color_ramp:new o.bX(I),u_center_direction:new o.bY(I),u_radius:new o.bZ(I),u_opacity:new o.bZ(I),u_temporal_offset:new o.bZ(I)}),skyboxCapture:I=>({u_matrix_3f:new o.dm(I),u_sun_direction:new o.bY(I),u_sun_intensity:new o.bZ(I),u_color_tint_r:new o.cO(I),u_color_tint_m:new o.cO(I),u_luminance:new o.bZ(I)}),globeRaster:I=>({u_proj_matrix:new o.b$(I),u_globe_matrix:new o.b$(I),u_normalize_matrix:new o.b$(I),u_merc_matrix:new o.b$(I),u_zoom_transition:new o.bZ(I),u_merc_center:new o.b_(I),u_image0:new o.bX(I),u_image1:new o.bX(I),u_grid_matrix:new o.dm(I),u_skirt_height:new o.bZ(I),u_far_z_cutoff:new o.bZ(I),u_frustum_tl:new o.bY(I),u_frustum_tr:new o.bY(I),u_frustum_br:new o.bY(I),u_frustum_bl:new o.bY(I),u_globe_pos:new o.bY(I),u_globe_radius:new o.bZ(I),u_viewport:new o.b_(I),u_emissive_texture_available:new o.bZ(I)}),globeAtmosphere:I=>({u_frustum_tl:new o.bY(I),u_frustum_tr:new o.bY(I),u_frustum_br:new o.bY(I),u_frustum_bl:new o.bY(I),u_horizon:new o.bZ(I),u_transition:new o.bZ(I),u_fadeout_range:new o.bZ(I),u_atmosphere_fog_color:new o.cO(I),u_high_color:new o.cO(I),u_space_color:new o.cO(I),u_temporal_offset:new o.bZ(I),u_horizon_angle:new o.bZ(I)}),model:I=>({u_matrix:new o.b$(I),u_lighting_matrix:new o.b$(I),u_normal_matrix:new o.b$(I),u_node_matrix:new o.b$(I),u_lightpos:new o.bY(I),u_lightintensity:new o.bZ(I),u_lightcolor:new o.bY(I),u_camera_pos:new o.bY(I),u_opacity:new o.bZ(I),u_baseColorFactor:new o.cO(I),u_emissiveFactor:new o.cO(I),u_metallicFactor:new o.bZ(I),u_roughnessFactor:new o.bZ(I),u_baseTextureIsAlpha:new o.bX(I),u_alphaMask:new o.bX(I),u_alphaCutoff:new o.bZ(I),u_baseColorTexture:new o.bX(I),u_metallicRoughnessTexture:new o.bX(I),u_normalTexture:new o.bX(I),u_occlusionTexture:new o.bX(I),u_emissionTexture:new o.bX(I),u_lutTexture:new o.bX(I),u_color_mix:new o.cO(I),u_aoIntensity:new o.bZ(I),u_emissive_strength:new o.bZ(I),u_occlusionTextureTransform:new o.cO(I)}),modelDepth:I=>({u_matrix:new o.b$(I),u_instance:new o.b$(I),u_node_matrix:new o.b$(I)}),groundShadow:I=>({u_matrix:new o.b$(I),u_ground_shadow_factor:new o.bY(I)}),stars:I=>({u_matrix:new o.b$(I),u_up:new o.bY(I),u_right:new o.bY(I),u_intensity_multiplier:new o.bZ(I)}),snowParticle:I=>({u_modelview:new o.b$(I),u_projection:new o.b$(I),u_time:new o.bZ(I),u_cam_pos:new o.bY(I),u_velocityConeAperture:new o.bZ(I),u_velocity:new o.bZ(I),u_horizontalOscillationRadius:new o.bZ(I),u_horizontalOscillationRate:new o.bZ(I),u_boxSize:new o.bZ(I),u_billboardSize:new o.bZ(I),u_simpleShapeParameters:new o.b_(I),u_screenSize:new o.b_(I),u_thinningCenterPos:new o.b_(I),u_thinningShape:new o.bY(I),u_thinningAffectedRatio:new o.bZ(I),u_thinningParticleOffset:new o.bZ(I),u_particleColor:new o.cO(I),u_direction:new o.bY(I)}),rainParticle:I=>({u_modelview:new o.b$(I),u_projection:new o.b$(I),u_time:new o.bZ(I),u_cam_pos:new o.bY(I),u_texScreen:new o.bX(I),u_velocityConeAperture:new o.bZ(I),u_velocity:new o.bZ(I),u_boxSize:new o.bZ(I),u_rainDropletSize:new o.b_(I),u_distortionStrength:new o.bZ(I),u_rainDirection:new o.bY(I),u_color:new o.cO(I),u_screenSize:new o.b_(I),u_thinningCenterPos:new o.b_(I),u_thinningShape:new o.bY(I),u_thinningAffectedRatio:new o.bZ(I),u_thinningParticleOffset:new o.bZ(I),u_shapeDirectionalPower:new o.bZ(I),u_shapeNormalPower:new o.bZ(I),u_mode:new o.bZ(I)}),vignette:I=>({u_vignetteShape:new o.bY(I),u_vignetteColor:new o.cO(I)}),occlusion:I=>({u_matrix:new o.b$(I),u_anchorPos:new o.bY(I),u_screenSizePx:new o.b_(I),u_occluderSizePx:new o.b_(I),u_color:new o.cO(I)})};class Vp{constructor(y,C,R,$){this.id=Vp.uniqueIdxCounter,Vp.uniqueIdxCounter++,this.context=y;const G=y.gl;this.buffer=G.createBuffer(),this.dynamicDraw=!!R,this.context.unbindVAO(),y.bindElementBuffer.set(this.buffer),G.bufferData(G.ELEMENT_ARRAY_BUFFER,C.arrayBuffer,this.dynamicDraw?G.DYNAMIC_DRAW:G.STATIC_DRAW),this.dynamicDraw||$||C.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(y){this.id=Vp.uniqueIdxCounter,Vp.uniqueIdxCounter++;const C=this.context.gl;this.context.unbindVAO(),this.bind(),C.bufferSubData(C.ELEMENT_ARRAY_BUFFER,0,y.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}Vp.uniqueIdxCounter=0;const XN={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class JN{constructor(y,C,R,$,G,Z){this.length=C.length,this.attributes=R,this.itemSize=C.bytesPerElement,this.dynamicDraw=$,this.instanceCount=Z,this.context=y;const te=y.gl;this.buffer=te.createBuffer(),y.bindVertexBuffer.set(this.buffer),te.bufferData(te.ARRAY_BUFFER,C.arrayBuffer,this.dynamicDraw?te.DYNAMIC_DRAW:te.STATIC_DRAW),this.dynamicDraw||G||C.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(y){const C=this.context.gl;this.bind(),C.bufferSubData(C.ARRAY_BUFFER,0,y.arrayBuffer)}enableAttributes(y,C){for(const R of this.attributes){const $=C.getAttributeLocation(y,R.name);$!==-1&&y.enableVertexAttribArray($)}}setVertexAttribPointers(y,C,R){for(const $ of this.attributes){const G=C.getAttributeLocation(y,$.name);if(G!==-1){const Z=$.offset+this.itemSize*(R||0);$.type==="Float32"?y.vertexAttribPointer(G,$.components,y.FLOAT,!1,this.itemSize,Z):y.vertexAttribIPointer(G,$.components,y[XN[$.type]],this.itemSize,Z)}}}setVertexAttribDivisor(y,C,R){for(let $=0;$0&&y.vertexAttribDivisor(G,R)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Dj{constructor(y,C,R,$,G){this.context=y,this.width=C,this.height=R;const Z=this.framebuffer=y.gl.createFramebuffer();$>0&&(this.colorAttachment0=new y1(y,Z,0)),$>1&&(this.colorAttachment1=new y1(y,Z,1)),G&&(this.depthAttachmentType=G,this.depthAttachment=G==="renderbuffer"?new Cj(y,Z):new HN(y,Z))}static createWithTexture(y,C,R,$,G){const Z=y.gl;if(y.activeTexture.set(Z.TEXTURE1),y.viewport.set([0,0,R,$]),C&&C.width===R&&C.height===$)return Z.bindTexture(Z.TEXTURE_2D,C.colorAttachment0.get()),y.bindFramebuffer.set(C.framebuffer),C;C&&C.destroy();const te=new o.T(y,{width:R,height:$,data:null},y.extRenderToTextureHalfFloat?y.gl.RGBA16F:y.gl.RGBA8);te.bind(Z.LINEAR,Z.CLAMP_TO_EDGE);const ue=y.createFramebuffer(R,$,1,null);if(ue.colorAttachment0.set(te.texture),G){const xe=y.createRenderbuffer(Z.DEPTH24_STENCIL8,R,$);y.bindFramebuffer.set(ue.framebuffer),Z.framebufferRenderbuffer(Z.FRAMEBUFFER,Z.DEPTH_STENCIL_ATTACHMENT,Z.RENDERBUFFER,xe),ue._stencilRbo=xe}return ue}createColorAttachment(y,C){C===0?this.colorAttachment0=new y1(y,this.framebuffer,0):C===1&&(this.colorAttachment1=new y1(y,this.framebuffer,1))}removeColorAttachment(y,C){const R=this.context.gl;let $;C===0?($=this.colorAttachment0.get(),this.colorAttachment0=void 0):C===1&&($=this.colorAttachment1.get(),this.colorAttachment1=void 0),$&&R.deleteTexture($)}destroy(){const y=this.context.gl;if(this.colorAttachment0){const C=this.colorAttachment0.get();C&&y.deleteTexture(C)}if(this.colorAttachment1){const C=this.colorAttachment1.get();C&&y.deleteTexture(C)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const C=this.depthAttachment.get();C&&y.deleteRenderbuffer(C)}else{const C=this.depthAttachment.get();C&&y.deleteTexture(C)}this._stencilRbo&&(y.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),y.deleteFramebuffer(this.framebuffer)}}class _0{constructor(y,C){this.gl=y,this.clearColor=new vj(this),this.clearDepth=new qR(this),this.clearStencil=new BN(this),this.colorMask=new VR(this),this.depthMask=new Ff(this),this.stencilMask=new bj(this),this.stencilFunc=new f1(this),this.stencilOp=new $N(this),this.stencilTest=new Uy(this),this.depthRange=new qy(this),this.depthTest=new Vy(this),this.depthFunc=new _m(this),this.blend=new UN(this),this.blendFunc=new _j(this),this.blendColor=new y6(this),this.blendEquation=new x1(this),this.cullFace=new wj(this),this.cullFaceSide=new jj(this),this.frontFace=new qN(this),this.program=new Nj(this),this.activeTexture=new kj(this),this.viewport=new wm(this),this.bindFramebuffer=new Vh(this),this.bindRenderbuffer=new NC(this),this.bindTexture=new g1(this),this.bindVertexBuffer=new kC(this),this.bindElementBuffer=new v6(this),this.bindVertexArrayOES=new b6(this),this.pixelStoreUnpack=new SC(this),this.pixelStoreUnpackPremultiplyAlpha=new VN(this),this.pixelStoreUnpackFlipY=new Sj(this),this.options=C?Object.assign({},C):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=y.getExtension("EXT_texture_filter_anisotropic")||y.getExtension("MOZ_EXT_texture_filter_anisotropic")||y.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=y.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=y.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=y.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=y.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=C&&!!C.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=C&&!!C.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=y.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=y.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=y.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=y.getParameter(y.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(y.getParameter(y.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=y.getParameter(y.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=y.getExtension("WEBGL_blend_func_extended")}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(y,C,R){return new Vp(this,y,C,R)}createVertexBuffer(y,C,R,$,G){return new JN(this,y,C,R,$,G)}createRenderbuffer(y,C,R){const $=this.gl,G=$.createRenderbuffer();return this.bindRenderbuffer.set(G),$.renderbufferStorage($.RENDERBUFFER,y,C,R),this.bindRenderbuffer.set(null),G}createFramebuffer(y,C,R,$){return new Dj(this,y,C,R,$)}clear({color:y,depth:C,stencil:R,colorMask:$}){const G=this.gl;let Z=0;y&&(Z|=G.COLOR_BUFFER_BIT,this.clearColor.set(y.toNonPremultipliedRenderColor(null)),this.colorMask.set($||[!0,!0,!0,!0])),C!==void 0&&(Z|=G.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(C),this.depthMask.set(!0)),R!==void 0&&(Z|=G.STENCIL_BUFFER_BIT,this.clearStencil.set(R),this.stencilMask.set(255)),G.clear(Z)}setCullFace(y){y.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(y.mode),this.frontFace.set(y.frontFace))}setDepthMode(y){y.func!==this.gl.ALWAYS||y.mask?(this.depthTest.set(!0),this.depthFunc.set(y.func),this.depthMask.set(y.mask),this.depthRange.set(y.range)):this.depthTest.set(!1)}setStencilMode(y){y.test.func!==this.gl.ALWAYS||y.mask?(this.stencilTest.set(!0),this.stencilMask.set(y.mask),this.stencilOp.set([y.fail,y.depthFail,y.pass]),this.stencilFunc.set({func:y.test.func,ref:y.ref,mask:y.test.mask})):this.stencilTest.set(!1)}setColorMode(y){o.b6(y.blendFunction,na.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(y.blendFunction),this.blendColor.set(y.blendColor),y.blendEquation?this.blendEquation.set(y.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(y.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let w0;function Yn(I,y,C,R,$,G,Z){const te=I.context,ue=te.gl,xe=I.transform,je=[o.aH(xe.center.lng),o.aL(xe.center.lat)],Re=C.layout.get("symbol-placement"),Le=C.layout.get("text-variable-anchor"),Ue=C.layout.get("icon-rotation-alignment")==="map",st=C.layout.get("text-rotation-alignment")==="map",Xe=Re!=="point",pt=[];let mt=0,jt=0;for(let At=0;At0){const Er=o.bb(),ar=Cn;o.cz(Er,ys.placementInvProjMatrix,xe.glCoordMatrix),o.cz(Er,Er,ys.placementViewportMatrix),pt.push({circleArray:dn,circleOffset:jt,transform:ar,invTransform:Er,projection:ys.getProjection()}),mt+=dn.length/4,jt=mt}if(!Tn)continue;I.terrain&&I.terrain.setupElevationDraw(Wt,Dn);const mr=qs?[Rt.canonical.x,Rt.canonical.y,1<=0&&(Ue[Tt.associatedIconIndex]={x:rs,y:zs,z:Is,angle:Rs})}else oi(Ft,Re)}if(xe){Le.clear();const jt=I.icon.placedSymbolArray;for(let Tt=0;Tt{let Ea=[0,0,0];if(Hi){const ul=I.style.directionalLight,_o=I.style.ambientLight;ul&&_o&&(Ea=Bp(I.style,ul,_o))}return Ea},Ya=Hi=>{if(I.context.disableSymbolUBO)return;Hi.push("USE_PAINT_PROPERTIES_UBO");const Ea=Math.floor(I.context.maxUniformBlockSize/4),ul=Math.floor(Ea/4);Hi.push(`MAX_UBO_SIZE_VEC4 ${ul}u`)},_a=Hi=>{Rt.depthOcclusionForSymbolsAndCircles&&(C.hasOcclusionOpacityProperties||I.terrain)&&(Hi.push("DEPTH_D24"),Hi.push("DEPTH_OCCLUSION"))},Pi=Hi=>{C.lut&&!Ft&&(C.lut.texture||(C.lut.texture=new o.dR(I.context,C.lut.image,[C.lut.image.height,C.lut.image.height,C.lut.image.height],Jt.gl.RGBA8)),Jt.activeTexture.set(Jt.gl.TEXTURE0+10),C.lut.texture&&C.lut.texture.bind(Jt.gl.LINEAR,Jt.gl.CLAMP_TO_EDGE),Hi.push("APPLY_LUT_ON_GPU"))},bo=()=>{const Hi=Wt&&C.layout.get("symbol-placement")!=="point",Ea=[];_a(Ea),Pi(Ea);const ul=Hi||Na,_o=dn.elevationType==="road",Sc=I.shadowRenderer,li=_o&&rs&&!!Sc&&Sc.enabled,ko=Kr(li),Xc=_o&&rs&&!I.terrain?js:mn,kh=C.paint.get("icon-image-cross-fade");I.terrainRenderModeElevated()&&rs&&Ea.push("PITCH_WITH_MAP_TERRAIN"),mr&&(Ea.push("PROJECTION_GLOBE_VIEW"),ul&&Ea.push("PROJECTED_POS_ON_VIEWPORT")),kh>0&&dn.hasAnySecondaryIcon&&Ea.push("ICON_TRANSITION"),!dn.icon.zOffsetVertexBuffer||_o&&I.terrain||Ea.push("Z_OFFSET"),mt===0&&jt===0&&Tt===0&&xt===1||Ea.push("COLOR_ADJUSTMENT"),dn.sdfIcons&&Ea.push("RENDER_SDF"),li&&Ea.push("RENDER_SHADOWS","NORMAL_OFFSET"),_o&&rs&&!I.terrain&&dn.icon.orientationVertexBuffer&&Ea.push("ELEVATED_ROADS"),Ya(Ea);const hd=Jt.disableSymbolUBO?dn.icon.programConfigurations.get(C.id):null,_u=I.getOrCreateProgram("symbol",{config:hd,defines:Ea}),$f=Tn.imageAtlasTexture?Tn.imageAtlasTexture.size:[0,0],so=dn.iconSizeData,Tx=o.bj(so,Rt.zoom),Ex=rs||!Rt.isOrthographic,$o=Td(ar,Tn.tileID.canonical,rs,Wt,Rt,dn.getProjection(),hr),Qo=sp(ar,Tn.tileID.canonical,rs,Wt,Rt,dn.getProjection(),hr),co=dn.icon.uboBinder&&dn.icon.uboBinder.cachedHeader&&256&dn.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:te,mc=I.translatePosMatrix(Qo,Tn,co,xe,!0),Kh=I.translatePosMatrix(ar,Tn,co,xe),Fl=ul?xo:$o,Uf=Wt&&!rs&&!Hi;let g_=Dn;!qs&&!Rt.mercatorFromTransition||Wt||(g_=hc(Rt));const Wj=mr?g_:Dn,Kj=C.getColorAdjustmentMatrix(mt,jt,Tt,xt),ck=j1(so.kind,Tx,Uf,rs,I,Kh,Fl,mc,es,!1,$f,[0,0],0,Cn,Er,ms,ba,Wj,dn.getProjection(),ko,Ka,Kj,kh,null),E1=Tn.imageAtlasTexture?Tn.imageAtlasTexture:null,Jy=C.layout.get("icon-size").constantOr(0)!==1||dn.iconsNeedLinear,dk=dn.sdfIcons||I.options.rotating||I.options.zooming||Jy||Ex?At.LINEAR:At.NEAREST,Yp=dn.sdfIcons&&C.paint.get("icon-halo-width").constantOr(1)!==0,y_=I.terrain&&rs&&Hi?o.b7(o.bb(),$o):xo;if(Hi&&dn.icon){const v_=o.bu.getAtTileOffsetFunc(Cn,Rt.center.lat,Rt.worldSize,dn.getProjection()),b_=Bc(ar,Tn.tileID.canonical,rs,Wt,Rt,dn.getProjection(),hr),B6=C.layout.get("icon-size-scale-range"),uk=o.aC(I.scaleFactor,B6[0],B6[1]);Lt(dn,ar,I,!1,b_,Qo,rs,Xe,v_,Cn,uk)}return{program:_u,buffers:dn.icon,uniformValues:ck,atlasTexture:E1,atlasTextureIcon:null,atlasInterpolation:dk,atlasInterpolationIcon:null,isSDF:dn.sdfIcons,hasHalo:Yp,depthMode:Xc,tile:Tn,renderWithShadows:li,labelPlaneMatrixInv:y_}},bl=()=>{const Hi=ys&&C.layout.get("symbol-placement")!=="point",Ea=[],ul=Hi||Rs||Na,_o=dn.elevationType==="road",Sc=I.shadowRenderer,li=_o&&zs&&!!Sc&&Sc.enabled,ko=Kr(li),Xc=_o&&zs&&!I.terrain?js:mn;I.terrainRenderModeElevated()&&zs&&Ea.push("PITCH_WITH_MAP_TERRAIN"),mr&&(Ea.push("PROJECTION_GLOBE_VIEW"),ul&&Ea.push("PROJECTED_POS_ON_VIEWPORT")),!dn.text.zOffsetVertexBuffer||_o&&I.terrain||Ea.push("Z_OFFSET"),dn.iconsInText&&Ea.push("RENDER_TEXT_AND_SYMBOL"),Ea.push("RENDER_SDF"),li&&Ea.push("RENDER_SHADOWS","NORMAL_OFFSET"),_o&&zs&&!I.terrain&&dn.text.orientationVertexBuffer&&Ea.push("ELEVATED_ROADS"),_a(Ea),Ya(Ea);const kh=Jt.disableSymbolUBO?dn.text.programConfigurations.get(C.id):null,hd=I.getOrCreateProgram("symbol",{config:kh,defines:Ea});let _u,$f=[0,0],so=null;const Tx=dn.textSizeData;dn.iconsInText&&($f=Tn.imageAtlasTexture?Tn.imageAtlasTexture.size:[0,0],so=Tn.imageAtlasTexture?Tn.imageAtlasTexture:null,_u=zs||!Rt.isOrthographic||I.options.rotating||I.options.zooming||Tx.kind==="composite"||Tx.kind==="camera"?At.LINEAR:At.NEAREST);const Ex=Tn.glyphAtlasTexture?Tn.glyphAtlasTexture.size:[0,0],$o=C.layout.get("text-size-scale-range"),Qo=o.aC(I.scaleFactor,$o[0],$o[1]),co=o.bj(Tx,Rt.zoom,Qo),mc=Td(ar,Tn.tileID.canonical,zs,ys,Rt,dn.getProjection(),hr),Kh=sp(ar,Tn.tileID.canonical,zs,ys,Rt,dn.getProjection(),hr),Fl=dn.text.uboBinder&&dn.text.uboBinder.cachedHeader&&256&dn.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:ue,Uf=I.translatePosMatrix(Kh,Tn,Fl,je,!0),g_=I.translatePosMatrix(ar,Tn,Fl,je),Wj=ul?xo:mc,Kj=ys&&!zs&&!Hi;let ck=Dn;!qs&&!Rt.mercatorFromTransition||ys||(ck=hc(Rt));const E1=j1(Tx.kind,co,Kj,zs,I,g_,Wj,Uf,es,!0,Ex,$f,0,Cn,Er,ms,ba,mr?ck:Dn,dn.getProjection(),ko,Ka,null,null,Qo),Jy=Tn.glyphAtlasTexture?Tn.glyphAtlasTexture:null,dk=At.LINEAR,Yp=C.paint.get("text-halo-width").constantOr(1)!==0,y_=I.terrain&&zs&&Hi?o.b7(o.bb(),mc):xo;if(Hi&&dn.text){const v_=o.bu.getAtTileOffsetFunc(Cn,Rt.center.lat,Rt.worldSize,dn.getProjection()),b_=Bc(ar,Tn.tileID.canonical,zs,ys,Rt,dn.getProjection(),hr);Lt(dn,ar,I,!0,b_,Kh,zs,pt,v_,Cn,Qo)}return{program:hd,buffers:dn.text,uniformValues:E1,atlasTexture:Jy,atlasTextureIcon:so,atlasInterpolation:dk,atlasInterpolationIcon:_u,isSDF:!0,hasHalo:Yp,depthMode:Xc,tile:Tn,renderWithShadows:li,labelPlaneMatrixInv:y_}},Lo=dn.icon.segments.get().length,Vi=dn.text.segments.get().length,Ba=Lo&&!Z.onlyText?bo():null,$a=Vi&&!Z.onlyIcons?bl():null,Do=C.paint.get("icon-opacity").constantOr(1),kl=C.paint.get("text-opacity").constantOr(1);if(Is&&dn.canOverlap){an=!0;const Hi=Do&&!Z.onlyText?dn.icon.segments.get():[],Ea=kl&&!Z.onlyIcons?dn.text.segments.get():[];for(const ul of Hi)Qs.push({segments:new o.dy([ul]),sortKey:ul.sortKey,state:Ba});for(const ul of Ea)Qs.push({segments:new o.dy([ul]),sortKey:ul.sortKey,state:$a})}else Z.onlyText||Qs.push({segments:Do?dn.icon.segments:new o.dy([]),sortKey:0,state:Ba}),Z.onlyIcons||Qs.push({segments:kl?dn.text.segments:new o.dy([]),sortKey:0,state:$a})}an&&Qs.sort((Cn,Tn)=>Cn.sortKey-Tn.sortKey);for(const Cn of Qs){const Tn=Cn.state;if(Tn)if(I.terrain?I.terrain.setupElevationDraw(Tn.tile,Tn.program,{useDepthForOcclusion:Rt.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Tn.labelPlaneMatrixInv}):I.setupDepthForOcclusion(Rt.depthOcclusionForSymbolsAndCircles,Tn.program),Jt.activeTexture.set(At.TEXTURE0),Tn.atlasTexture&&Tn.atlasTexture.bind(Tn.atlasInterpolation,At.CLAMP_TO_EDGE,!0),Tn.atlasTextureIcon&&(Jt.activeTexture.set(At.TEXTURE1),Tn.atlasTextureIcon&&Tn.atlasTextureIcon.bind(Tn.atlasInterpolationIcon,At.CLAMP_TO_EDGE,!0)),Tn.renderWithShadows&&I.shadowRenderer.setupShadows(Tn.tile.tileID.toUnwrapped(),Tn.program,"vector-tile"),I.uploadCommonLightUniforms(I.context,Tn.program),Tn.hasHalo){const dn=Tn.uniformValues;dn.u_is_halo=1,j0(Tn.buffers,Cn.segments,C,I,Tn.program,Tn.depthMode,$,G,dn,2),dn.u_is_halo=0}else{if(Tn.isSDF){const dn=Tn.uniformValues;Tn.hasHalo&&(dn.u_is_halo=1,j0(Tn.buffers,Cn.segments,C,I,Tn.program,Tn.depthMode,$,G,dn,1)),dn.u_is_halo=0}j0(Tn.buffers,Cn.segments,C,I,Tn.program,Tn.depthMode,$,G,Tn.uniformValues,1)}}}function j0(I,y,C,R,$,G,Z,te,ue,xe){const je=R.context,Re=je.gl,Le=[I.dynamicLayoutVertexBuffer,I.opacityVertexBuffer,I.iconTransitioningVertexBuffer,I.globeExtVertexBuffer,I.zOffsetVertexBuffer,I.orientationVertexBuffer];I.featureIdBuffer&&Le.push(I.featureIdBuffer);const Ue=I.uboBinder?null:I.programConfigurations.get(C.id);if(I.uboBinder){I.uboBinder.layer=C;const pt=R.transform.zoom,mt=R.style.getBrightness?R.style.getBrightness():null,jt=I.uboBinder.getConstantUniformValues(pt,mt);ue.u_spp_fill_np_color=jt.fill_np_color,ue.u_spp_halo_np_color=jt.halo_np_color,ue.u_spp_opacity=jt.opacity,ue.u_spp_halo_width=jt.halo_width,ue.u_spp_halo_blur=jt.halo_blur,ue.u_spp_emissive_strength=jt.emissive_strength,ue.u_spp_occlusion_opacity=jt.occlusion_opacity,ue.u_spp_z_offset=jt.z_offset;const Tt=C.paint.get(I.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),xt=I.uboBinder.cachedHeader&&256&I.uboBinder.cachedHeader.dataDrivenMask&&Tt==="map"?R.transform.angle:0;ue.u_spp_translate_rotation=[Math.cos(xt),Math.sin(xt)]}const{batchIndices:st,batchSegments:Xe}=I.getBatchGrouping(y);for(const pt of st){const mt=Xe.get(pt);I.uboBinder&&I.uboBinder.bind(je,$.program,pt),$.draw(R,Re.TRIANGLES,G,Z,te,Fr.disabled,ue,C.id,I.layoutVertexBuffer,I.indexBuffer,mt,C.paint,R.transform.zoom,Ue,Le,xe)}}function dd(I,y,C,R,$,G){const Z=C.paint.get("line-width"),te=C.paint.get("line-emissive-strength").isConstant(),ue=C.paint.get("line-emissive-strength").constantOr(0),xe=C.paint.get("line-occlusion-opacity"),je=C.layout.get("line-elevation-reference"),Re=C.layout.get("line-width-unit")==="meters",Le=je==="sea",Ue=!(!I.terrain||!I.terrain.enabled),st=I.context,Xe=st.gl;if(C.hasElevatedBuckets&&I.transform.projection.name==="globe")return;const pt=C.layout.get("line-cross-slope"),mt=pt!==void 0,jt=pt<1,Tt=$||I.colorModeForDrapableLayerRenderPass(te?ue:null),xt=I.terrain&&I.terrain.renderingToTexture||G,es=xt?1:o.o.devicePixelRatio,Ft=C.paint.get("line-dasharray"),Jt=Ft.constantOr(1),At=C.layout.get("line-cap"),Rt=Ft.constantOr(null),Wt=At.constantOr(null),ys=C.paint.get("line-pattern"),rs=ys.constantOr(1),zs=C.paint.get("line-pattern-cross-fade"),Is=ys.constantOr(null),an=C.paint.get("line-opacity").constantOr(1);let mn=!rs&&an!==1||I.depthOcclusion&&xe>0&&xe<1;const js=C.paint.get("line-gradient"),ms=rs?"linePattern":"line",Rs=o.dU(C);let qs;if(xt&&I.terrain&&I.terrain.clipOrMaskOverlapStencilType()&&(mn=!1),xe!==0&&I.depthOcclusion){const dn=C.paint._values["line-opacity"];dn&&dn.value&&dn.value.kind==="constant"?qs=dn.value:o.w(`Occlusion opacity for layer ${C.id} is supported only when line-opacity isn't data-driven.`)}Z.value.kind!=="constant"&&Z.value.isLineProgressConstant===!1&&Rs.push("VARIABLE_LINE_WIDTH"),xt&&(I.emissiveMode!=="dual-source-blending"||te?I.emissiveMode==="mrt-fallback"&&Rs.push("USE_MRT1"):Rs.push("DUAL_SOURCE_BLENDING"));const Qs={},Dn=(dn,mr,Er,ar,hr,ra)=>{for(const Na of dn){const ba=y.getTile(Na);if(rs&&!ba.patternsLoaded())continue;const Ka=ba.getBucket(C);if(!Ka||Ka.elevationType!=="none"&&!hr||Ka.elevationType==="none"&&hr)continue;I.prepareDrawTile();const Kr=[...mr],Ya=I.shadowRenderer,_a=Ka.elevationType==="road"&&!!Ya&&Ya.enabled;let Pi=[0,0,0];if(_a){const li=I.style.directionalLight,ko=I.style.ambientLight;li&&ko&&(Pi=Bp(I.style,li,ko)),Kr.push("RENDER_SHADOWS","NORMAL_OFFSET")}const bo=Ka.programConfigurations.get(C.id);let bl=!1;if(Is&&ba.imageAtlas){const li=o.dV.from(Is),ko=li.getPrimary().scaleSelf(es).toString(),Xc=ba.imageAtlas.patternPositions.get(ko),kh=li.getSecondary(),hd=kh?ba.imageAtlas.patternPositions.get(kh.scaleSelf(es).toString()):null;bl=!!Xc&&!!hd,Xc&&bo.setConstantPatternPositions(Xc,hd)}zs>0&&(bl||bo.getPatternTransitionVertexBuffer("line-pattern"))&&Kr.push("LINE_PATTERN_TRANSITION"),Ka.elevationGroundScaleVertexBuffer&&Kr.push("ELEVATION_GROUND_SCALE");const Lo=I.isTileAffectedByFog(Na),Vi=I.getOrCreateProgram(ms,{config:bo,defines:Kr,overrideFog:Lo});if(!rs&&Rt&&Wt&&ba.lineAtlas){const li=ba.lineAtlas.getDash(Rt,Wt);li&&bo.setConstantPatternPositions(li)}_a&&Ya.setupShadows(ba.tileID.toUnwrapped(),Vi,"vector-tile");let[Ba,$a]=C.paint.get("line-trim-offset");(Wt==="round"||Wt==="square")&&Ba!==$a&&(Ba===0&&(Ba-=1),$a===1&&($a+=1));const Do=xt?Na.projMatrix:null,kl=Re?1/Ka.tileToMeter/o.aA(ba,1,I.transform.zoom):1,Hi=Re?1/Ka.tileToMeter/o.aA(ba,1,Math.floor(I.transform.zoom)):1,Ea=Jt?C.paint._values["line-floorwidth"]:null;let ul;if(Ea&&Ea.value.kind==="constant"){const li=Ka.zoom;li in Qs||(Qs[li]=Math.max(.01,C.widthExpression().evaluate({zoom:li}))),ul=Ea.value.value;const ko=Math.floor(I.transform.zoom);Ea.value.value=Qs[li]*Math.pow(2,ko-ba.tileID.overscaledZ)}const _o=rs?o.dW(I,ba,C,Do,es,kl,Hi,[Ba,$a],Pi,zs):o.dX(I,ba,C,Do,Ka.lineClipsArray.length,es,kl,Hi,[Ba,$a],Pi);if(js){const li=Ka.gradients[C.id];let ko=li.texture;if(C.gradientVersion!==li.version){let Xc=256;if(C.stepInterpolant){const kh=y.getSource().maxzoom,hd=Na.canonical.z===kh?Math.ceil(1<{qs!=null&&(qs.value=an*xe),Vi.draw(I,Xe.TRIANGLES,Er,li,Tt,Fr.disabled,_o,C.id,Ka.layoutVertexBuffer,Ka.indexBuffer,Ka.segments,C.paint,I.transform.zoom,bo,[Ka.layoutVertexBuffer2,Ka.patternVertexBuffer,Ka.zOffsetVertexBuffer,Ka.elevationGroundScaleVertexBuffer]),qs!=null&&(qs.value=an)};if(mn&&!hr){const li=I.stencilModeForClipping(Na).ref;li===0&&xt&&st.clear({stencil:0});const ko={func:Xe.EQUAL,mask:255};_o.u_alpha_discard_threshold=.8,Sc(new la(ko,li,255,Xe.KEEP,Xe.KEEP,Xe.INVERT)),_o.u_alpha_discard_threshold=0,Sc(new la(ko,li,255,Xe.KEEP,Xe.KEEP,Xe.KEEP))}else _o.u_alpha_discard_threshold=mn&&hr&&ra?.8:0,Sc(hr?ar:I.stencilModeForClipping(Na));ul!==void 0&&(Ea.value.value=ul)}};let Cn=I.depthModeForSublayer(0,rr.ReadOnly);const Tn=new rr(I.depthOcclusion?Xe.GREATER:Xe.LEQUAL,rr.ReadOnly,I.depthRangeFor3D);if(C.hasNonElevatedBuckets){const dn=!xt&&I.terrain;xe!==0&&dn?o.w(`Occlusion opacity for layer ${C.id} is supported on terrain only if the layer has line-z-offset enabled.`):dn?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${C.id}.`):Dn(R,Rs,Cn,la.disabled,!1,!0)}if(C.hasElevatedBuckets){je==="hd-road-markup"?Ue||(Cn=Tn,Rs.push("ELEVATED_ROADS")):(Rs.push("ELEVATED"),Cn=Tn,mt&&Rs.push(jt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Le&&Rs.push("ELEVATION_REFERENCE_SEA"));const dn=mn?I.stencilModeFor3D():la.disabled;I.forceTerrainMode=!0,Dn(R,Rs,Cn,dn,!0,!0),mn&&Dn(R,Rs,Cn,dn,!0,!1),I.forceTerrainMode=!1}mn&&(I.resetStencilClippingMasks(),xt&&st.clear({stencil:0})),xe===0||I.depthOcclusion||xt||I.layersWithOcclusionOpacity.push(I.currentLayer)}const Hp={additive:{clearColor:new o.aq(0,0,0,0),colorMode:na.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:na.multiply,compositeUniformValue:0}};function N0(I,y){const C=1<=Df?1:Ue.pitch/Df))),2*st}(I.transform),xe=I.transform.getFreeCameraOptions().position,je="elevatedStructuresDepthReconstruct",Re=I.getOrCreateProgram(je,{defines:["DEPTH_RECONSTRUCTION"]}),Le=I.getOrCreateProgram(je);for(const Ue of R){const st=y.getTile(Ue),Xe=st.getBucket(C);if(!Xe)continue;const pt=Xe.elevatedStructures;if(!pt)continue;const mt=Xe.elevationBufferData.heightRange,jt=N0(Ue.toUnwrapped(),xe),Tt=I.translatePosMatrix(Ue.projMatrix,st,C.paint.get("fill-translate"),C.paint.get("fill-translate-anchor"));let xt,es,Ft,Jt;if($==="initialize"){if(!mt||mt.min>=1||pt.depthSegments.segments[0].primitiveLength===0)continue;xt=w1(Tt,jt,ue,1,0),es=Z,Ft=pt.depthSegments,Jt=Re}else if($==="reset"){if(!mt||mt.min>=0||pt.maskSegments.segments[0].primitiveLength===0)continue;xt=w1(Tt,jt,0,0,1),es=te,Ft=pt.maskSegments,Jt=Re}else if($==="geometry"){if(pt.depthSegments.segments[0].primitiveLength===0)continue;xt=w1(Tt,jt,ue,1,0),es=Z,Ft=pt.depthSegments,Jt=Le}Jt.draw(I,G.TRIANGLES,es,la.disabled,na.disabled,Fr.disabled,xt,C.id,pt.vertexBuffer,pt.indexBuffer,Ft,C.paint,I.transform.zoom)}}function N1(I,y,C,R){const{painter:$,sourceCache:G,layer:Z,coords:te,colorMode:ue,elevationType:xe,terrainEnabled:je,pass:Re}=I,Le=$.context.gl,Ue=Z.paint.get("fill-pattern"),st=Z.paint.get("fill-pattern-cross-fade"),Xe=Ue.constantOr(null);let pt=xe;xe!=="road"||y&&!je||(pt="none");const mt=pt==="road",jt=I.painter.shadowRenderer,Tt=mt&&!!jt&&jt.enabled,xt=new rr($.context.gl.LEQUAL,rr.ReadOnly,$.depthRangeFor3D);let es=[0,0,0];if(Tt){const Rt=$.style.directionalLight,Wt=$.style.ambientLight;Rt&&Wt&&(es=Bp($.style,Rt,Wt))}const Ft=Ue&&Ue.constantOr(1),Jt=$.terrain&&$.terrain.renderingToTexture,At=(Rt,Wt)=>{let ys,rs,zs,Is,an;Wt?(ys=Ft&&!Z.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",zs=Le.LINES):(ys=Ft?"fillPattern":"fill",zs=Le.TRIANGLES);for(const mn of te){const js=G.getTile(mn);if(Ft&&!js.patternsLoaded())continue;const ms=js.getBucket(Z);if(!ms)continue;const Rs=y?ms.elevationBufferData:ms.bufferData;if(Rs.isEmpty())continue;$.prepareDrawTile();const qs=Rs.programConfigurations.get(Z.id),Qs=$.isTileAffectedByFog(mn),Dn=[],Cn=[];mt&&(Dn.push("ELEVATED_ROADS"),Cn.push(Rs.elevatedLayoutVertexBuffer)),Tt&&Dn.push("RENDER_SHADOWS","NORMAL_OFFSET"),Jt&&C&&Dn.push("USE_MRT1"),Ft&&($.context.activeTexture.set(Le.TEXTURE0),js.imageAtlasTexture&&js.imageAtlasTexture.bind(Le.LINEAR,Le.CLAMP_TO_EDGE),qs.updatePaintBuffers());let Tn=!1;if(Xe&&js.imageAtlas){const hr=js.imageAtlas,ra=o.dV.from(Xe),Na=ra.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),ba=ra.getSecondary(),Ka=hr.patternPositions.get(Na),Kr=ba?hr.patternPositions.get(ba.scaleSelf(o.o.devicePixelRatio).toString()):null;Tn=!!Ka&&!!Kr,Ka&&qs.setConstantPatternPositions(Ka,Kr)}st>0&&(Tn||qs.getPatternTransitionVertexBuffer("fill-pattern"))&&Dn.push("FILL_PATTERN_TRANSITION");const dn=$.getOrCreateProgram(ys,{config:qs,overrideFog:Qs,defines:Dn}),mr=$.translatePosMatrix(mn.projMatrix,js,Z.paint.get("fill-translate"),Z.paint.get("fill-translate-anchor"));Tt&&jt.setupShadows(js.tileID.toUnwrapped(),dn,"vector-tile");const Er=Z.paint.get("fill-emissive-strength");if(Wt){Is=Rs.lineIndexBuffer,an=Rs.lineSegments;const hr=$.terrain&&$.terrain.renderingToTexture?$.terrain.drapeBufferSize:[Le.drawingBufferWidth,Le.drawingBufferHeight];rs=ys==="fillOutlinePattern"&&Ft?o_(mr,Er,$,js,hr,es,st):EC(mr,Er,hr,es)}else Is=Rs.indexBuffer,an=Rs.triangleSegments,rs=Ft?i_(mr,Er,$,js,es,st):y0(mr,Er,es);$.uploadCommonUniforms($.context,dn,mn.toUnwrapped());let ar=Rt;(xe==="road"&&!je||xe==="offset")&&(ar=xt),dn.draw($,zs,ar,R||$.stencilModeForClipping(mn),ue,Fr.disabled,rs,Z.id,Rs.layoutVertexBuffer,Is,an,Z.paint,$.transform.zoom,qs,Cn)}};$.renderPass===Re&&At($.depthModeForSublayer(1,$.renderPass==="opaque"?rr.ReadWrite:rr.ReadOnly),!1),pt==="none"&&$.renderPass==="translucent"&&Z.paint.get("fill-antialias")&&At($.depthModeForSublayer(Z.getPaintProperty("fill-outline-color")?2:0,rr.ReadOnly),!0)}function kx(I,y,C,R,$,G,Z,te){C.resetLayerRenderingStats(I);const ue=I.context,xe=ue.gl,je=I.transform,Re=C.paint.get("fill-extrusion-pattern"),Le=C.paint.get("fill-extrusion-pattern-cross-fade"),Ue=Re.constantOr(null),st=Re.constantOr(1),Xe=C.paint.get("fill-extrusion-opacity"),pt=I.style.enable3dLights(),mt=C.paint.get(pt&&!st?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),jt=[C.paint.get("fill-extrusion-ambient-occlusion-intensity"),mt],Tt=C.layout.get("fill-extrusion-edge-radius"),xt=Tt>0&&!C.paint.get("fill-extrusion-rounded-roof"),es=xt?0:Tt,Ft=je.projection.name==="globe"?o.e1():0,Jt=je.projection.name==="globe",At=Jt?o.al(je.zoom):0,Rt=[o.aH(je.center.lng),o.aL(je.center.lat)],Wt=C.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",ys=C.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Wt?null:C.lut).toArray01().slice(0,3),rs=C.paint.get("fill-extrusion-flood-light-intensity"),zs=C.paint.get("fill-extrusion-vertical-scale"),Is=C.paint.get("fill-extrusion-line-width").constantOr(1)!==0,an=C.paint.get("fill-extrusion-height-alignment"),mn=C.paint.get("fill-extrusion-base-alignment"),js=$c(I,C.paint.get("fill-extrusion-cutoff-fade-range")),ms=C.paint.get("fill-extrusion-front-cutoff"),Rs=u_(je.pitch,ms,!!I.terrain),qs=Rs[2]<1;qs&&(I.maxFrontCutoffRawStart=Math.max(I.maxFrontCutoffRawStart,ms[0]));const Qs=[];let Dn;Jt&&Qs.push("PROJECTION_GLOBE_VIEW"),jt[0]>0&&Qs.push("FAUX_AO"),xt&&Qs.push("ZERO_ROOF_RADIUS"),te&&Qs.push("HAS_CENTROID"),rs>0&&Qs.push("FLOOD_LIGHT"),js.shouldRenderCutoff&&Qs.push("RENDER_CUTOFF"),qs&&Qs.push("RENDER_FRONT_CUTOFF"),Is&&Qs.push("RENDER_WALL_MODE");const Cn=I.renderPass==="shadow",Tn=I.shadowRenderer,dn=Cn&&!!Tn,mr=Cn?Fr.disabled:Fr.backCCW;I.shadowRenderer&&(I.shadowRenderer.useNormalOffset=!0);let Er=[0,0,0];if(Tn){const ra=I.style.directionalLight,Na=I.style.ambientLight;ra&&Na&&(Er=Bp(I.style,ra,Na)),Cn||(Qs.push("RENDER_SHADOWS"),Tn.useNormalOffset&&Qs.push("NORMAL_OFFSET")),Dn=Qs.concat(["SHADOWS_SINGLE_CASCADE"])}const ar=dn?"fillExtrusionDepth":st?"fillExtrusionPattern":"fillExtrusion",hr=C.getLayerRenderingStats();for(const ra of R){const Na=y.getTile(ra),ba=Na.getBucket(C);if(!ba||ba.projection.name!==je.projection.name)continue;let Ka=!1;Tn&&(Ka=Tn.getMaxCascadeForTile(ra.toUnwrapped())===0);const Kr=I.isTileAffectedByFog(ra),Ya=ba.programConfigurations.get(C.id);let _a=!1;if(Ue&&Na.imageAtlas){const $a=Na.imageAtlas,Do=o.dV.from(Ue),kl=Do.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),Hi=Do.getSecondary(),Ea=$a.patternPositions.get(kl),ul=Hi?$a.patternPositions.get(Hi.scaleSelf(o.o.devicePixelRatio).toString()):null;_a=!!Ea&&!!ul,Ea&&Ya.setConstantPatternPositions(Ea,ul)}Le>0&&(_a||Ya.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&Qs.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Pi=I.getOrCreateProgram(ar,{config:Ya,defines:Ka?Dn:Qs,overrideFog:Kr});if(I.terrain&&I.terrain.setupElevationDraw(Na,Pi,{useMeterToDem:!0}),!ba.centroidVertexBuffer){const $a=Pi.getAttributeLocation(xe,"a_centroid_pos");$a!==-1&&xe.vertexAttribI4ui($a,0,0,0,0)}!Cn&&Tn&&Tn.setupShadows(Na.tileID.toUnwrapped(),Pi,"vector-tile"),st&&(I.context.activeTexture.set(xe.TEXTURE0),Na.imageAtlasTexture&&Na.imageAtlasTexture.bind(xe.LINEAR,xe.CLAMP_TO_EDGE),Ya.updatePaintBuffers());const bo=C.paint.get("fill-extrusion-vertical-gradient"),bl=1/ba.tileToMeter;let Lo;if(Cn&&Tn){if(Sx(Na.tileID,ba.maxHeight,I))continue;const $a=Tn.calculateShadowPassMatrixFromTile(Na.tileID.toUnwrapped());Lo=HR($a,es,bl,zs,an,mn)}else{const $a=I.translatePosMatrix(ra.expandedProjMatrix,Na,C.paint.get("fill-extrusion-translate"),C.paint.get("fill-extrusion-translate-anchor")),Do=je.projection.createInversionMatrix(je,ra.canonical);Lo=st?qa($a,I,bo,Xe,jt,es,bl,ra,Na,Ft,an,mn,At,Rt,Do,ys,zs,Le):wh($a,I,bo,Xe,jt,es,bl,ra,Ft,an,mn,At,Rt,Do,ys,zs,rs,Er,Rs)}I.uploadCommonUniforms(ue,Pi,ra.toUnwrapped(),null,js);let Vi=ba.segments;if(je.projection.name==="mercator"&&!Cn&&(Vi=ba.getVisibleSegments(Na.tileID,I.terrain,I.transform.getFrustum(0)),!Vi.get().length))continue;if(hr)if(Cn)for(const $a of Vi.get())hr.numRenderedVerticesInShadowPass+=$a.primitiveLength;else for(const $a of Vi.get())hr.numRenderedVerticesInTransparentPass+=$a.primitiveLength;const Ba=[];(I.terrain||te)&&Ba.push(ba.centroidVertexBuffer),Jt&&Ba.push(ba.layoutVertexExtBuffer),Is&&Ba.push(ba.wallVertexBuffer),Pi.draw(I,ue.gl.TRIANGLES,$,G,Z,mr,Lo,C.id,ba.layoutVertexBuffer,ba.indexBuffer,Vi,C.paint,I.transform.zoom,Ya,Ba)}I.shadowRenderer&&(I.shadowRenderer.useNormalOffset=!1)}class Gh{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function u_(I,y,C){if(!(y[2]<1)||C)return[0,0,1];const R=180*I/Math.PI;if(R<15)return[-.5,y[1],y[2]];const $=Math.min(1,Math.max(0,(R-15)/5)),G=$*$*(3-2*$);return[-.5*(1-G)+y[0]*G,y[1],y[2]]}function zf(I,y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue,st,Xe,pt,mt,jt,Tt,xt){const es=y.context,Ft=es.gl,Jt=y.transform,At=y.transform.zoom,Rt=[],Wt=I.translate,ys=I.translateAnchor,rs=I.edgeRadius,zs=$c(y,I.cutoffFadeRange);je==="clear"?(Rt.push("CLEAR_SUBPASS"),Tt&&(Rt.push("CLEAR_FROM_TEXTURE"),es.activeTexture.set(Ft.TEXTURE0),Tt.bind(Ft.LINEAR,Ft.CLAMP_TO_EDGE))):je==="sdf"?Rt.push("SDF_SUBPASS"):je==="emissive"&&(Rt.push("USE_MRT1"),es.activeTexture.set(Ft.TEXTURE0),Tt.bind(Ft.LINEAR,Ft.CLAMP_TO_EDGE)),mt&&Rt.push("HAS_CENTROID"),zs.shouldRenderCutoff&&Rt.push("RENDER_CUTOFF");const Is=(an,mn,js,ms,Rs)=>{let qs=Rt;mn.groundRadiusBuffer!=null&&(qs=Rt.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const Qs=mn.programConfigurations.get(R.id),Dn=y.isTileAffectedByFog(an),Cn=y.getOrCreateProgram("fillExtrusionGroundEffect",{config:Qs,defines:qs,overrideFog:Dn}),Tn=((mr,Er,ar,hr,ra,Na,ba,Ka,Kr,Ya,_a)=>({u_matrix:Er,u_opacity:ar,u_ao_pass:hr?1:0,u_meter_to_tile:ra,u_ao:Na,u_flood_light_intensity:ba,u_flood_light_color:Ka,u_attenuation:Kr,u_edge_radius:Ya,u_fb:0,u_fb_size:_a,u_dynamic_offset:1}))(0,ms,Re,xe,Rs,[Le,Ue*Rs],st,Xe,pt,At>=17?0:rs*Rs,Tt?Tt.size[0]:0),dn=[];mt&&dn.push(mn.hiddenByLandmarkVertexBuffer),mn.groundRadiusBuffer!=null&&dn.push(mn.groundRadiusBuffer),y.uploadCommonUniforms(es,Cn,an.toUnwrapped(),null,zs),Cn.draw(y,es.gl.TRIANGLES,G,Z,te,ue,Tn,R.id,mn.vertexBuffer,mn.indexBuffer,js,R.paint,At,Qs,dn)};for(const an of $){const mn=C.getTile(an),js=mn.getBucket(R);if(!js||js.projection.name!==Jt.projection.name||!js.groundEffect||js.groundEffect&&!js.groundEffect.hasData())continue;const ms=js.groundEffect,Rs=1/js.tileToMeter;{const qs=y.translatePosMatrix(an.projMatrix,mn,Wt,ys),Qs=ms.getDefaultSegment();Is(an,ms,Qs,qs,Rs)}if(jt)for(let qs=0;qs<4;qs++){const Qs=o.d$[qs](an),Dn=C.getTile(Qs);if(!Dn)continue;const Cn=Dn.getBucket(R);if(!Cn||Cn.projection.name!==Jt.projection.name||!Cn.groundEffect||Cn.groundEffect&&!Cn.groundEffect.hasData())continue;const Tn=Cn.groundEffect;let dn,mr;qs===0?(dn=[-o.an,0,0],mr=1):qs===1?(dn=[o.an,0,0],mr=0):qs===2?(dn=[0,-o.an,0],mr=3):(dn=[0,o.an,0],mr=2);const Er=Tn.regionSegments[mr];if(!Er)continue;const ar=new Float32Array(16);o.bx(ar,an.projMatrix,dn),Is(an,Tn,Er,y.translatePosMatrix(ar,mn,Wt,ys),Rs)}}}function xg(I,y,C,R,$,G,Z){R.centroidVertexArray.length===0&&R.createCentroidsBuffer();const te=G?G.findDEMTileFor(C):null;if(!(te&&te.dem||Z))return;G&&te&&te.dem&&R.selfDEMTileTimestamp!==te.dem._timestamp&&(R.borderDoneWithNeighborZ=[-1,-1,-1,-1],R.selfDEMTileTimestamp=te.dem._timestamp);const ue=(mt,jt)=>{(mt.flags|jt.flags)&o.e3?(mt.flags|=o.e3,jt.flags|=o.e3):(mt.flags&=~o.e3,jt.flags&=~o.e3)},xe=mt=>new o.P(Math.ceil((mt+o.e4)*o.e5),0),je=(mt,jt,Tt)=>{const xt=Math.ceil((mt+o.e4)*o.e5),es=Math.floor(Math.max(0,Math.min(o.an-1,Tt))/4);return new o.P(xt,es<<5|(3&jt)<<3|7)},Re=mt=>{const jt=y.getSource().minzoom,Tt=es=>{const Ft=y.getTileByID(es);if(Ft&&Ft.hasData())return Ft.getBucket($)},xt=[0,-1,1];for(const es of xt){if(mt.overscaledZ+es(Le[0]=Math.min(mt.min.y,jt.min.y),Le[1]=Math.max(mt.max.y,jt.max.y),Le[2]=o.an-jt.min.x>mt.max.x?jt.min.x-o.an:mt.max.x,Le),st=(mt,jt)=>(Le[0]=Math.min(mt.min.x,jt.min.x),Le[1]=Math.max(mt.max.x,jt.max.x),Le[2]=o.an-jt.min.y>mt.max.y?jt.min.y-o.an:mt.max.y,Le),Xe=[(mt,jt)=>Ue(mt,jt),(mt,jt)=>Ue(jt,mt),(mt,jt)=>st(mt,jt),(mt,jt)=>st(jt,mt)],pt=(mt,jt,Tt,xt,es,Ft,Jt)=>{if(!G)return 0;const At=[[Ft?Tt:mt,Ft?mt:Tt,0],[Ft?Tt:jt,Ft?jt:Tt,0]],Rt=Jt<0?o.an+Jt:Jt,Wt=[Ft?Rt:(mt+jt)/2,Ft?(mt+jt)/2:Rt,0];return Tt===0&&Jt<0||Tt!==0&&Jt>0?G.getForTilePoints(es,[Wt],!0,xt):At.push(Wt),G.getForTilePoints(C,At,!0,te),Math.max(At[0][2],At[1][2],Wt[2])/G.exaggeration()};for(let mt=0;mt<4;mt++){const jt=R.borderFeatureIndices[mt];if(jt.length===0)continue;const Tt=o.d$[mt](C),xt=Re(Tt);if(!(xt&&xt instanceof o.e0))continue;const es=G?G.findDEMTileFor(Tt):null;if(!(es&&es.dem||Z)||(G&&es&&es.dem&&R.borderDEMTileTimestamp[mt]!==es.dem._timestamp&&(R.borderDoneWithNeighborZ[mt]=-1,R.borderDEMTileTimestamp[mt]=es.dem._timestamp),R.borderDoneWithNeighborZ[mt]===xt.canonical.z))continue;xt.centroidVertexArray.length===0&&xt.createCentroidsBuffer();const Ft=(mt<2?1:5)-mt,Jt=xt.borderDoneWithNeighborZ[Ft]!==R.canonical.z,At=xt.borderFeatureIndices[Ft];let Rt=0;if(R.canonical.z!==xt.canonical.z){for(const zs of jt)R.showCentroid(R.featuresOnBorder[zs]);if(Jt)for(const zs of At)xt.showCentroid(xt.featuresOnBorder[zs]);R.borderDoneWithNeighborZ[mt]=xt.canonical.z,xt.borderDoneWithNeighborZ[Ft]=R.canonical.z;continue}const Wt=new Map,ys=new Set,rs=new Set;for(let zs=0;zs1||js.intersectsCount()>1;{let Cn=0;if(es&&es.dem&&!Dn){const Tn=Xe[mt](an,ms),dn=mt%2?o.an-1:0;Cn=pt(Tn[0],Math.min(o.an-1,Tn[1]),dn,es,Tt,mt<2,Tn[2])}an.centroidXY=je(Cn,mt,Qs),ms.centroidXY=je(Cn,Ft,Qs)}if(R.writeCentroidToBuffer(an),xt.writeCentroidToBuffer(ms),Is.buildingId!==void 0){for(const Cn of R.centroidData)Cn.buildingId===Is.buildingId&&Cn!==an&&(Cn.centroidXY=an.centroidXY,R.writeCentroidToBuffer(Cn));for(const Cn of xt.centroidData)Cn.buildingId===Is.buildingId&&Cn!==ms&&(Cn.centroidXY=ms.centroidXY,xt.writeCentroidToBuffer(Cn))}}for(const zs of jt){if(ys.has(zs))continue;const Is=R.featuresOnBorder[zs],an=R.centroidData[Is.centroidDataIndex],mn=Is.borders[mt];let js;for(;Rtmn[0]+3||ms[0]>mn[0]-3)break;xt.showCentroid(js),Rt++}if(js&&Rtmn[1]-3||(Rs++,++Rt===At.length))break;js=xt.featuresOnBorder[At[Rt]]}for(;ms=At.length){R.showCentroid(Is);continue}js=xt.featuresOnBorder[At[ms]];let qs=!1;if(Rs>=1){const Cn=js.borders[Ft];Math.abs(mn[0]-Cn[0])<3&&Math.abs(mn[1]-Cn[1])<3&&(Rs=1,qs=!0,Rt=ms+1)}else if(Rs===0){R.showCentroid(Is);continue}const Qs=xt.centroidData[js.centroidDataIndex];Z&&qs&&ue(an,Qs);const Dn=Is.intersectsCount()>1||js.intersectsCount()>1;if(Rs>1)Rt=ms,an.centroidXY=Qs.centroidXY=new o.P(0,0);else if(es&&es.dem&&!Dn){const Cn=Xe[mt](an,Qs),Tn=mt%2?o.an-1:0,dn=pt(Cn[0],Math.min(o.an-1,Cn[1]),Tn,es,Tt,mt<2,Cn[2]);an.centroidXY=Qs.centroidXY=xe(dn)}else Dn?an.centroidXY=Qs.centroidXY=new o.P(0,0):(an.centroidXY=R.encodeBorderCentroid(Is),Qs.centroidXY=xt.encodeBorderCentroid(js));R.writeCentroidToBuffer(an),xt.writeCentroidToBuffer(Qs)}else R.showCentroid(Is)}R.borderDoneWithNeighborZ[mt]=xt.canonical.z,xt.borderDoneWithNeighborZ[Ft]=R.canonical.z}(R.needsCentroidUpdate||!R.centroidVertexBuffer&&R.centroidVertexArray.length!==0)&&R.uploadCentroid(I)}const k1=[1,0,0],Rj=[0,1,0],Oj=[0,0,1];function Sx(I,y,C){const R=C.transform,$=C.shadowRenderer;if(!$)return!0;const G=I.toUnwrapped(),Z=R.tileSize*$._cascades[C.currentShadowCascade].scale;let te=y;if(R.elevation){const st=R.elevation.getMinMaxForTile(I);st&&(te+=st.max)}const ue=R.scaleZoom(Z);te/=o.e2(R.center.lat,ue);const xe=[...$.shadowDirection];xe[2]=-xe[2];const je=$.computeSimplifiedTileShadowVolume(G,te,Z,xe);if(!je)return!1;const Re=[k1,Rj,Oj,xe,[xe[0],0,xe[2]],[0,xe[1],xe[2]]],Le=o.cl.fromInvProjectionMatrix(R.invProjMatrix,R.worldSize,ue,R.projection.name!=="globe"),Ue=$.getCurrentCascadeFrustum();return Le.intersectsPrecise(je.vertices,je.planes,Re)===0||Ue.intersectsPrecise(je.vertices,je.planes,Re)===0}function Yy(I){const{painter:y,source:C,layer:R,coords:$}=I;let G=I.defines;const Z=y.context,te=y.renderPass==="shadow",ue=y.renderPass==="light-beam",xe=y.shadowRenderer,je=o.e2(y.transform.center.lat,y.transform.zoom),Re=$c(y,R.paint.get("building-cutoff-fade-range"));Re.shouldRenderCutoff&&(G=G.concat("RENDER_CUTOFF"));const Le=R.paint.get("building-front-cutoff"),Ue=Le[2]<1&&!y.terrain,st=u_(y.transform.pitch,Le,!!y.terrain);Ue&&(G=G.concat("RENDER_FRONT_CUTOFF"),y.maxFrontCutoffRawStart=Math.max(y.maxFrontCutoffRawStart,Le[0])),I.floodLightIntensity>0&&(G=G.concat("FLOOD_LIGHT"));for(const Xe of $){const pt=C.getTile(Xe),mt=pt.getBucket(R);if(!mt)continue;xe&&xe.getMaxCascadeForTile(Xe.toUnwrapped())===0&&(G=G.concat("SHADOWS_SINGLE_CASCADE"));const jt=mt.programConfigurations.get(R.id);let Tt,xt,es,Ft=y.translatePosMatrix(Xe.expandedProjMatrix,pt,[0,0],"map");if(Ft=o.cC(o.bb(),Ft,[1,1,I.verticalScale]),te&&xe){if(Sx(pt.tileID,mt.maxHeight*je,y))continue;let At=xe.calculateShadowPassMatrixFromTile(pt.tileID.toUnwrapped());At=o.cC(o.bb(),At,[1,1,I.verticalScale]),es=c_(At),Tt=xt=y.getOrCreateProgram("buildingDepth",{config:jt,defines:G,overrideFog:!1})}else if(ue)Tt=xt=y.getOrCreateProgram("buildingBloom",{config:jt,defines:G,overrideFog:!1}),es=Ij(Ft);else{const At=y.transform.calculatePosMatrix(Xe.toUnwrapped(),y.transform.worldSize);o.cC(At,At,[1,1,I.verticalScale]);const Rt=o.bb();o.cC(Rt,At,[1,-1,1/je]),o.b7(Rt,Rt),o.e6(Rt,Rt);const Wt=y.transform.getFreeCameraOptions().position,ys=1<{if(ue){const Wt=At.entranceBloom;Rt.draw(y,Z.gl.TRIANGLES,I.depthMode,la.disabled,I.blendMode,Fr.disabled,es,R.id,Wt.layoutVertexBuffer,Wt.indexBuffer,Wt.segmentsBucket,R.paint,y.transform.zoom,jt,[Wt.layoutAttenuationBuffer,Wt.layoutColorBuffer])}else{const Wt=At.segmentsBucket;let ys=[At.layoutNormalBuffer,At.layoutCentroidBuffer,At.layoutColorBuffer,At.layoutFloodLightDataBuffer];At.layoutFacadePaintBuffer&&(ys=ys.concat([At.layoutFacadeDataBuffer,At.layoutFacadeVerticalRangeBuffer,At.layoutFacadePaintBuffer])),Rt.draw(y,Z.gl.TRIANGLES,I.depthMode,la.disabled,I.blendMode,te?Fr.disabled:Fr.backCW,es,R.id,At.layoutVertexBuffer,At.indexBuffer,Wt,R.paint,y.transform.zoom,jt,ys)}};y.uploadCommonUniforms(Z,xt,Xe.toUnwrapped(),null,Re),mt.buildingWithoutFacade&&Jt(mt.buildingWithoutFacade,xt),mt.buildingWithFacade&&(Tt!==xt&&y.uploadCommonUniforms(Z,Tt,Xe.toUnwrapped(),null,Re),Jt(mt.buildingWithFacade,Tt))}}function gg(I,y,C,R,$,G,Z,te,ue,xe,je,Re,Le,Ue){const st=I.context.gl,Xe=I.depthModeForSublayer(1,rr.ReadOnly,st.LEQUAL,!0),pt=.1*(1-(mt=je))+3*mt;var mt;const jt=I._showOverdrawInspector,Tt=Re,xt=new Gh;jt||zf(xt,I,y,C,R,Xe,new la({func:st.ALWAYS,mask:255},255,255,st.KEEP,st.KEEP,st.REPLACE),new na([st.ONE,st.ONE,st.ONE,st.ONE],o.aq.transparent,[!1,!1,!1,!0],st.MIN),Fr.disabled,$,"sdf",G,Z,te,ue,xe,pt,Tt,!1,void 0);{const es=jt?la.disabled:new la({func:st.EQUAL,mask:255},255,255,st.KEEP,st.DECR,st.DECR),Ft=jt?I.colorModeForRenderPass():new na([st.ONE_MINUS_DST_ALPHA,st.DST_ALPHA,st.ONE,st.ONE],o.aq.transparent,[!0,!0,!0,!0]);zf(xt,I,y,C,R,Xe,es,Ft,Fr.disabled,$,"color",G,Z,te,ue,xe,pt,Tt,!1,void 0)}}function h_(I){return[I[0]*o.e7,I[1]*o.e7,I[2]*o.e7,0]}function Zy(I,y,C,R,$,G,Z,te,ue){const xe=R.getSource(),je=C.globeSharedBuffers;if(!je)return;let Re,Le,Ue;if(y&&(Re=R.getTile(y)),xe instanceof o.aV?(Le=xe.texture,Ue=o.dw(0,0,C.transform)):Re&&y&&(Le=Re.texture,Ue=o.dw(y.canonical.z,y.canonical.x,C.transform)),!Le||!Ue)return;I||(Ue=o.cC(o.bb(),Ue,[1,-1,1]));const st=C.context,Xe=st.gl,pt=$.paint.get("raster-resampling")==="nearest"?Xe.NEAREST:Xe.LINEAR,mt=C.colorModeForDrapableLayerRenderPass(G),jt=Z.defines;jt.push("GLOBE_POLES");const Tt=new rr(Xe.LEQUAL,rr.ReadWrite,C.depthRangeFor3D),xt=Float32Array.from(C.transform.expandedFarZProjMatrix),es=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));C.terrain&&C.terrain.prepareDrawTile(),st.activeTexture.set(Xe.TEXTURE0),Le.bind(pt,Xe.CLAMP_TO_EDGE),st.activeTexture.set(Xe.TEXTURE1),Le.bind(pt,Xe.CLAMP_TO_EDGE),"useMipmap"in Le&&st.extTextureFilterAnisotropic&&C.transform.pitch>20&&Xe.texParameterf(Xe.TEXTURE_2D,st.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,st.extTextureFilterAnisotropicMax);const[Ft,Jt,At,Rt]=y?je.getPoleBuffers(y.canonical.z,!1):je.getPoleBuffers(0,!0),Wt=$.paint.get("raster-elevation");let ys;I?(ys=Ft,C.renderDefaultNorthPole=Wt!==0):(ys=Jt,C.renderDefaultSouthPole=Wt!==0);const rs=h_(Z.mix),zs=((an,mn,js,ms,Rs,qs,Qs,Dn,Cn,Tn,dn,mr,Er,ar)=>_x(an,mn,js,ms,new Float32Array(16),new Float32Array(9),[0,0],Rs,[0,0],[0,0,0,0],1,{opacity:1,mix:0},Qs,[0,0],Cn,2,dn,mr,Er,1,0,ar))(C,xt,es,Ue,o.al(C.transform.zoom),0,$,0,Wt,0,rs,Z.offset,Z.range,G),Is=C.getOrCreateProgram("raster",{defines:jt});C.uploadCommonUniforms(st,Is,null),Is.draw(C,Xe.TRIANGLES,Tt,ue,mt,te,zs,$.id,ys,At,Rt)}function Fj(I){if(I.isOrthographic)return[0,0,0,0];const y=I._nearZ,C=I.projection.farthestPixelDistance(I),R=C-y,$=.2*I.height,G=y+$;return[y,C,(G-$-y)/R,(G-y)/R]}function zj(I,y,C,R){if(I)return y instanceof xm&&I instanceof $h?y.getTextureDescriptor(I,C,!0):{texture:I.texture,mix:h_(R.mix),offset:R.offset,buffer:0,tileSize:1}}var m_=o.e8([{name:"a_index",type:"Int16",components:1}]);class jh{constructor(y,C,R,$){const G={width:R[0],height:R[1],data:null},Z=y.gl;this.targetColorTexture=new o.T(y,G,Z.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(y,G,Z.RGBA8,{useMipmap:!1}),this.context=y,this.updateParticleTexture(C,$),this.lastInvalidatedAt=0}updateParticleTexture(y,C){if(this.particleTextureDimension===C.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const R=this.context.gl,$=C.width*C.height;this.particleTexture0=new o.T(this.context,C,R.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,C,R.RGBA8,{premultiply:!1,useMipmap:!1});const G=new o.e9;G.reserve($);for(let Z=0;Z<$;Z++)G.emplaceBack(Z);this.particleIndexBuffer=this.context.createVertexBuffer(G,m_.members,!0),this.particleSegment=o.dy.simpleSegment(0,0,this.particleIndexBuffer.length,0),this.particleTextureDimension=C.width}update(y){return!(this.lastInvalidatedAt0){const rs=o.ec(C.canonical,ue),zs=o.ed(rs);Le=o.aD(new Float32Array(16),ue.globeMatrix,zs),o.aD(Le,ue.projMatrix,Le)}const Ue=o.bb();Ue[12]+=2*$/(o.o.devicePixelRatio*ue.width),Ue[13]+=2*G/(o.o.devicePixelRatio*ue.height),o.aD(Le,Ue,Le);const st=I.getOrCreateProgram("debug",{defines:Re}),Xe=y.getTileByID(C.key);I.terrain&&I.terrain.setupElevationDraw(Xe,st);const pt=rr.disabled,mt=la.disabled,jt=I.colorModeForRenderPass(),Tt="$debug";te.activeTexture.set(xe.TEXTURE0),I.emptyTexture.bind(xe.LINEAR,xe.CLAMP_TO_EDGE),je?Xe._makeGlobeTileDebugBuffers(I.context,ue):Xe._makeDebugTileBoundsBuffers(I.context,ue.projection);const xt=Xe._tileDebugBuffer||I.debugBuffer,es=Xe._tileDebugIndexBuffer||I.debugIndexBuffer,Ft=Xe._tileDebugSegments||I.debugSegments;if(st.draw(I,xe.LINE_STRIP,pt,mt,jt,Fr.disabled,jm(Le,R.toPremultipliedRenderColor(null)),Tt,xt,es,Ft,null,null,null,[Xe._globeTileDebugBorderBuffer]),Z){const rs=Xe.latestRawTileData,zs=Math.floor((rs&&rs.byteLength||0)/1024);let Is=C.canonical.toString();C.overscaledZ!==C.canonical.z&&(Is+=` => ${C.overscaledZ}`),Is+=` ${Xe.state}`,Is+=` ${zs}kb`,function(an,mn){an.initDebugOverlayCanvas();const js=an.debugOverlayCanvas,ms=an.context.gl,Rs=an.debugOverlayCanvas.getContext("2d");Rs.clearRect(0,0,js.width,js.height),Rs.shadowColor="white",Rs.shadowBlur=2,Rs.lineWidth=1.5,Rs.strokeStyle="white",Rs.textBaseline="top",Rs.font="bold 36px Open Sans, sans-serif",Rs.fillText(mn,5,5),Rs.strokeText(mn,5,5),an.debugOverlayTexture.update(js),an.debugOverlayTexture.bind(ms.LINEAR,ms.CLAMP_TO_EDGE)}(I,Is)}const Jt=y.getTile(C).tileSize,At=512/Math.min(Jt,512)*(C.overscaledZ/ue.zoom)*.5,Rt=Xe._tileDebugTextBuffer||I.debugBuffer,Wt=Xe._tileDebugTextIndexBuffer||I.quadTriangleIndexBuffer,ys=Xe._tileDebugTextSegments||I.debugSegments;st.draw(I,xe.TRIANGLES,pt,mt,na.alphaBlended,Fr.disabled,jm(Le,o.aq.transparent.toPremultipliedRenderColor(null),At),Tt,Rt,Wt,ys,null,null,null,[Xe._globeTileDebugTextBuffer])}function LC(I,y,C,R){vg(I,0,y+C/2,I.transform.width,C,R)}function Bj(I,y,C,R){vg(I,y-C/2,0,C,I.transform.height,R)}function vg(I,y,C,R,$,G){const Z=I.context,te=Z.gl;te.enable(te.SCISSOR_TEST),te.scissor(y*o.o.devicePixelRatio,C*o.o.devicePixelRatio,R*o.o.devicePixelRatio,$*o.o.devicePixelRatio),Z.clear({color:G}),te.disable(te.SCISSOR_TEST)}const C6=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:Nm}=C6;function Bf(I,y,C,R){I.emplaceBack(y,C,R)}class Zd{constructor(y){this.vertexArray=new o.ee,this.indices=new o.dC,Bf(this.vertexArray,-1,-1,1),Bf(this.vertexArray,1,-1,1),Bf(this.vertexArray,-1,1,1),Bf(this.vertexArray,1,1,1),Bf(this.vertexArray,-1,-1,-1),Bf(this.vertexArray,1,-1,-1),Bf(this.vertexArray,-1,1,-1),Bf(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=y.createVertexBuffer(this.vertexArray,Nm),this.indexBuffer=y.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function Gp(I,y,C,R,$,G){const Z=I.context.gl,te=y.paint.get("sky-atmosphere-color"),ue=y.paint.get("sky-atmosphere-halo-color"),xe=y.paint.get("sky-atmosphere-sun-intensity"),je=((Re,Le,Ue,st,Xe)=>({u_matrix_3f:Re,u_sun_direction:Le,u_sun_intensity:Ue,u_color_tint_r:[st.r,st.g,st.b,st.a],u_color_tint_m:[Xe.r,Xe.g,Xe.b,Xe.a],u_luminance:5e-5}))(o.eg(o.dE(),R),$,xe,te.toPremultipliedRenderColor(null),ue.toPremultipliedRenderColor(null));Z.framebufferTexture2D(Z.FRAMEBUFFER,Z.COLOR_ATTACHMENT0,Z.TEXTURE_CUBE_MAP_POSITIVE_X+G,y.skyboxTexture,0),C.draw(I,Z.TRIANGLES,rr.disabled,la.disabled,na.unblended,Fr.frontCW,je,"skyboxCapture",y.skyboxGeometry.vertexBuffer,y.skyboxGeometry.indexBuffer,y.skyboxGeometry.segment)}const T6=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class ek{constructor(y){const C=new o.eh;C.emplaceBack(-1,1,1,0,0),C.emplaceBack(1,1,1,1,0),C.emplaceBack(1,-1,1,1,1),C.emplaceBack(-1,-1,1,0,1);const R=new o.dC;R.emplaceBack(0,1,2),R.emplaceBack(2,3,0),this.vertexBuffer=y.createVertexBuffer(C,T6.members),this.indexBuffer=y.createIndexBuffer(R),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const tk=o.e8([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_size_scale",components:1},{type:"Float32",name:"a_opacity",components:1}]);class S0{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class E6{constructor(y){this.colorModeAlphaBlendedWriteRGB=new na([1,Ml,1,Ml],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new na([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new S0,this.updateNeeded=!0}update(y){const C=y.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new ek(C);const R=this.params.sizeRange,$=this.params.intensityRange,G=function(je){const Re=o.em(30),Le=[];for(let Ue=0;Ue{const At=G.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Jt&&At.push("ALPHA_PASS");const Rt=y.getOrCreateProgram("globeAtmosphere",{defines:At}),Wt=((rs,zs,Is,an,mn,js,ms,Rs,qs,Qs,Dn,Cn)=>({u_frustum_tl:rs,u_frustum_tr:zs,u_frustum_br:Is,u_frustum_bl:an,u_horizon:mn,u_transition:js,u_fadeout_range:ms,u_atmosphere_fog_color:Rs.toArray01(),u_high_color:qs.toArray01(),u_space_color:Qs.toArray01(),u_temporal_offset:Dn,u_horizon_angle:Cn}))(G.frustumCorners.TL,G.frustumCorners.TR,G.frustumCorners.BR,G.frustumCorners.BL,G.frustumCorners.horizon,te,pt,je,Le,st,jt,es);y.uploadCommonUniforms(R,Rt);const ys=this.atmosphereBuffer;ys&&Rt.draw(y,$.TRIANGLES,Z,la.disabled,Jt?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,Fr.backCW,Wt,Jt?"atmosphere_glow_alpha":"atmosphere_glow",ys.vertexBuffer,ys.indexBuffer,ys.segments)};Ft(!1),Ft(!0)}drawStars(y,C){const R=o.aC(C.properties.get("star-intensity"),0,1);if(R===0)return;const $=y.context,G=$.gl,Z=y.transform,te=y.getOrCreateProgram("stars"),ue=o.bL([]);o.bN(ue,ue,-Z._pitch),o.bM(ue,ue,-Z.angle),o.bN(ue,ue,o.ap(Z._center.lat)),o.ek(ue,ue,-o.ap(Z._center.lng));const xe=o.bR(new Float32Array(16),ue),je=o.aD([],Z.starsProjMatrix,xe),Re=o.eg([],xe),Le=o.el([],Re),Ue=[0,1,0];o.dG(Ue,Ue,Le),o.bJ(Ue,Ue,this.params.sizeMultiplier);const st=[1,0,0];o.dG(st,st,Le),o.bJ(st,st,this.params.sizeMultiplier);const Xe=(pt=Ue,mt=st,jt=R,{u_matrix:Float32Array.from(je),u_up:pt,u_right:mt,u_intensity_multiplier:jt});var pt,mt,jt;y.uploadCommonUniforms($,te),this.starsVx&&this.starsIdx&&te.draw(y,G.TRIANGLES,rr.disabled,la.disabled,this.colorModeAlphaBlendedWriteRGB,Fr.disabled,Xe,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class km{constructor(){this.visibleTiles=[]}updateBorders(y,C){const R=[],$=[],G=y._getRenderableCoordinates(!1,!0);for(const ue of G){const xe=y.getTile(ue);if(!xe.hasData())continue;const je=xe.getBucket(C);je&&(je.isEmpty()||(R.push(ue.key),$.push({bucket:je,tileID:ue.canonical})))}let Z=R.length!==this.visibleTiles.length;if(!Z){R.sort();for(let ue=0;ueue.tileID.z-xe.tileID.z||ue.tileID.x-xe.tileID.x||ue.tileID.y-xe.tileID.y);for(const ue of $){const xe=new Array,je=new Array,Re=ue.bucket;for(const Le of Re.featuresOnBorder)te.has(Le.featureId)?je.push(Le.footprintIndex):(te.add(Le.featureId),xe.push(Le.footprintIndex));Re.updateFootprintHiddenFlags(xe,o.en,!1),Re.updateFootprintHiddenFlags(je,o.en,!0)}}}function DC(I,y){const C=[...I],R=y.cameraWorldSizeForFog/y.worldSize,$=o.b9([]);return o.cC($,$,[R,R,1]),o.aD(C,$,C),o.aD(C,y.worldToFogMatrix,C),C}function Ra(I,y,C,R,$){const G=C.material,Z=R.context,{baseColorTexture:te,metallicRoughnessTexture:ue}=G.pbrMetallicRoughness,{normalTexture:xe,occlusionTexture:je,emissionTexture:Re}=G;function Le(st,Xe,pt){if(st&&(I.push(Xe),Z.activeTexture.set(Z.gl.TEXTURE0+pt),st.gfxTexture)){const{minFilter:mt,magFilter:jt,wrapS:Tt,wrapT:xt}=st.sampler;st.gfxTexture.bindExtraParam(mt,jt,Tt,xt)}}Le(te,"HAS_TEXTURE_u_baseColorTexture",5),Le(ue,"HAS_TEXTURE_u_metallicRoughnessTexture",6),Le(xe,"HAS_TEXTURE_u_normalTexture",7),Le(je,"HAS_TEXTURE_u_occlusionTexture",8),Le(Re,"HAS_TEXTURE_u_emissionTexture",9),$&&($.texture||($.texture=new o.dR(R.context,$.image,[$.image.height,$.image.height,$.image.height],Z.gl.RGBA8)),Z.activeTexture.set(Z.gl.TEXTURE0+10),$.texture&&$.texture.bind(Z.gl.LINEAR,Z.gl.CLAMP_TO_EDGE),I.push("APPLY_LUT_ON_GPU")),C.texcoordBuffer&&(I.push("HAS_ATTRIBUTE_a_uv_2f"),y.push(C.texcoordBuffer)),C.colorBuffer&&(I.push(C.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),y.push(C.colorBuffer)),C.normalBuffer&&(I.push("HAS_ATTRIBUTE_a_normal_3f"),y.push(C.normalBuffer)),C.pbrBuffer&&(I.push("HAS_ATTRIBUTE_a_pbr"),I.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),y.push(C.pbrBuffer)),G.alphaMode!=="OPAQUE"&&G.alphaMode!=="MASK"||I.push("UNPREMULT_TEXTURE_IN_SHADER"),G.defined||I.push("DIFFUSE_SHADED");const Ue=R.shadowRenderer;Ue&&(I.push("RENDER_SHADOWS"),Ue.useNormalOffset&&I.push("NORMAL_OFFSET"))}function p_(I,y,C,R,$,G){const Z=I.modelOpacity,te=y.context,ue=new rr(y.context.gl.LEQUAL,I.isLightMesh?rr.ReadOnly:rr.ReadWrite,y.depthRangeFor3D),xe=y.transform,je=I.mesh,Re=je.material,Le=Re.pbrMetallicRoughness,Ue=y.style.fog;let st;st=y.transform.projection.zAxisUnit==="pixels"?[...I.nodeModelMatrix]:o.aD([],R.zScaleMatrix,I.nodeModelMatrix),o.aD(st,R.negCameraPosMatrix,st);const Xe=o.b7([],st);o.e6(Xe,Xe);const pt=C.paint.get("model-color-use-theme").constantOr("default")==="none",mt=C.paint.get("model-emissive-strength").constantOr(0),jt=Nx(new Float32Array(I.worldViewProjection),new Float32Array(st),new Float32Array(Xe),null,y,Z,Le.baseColorFactor,Re.emissiveFactor,Le.metallicFactor,Le.roughnessFactor,Re,mt,C,void 0,void 0,I.materialOverride,I.modelColor),Tt={defines:[]},xt=[],es=y.shadowRenderer;es&&(es.useNormalOffset=!1),Ra(Tt.defines,xt,je,y,pt?null:C.lut);let Ft=null;if(Ue){const Rt=DC(I.nodeModelMatrix,y.transform);if(Ft=new Float32Array(Rt),xe.projection.name!=="globe"){const Wt=je.aabb.min,ys=je.aabb.max,[rs,zs]=Ue.getOpacityForBounds(Rt,Wt[0],Wt[1],ys[0],ys[1]);Tt.overrideFog=rs>=wn||zs>=wn}}const Jt=$c(y,C.paint.get("model-cutoff-fade-range"));Jt.shouldRenderCutoff&&Tt.defines.push("RENDER_CUTOFF");const At=y.getOrCreateProgram("model",Tt);y.uploadCommonUniforms(te,At,null,Ft,Jt),y.renderPass!=="shadow"&&es&&es.setupShadowsFromMatrix(I.nodeModelMatrix,At),At.draw(y,te.gl.TRIANGLES,ue,$,G,je.material.doubleSided?Fr.disabled:Fr.backCCW,jt,C.id,je.vertexBuffer,je.indexBuffer,je.segments,C.paint,y.transform.zoom,void 0,xt)}function $j(I,y){return I.style._importedAsBasemap?"basemap":y.scope}function sk(I,y,C,R,$,G,Z,te,ue,xe){const je=I.transform,Re=!!y.isGeometryBloom&&y.isGeometryBloom;if(Re&&I.renderPass==="shadow")return;const Le=je.projection.name==="globe"?o.ev(C,je):[...C];o.aD(Le,Le,y.globalMatrix);const Ue=o.aD([],R,Le);if(y.meshes)for(const st of y.meshes){const Xe=te.get(st.material.name);if(Xe&&Xe.opacity<=0)continue;if(st.material.alphaMode!=="BLEND"){Z.push({mesh:st,depth:0,modelIndex:$,worldViewProjection:Ue,nodeModelMatrix:Le,isLightMesh:Re,materialOverride:Xe,modelOpacity:ue,modelColor:xe,node:y,modelMatrix:C});continue}const pt=o.ah([],st.centroid,Ue);!je.isOrthographic&&pt[2]<=0||G.push({mesh:st,depth:pt[2],modelIndex:$,worldViewProjection:Ue,nodeModelMatrix:Le,isLightMesh:Re,materialOverride:Xe,modelOpacity:ue,modelColor:xe,node:y,modelMatrix:C})}if(y.children)for(const st of y.children)sk(I,st,C,R,$,G,Z,te,ue,xe)}function f_(I,y,C,R){const $=C.shadowRenderer;if(!$)return;const G=$.getShadowPassDepthMode(),Z=$.calculateShadowPassMatrixFromMatrix(y),te=Lj(Z);C.getOrCreateProgram("modelDepth").draw(C,C.context.gl.TRIANGLES,G,la.disabled,na.disabled,Fr.disabled,te,R.id,I.vertexBuffer,I.indexBuffer,I.segments,R.paint,C.transform.zoom,void 0,void 0)}function nk(I,y,C,R){const $=function(je,Re){if(Re.footprintDebugMesh)return Re.footprintDebugMesh;if(!Re.footprint)return null;const Le=je.context,Ue=Re.footprint.vertices,st=Re.footprint.indices,Xe=new o.dB;Xe.reserve(Ue.length);for(const Wt of Ue)Xe.emplaceBack(Wt.x,Wt.y);const pt=new o.dC;pt.reserve(st.length);for(let Wt=0;Wt0){const Le=G.terrain,Ue=Le.findDEMTileFor(te);Ue&&Ue.dem?ue=o.ex.create(Le,te,Ue):Re=0}if(Re===0&&(Z.terrainElevationMin=0,Z.terrainElevationMax=0),Re===Z.validForExaggeration&&(Re===0||ue&&ue._demTile&&ue._demTile.tileID===Z.validForDEMTile.id&&ue._dem._timestamp===Z.validForDEMTile.timestamp))return!1;for(const Le in Z.instancesPerModel){const Ue=Z.instancesPerModel[Le];for(let st=0;stxe&&(xe=Ue.max)}const je=o.aC(R.x,G,Z)-R.x,Re=o.aC(R.y,te,ue)-R.y,Le=o.bU(xe,y.center.lat)-R.z;return y._zoomFromMercatorZ(Math.sqrt(je*je+Re*Re+Le*Le))}function Zo(I,y,C,R,$,G,Z){const te=I.context,ue=I.renderPass==="shadow",xe=I.shadowRenderer,je=ue&&xe?xe.getShadowPassDepthMode():new rr(te.gl.LEQUAL,rr.ReadWrite,I.depthRangeFor3D),Re=I.isTileAffectedByFog(G),Le=I.transform.projection.name==="globe";if(C.meshes)for(const Ue of C.meshes){const st=Le?[]:["MODEL_POSITION_ON_GPU"],Xe=[];let pt,mt,jt;const Tt=!Le&&R.instancedDataArray.length>20;Tt&&st.push("INSTANCED_ARRAYS");const xt=$c(I,y.paint.get("model-cutoff-fade-range"));if(xt.shouldRenderCutoff&&st.push("RENDER_CUTOFF"),ue&&xe)pt=I.getOrCreateProgram("modelDepth",{defines:st}),mt=Lj(Z.shadowTileMatrix,Z.shadowTileMatrix,Float32Array.from(C.globalMatrix)),jt=na.disabled;else{Ra(st,Xe,Ue,I,y.paint.get("model-color-use-theme").constantOr("default")==="none"?null:y.lut),pt=I.getOrCreateProgram("model",{defines:st,overrideFog:Re});const Ft=Ue.material,Jt=Ft.pbrMetallicRoughness,At=y.paint.get("model-opacity").constantOr(1),Rt=y.paint.get("model-emissive-strength").constantOr(0);mt=Nx(G.expandedProjMatrix,Float32Array.from(C.globalMatrix),new Float32Array(16),null,I,At,Jt.baseColorFactor,Ft.emissiveFactor,Jt.metallicFactor,Jt.roughnessFactor,Ft,Rt,y,$),xe&&(Z.shadowUniformsInitialized?pt.setShadowUniformValues(te,xe.getShadowUniformValues()):(xe.setupShadows(G.toUnwrapped(),pt,"model-tile"),Z.shadowUniformsInitialized=!0)),jt=xt.shouldRenderCutoff||At<1||Ft.alphaMode!=="OPAQUE"?na.alphaBlended:na.unblended}I.uploadCommonUniforms(te,pt,G.toUnwrapped(),null,xt);const es=Ue.material.doubleSided?Fr.disabled:Fr.backCCW;if(Tt)Xe.push(R.instancedDataBuffer),pt.draw(I,te.gl.TRIANGLES,je,la.disabled,jt,es,mt,y.id,Ue.vertexBuffer,Ue.indexBuffer,Ue.segments,y.paint,I.transform.zoom,void 0,Xe,R.instancedDataArray.length);else{const Ft=ue?"u_instance":"u_normal_matrix";for(let Jt=0;Jtue[1]?Z:ue,G[0]=C.max[0],Z=o.aE(o.bE(),G,$),te=Z[1]ue[1]?Z:ue,G[1]=C.min[1],Z=o.aE(o.bE(),G,$),te=Z[1]ue[1]?Z:ue;const xe=o.aC(R[0],0,1),je=100*y.pixelsPerMeter*o.aC(R[1],0,1),Re=o.aC(R[2],0,1),Le=o.ey(o.bE(),te,ue,xe),Ue=Math.tan(.5*y.fovX),st=-Le[2]*Ue;if(je===0)return Le[1]<-Math.abs(st)?Re:1;const Xe=(-Math.abs(st)-Le[1])/je,pt=(jt,Tt,xt)=>(1-xt)*jt+xt*Tt,mt=o.aC(pt(1,Re,Xe),Re,1);return pt(1,mt,o.aC((y.pitch-20)/20,0,1))}class ak{}class RC{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(y,C,R){{const Re=this._storage.get(C.id);if(Re)return Re.lastUsedFrameIdx=y,Re.buf}const $=R.gl,G=$.getBufferParameter($.ELEMENT_ARRAY_BUFFER,$.BUFFER_SIZE),Z=new ArrayBuffer(G),te=new Int16Array(Z);$.getBufferSubData($.ELEMENT_ARRAY_BUFFER,0,new Int16Array(Z));const ue=new o.eA;for(let Re=0;Re30&&(R.buf.destroy(),this._storage.delete(C))}destroy(){for(const[y,C]of this._storage)C.buf.destroy(),this._storage.delete(y)}}class OC{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const C1=o.e8([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]);class FC{constructor(y){this.revealStart=11,this.revealRange=2}}const ik=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class A6{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(y,C){const R=y.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const Z=new o.eB,te=new o.dC;Z.emplaceBack(-1,-1),Z.emplaceBack(1,-1),Z.emplaceBack(1,1),Z.emplaceBack(-1,1),te.emplaceBack(0,1,2),te.emplaceBack(0,2,3),this.vignetteVx=y.context.createVertexBuffer(Z,ik.members),this.vignetteIdx=y.context.createIndexBuffer(te)}const $=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){y.uploadCommonUniforms(y.context,R);const Z={u_vignetteShape:(G={vignetteShape:[C.start,C.range,Math.pow(10,C.fadePower)],vignetteColor:[C.color.r,C.color.g,C.color.b,C.color.a*C.strength]}).vignetteShape,u_vignetteColor:G.vignetteColor};R.draw(y,y.context.gl.TRIANGLES,rr.disabled,la.disabled,na.alphaBlended,Fr.disabled,Z,"vignette",this.vignetteVx,this.vignetteIdx,$)}var G}}class ok{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(y,C){const R=y.getFreeCameraOptions().position,$=R.toAltitude(),G=R.toLngLat(),Z=o.ap(G.lng),te=o.ap(G.lat),ue=y.pixelsPerMeter/C,xe=Z*o.eD,je=o.eD*Math.log(Math.tan(Math.PI/4+te/2));if(this._offsetXPrev===void 0)this._offsetXPrev=0,this._offsetYPrev=0,this._elevationPrev=0,this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0;else{const Re=-this._offsetYPrev+je,Le=-this._elevationPrev+$;this._accumulatedOffsetX+=(-this._offsetXPrev+xe)*ue,this._accumulatedOffsetY+=Re*ue,this._accumulatedElevation+=Le*ue,this._offsetXPrev=xe,this._offsetYPrev=je,this._elevationPrev=$}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Q(I,y){return[-(I[0]-Math.floor(I[0]/y)*y),-(I[1]-Math.floor(I[1]/y)*y),-(I[2]-Math.floor(I[2]/y)*y)]}function J(I){const y=o.em(1323123451230),C=[];for(let R=0;R Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(y){const C=y.context;if(!this.particlesVx){const R=J(this.particlesCount),$=new o.eE,G=new o.dC;let Z=0;const te=o.em(1323123451230);for(let ue=0;ueR)return;const $=ke(0,1,C.revealStart,C.revealStart+C.revealRange,R);if(!this.particlesVx||!this.particlesIdx)return;const G=structuredClone(this._params);let Z=[-G.direction.x,G.direction.y,-100];o.ay(Z,Z);const te=structuredClone(this._vignetteParams);te.strength*=$,G.overrideStyleParameters||(G.intensity=y.style.rain.state.density,G.timeFactor=y.style.rain.state.intensity,G.color=structuredClone(y.style.rain.state.color),Z=structuredClone(y.style.rain.state.direction),G.screenThinning.intensity=y.style.rain.state.centerThinning,G.dropletSizeX=y.style.rain.state.dropletSize[0],G.dropletSizeYScale=y.style.rain.state.dropletSize[1]/y.style.rain.state.dropletSize[0],G.distortionStrength=100*y.style.rain.state.distortionStrength,te.strength=1,te.color=structuredClone(y.style.rain.state.vignetteColor));const ue=this.updateOnRender(y,G.timeFactor),xe=y.context,je=xe.gl,Re=y.transform;this.screenTexture&&this.screenTexture.size[0]===y.width&&this.screenTexture.size[1]===y.height||(this.screenTexture=new o.T(xe,{width:y.width,height:y.height,data:null},je.RGBA8)),G.distortionStrength>0&&(xe.activeTexture.set(je.TEXTURE0),this.screenTexture.bind(je.LINEAR,je.CLAMP_TO_EDGE),je.copyTexSubImage2D(je.TEXTURE_2D,0,0,0,0,0,y.width,y.height));const Le=y.getOrCreateProgram("rainParticle");y.uploadCommonUniforms(xe,Le),xe.activeTexture.set(je.TEXTURE0),this.screenTexture.bind(je.LINEAR,je.CLAMP_TO_EDGE);const Ue=[G.color.r,G.color.g,G.color.b,G.color.a],st=(Xe,pt)=>{const mt=Q(this._movement.getPosition(),Xe),jt=G.dropletSizeX,Tt=G.dropletSizeX*G.dropletSizeYScale,xt=y.width/2,es=y.height/2,Ft=ke(0,G.screenThinning.start,0,1,G.screenThinning.intensity),Jt=ke(.001,G.screenThinning.range,0,1,G.screenThinning.intensity),At=ke(0,G.screenThinning.particleOffset,0,1,G.screenThinning.intensity),Rt=(Wt={modelview:ue.modelviewMatrix,projection:ue.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:mt,velocityConeAperture:G.velocityConeAperture,velocity:G.velocity,boxSize:Xe,rainDropletSize:[jt,Tt],distortionStrength:G.distortionStrength,rainDirection:Z,color:Ue,screenSize:[Re.width,Re.height],thinningCenterPos:[xt,es],thinningShape:[Ft,Jt,Math.pow(10,G.screenThinning.fadePower)],thinningAffectedRatio:G.screenThinning.affectedRatio,thinningParticleOffset:At,shapeDirectionalPower:G.shapeDirPower,shapeNormalPower:G.shapeNormalPower,mode:pt?0:1},{u_modelview:Float32Array.from(Wt.modelview),u_projection:Float32Array.from(Wt.projection),u_time:Wt.time,u_cam_pos:Wt.camPos,u_texScreen:0,u_velocityConeAperture:Wt.velocityConeAperture,u_velocity:Wt.velocity,u_boxSize:Wt.boxSize,u_rainDropletSize:Wt.rainDropletSize,u_distortionStrength:Wt.distortionStrength,u_rainDirection:Wt.rainDirection,u_color:Wt.color,u_screenSize:Wt.screenSize,u_thinningCenterPos:Wt.thinningCenterPos,u_thinningShape:Wt.thinningShape,u_thinningAffectedRatio:Wt.thinningAffectedRatio,u_thinningParticleOffset:Wt.thinningParticleOffset,u_shapeDirectionalPower:Wt.shapeDirectionalPower,u_shapeNormalPower:Wt.shapeNormalPower,u_mode:Wt.mode});var Wt;const ys=Math.round(G.intensity*this.particlesCount),rs=o.dy.simpleSegment(0,0,4*ys,2*ys);Le.draw(y,je.TRIANGLES,rr.disabled,la.disabled,na.alphaBlended,Fr.disabled,Rt,"rain_particles",this.particlesVx,this.particlesIdx,rs)};G.distortionStrength>0&&st(G.boxSize,!0),st(G.boxSize,!1),this._vignette.draw(y,te)}}const yt=o.e8([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_snowParticleData",components:4},{type:"Float32",name:"a_snowParticleDataHorizontalOscillation",components:2}]);class ps extends Ve{constructor(y){super(2.25),this._params={overrideStyleParameters:!1,intensity:.85,timeFactor:.75,velocityConeAperture:70,velocity:40,horizontalOscillationRadius:4,horizontalOscillationRate:1.5,boxSize:2e3,billboardSize:2,shapeFadeStart:.27,shapeFadePower:.21,screenThinning:{intensity:.4,start:.15,range:1.4,fadePower:.24,affectedRatio:1,particleOffset:-.2},color:{r:1,g:1,b:1,a:1},direction:{x:-50,y:-35}},this._revealParams=new FC("Precipitation > Snow"),this._vignetteParams={strength:.3,start:.78,range:.46,fadePower:.2,color:{r:1,g:1,b:1,a:1}},this.particlesCount=16e3}update(y){const C=y.context;if(!this.particlesVx){const R=J(this.particlesCount),$=new o.eF,G=new o.dC;let Z=0;const te=o.em(1323123451230);for(let ue=0;ueZ)return;const te=ke(0,1,G.revealStart,G.revealStart+G.revealRange,Z);$.strength*=te,C.overrideStyleParameters||(C.intensity=y.style.snow.state.density,C.timeFactor=y.style.snow.state.intensity,C.color=structuredClone(y.style.snow.state.color),R=structuredClone(y.style.snow.state.direction),C.screenThinning.intensity=y.style.snow.state.centerThinning,C.billboardSize=2.79*y.style.snow.state.flakeSize,$.strength=1,$.color=structuredClone(y.style.snow.state.vignetteColor));const ue=this.updateOnRender(y,C.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const xe=y.context,je=xe.gl,Re=y.transform,Le=y.getOrCreateProgram("snowParticle");y.uploadCommonUniforms(xe,Le),((Ue,st,Xe)=>{const pt=Q(this._movement.getPosition(),Ue),mt=Re.width/2,jt=Re.height/2,Tt=ke(0,Xe.screenThinning.start,0,1,Xe.screenThinning.intensity),xt=ke(.001,Xe.screenThinning.range,0,1,Xe.screenThinning.intensity),es=ke(0,Xe.screenThinning.particleOffset,0,1,Xe.screenThinning.intensity),Ft=(Jt={modelview:ue.modelviewMatrix,projection:ue.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:pt,velocityConeAperture:Xe.velocityConeAperture,velocity:Xe.velocity,horizontalOscillationRadius:Xe.horizontalOscillationRadius,horizontalOscillationRate:Xe.horizontalOscillationRate,boxSize:Ue,billboardSize:1*Xe.billboardSize,simpleShapeParameters:[Xe.shapeFadeStart,Xe.shapeFadePower],screenSize:[Re.width,Re.height],thinningCenterPos:[mt,jt],thinningShape:[Tt,xt,Math.pow(10,Xe.screenThinning.fadePower)],thinningAffectedRatio:Xe.screenThinning.affectedRatio,thinningParticleOffset:es,color:[Xe.color.r,Xe.color.g,Xe.color.b,Xe.color.a],direction:R},{u_modelview:Float32Array.from(Jt.modelview),u_projection:Float32Array.from(Jt.projection),u_time:Jt.time,u_cam_pos:Jt.camPos,u_velocityConeAperture:Jt.velocityConeAperture,u_velocity:Jt.velocity,u_horizontalOscillationRadius:Jt.horizontalOscillationRadius,u_horizontalOscillationRate:Jt.horizontalOscillationRate,u_boxSize:Jt.boxSize,u_billboardSize:Jt.billboardSize,u_simpleShapeParameters:Jt.simpleShapeParameters,u_screenSize:Jt.screenSize,u_thinningCenterPos:Jt.thinningCenterPos,u_thinningShape:Jt.thinningShape,u_thinningAffectedRatio:Jt.thinningAffectedRatio,u_thinningParticleOffset:Jt.thinningParticleOffset,u_particleColor:Jt.color,u_direction:Jt.direction});var Jt;const At=Math.round(Xe.intensity*this.particlesCount),Rt=o.dy.simpleSegment(0,0,4*At,2*At);this.particlesVx&&this.particlesIdx&&Le.draw(y,je.TRIANGLES,rr.disabled,la.disabled,na.alphaBlended,Fr.disabled,Ft,"snow_particles",this.particlesVx,this.particlesIdx,Rt)})(C.boxSize,0,C),this._vignette.draw(y,$)}}const pn={symbol:function(I,y,C,R,$){if(I.renderPass!=="translucent")return;const G=la.disabled,Z=I.colorModeForRenderPass(),te=C.layout.get("text-variable-anchor"),ue=C.layout.get("text-size-scale-range"),xe=o.aC(I.scaleFactor,ue[0],ue[1]);te&&function(Le,Ue,st,Xe,pt,mt,jt,Tt){const xt=Ue.transform,es=pt==="map",Ft=mt==="map";for(const Jt of Le){const At=Xe.getTile(Jt),Rt=At.getBucket(st);if(!Rt||!Rt.text||!Rt.text.segments.get().length)continue;const Wt=o.bj(Rt.textSizeData,xt.zoom,Tt),ys=tp(Jt,Rt.getProjection(),xt),rs=xt.calculatePixelsToTileUnitsMatrix(At),zs=Td(ys,At.tileID.canonical,Ft,es,xt,Rt.getProjection(),rs),Is=Rt.hasIconTextFit()&&Rt.hasIconData();Wt&&Xu(Rt,es,Ft,jt,xt,zs,Jt,Math.pow(2,xt.zoom-At.tileID.overscaledZ),Wt,Is)}}(R,I,C,y,C.layout.get("text-rotation-alignment"),C.layout.get("text-pitch-alignment"),$,xe);const je=C.paint.get("icon-opacity").constantOr(1)!==0,Re=C.paint.get("text-opacity").constantOr(1)!==0;C.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(je||Re)?Hh(I,y,C,R,G,Z):(je&&Hh(I,y,C,R,G,Z,{onlyIcons:!0}),Re&&Hh(I,y,C,R,G,Z,{onlyText:!0})),y.map.showCollisionBoxes&&(Yn(I,y,C,R,C.paint.get("text-translate"),C.paint.get("text-translate-anchor"),!0),Yn(I,y,C,R,C.paint.get("icon-translate"),C.paint.get("icon-translate-anchor"),!1))},circle:function(I,y,C,R){if(I.renderPass!=="translucent")return;const $=C.paint.get("circle-opacity"),G=C.paint.get("circle-stroke-width"),Z=C.paint.get("circle-stroke-opacity"),te=C.layout.get("circle-sort-key").constantOr(1)!==void 0,ue=C.paint.get("circle-emissive-strength");if($.constantOr(1)===0&&(G.constantOr(1)===0||Z.constantOr(1)===0))return;const xe=I.context,je=xe.gl,Re=I.transform,Le=!(!I.terrain||!I.terrain.enabled),Ue=C.layout.get("circle-elevation-reference"),st=I.depthModeForSublayer(0,rr.ReadOnly),Xe=new rr(I.context.gl.LEQUAL,rr.ReadOnly,I.depthRangeFor3D),pt=Ue==="none"||Le?st:Xe,mt=la.disabled,jt=I.colorModeForDrapableLayerRenderPass(ue),Tt=Re.projection.name==="globe",xt=[o.aH(Re.center.lng),o.aL(Re.center.lat)],es=[];for(let Jt=0;JtJt.sortKey-At.sortKey);const Ft={useDepthForOcclusion:Re.depthOcclusionForSymbolsAndCircles};for(const Jt of es){const{programConfiguration:At,program:Rt,layoutVertexBuffer:Wt,dynamicBuffers:ys,indexBuffer:rs,uniformValues:zs,tile:Is}=Jt.state,an=Jt.segments;I.terrain&&I.terrain.setupElevationDraw(Is,Rt,Ft),I.uploadCommonUniforms(xe,Rt,Is.tileID.toUnwrapped()),Rt.draw(I,je.TRIANGLES,pt,mt,jt,Fr.disabled,zs,C.id,Wt,rs,an,C.paint,Re.zoom,At,ys)}},heatmap:function(I,y,C,R){if(C.paint.get("heatmap-opacity")!==0)if(I.renderPass==="offscreen"){const $=I.context,G=$.gl,Z=la.disabled,te=new na([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!0,!0,!0,!0]),ue=I.transform.projection.name==="globe"?.5:.25;C.heatmapFbo=Dj.createWithTexture($,C.heatmapFbo,I.width*ue,I.height*ue),$.clear({color:o.aq.transparent});const xe=I.transform,je=xe.projection.name==="globe",Re=je?["PROJECTION_GLOBE_VIEW"]:[],Le=je?Fr.frontCCW:Fr.disabled,Ue=[o.aH(xe.center.lng),o.aL(xe.center.lat)];for(let st=0;st({u_image:0,u_color_ramp:1,u_opacity:Re.paint.get("heatmap-opacity")}))(0,G),G.id,$.viewportBuffer,$.quadTriangleIndexBuffer,$.viewportSegments,G.paint,$.transform.zoom)}(I,C))},line:function(I,y,C,R){const $=C.paint.get("line-opacity"),G=C.paint.get("line-width");if($.constantOr(1)===0||G.constantOr(1)===0)return;const Z=C.paint.get("line-blend-mode");if(Z!=="default"&&I.transform.projection.name!=="globe")return I.terrain&&I.terrain.renderingToTexture?void function(te,ue,xe,je,Re){if(te.renderPass!=="translucent")return;const Le=te.context,Ue=Le.gl,st=te.terrain;if(!st)return;const Xe=Le.bindFramebuffer.current,pt=te.emissiveMode==="mrt-fallback";xe.lineBlendDrapeFbo=Dj.createWithTexture(Le,xe.lineBlendDrapeFbo,st.drapeBufferSize[0],st.drapeBufferSize[1],!0),xe.lineBlendDrapeStencil=xe.lineBlendDrapeFbo._stencilRbo,pt&&Ue.drawBuffers([Ue.COLOR_ATTACHMENT0]),Le.clear({color:Hp[Re].clearColor,depth:1,stencil:0});const mt=te.currentStencilSource,jt=te._tileClippingMaskIDs,Tt=te.nextStencilID;te.currentStencilSource=void 0,te._tileClippingMaskIDs={},te.nextStencilID=1;const xt=te._terrain;te._terrain=null,te._renderTileClippingMasks(xe,ue,je),dd(te,ue,xe,je,Hp[Re].colorMode,!0),te._terrain=xt,te.currentStencilSource=mt,te._tileClippingMaskIDs=jt,te.nextStencilID=Tt,Le.bindFramebuffer.set(Xe),pt&&Ue.drawBuffers([Ue.COLOR_ATTACHMENT0,Ue.COLOR_ATTACHMENT1]);const es=st.drapeBufferSize;Le.viewport.set([0,0,es[0],es[1]]);const Ft=xe.lineBlendDrapeFbo;if(!Ft)return;Le.activeTexture.set(Ue.TEXTURE0),Ue.bindTexture(Ue.TEXTURE_2D,Ft.colorAttachment0.get());const Jt=Re==="additive"?1:xe.paint.get("line-opacity").constantOr(1),At=xe.paint.get("line-emissive-strength").constantOr(0),Rt=Re==="additive"?te.colorModeForDrapableLayerRenderPass(At):Hp[Re].colorMode;te.getOrCreateProgram("lineBlendComposite").draw(te,Ue.TRIANGLES,rr.disabled,la.disabled,Rt,Fr.disabled,Mj(0,Jt,Hp[Re].compositeUniformValue),xe.id,te.viewportBuffer,te.quadTriangleIndexBuffer,te.viewportSegments,xe.paint,te.transform.zoom)}(I,y,C,R,Z):I.renderPass==="offscreen"?void function(te,ue,xe,je,Re){const Le=te.context,Ue=Math.ceil(te.width),st=Math.ceil(te.height);xe.lineBlendFbo=Dj.createWithTexture(Le,xe.lineBlendFbo,Ue,st,!0),xe.lineBlendStencil=xe.lineBlendFbo._stencilRbo,Le.clear({color:Hp[Re].clearColor,depth:1,stencil:0});const Xe=te.currentStencilSource,pt=te._tileClippingMaskIDs,mt=te.nextStencilID;te.currentStencilSource=void 0,te._tileClippingMaskIDs={},te.nextStencilID=1,te._renderTileClippingMasks(xe,ue,je);const jt=te.renderPass;te.renderPass="translucent",dd(te,ue,xe,je,Hp[Re].colorMode),te.renderPass=jt,te.currentStencilSource=Xe,te._tileClippingMaskIDs=pt,te.nextStencilID=mt,Le.viewport.set([0,0,te.width,te.height])}(I,y,C,R,Z):I.renderPass==="translucent"?void function(te,ue,xe){const je=te.context,Re=je.gl,Le=ue.lineBlendFbo;if(!Le)return;je.activeTexture.set(Re.TEXTURE0),Re.bindTexture(Re.TEXTURE_2D,Le.colorAttachment0.get());const Ue=xe==="additive"?1:ue.paint.get("line-opacity").constantOr(1),st=xe==="additive"?te.colorModeForDrapableLayerRenderPass(ue.paint.get("line-emissive-strength").constantOr(0)):Hp[xe].colorMode;te.getOrCreateProgram("lineBlendComposite").draw(te,Re.TRIANGLES,rr.disabled,la.disabled,st,Fr.disabled,Mj(0,Ue,Hp[xe].compositeUniformValue),ue.id,te.viewportBuffer,te.quadTriangleIndexBuffer,te.viewportSegments,ue.paint,te.transform.zoom)}(I,C,Z):void 0;I.renderPass==="translucent"&&dd(I,y,C,R)},fill:function(I,y,C,R){const $=C.paint.get("fill-color"),G=C.paint.get("fill-opacity");if(G.constantOr(1)===0)return;const Z=C.paint.get("fill-emissive-strength"),te=I.colorModeForDrapableLayerRenderPass(Z),ue=C.paint.get("fill-pattern"),xe=I.opaquePassEnabledForLayer()&&!ue.constantOr(1)&&$.constantOr(o.aq.transparent).a===1&&G.constantOr(0)===1?"opaque":"translucent";let je="none";C.layout.get("fill-elevation-reference")!=="none"?je="road":C.paint.get("fill-z-offset").constantOr(1)!==0&&(je="offset");const Re=!(!I.terrain||!I.terrain.enabled),Le={painter:I,sourceCache:y,layer:C,coords:R,colorMode:te,elevationType:je,terrainEnabled:Re,pass:xe};if(I.renderPass==="shadow")return void(I.shadowRenderer&&je==="road"&&!Re&&function(st){const{painter:Xe,sourceCache:pt,layer:mt,coords:jt}=st,Tt=Xe.context.gl,xt=st.painter.shadowRenderer;for(const es of jt){const Ft=pt.getTile(es),Jt=Ft.getBucket(mt);if(!Jt)continue;const At=Jt.elevatedStructures;if(!At||!At.shadowCasterSegments||At.shadowCasterSegments.segments[0].primitiveLength===0)continue;Xe.prepareDrawTile();const Rt=Jt.bufferData.programConfigurations.get(mt.id),Wt=Xe.isTileAffectedByFog(es),ys=Xe.getOrCreateProgram("elevatedStructuresDepth",{config:Rt,overrideFog:Wt}),rs=xt.calculateShadowPassMatrixFromTile(Ft.tileID.toUnwrapped());Xe.uploadCommonUniforms(Xe.context,ys,es.toUnwrapped());const zs=l_(rs,0);ys.draw(Xe,Tt.TRIANGLES,xt.getShadowPassDepthMode(),la.disabled,na.disabled,Fr.disabled,zs,mt.id,At.vertexBuffer,At.indexBuffer,At.shadowCasterSegments,mt.paint,Xe.transform.zoom,Rt)}}(Le));const Ue=I.emissiveMode==="mrt-fallback";if(je!=="offset"){if(N1(Le,!1,Ue),je==="road"){const st=!Re&&I.renderPass==="translucent";st&&Ky(I,y,C,R,"geometry"),N1(Le,!0,Ue,la.disabled),st&&function(Xe){const{painter:pt,sourceCache:mt,layer:jt,coords:Tt,colorMode:xt}=Xe,es=pt.context.gl,Ft=Xe.painter.shadowRenderer,Jt=!!Ft&&Ft.enabled,At=new rr(pt.context.gl.LEQUAL,rr.ReadOnly,pt.depthRangeFor3D);let Rt=[0,0,0];if(Jt){const ys=pt.style.directionalLight,rs=pt.style.ambientLight;ys&&rs&&(Rt=Bp(pt.style,ys,rs))}const Wt=ys=>{for(const rs of Tt){const zs=mt.getTile(rs),Is=zs.getBucket(jt);if(!Is)continue;const an=Is.elevatedStructures;if(!an)continue;let mn,js;if(ys?(mn=an.renderableBridgeSegments,js=an.bridgeProgramConfigurations.get(jt.id)):(mn=an.renderableTunnelSegments,js=an.tunnelProgramConfigurations.get(jt.id)),!mn||mn.segments[0].primitiveLength===0)continue;js.updatePaintBuffers(),pt.prepareDrawTile();const ms=pt.isTileAffectedByFog(rs),Rs=[];Jt&&Rs.push("RENDER_SHADOWS","NORMAL_OFFSET");const qs=pt.getOrCreateProgram("elevatedStructures",{config:js,overrideFog:ms,defines:Rs}),Qs=pt.translatePosMatrix(rs.projMatrix,zs,jt.paint.get("fill-translate"),jt.paint.get("fill-translate-anchor"));Jt&&Ft.setupShadows(zs.tileID.toUnwrapped(),qs,"vector-tile");const Dn=Aj(Qs,Rt);pt.uploadCommonUniforms(pt.context,qs,rs.toUnwrapped()),qs.draw(pt,es.TRIANGLES,At,la.disabled,xt,Fr.backCCW,Dn,jt.id,an.vertexBuffer,an.indexBuffer,mn,jt.paint,pt.transform.zoom,js,[an.vertexBufferNormal])}};Wt(!0),Wt(!1)}(Le)}}else N1(Le,!1,Ue,I.stencilModeFor3D())},"fill-extrusion":function(I,y,C,R){const $=C.paint.get("fill-extrusion-opacity"),G=I.context,Z=G.gl,te=I.terrain,ue=te&&te.renderingToTexture;if($===0)return;const xe=I.emissiveMode==="mrt-fallback",je=I.conflationActive&&I.style.isLayerClipped(C,y.getSource()),Re=I.style.order.indexOf(C.fqid);if(je&&function(Le,Ue,st,Xe,pt){for(const mt of Xe){const jt=Ue.getTile(mt).getBucket(st);jt&&(jt.updateReplacement(mt,Le.replacementSource,pt),jt.uploadCentroid(Le.context))}}(I,y,C,R,Re),te||je)for(const Le of R){const Ue=y.getTile(Le).getBucket(C);Ue&&xg(I.context,y,Le,Ue,C,te,je)}if(I.renderPass==="shadow"&&I.shadowRenderer){if(te&&$<.65&&C._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const Le=I.shadowRenderer.getShadowPassDepthMode();kx(I,y,C,R,Le,la.disabled,na.disabled,je)}else if(I.renderPass==="translucent"){const Le=!C.paint.get("fill-extrusion-pattern").constantOr(1),Ue=C.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!ue&&Ue.a!==0){const st=new rr(I.context.gl.LEQUAL,rr.ReadWrite,I.depthRangeFor3D);$===1&&Le?kx(I,y,C,R,st,la.disabled,na.unblended,je):(kx(I,y,C,R,st,la.disabled,na.disabled,je),kx(I,y,C,R,st,I.stencilModeFor3D(),I.colorModeForRenderPass(),je),I.resetStencilClippingMasks())}if(I.style.enable3dLights()&&Le&&(!te&&I.transform.projection.name!=="globe"||ue)){const st=C.paint.get("fill-extrusion-opacity"),Xe=C.paint.get("fill-extrusion-ambient-occlusion-intensity"),pt=C.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),mt=C.paint.get("fill-extrusion-flood-light-intensity"),jt=C.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Tt=C.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(jt?null:C.lut).toArray01().slice(0,3),xt=Xe>0&&pt>0,es=mt>0,Ft=(Rt,Wt,ys)=>(1-ys)*Rt+ys*Wt,Jt=new Gh;Jt.translate=C.paint.get("fill-extrusion-translate"),Jt.translateAnchor=C.paint.get("fill-extrusion-translate-anchor"),Jt.edgeRadius=C.layout.get("fill-extrusion-edge-radius"),Jt.cutoffFadeRange=C.paint.get("fill-extrusion-cutoff-fade-range");const At=Rt=>{const Wt=I.depthModeForSublayer(1,rr.ReadOnly,Z.LEQUAL,!0),ys=C.paint.get(Rt?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),rs=Ft(.1,3,ys),zs=I._showOverdrawInspector;if(!zs){const Is=new la({func:Z.ALWAYS,mask:255},255,255,Z.KEEP,Z.KEEP,Z.REPLACE),an=new na([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!1,!1,!1,!0],Z.MIN);zf(Jt,I,y,C,R,Wt,Is,an,Fr.disabled,Rt,"sdf",st,Xe,pt,mt,Tt,rs,je,!1)}{const Is=zs?la.disabled:new la({func:Z.EQUAL,mask:255},255,255,Z.KEEP,Z.DECR,Z.DECR),an=zs?I.colorModeForRenderPass():new na([Z.ONE_MINUS_DST_ALPHA,Z.DST_ALPHA,Z.ONE,Z.ONE],o.aq.transparent,[!0,!0,!0,!0]);zf(Jt,I,y,C,R,Wt,Is,an,Fr.disabled,Rt,"color",st,Xe,pt,mt,Tt,rs,je,!1)}};if(ue){const Rt=()=>{const ys=te.drapeBufferSize[0],rs=te.drapeBufferSize[1];let zs=te.framebufferCopyTexture;return zs&&(!zs||zs.size[0]===ys&&zs.size[1]===rs)||(zs&&zs.destroy(),zs=te.framebufferCopyTexture=new o.T(G,new o.q({width:ys,height:rs}),Z.RGBA8)),zs.bind(Z.LINEAR,Z.CLAMP_TO_EDGE),Z.copyTexSubImage2D(Z.TEXTURE_2D,0,0,0,0,0,ys,rs),zs},Wt=(ys,rs,zs)=>{const Is=I.depthModeForSublayer(1,rr.ReadOnly,Z.LEQUAL,!1),an=C.paint.get(ys?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),mn=Ft(.1,3,an);{const js=new na([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!1,!1,!1,!0]);zf(Jt,I,y,C,R,Is,la.disabled,js,Fr.disabled,ys,"clear",st,Xe,pt,mt,Tt,mn,je,rs)}{const js=new la({func:Z.ALWAYS,mask:255},255,255,Z.KEEP,Z.KEEP,Z.REPLACE),ms=new na([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!1,!1,!1,!0],Z.MIN);zf(Jt,I,y,C,R,Is,js,ms,Fr.disabled,ys,"sdf",st,Xe,pt,mt,Tt,mn,je,rs)}xe&&!ys&&(zs=Rt());{const js=ys?Z.ZERO:Z.ONE_MINUS_DST_ALPHA,ms=new la({func:Z.EQUAL,mask:255},255,255,Z.KEEP,Z.DECR,Z.DECR),Rs=new na([js,Z.DST_ALPHA,Z.ONE_MINUS_DST_ALPHA,Z.ZERO],o.aq.transparent,[!0,!0,!0,!0]);zf(Jt,I,y,C,R,Is,ms,Rs,Fr.disabled,ys,"color",st,Xe,pt,mt,Tt,mn,je,rs)}if(!xe||ys){const js=new na([Z.ONE,Z.ONE,Z.ONE,ys?Z.ZERO:Z.ONE],o.aq.transparent,[!1,!1,!1,!0],ys?Z.FUNC_ADD:Z.MAX);zf(Jt,I,y,C,R,Is,la.disabled,js,Fr.disabled,ys,"clear",st,Xe,pt,mt,Tt,mn,je,rs,zs)}else{Z.drawBuffers([Z.NONE,Z.COLOR_ATTACHMENT1]);const js=new la({func:Z.EQUAL,mask:255},254,255,Z.KEEP,Z.DECR,Z.DECR),ms=new na([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!0,!1,!1,!1],Z.MAX);zf(Jt,I,y,C,R,Is,js,ms,Fr.disabled,ys,"emissive",st,Xe,pt,mt,Tt,mn,je,rs,zs),Z.drawBuffers([Z.COLOR_ATTACHMENT0])}};if(xt||es){let ys;I.prepareDrawTile(),xe&&!xt||(ys=Rt()),xt&&Wt(!0,!1,ys),es&&Wt(!1,!0,ys)}}else xt&&At(!0),es&&At(!1),(xt||es)&&I.resetStencilClippingMasks()}}},building:function(I,y,C,R){I.currentLayer0&&G>0,xe=!0;const je=C.paint.get("building-vertical-scale");if(je<=0)return;I.shadowRenderer||(xe=!1);const Re=I.conflationActive&&I.style.isLayerClipped(C,y.getSource()),Le=I.style.order.indexOf(C.fqid);if(function(Ue,st,Xe,pt,mt,jt){for(const Tt of jt){const xt=st.getTile(Tt).getBucket(Xe);xt&&(mt&&xt.updateReplacement(Tt,Ue.replacementSource,pt),xt.uploadUpdatedIndexBuffer(Ue.context))}}(I,y,C,Le,Re,R),function(Ue,st,Xe,pt){for(const mt of pt){const jt=st.getTile(mt).getBucket(Xe);jt&&jt.needsEvaluation()&&jt.uploadUpdatedColorBuffer(Ue.context)}}(I,y,C,R),C.resetLayerRenderingStats(I),I.shadowRenderer&&(I.shadowRenderer.useNormalOffset=!0),I.renderPass==="shadow"&&I.shadowRenderer){const Ue=[],st=I.shadowRenderer.getShadowPassDepthMode();Yy({painter:I,source:y,layer:C,coords:R,defines:Ue,blendMode:na.disabled,depthMode:st,opacity:te,verticalScale:je,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(I.renderPass==="translucent"){let Ue=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];xe&&(Ue=Ue.concat("RENDER_SHADOWS")),I.shadowRenderer&&I.shadowRenderer.useNormalOffset&&(Ue=Ue.concat("NORMAL_OFFSET"));const st=C.paint.get("building-facade-emissive-chance"),Xe=C.paint.get("building-ambient-occlusion-intensity"),pt=C.paint.get("building-flood-light-intensity"),mt=C.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",jt=C.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(mt?null:C.lut).toArray01().slice(0,3),Tt=C.paint.get("building-flood-light-ground-attenuation"),xt=pt>0,es=new rr(I.context.gl.LEQUAL,rr.ReadWrite,I.depthRangeFor3D);te<1&&Yy({painter:I,source:y,layer:C,coords:R,defines:Ue,blendMode:na.disabled,depthMode:es,opacity:te,verticalScale:je,facadeEmissiveChance:st,facadeAOIntensity:Xe,floodLightIntensity:pt,floodLightColor:jt,depthOnly:!0});const Ft=I.colorModeForRenderPass();Yy({painter:I,source:y,layer:C,coords:R,defines:Ue,blendMode:Ft,depthMode:es,opacity:te,verticalScale:je,facadeEmissiveChance:st,facadeAOIntensity:Xe,floodLightIntensity:pt,floodLightColor:jt});const Jt=C.paint.get("building-front-cutoff");u_(I.transform.pitch,Jt,!!I.terrain),ue&&gg(I,y,C,R,!0,te,$,G,pt,jt,Z,Re),xt&&gg(I,y,C,R,!1,te,$,G,pt,jt,Tt,Re)}else if(I.renderPass==="light-beam"){const Ue=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],st=new rr(I.context.gl.LEQUAL,rr.ReadOnly,I.depthRangeFor3D);Yy({painter:I,source:y,layer:C,coords:R,defines:Ue,blendMode:na.alphaBlended,depthMode:st,opacity:te,verticalScale:je,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}I.shadowRenderer&&(I.shadowRenderer.useNormalOffset=!1),I.resetStencilClippingMasks()},hillshade:function(I,y,C,R){if(I.renderPass!=="offscreen"&&I.renderPass!=="translucent"||I.style.disableElevatedTerrain)return;const $=I.context,G=I.terrain&&I.terrain.renderingToTexture,[Z,te]=I.renderPass!=="translucent"||G?[{},R]:I.stencilConfigForOverlap(R);for(const ue of te){const xe=y.getTile(ue);if(xe.needsHillshadePrepare&&I.renderPass==="offscreen")g6(I,xe,C);else if(I.renderPass==="translucent"){const je=I.depthModeForSublayer(0,rr.ReadOnly),Re=C.paint.get("hillshade-emissive-strength"),Le=I.colorModeForDrapableLayerRenderPass(Re),Ue=G&&I.terrain?I.terrain.stencilModeForRTTOverlap(ue):Z[ue.overscaledZ];UR(I,ue,xe,C,je,Ue,Le)}}$.viewport.set([0,0,I.width,I.height]),I.resetStencilClippingMasks()},raster:function(I,y,C,R,$,G){if(I.renderPass!=="translucent")return;const Z=C.paint.get("raster-opacity");if(Z===0)return;const te=I.transform.projection.name==="globe",ue=C.paint.get("raster-elevation")!==0,xe=ue&&te,je=I.terrain&&I.terrain.exaggeration()>0&&ue&&C.paint.get("raster-elevation-reference")==="ground",Re=!te&&je;if(I.renderElevatedRasterBackface&&!xe)return;const Le=I.context,Ue=Le.gl,st=y.getSource(),Xe=function(Rt,Wt,ys,rs,zs){const Is=Wt.paint.get("raster-color"),an=Rt.type==="raster-array",mn=[],js=Wt.paint.get("raster-resampling"),ms=Wt.paint.get("raster-color-mix");let Rs=Wt.paint.get("raster-color-range");const qs=[ms[0],ms[1],ms[2],0],Qs=ms[3];let Dn=js==="nearest"?rs.NEAREST:rs.LINEAR;if(an&&(mn.push("RASTER_ARRAY"),Is||mn.push("RASTER_COLOR"),js==="linear"&&mn.push("RASTER_ARRAY_LINEAR"),Dn=rs.NEAREST,!Rs&&Rt.rasterLayers)){const Cn=Rt.rasterLayers.find(({id:Tn})=>Tn===Wt.sourceLayer);Cn&&Cn.fields&&Cn.fields.range&&(Rs=Cn.fields.range)}if(Rs=Rs||[0,1],Is){mn.push("RASTER_COLOR"),ys.activeTexture.set(rs.TEXTURE2),Wt.updateColorRamp(Rs);let Cn=Wt.colorRampTexture;Cn||(Cn=Wt.colorRampTexture=new o.T(ys,Wt.colorRamp,rs.RGBA8)),Cn.bind(Dn,rs.CLAMP_TO_EDGE)}return zs&&mn.push("USE_MRT1"),{mix:qs,range:Rs,offset:Qs,defines:mn,resampling:Dn}}(st,C,Le,Ue,I.terrain&&I.terrain.renderingToTexture&&I.emissiveMode==="mrt-fallback");if(st instanceof o.aV&&!R.length&&!te)return;const pt=C.paint.get("raster-emissive-strength"),mt=I.colorModeForDrapableLayerRenderPass(pt),jt=I.terrain&&I.terrain.renderingToTexture,Tt=!I.options.moving,xt=C.paint.get("raster-resampling")==="nearest"?Ue.NEAREST:Ue.LINEAR;if(st instanceof o.aV&&!R.length&&(st.onNorthPole||st.onSouthPole)){const Rt=ue?I.stencilModeFor3D():la.disabled;return void Zy(!!st.onNorthPole,null,I,y,C,pt,Xe,Fr.disabled,Rt)}if(!R.length)return;const[es,Ft]=st instanceof o.aV||jt?[{},R]:I.stencilConfigForOverlap(R),Jt=Ft[Ft.length-1].overscaledZ;xe&&Xe.defines.push("PROJECTION_GLOBE_VIEW"),ue&&Xe.defines.push("RENDER_CUTOFF","ELEVATED"),je&&Xe.defines.push("ELEVATION_REFERENCE_GROUND");const At=(Rt,Wt,ys)=>{for(const rs of Rt){const zs=rs.toUnwrapped(),Is=y.getTile(rs);if(jt&&(!Is||!Is.hasData()))continue;Le.activeTexture.set(Ue.TEXTURE0);const an=zj(Is,st,C,Xe);if(!an||!an.texture)continue;const{texture:mn,mix:js,offset:ms,tileSize:Rs,buffer:qs}=an;let Qs,Dn;jt?(Qs=rr.disabled,Dn=rs.projMatrix):ue?(Qs=new rr(Ue.LEQUAL,rr.ReadWrite,I.depthRangeFor3D),Dn=te?Float32Array.from(I.transform.expandedFarZProjMatrix):I.transform.calculateProjMatrix(zs,Tt)):(Qs=I.depthModeForSublayer(rs.overscaledZ-Jt,Z===1?rr.ReadWrite:rr.ReadOnly,Ue.LESS),Dn=I.transform.calculateProjMatrix(zs,Tt));const Cn=I.terrain&&jt?I.terrain.stencilModeForRTTOverlap(rs):es[rs.overscaledZ],Tn=G?0:C.paint.get("raster-fade-duration");Is.registerFadeDuration(Tn);const dn=y.findLoadedParent(rs,0),mr=lp(Is,dn,y,I.transform,Tn);let Er,ar;!mr.isFading&&Is.refreshedUponExpiration&&(Is.refreshedUponExpiration=!1),I.terrain&&I.terrain.prepareDrawTile(),Le.activeTexture.set(Ue.TEXTURE0),mn.bind(xt,Ue.CLAMP_TO_EDGE),Le.activeTexture.set(Ue.TEXTURE1),dn?(dn.texture&&dn.texture.bind(xt,Ue.CLAMP_TO_EDGE),Er=Math.pow(2,dn.tileID.overscaledZ-Is.tileID.overscaledZ),ar=[Is.tileID.canonical.x*Er%1,Is.tileID.canonical.y*Er%1]):mn.bind(xt,Ue.CLAMP_TO_EDGE),"useMipmap"in mn&&Le.extTextureFilterAnisotropic&&I.transform.pitch>20&&Ue.texParameterf(Ue.TEXTURE_2D,Le.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Le.extTextureFilterAnisotropicMax);const hr=I.transform;let ra;const Na=ue?Fj(hr):[0,0,0,0];let ba,Ka,Kr,Ya,_a,Pi=0;if(xe&&st instanceof o.aV&&st.coordinates.length>3)ba=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),Ka=Float32Array.from(hr.globeMatrix),Kr=Float32Array.from(o.dq(hr)),Ya=[o.aH(hr.center.lng),o.aL(hr.center.lat)],ra=st.elevatedGlobePerspectiveTransform,_a=st.elevatedGlobeGridMatrix||new Float32Array(9);else if(xe){const Vi=o.dr(rs.canonical);Pi=o.ds(Vi.getCenter().lat),ba=Float32Array.from(o.du(o.dv(rs.canonical))),Ka=Float32Array.from(hr.globeMatrix),Kr=Float32Array.from(o.dq(hr)),Ya=[o.aH(hr.center.lng),o.aL(hr.center.lat)],ra=[0,0],_a=Float32Array.from(o.dt(rs.canonical,Vi,Pi,hr.worldSize/hr._pixelsPerMercatorPixel))}else ra=st instanceof o.aV?st.perspectiveTransform:[0,0],ba=new Float32Array(16),Ka=new Float32Array(9),Kr=new Float32Array(16),Ya=[0,0],_a=new Float32Array(9);const bo=_x(I,Dn,ba,Ka,Kr,_a,ar||[0,0],o.al(I.transform.zoom),Ya,Na,Er||1,mr,C,ra,ue?C.paint.get("raster-elevation"):0,2,js,ms,Xe.range,Rs,qs,pt),bl=I.isTileAffectedByFog(rs),Lo=I.getOrCreateProgram("raster",{defines:Xe.defines,overrideFog:bl});if(I.uploadCommonUniforms(Le,Lo,zs),st instanceof o.aV){const Vi=st.elevatedGlobeVertexBuffer,Ba=st.elevatedGlobeIndexBuffer;if(jt||!te)st.boundsBuffer&&st.boundsSegments&&Lo.draw(I,Ue.TRIANGLES,Qs,la.disabled,mt,Fr.disabled,bo,C.id,st.boundsBuffer,I.quadTriangleIndexBuffer,st.boundsSegments);else if(Vi&&Ba){const $a=hr.zoom<=o.cJ?st.elevatedGlobeSegments:st.getSegmentsForLongitude(hr.center.lng);$a&&Lo.draw(I,Ue.TRIANGLES,Qs,la.disabled,mt,Wt,bo,C.id,Vi,Ba,$a)}}else if(xe){Qs=new rr(Ue.LEQUAL,rr.ReadOnly,I.depthRangeFor3D);const Vi=I.globeSharedBuffers;if(Vi){je&&(I.terrain.setupElevationDraw(Is,Lo),I.uploadCommonUniforms(Le,Lo,Is.tileID.toUnwrapped()));const[Ba,$a,Do]=Vi.getGridBuffers(Pi,!1),kl=Lo.getAttributeLocation(Ue,"a_texture_pos");kl!==-1&&Ue.vertexAttribI4ui(kl,0,0,0,0),Lo.draw(I,Ue.TRIANGLES,Qs,ys||Cn,I.colorModeForRenderPass(),Wt,bo,C.id,Ba,$a,Do)}}else if(Re)Qs=new rr(Ue.LEQUAL,rr.ReadWrite,I.depthRangeFor3D),I.terrain.setupElevationDraw(Is,Lo),I.uploadCommonUniforms(Le,Lo,Is.tileID.toUnwrapped()),hr.pitch>20&&Lo.draw(I,Ue.TRIANGLES,Qs,la.disabled,na.disabled,Fr.frontCCW,bo,C.id,I.terrain.gridBuffer,I.terrain.gridIndexBuffer,I.terrain.gridSegments),Lo.draw(I,Ue.TRIANGLES,Qs,Cn,mt,Fr.backCCW,bo,C.id,I.terrain.gridBuffer,I.terrain.gridIndexBuffer,I.terrain.gridSegments);else{const{tileBoundsBuffer:Vi,tileBoundsIndexBuffer:Ba,tileBoundsSegments:$a}=I.getTileBoundsBuffers(Is);Lo.draw(I,Ue.TRIANGLES,Qs,Cn,mt,Fr.disabled,bo,C.id,Vi,Ba,$a)}}if(!(st instanceof o.aV)&&xe)for(const rs of Rt){const zs=rs.canonical.y===(1<o.d$[qs](zs));js.push(zs);const ms=zs.canonical.x,Rs=zs.canonical.y;for(const qs of js){const Qs=xt.getTile(Wt?qs.wrapped():qs);if(!Qs)continue;const Dn=Qs.rasterParticleState;if(!Dn)continue;const Cn=qs.canonical.x+(1<Jt.tileID)),Ue&&(xe.activeTexture.set(je.TEXTURE0),I.imageManager.bind(I.context,C.scope));const Ft=[];if(I.terrain&&I.terrain.renderingToTexture&&I.emissiveMode==="mrt-fallback"&&Ft.push("USE_MRT1"),ue){const Jt=I.getOrCreateProgram(Tt,{overrideFog:!1,overrideRtt:!0,defines:Ft}),At=new Float32Array(o.b9([])),Rt=new o.aR(0,0,0,0,0),Wt=Ue?jx(At,te,Z,I,0,C.scope,st,ue,{tileID:Rt,tileSize:Le}):Wy(At,te,Z,$.toPremultipliedRenderColor(G?null:C.lut));return void Jt.draw(I,je.TRIANGLES,mt,pt,jt,Fr.disabled,Wt,C.id,I.viewportBuffer,I.quadTriangleIndexBuffer,I.viewportSegments)}for(const Jt of es){const At=I.isTileAffectedByFog(Jt),Rt=I.getOrCreateProgram(Tt,{overrideFog:At,defines:Ft}),Wt=Jt.toUnwrapped(),ys=R?Jt.projMatrix:I.transform.calculateProjMatrix(Wt);I.prepareDrawTile();const rs=y?y.getTile(Jt):xt?xt[Jt.key]:new o.b0(Jt,Le,Re.zoom,I),zs=Ue?jx(ys,te,Z,I,0,C.scope,st,ue,{tileID:Jt,tileSize:Le}):Wy(ys,te,Z,$.toPremultipliedRenderColor(G?null:C.lut));I.uploadCommonUniforms(xe,Rt,Wt);const{tileBoundsBuffer:Is,tileBoundsIndexBuffer:an,tileBoundsSegments:mn}=I.getTileBoundsBuffers(rs);Rt.draw(I,je.TRIANGLES,mt,pt,jt,Fr.disabled,zs,C.id,Is,an,mn)}},sky:function(I,y,C){const R=I._atmosphere?o.al(I.transform.zoom):1,$=C.paint.get("sky-opacity")*R;if($===0)return;const G=I.context,Z=C.paint.get("sky-type"),te=new rr(G.gl.LEQUAL,rr.ReadOnly,[0,1]),ue=I.frameCounter/1e3%1;Z==="atmosphere"?I.renderPass==="offscreen"?C.needsSkyboxCapture(I)&&(function(xe,je){const Re=xe.context,Le=Re.gl;let Ue=je.skyboxFbo;if(!Ue){Ue=je.skyboxFbo=Re.createFramebuffer(32,32,1,null),je.skyboxGeometry=new Zd(Re),je.skyboxTexture=Re.gl.createTexture(),Le.bindTexture(Le.TEXTURE_CUBE_MAP,je.skyboxTexture),Le.texParameteri(Le.TEXTURE_CUBE_MAP,Le.TEXTURE_WRAP_S,Le.CLAMP_TO_EDGE),Le.texParameteri(Le.TEXTURE_CUBE_MAP,Le.TEXTURE_WRAP_T,Le.CLAMP_TO_EDGE),Le.texParameteri(Le.TEXTURE_CUBE_MAP,Le.TEXTURE_MIN_FILTER,Le.LINEAR),Le.texParameteri(Le.TEXTURE_CUBE_MAP,Le.TEXTURE_MAG_FILTER,Le.LINEAR);for(let mt=0;mt<6;++mt)Le.texImage2D(Le.TEXTURE_CUBE_MAP_POSITIVE_X+mt,0,Le.RGBA,32,32,0,Le.RGBA,Le.UNSIGNED_BYTE,null)}Re.bindFramebuffer.set(Ue.framebuffer),Re.viewport.set([0,0,32,32]);const st=je.getCenter(xe,!0),Xe=xe.getOrCreateProgram("skyboxCapture"),pt=new Float64Array(16);o.b9(pt),o.ef(pt,pt,.5*-Math.PI),Gp(xe,je,Xe,pt,st,0),o.b9(pt),o.ef(pt,pt,.5*Math.PI),Gp(xe,je,Xe,pt,st,1),o.b9(pt),o.cE(pt,pt,.5*-Math.PI),Gp(xe,je,Xe,pt,st,2),o.b9(pt),o.cE(pt,pt,.5*Math.PI),Gp(xe,je,Xe,pt,st,3),o.b9(pt),Gp(xe,je,Xe,pt,st,4),o.b9(pt),o.ef(pt,pt,Math.PI),Gp(xe,je,Xe,pt,st,5),Re.viewport.set([0,0,xe.width,xe.height])}(I,C),C.markSkyboxValid(I)):I.renderPass==="sky"&&function(xe,je,Re,Le,Ue){const st=xe.context,Xe=st.gl,pt=xe.transform,mt=xe.getOrCreateProgram("skybox");st.activeTexture.set(Xe.TEXTURE0),Xe.bindTexture(Xe.TEXTURE_CUBE_MAP,je.skyboxTexture);const jt=((Tt,xt,es,Ft,Jt)=>({u_matrix:Tt,u_sun_direction:xt,u_cubemap:0,u_opacity:Ft,u_temporal_offset:Jt}))(pt.skyboxMatrix,je.getCenter(xe,!1),0,Le,Ue);xe.uploadCommonUniforms(st,mt),mt.draw(xe,Xe.TRIANGLES,Re,la.disabled,xe.colorModeForRenderPass(),Fr.backCW,jt,"skybox",je.skyboxGeometry.vertexBuffer,je.skyboxGeometry.indexBuffer,je.skyboxGeometry.segment)}(I,C,te,$,ue):Z==="gradient"&&I.renderPass==="sky"&&function(xe,je,Re,Le,Ue){const st=xe.context,Xe=st.gl,pt=xe.transform,mt=xe.getOrCreateProgram("skyboxGradient");je.skyboxGeometry||(je.skyboxGeometry=new Zd(st)),st.activeTexture.set(Xe.TEXTURE0);let jt=je.colorRampTexture;jt||(jt=je.colorRampTexture=new o.T(st,je.colorRamp,Xe.RGBA8)),jt.bind(Xe.LINEAR,Xe.CLAMP_TO_EDGE);const Tt=((xt,es,Ft,Jt,At)=>({u_matrix:xt,u_color_ramp:0,u_center_direction:es,u_radius:o.ap(Ft),u_opacity:Jt,u_temporal_offset:At}))(pt.skyboxMatrix,je.getCenter(xe,!1),je.paint.get("sky-gradient-radius"),Le,Ue);xe.uploadCommonUniforms(st,mt),mt.draw(xe,Xe.TRIANGLES,Re,la.disabled,xe.colorModeForRenderPass(),Fr.backCW,Tt,"skyboxGradient",je.skyboxGeometry.vertexBuffer,je.skyboxGeometry.indexBuffer,je.skyboxGeometry.segment)}(I,C,te,$,ue)},custom:function(I,y,C,R){const $=I.context,G=C.implementation;if(!I.transform.projection.unsupportedLayers||!I.transform.projection.unsupportedLayers.includes("custom")||I.terrain&&(I.terrain.renderingToTexture||I.renderPass==="offscreen")&&C.isDraped(y)){if(I.renderPass==="offscreen"){const Z=G.prerender;if(Z){if(I.setCustomLayerDefaults(),$.setColorMode(I.colorModeForRenderPass()),I.transform.projection.name==="globe"){const te=I.transform.pointMerc;Z.call(G,$.gl,I.transform.customLayerMatrix(),I.transform.getProjection(),I.transform.globeToMercatorMatrix(),o.al(I.transform.zoom),[te.x,te.y],I.transform.pixelsPerMeterRatio)}else Z.call(G,$.gl,I.transform.customLayerMatrix());$.setDirty(),I.setBaseState()}}else if(I.renderPass==="translucent"){if(I.terrain&&I.terrain.renderingToTexture){const te=G.renderToTile;if(te){const ue=R[0].canonical,xe={x:ue.x+R[0].wrap*(G.wrapTileId?0:1<{xe&&(xe.useNormalOffset=!0,je||(xe.enabled=!0))},Le=y.getSource();if(I.renderPass==="light-beam"&&Le.type!=="batched-model")return;if(Le.type==="vector"||Le.type==="geojson")return function(xt,es,Ft,Jt,At){const Rt=xt.transform,Wt=Rt.projection.name==="globe",ys=Rt.getFreeCameraOptions().position;if(!xt.modelManager)return;const rs=xt.modelManager;Ft.modelManager=rs;const zs=xt.shadowRenderer;if(!Ft._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const Is=Ft._unevaluatedLayout._values["model-id"],an=Object.assign({},Ft.layout.get("model-id").parameters),mn=xt.style.order.indexOf(Ft.fqid),js=Ft.paint.get("model-opacity").constantOr(1);for(const ms of Jt){const Rs=es.getTile(ms).getBucket(Ft);if(!Rs||Rs.projection.name!==Rt.projection.name)continue;const qs=Rs.getModelUris();if(qs&&!Rs.modelsRequested&&(rs.addModelsFromBucket(qs,At),Rs.modelsRequested=!0),Wt)an.zoom=ms.overscaledZ;else{const ar=Wp(ms,Rt);an.zoom=ar}const Qs=Is.possiblyEvaluate(an);if(kn(xt,Rs,ms),Nn.shadowUniformsInitialized=!1,Nn.useSingleShadowCascade=!!zs&&zs.getMaxCascadeForTile(ms.toUnwrapped())===0,xt.renderPass==="shadow"&&zs){if(xt.currentShadowCascade===1&&Rs.isInsideFirstShadowMapFrustum)continue;const ar=Rt.calculatePosMatrix(ms.toUnwrapped(),Rt.worldSize);if(Nn.tileMatrix.set(ar),Nn.shadowTileMatrix=Float32Array.from(zs.calculateShadowPassMatrixFromMatrix(ar)),Nn.aabb.min=[0,0,0],Nn.aabb.max[0]=Nn.aabb.max[1]=o.an,Nn.aabb.max[2]=0,Uj(Rs,Nn,xt,Ft.scope))continue}const Dn=1<0&&xt.style.isLayerClipped(Ft,es.getSource())&&Rs.updateReplacement(ms,xt.replacementSource,mn,Ft.scope)&&(Rs.uploaded=!1,Rs.upload(xt.context));let Tn=0;const dn=new Array,mr=new Array,Er=new Array;for(let ar in Rs.instancesPerModel){const hr=Rs.instancesPerModel[ar];hr.features.length>0&&!Wt&&(ar=Qs.evaluate(hr.features[0].feature,{}));const ra=rs.getModel(ar,At);if(ra||rs.hasURLBeenRequested(ar)||Rs.modelUris.includes(ar)||(Rs.modelUris.push(ar),Rs.modelsRequested=!1),ra&&ra.uploaded)if(Wt){const Na=o.bJ([],[ys.x,ys.y,ys.z],xt.transform.worldSize);o.eo(Na,Na);for(let ba=0;ba0&&Ya.elevationUpdate(ar.terrain,ba,Kr,ra.source),Ya.needsReEvaluation(ar,Ka,ra)&&Ya.evaluate(ra))}})(xt,es,Ft,Jt),function(){const ar=new Map;let hr,ra,Na;dn?(hr=Jt.length-1,ra=-1,Na=-1):(hr=0,ra=Jt.length,Na=1);const ba=new Float64Array(16),Ka=o.ce(),Kr=new o.P(0,0);for(let Ya=hr;Ya!==ra;Ya+=Na){const _a=Jt[Ya],Pi=es.getTile(_a).getBucket(Ft);if(!Pi||!Pi.uploaded)continue;let bo=!1;ys&&(bo=ys.getMaxCascadeForTile(_a.toUnwrapped())===0);const bl=Rt.calculatePosMatrix(_a.toUnwrapped(),Rt.worldSize),Lo=Pi.modelTraits;!Dn&&dn&&(o.b7(ba,bl),o.ah(Ka,zs,ba),Kr.x=Ka[0],Kr.y=Ka[1]);const Vi=[];Pi.setFilter(Ft.filter);for(const Ba of Pi.getNodesInfo()){if(Ba.hiddenByReplacement||!Ba.node.meshes)continue;const $a=Ba.node;let Do=0;xt.terrain&&$a.elevation&&(Do=$a.elevation*xt.terrain.exaggeration());const kl=(()=>{const _u=Ba.aabb;return Qs.min=[..._u.min],Qs.max=[..._u.max],Qs.min[2]+=Do,Qs.max[2]+=Do,o.ah(Qs.min,Qs.min,bl),o.ah(Qs.max,Qs.max,bl),Qs})(),Hi=Ba.evaluatedScale;if(Hi[0]<=1&&Hi[1]<=1&&Hi[2]<=1&&kl.intersects(Cn)===0)continue;if(!Dn&&dn){const _u=.16666666666666666;Ba.cameraCollisionOpacity=zs[0]>kl.min[0]&&zs[0]kl.min[1]&&zs[1]!dn||Ba.opacity===1&&$a.opacity===1?Ba.depth<$a.depth?-1:1:Ba.opacity===1?-1:$a.opacity===1?1:Ba.depth>$a.depth?-1:1);for(const Ba of Vi){const $a=Ba.nodeInfo,Do=$a.node;if(xt._debugParams.show3DModelFootprints&&Do.footprint){const li=Do.id||Do.name||"footprint";ar.has(li)||ar.set(li,{node:Do,mvp:Ba.wvpForTile})}let kl=o.aD([],js,Ba.tileModelMatrix);o.aD(kl,an,kl);const Hi=o.b7([],kl);o.e6(Hi,Hi),o.cC(Hi,Hi,fs),kl=o.aD(kl,kl,Do.globalMatrix);const Ea=xt.renderPass==="light-beam",ul=Ft.paint.get("model-color-use-theme").constantOr("default")==="none",_o=Lo&o.ez.HasMapboxMeshFeatures,Sc=_o?0:$a.evaluatedRMEA[0][2];for(let li=0;li=wn||Uf>=wn}}const so=ko.material;let Tx;so.occlusionTexture&&so.occlusionTexture.offsetScale&&(Tx=so.occlusionTexture.offsetScale,hd.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const Ex=xt.getOrCreateProgram("model",hd);!Dn&&ys&&ys.setupShadowsFromMatrix(Ba.tileModelMatrix,Ex,ys.useNormalOffset),xt.uploadCommonUniforms(At,Ex,null,$f);const $o=so.pbrMetallicRoughness;$o.metallicFactor=.9,$o.roughnessFactor=.5;const Qo=Nx(new Float32Array(kh),new Float32Array(kl),new Float32Array(Hi),new Float32Array(Do.globalMatrix),xt,Ba.opacity,$o.baseColorFactor,so.emissiveFactor,$o.metallicFactor,$o.roughnessFactor,so,Sc,Ft,[0,0,0],Tx);!Xc&&($a.hasTranslucentParts||Ba.opacity<1)&&Ex.draw(xt,At.gl.TRIANGLES,Rs,la.disabled,na.disabled,Fr.backCCW,Qo,Ft.id,ko.vertexBuffer,ko.indexBuffer,ko.segments,Ft.paint,xt.transform.zoom,void 0,_u),Ex.draw(xt,At.gl.TRIANGLES,Xc?qs:Rs,la.disabled,Xc||Ba.opacity<1||$a.hasTranslucentParts?na.alphaBlended:na.unblended,Fr.backCCW,Qo,Ft.id,ko.vertexBuffer,ko.indexBuffer,ko.segments,Ft.paint,xt.transform.zoom,void 0,_u)}}}if(xt._debugParams.show3DModelFootprints&&ar.size>0){const Ya=Array.from(ar.keys()).sort();for(const _a of Ya){const{node:Pi,mvp:bo}=ar.get(_a);nk(xt,0,Pi,bo)}}}()}(I,y,C,R),void Re();if(Le.type!=="model")return;const Ue=Le.getModels(),st=[],Xe=I.transform.getFreeCameraOptions().position,pt=o.bJ([],[Xe.x,Xe.y,Xe.z],I.transform.worldSize);o.eo(pt,pt);const mt=[],jt=[];let Tt=0;for(const xt of Ue){const es=y.getFeatureState("",xt.id),Ft={type:"Unknown",id:xt.id,properties:xt.featureProperties},Jt=C.paint.get("model-rotation").evaluate(Ft,es),At=C.paint.get("model-scale").evaluate(Ft,es),Rt=C.paint.get("model-translation").evaluate(Ft,es),Wt=C.paint.get("model-opacity").evaluate(Ft,es);rk(C,xt.id,es,xt.featureProperties,xt.nodeOverrideNames,xt.nodeOverrides),S1(C,xt.id,es,xt.featureProperties,xt.materialOverrideNames,xt.materialOverrides),xt.nodeOverrides.size>0&&xt.computeBoundsAndApplyParent(),xt.computeModelMatrix(I,Jt,At,Rt,te,Z,!1);const ys=o.b9([]),rs=o.e2(xt.position.lat,I.transform.zoom),zs=o.bP([],[1,1,1/rs]);o.bx(ys,ys,pt),st.push({zScaleMatrix:zs,negCameraPosMatrix:ys});for(const Is of xt.nodes)sk(I,Is,xt.matrix,I.transform.expandedFarZProjMatrix,Tt,mt,jt,xt.materialOverrides,Wt);Tt++}if(mt.sort((xt,es)=>es.depth-xt.depth),I.renderPass!=="shadow"){if(I._debugParams.show3DModelFootprints){const xt=I.transform.projMatrix,es=new Map,Ft=(At,Rt)=>{if(At.footprint){const Wt=At.id||At.name||"footprint";if(!es.has(Wt)){const ys=o.aD([],xt,Rt);es.set(Wt,{node:At,mvp:ys})}}};for(const At of jt)Ft(At.node,At.modelMatrix);for(const At of mt)Ft(At.node,At.modelMatrix);const Jt=Array.from(es.keys()).sort();for(const At of Jt){const{node:Rt,mvp:Wt}=es.get(At);nk(I,0,Rt,Wt)}}Qd(I,C,mt,jt,st),Re()}else{for(const xt of jt)f_(xt.mesh,xt.nodeModelMatrix,I,C);for(const xt of mt)f_(xt.mesh,xt.nodeModelMatrix,I,C);Re()}}},Kn={line:function(I,y,C){if(I.hasElevatedBuckets=!1,I.hasNonElevatedBuckets=!1,I._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||I._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(y){const R=y.getVisibleCoordinates();for(const $ of R){const G=y.getTile($).getBucket(I);if(G&&(G.elevationType!=="none"?I.hasElevatedBuckets=!0:I.hasNonElevatedBuckets=!0,I.hasElevatedBuckets&&I.hasNonElevatedBuckets))break}}}else I.hasNonElevatedBuckets=!0},model:function(I,y,C){const R=y.getSource();if(!R.loaded())return;if(R.type==="vector"||R.type==="geojson")return void(C.modelManager&&C.modelManager.upload(C,$j(C,I)));if(R.type==="batched-model"||R.type!=="model")return;const $=R.getModels();for(const G of $)G.upload(C.context)},raster:function(I,y,C){const R=y.getSource();if(!(R instanceof xm&&R.loaded()))return;const $=I.sourceLayer||R.rasterLayerIds&&R.rasterLayerIds[0];if(!$)return;const G=I.paint.get("raster-array-band")||R.getInitialBand($);if(G==null)return;const Z=y.getIds().map(te=>y.getTileByID(te));for(const te of Z)te.updateNeeded(I.id,G)&&R.prepareTile(te,$,I.id,G)},"raster-particle":function(I,y,C){const R=y.getSource();if(!(R instanceof xm&&R.loaded()))return;const $=I.sourceLayer||R.rasterLayerIds&&R.rasterLayerIds[0];if(!$)return;const G=I.paint.get("raster-particle-array-band")||R.getInitialBand($);if(G==null)return;const Z=y.getIds().map(te=>y.getTileByID(te));for(const te of Z)te.updateNeeded(I.id,G)&&R.prepareTile(te,$,I.id,G)}},qr={fill:Ky},Va={fill:function(I,y,C,R){if(!C.layout||C.layout.get("fill-elevation-reference")==="none"||C.paint.get("fill-opacity").constantOr(1)===0)return;const $=I.context.gl,G=new rr($.LEQUAL,rr.ReadOnly,I.depthRangeFor3D),Z=new la({func:$.ALWAYS,mask:255},255,255,$.KEEP,$.KEEP,$.REPLACE),te=I.transform.getFreeCameraOptions().position,ue=I.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const xe of R){const je=y.getTile(xe),Re=je.getBucket(C);if(!Re)continue;const Le=Re.elevatedStructures;if(!Le||Le.depthSegments.segments[0].primitiveLength===0)continue;const Ue=N0(xe.toUnwrapped(),te),st=I.translatePosMatrix(xe.projMatrix,je,C.paint.get("fill-translate"),C.paint.get("fill-translate-anchor")),Xe=w1(st,Ue,0,1,0);ue.draw(I,$.TRIANGLES,G,Z,na.disabled,Fr.disabled,Xe,C.id,Le.vertexBuffer,Le.indexBuffer,Le.depthSegments,C.paint,I.transform.zoom)}}};class oo{constructor(y,C,R,$,G){this.context=new _0(y,C),this.transform=R,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this._timeStamp=o.o.now(),this._averageFPS=0,this._fpsHistory=[],this._dt=0,this._debugParams={forceEnablePrecipitation:!1,showTerrainProxyTiles:!1,fpsWindow:30,continousRedraw:!1,show3DModelFootprints:!1,enabledLayers:{}};const Z=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const ue of Z)this._debugParams.enabledLayers[ue]=!0;for(const ue of Z);this.occlusionParams=new OC,this.setup(),this.numSublayers=al.maxUnderzooming+al.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new o.eG,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._shadowRenderer=new ec(this),this._wireframeDebugCache=new RC,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const te=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,te,y.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=$,this.maxFrontCutoffRawStart=0,this.worldview=G,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(y,C){const R=!!y&&!!y.terrain&&this.transform.projection.supportsTerrain;if(!(R||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new Gy(this,y));const $=this._terrain;this.transform.elevation=R?$:null,$.update(y,this.transform,C),this.transform.elevation&&!$.enabled&&(this.transform.elevation=null)}_updateFog(y){const C=y.fog;if(!C||this.transform.projection.name==="globe"||C.getOpacity(this.transform.pitch)<1||C.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[R,$]=C.getFovAdjustedRange(this.transform._fov);if(R>$)return void(this.transform.fogCullDistSq=null);const G=R+.78*($-R);this.transform.fogCullDistSq=G*G}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(y){y&&!this._terrain&&(this._terrain=new Gy(this,this.style)),this._forceTerrainMode=y}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(y,C){if(this.width=y*o.o.devicePixelRatio,this.height=C*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const R of this.style.order)this.style._mergedLayers[R].resize()}setup(){const y=this.context,C=new o.dB;C.emplaceBack(0,0),C.emplaceBack(o.an,0),C.emplaceBack(0,o.an),C.emplaceBack(o.an,o.an),this.tileExtentBuffer=y.createVertexBuffer(C,o.dx.members),this.tileExtentSegments=o.dy.simpleSegment(0,0,4,2);const R=new o.dB;R.emplaceBack(0,0),R.emplaceBack(o.an,0),R.emplaceBack(0,o.an),R.emplaceBack(o.an,o.an),this.debugBuffer=y.createVertexBuffer(R,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const $=new o.dB;$.emplaceBack(-1,-1),$.emplaceBack(1,-1),$.emplaceBack(-1,1),$.emplaceBack(1,1),this.viewportBuffer=y.createVertexBuffer($,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const G=new o.eH;G.emplaceBack(0,0,0,0),G.emplaceBack(o.an,0,o.an,0),G.emplaceBack(0,o.an,0,o.an),G.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=y.createVertexBuffer(G,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const Z=new o.dC;Z.emplaceBack(0,1,2),Z.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=y.createIndexBuffer(Z);const te=new o.eJ;for(const xe of[0,1,3,2,0])te.emplaceBack(xe);this.debugIndexBuffer=y.createIndexBuffer(te),this.emptyTexture=new o.T(y,new o.q({width:1,height:1},Uint8Array.of(0,0,0,0)),y.gl.RGBA8),this.identityMat=o.bb();const ue=this.context.gl;this.stencilClearMode=new la({func:ue.ALWAYS,mask:0},0,255,ue.ZERO,ue.ZERO,ue.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(y){return y._makeTileBoundsBuffers(this.context,this.transform.projection),y._tileBoundsBuffer?{tileBoundsBuffer:y._tileBoundsBuffer,tileBoundsIndexBuffer:y._tileBoundsIndexBuffer,tileBoundsSegments:y._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const y=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,y.TRIANGLES,rr.disabled,this.stencilClearMode,na.disabled,Fr.disabled,Tj(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(y,C,R){if(!C||this.currentStencilSource===C.id||!y.isTileClipped()||!R||R.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let te=!1;for(const ue of R)if(this._tileClippingMaskIDs[ue.key]===void 0){te=!0;break}if(!te)return}this.currentStencilSource=C.id;const $=this.context,G=$.gl;this.nextStencilID+R.length>256&&this.clearStencil(),$.setColorMode(na.disabled),$.setDepthMode(rr.disabled);const Z=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const te of R){const ue=C.getTile(te),xe=this._tileClippingMaskIDs[te.key]=this.nextStencilID++,{tileBoundsBuffer:je,tileBoundsIndexBuffer:Re,tileBoundsSegments:Le}=this.getTileBoundsBuffers(ue);Z.draw(this,G.TRIANGLES,rr.disabled,new la({func:G.ALWAYS,mask:0},xe,255,G.KEEP,G.KEEP,G.REPLACE),na.disabled,Fr.disabled,Tj(te.projMatrix),"$clipping",je,Re,Le)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const y=this.nextStencilID++,C=this.context.gl;return new la({func:C.NOTEQUAL,mask:255},y,255,C.KEEP,C.KEEP,C.REPLACE)}stencilModeForClipping(y){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(y);const C=this.context.gl;return new la({func:C.EQUAL,mask:255},this._tileClippingMaskIDs[y.key],0,C.KEEP,C.KEEP,C.REPLACE)}stencilConfigForOverlap(y){const C=this.context.gl,R=y.sort((Z,te)=>te.overscaledZ-Z.overscaledZ),$=R[R.length-1].overscaledZ,G=R[0].overscaledZ-$+1;if(G>1){this.currentStencilSource=void 0,this.nextStencilID+G>256&&this.clearStencil();const Z={};for(let te=0;tethis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((y,C)=>y+C/this._fpsHistory.length,0))}render(y,C){const R=o.o.now();this._dt=R-this._timeStamp,this._timeStamp=R,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=y.map.repaint,this.style=y,this.options=C;const $=this.style._mergedLayers,G=!(!this.terrain||!this.terrain.enabled),Z=()=>this.style._getOrder(G).filter(js=>{const ms=$[js];return!(ms.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[ms.type]});let te=Z(),ue=!1,xe=!1,je=null,Re=0,Le=!1;for(const js of te){const ms=$[js];ms.visibility!=="none"&&(ms.type==="circle"?ue=!0:ms.type==="building"?(je=ms,++Re):ms.type==="symbol"&&(ms.hasOcclusionOpacityProperties?xe=!0:ue=!0))}this.updateEmissiveMode();let Ue=te.map(js=>$[js]);const st=this.style._mergedSourceCaches;this.imageManager=y.imageManager,this.modelManager=y.modelManager,this.symbolFadeChange=y.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const js in st){const ms=st[js];ms.used&&(ms.prepare(this.context),ms.getSource().usedInConflation&&++Re)}let Xe=!1;for(const js of Ue)js.isHidden(this.transform.zoom)||(js.type==="clip"&&(Xe=!0),this.prepareLayer(js));const pt={},mt={},jt={},Tt={},xt={};for(const js in st){const ms=st[js];pt[js]=ms.getVisibleCoordinates(),mt[js]=pt[js].slice().reverse(),jt[js]=ms.getVisibleCoordinates(!0).reverse(),Tt[js]=ms.getShadowCasterCoordinates(),xt[js]=ms.sortCoordinatesByDistance(pt[js])}const es=js=>{const ms=this.style.getLayerSourceCache(js);return ms&&ms.used?ms.getSource():null};if(Re||Xe||this._clippingActiveLastFrame){const js=[],ms=[];let Rs=0;for(const qs of Ue)this.isSourceForClippingOrConflation(qs,es(qs))&&(js.push(qs),ms.push(Rs)),Rs++;if(js&&(Xe||js.length>1)||this._clippingActiveLastFrame){Xe=!1;const qs=[];for(let Qs=0;Qs0){const qs=es(ms);qs&&(this.minCutoffZoom=Math.max(qs.minzoom,this.minCutoffZoom)),ms.minzoom&&(this.minCutoffZoom=Math.max(ms.minzoom,this.minCutoffZoom))}ms.is3D(G)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=js),this._lastOcclusionLayer=js)}const Ft=this.style&&this.style.fog;Ft?(this._fogVisible=Ft.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Ft.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(jt),this.opaquePassCutoff=0,te=Z(),Ue=te.map(js=>$[js]));const Jt=this._shadowRenderer;if(Jt){Jt.updateShadowParameters(this.transform,this.style.directionalLight);for(const js in st)for(const ms of pt[js]){let Rs={min:0,max:0};this.terrain&&(Rs=this.terrain.getMinMaxForTile(ms)||Rs),Jt.addShadowReceiver(ms.toUnwrapped(),Rs.min,Rs.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new o.eL(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new E6(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const At=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),Rt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(At&&!this._snow&&(this._snow=new ps(this)),!At&&this._snow&&(this._snow.destroy(),delete this._snow),Rt&&!this._rain&&(this._rain=new et(this)),!Rt&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),je){this.buildingTileBorderManager||(this.buildingTileBorderManager=new km);const js=this.style.getLayerSourceCache(je);this.buildingTileBorderManager.updateBorders(js,je)}if(!He.has(this.context.gl))return;this.renderPass="offscreen";for(const js of Ue){const ms=y.getLayerSourceCache(js);if(!js.hasOffscreenPass()||js.isHidden(this.transform.zoom))continue;const Rs=ms?mt[ms.id]:void 0;(js.type==="custom"||js.type==="raster"||js.type==="raster-particle"||js.isSky()||Rs&&Rs.length)&&this.renderLayer(this,ms,js,Rs)}this.depthRangeFor3D=[0,1-(Ue.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Tt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Wt=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),ys=(()=>{if(C.showOverdrawInspector)return o.aq.black;const js=this.style.fog;if(js&&this.transform.projection.supportsFog){const ms=this.style.getLut(js.scope);if(!Wt){const Rs=js.properties.get("color-use-theme")==="none",qs=js.properties.get("color").toNonPremultipliedRenderColor(Rs?null:ms).toArray01();return new o.aq(...qs)}if(Wt){const Rs=js.properties.get("space-color-use-theme")==="none",qs=js.properties.get("space-color").toNonPremultipliedRenderColor(Rs?null:ms).toArray01();return new o.aq(...qs)}}return o.aq.transparent})();if(this.context.clear({color:ys,depth:1}),this.clearStencil(),this._showOverdrawInspector=C.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Wt&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=te.length-1;this.currentLayer>=0;this.currentLayer--){const js=Ue[this.currentLayer],ms=y.getLayerSourceCache(js);if(js.isSky())continue;const Rs=ms?(js.is3D(G)?xt:mt)[ms.id]:void 0;this._renderTileClippingMasks(js,ms,Rs),this.renderLayer(this,ms,js,Rs)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Wt&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||o.al(this.transform.zoom)>0)&&(this.transform.projection.name==="globe"||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer{for(this.currentLayer=0;this.currentLayer=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const Rs=this.currentLayer;this.depthOcclusion=!0;for(const qs of this.layersWithOcclusionOpacity){this.currentLayer=qs;const Qs=Ue[this.currentLayer],Dn=y.getLayerSourceCache(Qs),Cn=Dn?mt[Dn.id]:void 0;this.terrain||this._renderTileClippingMasks(Qs,Dn,Dn?pt[Dn.id]:void 0),this.renderLayer(this,Dn,Qs,Cn)}this.depthOcclusion=!1,this.currentLayer=Rs,this.renderPass="translucent",this.layersWithOcclusionOpacity=[]}++this.currentLayer}}if(this.terrain&&this.terrain.postRender(),this._snow&&this._snow.draw(this),this._rain&&this._rain.draw(this),this.options.showTileBoundaries||this.options.showQueryGeometry||this.options.showTileAABBs){let js=null;Ue.forEach(ms=>{const Rs=y.getLayerSourceCache(ms);Rs&&!ms.isHidden(this.transform.zoom)&&Rs.getVisibleCoordinates().length&&(!js||js.getSource().maxzoom0?C.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(y,C,R){const $=R===void 0?this.terrain&&this.terrain.renderingToTexture:R,G=[];return this.style&&this.style.enable3dLights()&&(y==="globeRaster"||y==="terrainRaster"?(G.push("LIGHTING_3D_MODE"),G.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):$||G.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(G.push("TERRAIN"),this.linearFloatFilteringSupported()&&G.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&G.push("GLOBE"),!this._fogVisible||$||C!==void 0&&!C||G.push("FOG"),$&&G.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&G.push("OVERDRAW_INSPECTOR"),G}getOrCreateProgram(y,C){this.cache=this.cache||{};const R=C&&C.defines||[],$=C&&C.config,G=this.currentGlobalDefines(y,C&&C.overrideFog,C&&C.overrideRtt).concat(R),Z=cd.cacheKey(vC[y],y,G,$);return this.cache[Z]||(this.cache[Z]=new cd(this.context,y,vC[y],$,d_[y],G)),this.cache[Z]}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 y=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(y.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new o.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA8))}destroy(){this._terrain&&this._terrain.destroy(),this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0),this.globeSharedBuffers&&this.globeSharedBuffers.destroy(),this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this._wireframeDebugCache.destroy(),this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),this.emptyDepthTexture&&this.emptyDepthTexture.destroy()}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(y,C){if(this.style.enable3dLights()){const R=this.style.directionalLight,$=this.style.ambientLight;if(R&&$){const G=((Z,te,ue)=>{const xe=Z.properties.get("direction"),je=Z.properties.get("color-use-theme")==="none",Re=Z.properties.get("color").toNonPremultipliedRenderColor(je?null:ue.getLut(Z.scope)).toArray01(),Le=Z.properties.get("intensity"),Ue=te.properties.get("color-use-theme")==="none",st=te.properties.get("color").toNonPremultipliedRenderColor(Ue?null:ue.getLut(te.scope)).toArray01(),Xe=te.properties.get("intensity"),pt=[xe.x,xe.y,xe.z],mt=o.dD(st,Xe),jt=o.dD(Re,Le);return{u_lighting_ambient_color:mt,u_lighting_directional_dir:pt,u_lighting_directional_color:jt,u_ground_radiance:r_(pt,jt,mt)}})(R,$,this.style);C.setLightsUniformValues(y,G)}}}uploadCommonUniforms(y,C,R,$,G){if(this.uploadCommonLightUniforms(y,C),this.terrain&&this.terrain.renderingToTexture)return;const Z=this.style.fog;if(Z){const te=Z.getOpacity(this.transform.pitch),ue=((xe,je,Re,Le,Ue,st,Xe,pt,mt,jt,Tt,xt)=>{const es=xe.transform,Ft=je.properties.get("color-use-theme")==="none",Jt=je.properties.get("color").toNonPremultipliedRenderColor(Ft?null:xe.style.getLut(je.scope)).toArray01();Jt[3]=Le;const At=xe.frameCounter/1e3%1,[Rt,Wt]=je.properties.get("vertical-range");return{u_fog_matrix:Re?es.calculateFogTileMatrix(Re):xt||xe.identityMat,u_fog_range:je.getFovAdjustedRange(es._fov),u_fog_color:Jt,u_fog_horizon_blend:je.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(Rt,Wt),Wt],u_fog_temporal_offset:At,u_frustum_tl:Ue,u_frustum_tr:st,u_frustum_br:Xe,u_frustum_bl:pt,u_globe_pos:mt,u_globe_radius:jt,u_viewport:Tt,u_globe_transition:o.al(es.zoom),u_is_globe:+(es.projection.name==="globe")}})(this,Z,R,te,this.transform.frustumCorners.TL,this.transform.frustumCorners.TR,this.transform.frustumCorners.BR,this.transform.frustumCorners.BL,this.transform.globeCenterInViewSpace,this.transform.globeRadius,[this.transform.width*o.o.devicePixelRatio,this.transform.height*o.o.devicePixelRatio],$);C.setFogUniformValues(y,ue)}G&&C.setCutoffUniformValues(y,G.uniformValues)}setTileLoadedFlag(y){this.tileLoaded=y}saveCanvasCopy(){const y=this.canvasCopy();y&&(this.frameCopies.push(y),this.tileLoaded=!1)}canvasCopy(){const y=this.context.gl,C=y.createTexture();return y.bindTexture(y.TEXTURE_2D,C),y.copyTexImage2D(y.TEXTURE_2D,0,y.RGBA,0,0,y.drawingBufferWidth,y.drawingBufferHeight,0),C}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const y=this.style&&this.style.fog;return!!y&&y.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const y=this._backgroundTiles,C=this._backgroundTiles={},R=this.transform.coveringTiles({tileSize:512});for(const $ of R)C[$.key]=y[$.key]||new o.b0($,512,this.transform.tileZoom,this,void 0,this.worldview);return C}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(y,C){return!(!y.is3D(!(!this.terrain||!this.terrain.enabled))||y.type!=="clip"&&y.type!=="building"&&(y.minzoom&&y.minzoom>this.transform.zoom||(this.style._clipLayerPresent||y.sourceLayer!=="building"&&y.sourceLayer!=="procedural_buildings")&&(!C||C.type!=="batched-model")))}isTileAffectedByFog(y){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let C=this._cachedTileFogOpacities[y.key];return C||(this._cachedTileFogOpacities[y.key]=C=this.style.fog.getOpacityForTile(y)),C[0]>=wn||C[1]>=wn}setupDepthForOcclusion(y,C,R){const $=this.context,G=$.gl,Z=!!R;var te;R||(R={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),$.activeTexture.set(G.TEXTURE3),y&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(G.NEAREST,G.CLAMP_TO_EDGE),R.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],R.u_depth_range_unpack=[2/((te=this.depthRangeFor3D)[1]-te[0]),-1-2*te[0]/(te[1]-te[0])],R.u_occluder_half_size=.5*this.occlusionParams.occluderSize,R.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(G.NEAREST,G.CLAMP_TO_EDGE),$.activeTexture.set(G.TEXTURE0),Z||C.setTerrainUniformValues($,R)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const y=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=y?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function Ta(I,y){let C=!1,R=null;const $=()=>{R=null,C&&(I(),R=setTimeout($,y),C=!1)};return()=>(C=!0,R||$(),R)}class kc{constructor(y){this._hashName=y&&encodeURIComponent(y),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=Ta(this._updateHashUnthrottled.bind(this),300)}addTo(y){return this._map=y,window.addEventListener("hashchange",this._onHashChange,!1),y.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 y=this._map;if(!y)return"";const C=lo(y);if(this._hashName){const R=this._hashName;let $=!1;const G=location.hash.slice(1).split("&").map(Z=>{const te=Z.split("=")[0];return te===R?($=!0,`${te}=${C}`):Z}).filter(Z=>Z);return $||G.push(`${R}=${C}`),`#${G.join("&")}`}return`#${C}`}_getCurrentHash(){const y=location.hash.replace("#","");if(this._hashName){let C;return y.split("&").map(R=>R.split("=")).forEach(R=>{R[0]===this._hashName&&(C=R)}),(C&&C[1]||"").split("/")}return y.split("/")}_onHashChange(){const y=this._map;if(!y)return!1;const C=this._getCurrentHash();if(C.length>=3&&!C.some(R=>isNaN(Number(R)))){const R=y.dragRotate.isEnabled()&&y.touchZoomRotate.isEnabled()?+(C[3]||0):y.getBearing();return y.jumpTo({center:[+C[2],+C[1]],zoom:+C[0],bearing:R,pitch:+(C[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function lo(I,y){const C=I.getCenter(),R=Math.round(100*I.getZoom())/100,$=Math.ceil((R*Math.LN2+Math.log(512/360/.5))/Math.LN10),G=Math.pow(10,$),Z=Math.round(C.lng*G)/G,te=Math.round(C.lat*G)/G,ue=I.getBearing(),xe=I.getPitch();let je=y?`/${Z}/${te}/${R}`:`${R}/${te}/${Z}`;return(ue||xe)&&(je+="/"+Math.round(10*ue)/10),xe&&(je+=`/${Math.round(xe)}`),je}const Nh={linearity:.3,easing:o.eN(0,0,.3,1)},Kp=Object.assign({deceleration:2500,maxSpeed:1400},Nh),Vn=Object.assign({deceleration:20,maxSpeed:1400},Nh),Zs=Object.assign({deceleration:1e3,maxSpeed:360},Nh),cn=Object.assign({deceleration:1e3,maxSpeed:90},Nh);class Oa{constructor(y){this._map=y,this.clear()}clear(){this._inertiaBuffer=[]}record(y){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.o.now(),settings:y})}_drainInertiaBuffer(){const y=this._inertiaBuffer,C=o.o.now();for(;y.length>0&&C-y[0].time>160;)y.shift()}_onMoveEnd(y){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const C={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:G}of this._inertiaBuffer)C.zoom+=G.zoomDelta||0,C.bearing+=G.bearingDelta||0,C.pitch+=G.pitchDelta||0,G.panDelta&&C.pan._add(G.panDelta),G.around&&(C.around=G.around),G.pinchAround&&(C.pinchAround=G.pinchAround);const R=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,$={};if(C.pan.mag()){const G=Ui(C.pan.mag(),R,Object.assign({},Kp,y||{}));$.offset=C.pan.mult(G.amount/C.pan.mag()),$.center=this._map.transform.center,Wa($,G)}if(C.zoom){const G=Ui(C.zoom,R,Vn);$.zoom=this._map.transform.zoom+G.amount,Wa($,G)}if(C.bearing){const G=Ui(C.bearing,R,Zs);$.bearing=this._map.transform.bearing+o.aC(G.amount,-179,179),Wa($,G)}if(C.pitch){const G=Ui(C.pitch,R,cn);$.pitch=this._map.transform.pitch+G.amount,Wa($,G)}if($.zoom||$.bearing){const G=C.pinchAround===void 0?C.around:C.pinchAround;$.around=G?this._map.unproject(G):this._map.getCenter()}return this.clear(),$.noMoveStart=!0,$}}function Wa(I,y){(!I.duration||I.durationC.unproject(ue)),te=G.reduce((ue,xe,je,Re)=>ue.add(xe.div(Re.length)),new o.P(0,0));super(y,{points:G,point:te,lngLats:Z,lngLat:C.unproject(te),originalEvent:R}),this._defaultPrevented=!1}}class Xd extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(y,C){super("wheel",{originalEvent:C}),this._defaultPrevented=!1}}class il{constructor(y,C){this._map=y,this._clickTolerance=C.clickTolerance}reset(){this._mousedownPos=void 0}wheel(y){return this._firePreventable(new Xd(this._map,y))}mousedown(y,C){return this._mousedownPos=C,this._firePreventable(new ai(y.type,this._map,y))}mouseup(y){this._map.fire(new ai(y.type,this._map,y))}preclick(y){const C=new MouseEvent("preclick",y);this._map.fire(new ai(C.type,this._map,C))}click(y,C){this._mousedownPos&&this._mousedownPos.dist(C)>=this._clickTolerance||(this.preclick(y),this._map.fire(new ai(y.type,this._map,y)))}dblclick(y){return this._firePreventable(new ai(y.type,this._map,y))}mouseover(y){this._map.fire(new ai(y.type,this._map,y))}mouseout(y){this._map.fire(new ai(y.type,this._map,y))}touchstart(y){return this._firePreventable(new ro(y.type,this._map,y))}touchmove(y){this._map.fire(new ro(y.type,this._map,y))}touchend(y){this._map.fire(new ro(y.type,this._map,y))}touchcancel(y){this._map.fire(new ro(y.type,this._map,y))}_firePreventable(y){if(this._map.fire(y),y.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class bg{constructor(y){this._map=y}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(y){this._map.fire(new ai(y.type,this._map,y))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new ai("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(y){this._delayContextMenu?this._contextMenuEvent=y:this._map.fire(new ai(y.type,this._map,y)),this._map.listens("contextmenu")&&y.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class zC{constructor(y,C){this._map=y,this._el=y.getCanvasContainer(),this._container=y.getContainer(),this._clickTolerance=C.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(y,C){this.isEnabled()&&y.shiftKey&&y.button===0&&(A(),this._startPos=this._lastPos=C,this._active=!0)}mousemoveWindow(y,C){if(!this._active)return;const R=C,$=this._startPos,G=this._lastPos;if(!$||!G||G.equals(R)||!this._box&&R.dist($){this._box&&(this._box.style.transform=`translate(${Z}px,${ue}px)`,this._box.style.width=te-Z+"px",this._box.style.height=xe-ue+"px")})}mouseupWindow(y,C){if(!this._active)return;const R=this._startPos,$=C;if(R&&y.button===0){if(this.reset(),L(),R.x!==$.x||R.y!==$.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:y})),{cameraAnimation:G=>G.fitScreenCoordinates(R,$,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",y)}}keydown(y){this._active&&y.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",y))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),T(),delete this._startPos,delete this._lastPos}_fireEvent(y,C){return this._map.fire(new o.C(y,{originalEvent:C}))}}function BC(I,y){const C={};for(let R=0;Rthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=y.timeStamp),R.length===this.numTouches&&(this.centroid=function($){const G=new o.P(0,0);for(const Z of $)G._add(Z);return G.div($.length)}(C),this.touches=BC(R,C)))}touchmove(y,C,R){if(this.aborted||!this.centroid)return;const $=BC(R,C);for(const G in this.touches){const Z=$[G];(!Z||Z.dist(this.touches[G])>30)&&(this.aborted=!0)}}touchend(y,C,R){if((!this.centroid||y.timeStamp-this.startTime>500)&&(this.aborted=!0),R.length===0){const $=!this.aborted&&this.centroid;if(this.reset(),$)return $}}}class Xy{constructor(y){this.singleTap=new _g(y),this.numTaps=y.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(y,C,R){this.singleTap.touchstart(y,C,R)}touchmove(y,C,R){this.singleTap.touchmove(y,C,R)}touchend(y,C,R){const $=this.singleTap.touchend(y,C,R);if($){const G=y.timeStamp-this.lastTime<500,Z=!this.lastTap||this.lastTap.dist($)<30;if(G&&Z||this.reset(),this.count++,this.lastTime=y.timeStamp,this.lastTap=$,this.count===this.numTaps)return this.reset(),$}}}class lk{constructor(){this._zoomIn=new Xy({numTouches:1,numTaps:2}),this._zoomOut=new Xy({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(y,C,R){this._zoomIn.touchstart(y,C,R),this._zoomOut.touchstart(y,C,R)}touchmove(y,C,R){this._zoomIn.touchmove(y,C,R),this._zoomOut.touchmove(y,C,R)}touchend(y,C,R){const $=this._zoomIn.touchend(y,C,R),G=this._zoomOut.touchend(y,C,R);return $?(this._active=!0,y.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:Z=>Z.easeTo({duration:300,zoom:Z.getZoom()+1,around:Z.unproject($)},{originalEvent:y})}):G?(this._active=!0,y.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:Z=>Z.easeTo({duration:300,zoom:Z.getZoom()-1,around:Z.unproject(G)},{originalEvent:y})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const M6=0,GR=2,WR={[M6]:1,[GR]:2},T1={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class $C{constructor(y){this.reset(),this._clickTolerance=y.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(y,C){return!1}_move(y,C){return{}}mousedown(y,C){if(this._lastPoint)return;const R=z(y);this._correctButton(y,R)&&(this._lastPoint=C,this._eventButton=R)}mousemoveWindow(y,C){const R=this._lastPoint;if(R){if(y.preventDefault(),this._eventButton!=null&&function($,G){const Z=WR[G];return $.buttons===void 0||($.buttons&Z)!==Z}(y,this._eventButton))this.reset();else if(this._moved||!(C.dist(R)0&&(this._active=!0);const $=BC(R,C),G=new o.P(0,0),Z=new o.P(0,0);let te=0;for(const xe in $){const je=$[xe],Re=this._touches[xe];Re&&(G._add(je),Z._add(je.sub(Re)),te++,$[xe]=je)}if(this._touches=$,te{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class qC{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(y){}_move(y,C,R){return{}}touchstart(y,C,R){this._firstTwoTouches||R.length<2||(this._firstTwoTouches=[R[0].identifier,R[1].identifier],this._start([C[0],C[1]]))}touchmove(y,C,R){const $=this._firstTwoTouches;if(!$)return;y.preventDefault();const[G,Z]=$,te=sc(R,C,G),ue=sc(R,C,Z);if(!te||!ue)return;const xe=this._aroundCenter?null:te.add(ue).div(2);return this._move([te,ue],xe,y)}touchend(y,C,R){if(!this._firstTwoTouches)return;const[$,G]=this._firstTwoTouches,Z=sc(R,C,$),te=sc(R,C,G);Z&&te||(this._active&&L(),this.reset())}touchcancel(){this.reset()}enable(y){this._enabled=!0,this._aroundCenter=!!y&&y.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function sc(I,y,C){for(let R=0;RMath.abs(I.x)}class ZR extends qC{constructor(y){super(),this._map=y}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(y){this._lastPoints=y,VC(y[0].sub(y[1]))&&(this._valid=!1)}_move(y,C,R){const $=this._lastPoints;if(!$)return;const G=y[0].sub($[0]),Z=y[1].sub($[1]);return this._map._cooperativeGestures&&!o.eO()&&R.touches.length<3||(this._valid=this.gestureBeginsVertically(G,Z,R.timeStamp),!this._valid)?void 0:(this._lastPoints=y,this._active=!0,{pitchDelta:(G.y+Z.y)/2*-.5})}gestureBeginsVertically(y,C,R){if(this._valid!==void 0)return this._valid;const $=y.mag()>=2,G=C.mag()>=2;if(!$&&!G)return;if(!$||!G)return this._firstMove==null&&(this._firstMove=R),R-this._firstMove<100&&void 0;const Z=y.y>0==C.y>0;return VC(y)&&VC(C)&&Z}}const QR={panStep:100,bearingStep:15,pitchStep:10};class Hj{constructor(){const y=QR;this._panStep=y.panStep,this._bearingStep=y.bearingStep,this._pitchStep=y.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(y){if(y.altKey||y.ctrlKey||y.metaKey)return;let C=0,R=0,$=0,G=0,Z=0;switch(y.keyCode){case 61:case 107:case 171:case 187:C=1;break;case 189:case 109:case 173:C=-1;break;case 37:y.shiftKey?R=-1:(y.preventDefault(),G=-1);break;case 39:y.shiftKey?R=1:(y.preventDefault(),G=1);break;case 38:y.shiftKey?$=1:(y.preventDefault(),Z=-1);break;case 40:y.shiftKey?$=-1:(y.preventDefault(),Z=1);break;default:return}return this._rotationDisabled&&(R=0,$=0),{cameraAnimation:te=>{const ue=te.getZoom();te.easeTo({duration:300,easeId:"keyboardHandler",easing:XR,zoom:C?Math.round(ue)+C*(y.shiftKey?2:1):ue,bearing:te.getBearing()+R*this._bearingStep,pitch:te.getPitch()+$*this._pitchStep,offset:[-G*this._panStep,-Z*this._panStep],center:te.getCenter()},{originalEvent:y})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function XR(I){return I*(2-I)}const Gj=4.000244140625,JR=1/450;class D6{constructor(y,C){this._map=y,this._el=y.getCanvasContainer(),this._handler=C,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=JR,o.aZ(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(y){this._defaultZoomRate=y}setWheelZoomRate(y){this._wheelZoomRate=y}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(y){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!y&&y.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(y){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(y.ctrlKey||y.metaKey||this.isZooming()||o.eO()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let C=y.deltaMode===WheelEvent.DOM_DELTA_LINE?40*y.deltaY:y.deltaY;const R=o.o.now(),$=R-(this._lastWheelEventTime||0);this._lastWheelEventTime=R,C!==0&&C%Gj===0?this._type="wheel":C!==0&&Math.abs(C)<4?this._type="trackpad":$>400?(this._type=null,this._lastValue=C,this._timeout=window.setTimeout(this._onTimeout,40,y)):this._type||(this._type=Math.abs($*C)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,C+=this._lastValue)),y.shiftKey&&C&&(C/=4),this._type&&(this._lastWheelEvent=y,this._delta-=C,this._active||this._start(y)),y.preventDefault()}_onTimeout(y){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(y)}_start(y){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const C=M(this._el,y);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:C,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame())}renderFrame(){if(!this._frameId||(this._frameId=null,!this.isActive()))return;const y=this._map.transform;this._type==="wheel"&&y.projection.wrap&&(y._center.lng>=180||y._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const C=()=>y._terrainEnabled()&&this._aroundCoord?y.computeZoomRelativeTo(this._aroundCoord):y.zoom;if(this._delta!==0){const xe=this._type==="wheel"&&Math.abs(this._delta)>Gj?this._wheelZoomRate:this._defaultZoomRate;let je=2/(1+Math.exp(-Math.abs(this._delta*xe)));this._delta<0&&je!==0&&(je=1/je);const Re=C(),Le=Math.pow(2,Re),Ue=typeof this._targetZoom=="number"?y.zoomScale(this._targetZoom):Le;this._targetZoom=Math.min(y.maxZoom,Math.max(y.minZoom,y.scaleZoom(Ue*je))),this._type==="wheel"&&(this._startZoom=Re,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const R=typeof this._targetZoom=="number"?this._targetZoom:C(),$=this._startZoom,G=this._easing;let Z,te=!1;if(this._type==="wheel"&&$&&G){const xe=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),je=G(xe);Z=o.am($,R,je),xe<1?this._frameId||(this._frameId=!0):te=!0}else Z=R,te=!0;this._active=!0,te&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let ue=Z-C();return ue*this._lastDelta<0&&(ue=0),{noInertia:!0,needsRenderFrame:!te,zoomDelta:ue,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(y){let C=o.eP;if(this._prevEase){const R=this._prevEase,$=(o.o.now()-R.start)/R.duration,G=R.easing($+.01)-R.easing($),Z=.27/Math.sqrt(G*G+1e-4)*.01,te=Math.sqrt(.0729-Z*Z);C=o.eN(Z,te,.25,1)}return this._prevEase={start:o.o.now(),duration:y,easing:C},C}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=b("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=/(Mac|iPad)/i.test(navigator.userAgent)?this._map._getUIString("ScrollZoomBlocker.CmdMessage"):this._map._getUIString("ScrollZoomBlocker.CtrlMessage"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`)}_showBlockerAlert(){this._alertContainer.style.visibility="visible",this._alertContainer.classList.add("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.setAttribute("role","alert"),clearTimeout(this._alertTimer),this._alertTimer=window.setTimeout(()=>{this._alertContainer.classList.remove("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.removeAttribute("role")},200)}}class R6{constructor(y,C){this._clickZoom=y,this._tapZoom=C}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class O6{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(y,C){return y.preventDefault(),{cameraAnimation:R=>{R.easeTo({duration:300,zoom:R.getZoom()+(y.shiftKey?-1:1),around:R.unproject(C)},{originalEvent:y})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class aq{constructor(){this._tap=new Xy({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(y,C,R){this._swipePoint||(this._tapTime&&y.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?R.length>0&&(this._swipePoint=C[0],this._swipeTouch=R[0].identifier):this._tap.touchstart(y,C,R))}touchmove(y,C,R){if(this._tapTime){if(this._swipePoint){if(R[0].identifier!==this._swipeTouch)return;const $=C[0],G=$.y-this._swipePoint.y;return this._swipePoint=$,y.preventDefault(),this._active=!0,{zoomDelta:G/128}}}else this._tap.touchmove(y,C,R)}touchend(y,C,R){this._tapTime?this._swipePoint&&R.length===0&&this.reset():this._tap.touchend(y,C,R)&&(this._tapTime=y.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class eO{constructor(y,C,R){this._el=y,this._mousePan=C,this._touchPan=R}enable(y){this._inertiaOptions=y||{},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 iq{constructor(y,C,R){this._pitchWithRotate=y.pitchWithRotate,this._mouseRotate=C,this._mousePitch=R}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class oq{constructor(y,C,R,$){this._el=y,this._touchZoom=C,this._touchRotate=R,this._tapDragZoom=$,this._rotationDisabled=!1,this._enabled=!0}enable(y){this._touchZoom.enable(y),this._rotationDisabled||this._touchRotate.enable(y),this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}const HC=I=>I.zoom||I.drag||I.pitch||I.rotate;class lq extends o.C{}class cq{constructor(){this.constants=[1,1,.01],this.radius=0}setup(y,C){const R=o.ax([],C,y);this.radius=o.ai(R[2]<0?o.eR([],R,this.constants):[R[0],R[1],0])}projectRay(y){o.eR(y,y,this.constants),o.ay(y,y),o.eS(y,y,this.constants);const C=o.bJ([],y,this.radius);if(C[2]>0){const R=o.bJ([],[0,0,1],o.bi(C,[0,0,1])),$=o.bJ([],o.ay([],[C[0],C[1],0]),this.radius),G=o.cT([],C,o.bJ([],o.ax([],o.cT([],$,R),C),2));C[0]=G[0],C[1]=G[1]}return C}}function GC(I){return I.panDelta&&I.panDelta.mag()||I.zoomDelta||I.bearingDelta||I.pitchDelta}class dq{constructor(y,C){this._map=y,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Oa(y),this._bearingSnap=C.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new cq,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(C),o.aZ(["handleEvent","handleWindowEvent"],this);const R=this._el;this._listeners=[[R,"touchstart",{passive:!0}],[R,"touchmove",{passive:!1}],[R,"touchend",void 0],[R,"touchcancel",void 0],[R,"mousedown",void 0],[R,"mousemove",void 0],[R,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[R,"mouseover",void 0],[R,"mouseout",void 0],[R,"dblclick",void 0],[R,"click",void 0],[R,"keydown",{capture:!1}],[R,"keyup",void 0],[R,"wheel",{passive:!1}],[R,"contextmenu",void 0],[window,"blur",void 0]];for(const[$,G,Z]of this._listeners){const te=$===document?this.handleWindowEvent:this.handleEvent;$.addEventListener(G,te,Z)}}destroy(){for(const[y,C,R]of this._listeners){const $=y===document?this.handleWindowEvent:this.handleEvent;y.removeEventListener(C,$,R)}}_addDefaultHandlers(y){const C=this._map,R=C.getCanvasContainer();this._add("mapEvent",new il(C,y));const $=C.boxZoom=new zC(C,y);this._add("boxZoom",$);const G=new lk,Z=new O6;C.doubleClickZoom=new R6(Z,G),this._add("tapZoom",G),this._add("clickZoom",Z);const te=new aq;this._add("tapDragZoom",te);const ue=C.touchPitch=new ZR(C);this._add("touchPitch",ue);const xe=new I6(y),je=new UC(y);C.dragRotate=new iq(y,xe,je),this._add("mouseRotate",xe,["mousePitch"]),this._add("mousePitch",je,["mouseRotate"]);const Re=new wg(y),Le=new KR(C,y);C.dragPan=new eO(R,Re,Le),this._add("mousePan",Re),this._add("touchPan",Le,["touchZoom","touchRotate"]);const Ue=new Vj,st=new YR;C.touchZoomRotate=new oq(R,st,Ue,te),this._add("touchRotate",Ue,["touchPan","touchZoom"]),this._add("touchZoom",st,["touchPan","touchRotate"]),this._add("blockableMapEvent",new bg(C));const Xe=C.scrollZoom=new D6(C,this);this._add("scrollZoom",Xe,["mousePan"]);const pt=C.keyboard=new Hj;this._add("keyboard",pt);for(const mt of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])y.interactive&&y[mt]&&C[mt].enable(y[mt])}_add(y,C,R){this._handlers.push({handlerName:y,handler:C,allowed:R}),this._handlersById[y]=C}stop(y){if(!this._updatingCamera){for(const{handler:C}of this._handlers)C.reset();this._inertia.clear(),this._fireEvents({},{},y),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:y}of this._handlers)if(y.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!HC(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(y,C,R){for(const $ in y)if($!==R&&(!C||C.indexOf($)<0))return!0;return!1}handleWindowEvent(y){this.handleEvent(y,`${y.type}Window`)}_getMapTouches(y){const C=[];for(const R of y)this._el.contains(R.target)&&C.push(R);return C}handleEvent(y,C){this._updatingCamera=!0;const R=y.type==="renderFrame",$=R?void 0:y,G={needsRenderFrame:!1},Z={},te={},ue=y.touches?this._getMapTouches(y.touches):void 0,xe=ue?F(this._el,ue):R?void 0:M(this._el,y);for(const{handlerName:Le,handler:Ue,allowed:st}of this._handlers){if(!Ue.isEnabled())continue;let Xe;this._blockedByActive(te,st,Le)?Ue.reset():Ue[C||y.type]&&(Xe=Ue[C||y.type](y,xe,ue),this.mergeHandlerResult(G,Z,Xe,Le,$),Xe&&Xe.needsRenderFrame&&this._triggerRenderFrame()),(Xe||Ue.isActive())&&(te[Le]=Ue)}const je={};for(const Le in this._previousActiveHandlers)te[Le]||(je[Le]=$);this._previousActiveHandlers=te,(Object.keys(je).length||GC(G))&&(this._changes.push([G,Z,je]),this._triggerRenderFrame()),(Object.keys(te).length||GC(G))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:Re}=G;Re&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Re(this._map))}mergeHandlerResult(y,C,R,$,G){if(!R)return;Object.assign(y,R);const Z={handlerName:$,originalEvent:R.originalEvent||G};R.zoomDelta!==void 0&&(C.zoom=Z),R.panDelta!==void 0&&(C.drag=Z),R.pitchDelta!==void 0&&(C.pitch=Z),R.bearingDelta!==void 0&&(C.rotate=Z)}_applyChanges(){const y={},C={},R={};for(const[$,G,Z]of this._changes)$.panDelta&&(y.panDelta=(y.panDelta||new o.P(0,0))._add($.panDelta)),$.zoomDelta&&(y.zoomDelta=(y.zoomDelta||0)+$.zoomDelta),$.bearingDelta&&(y.bearingDelta=(y.bearingDelta||0)+$.bearingDelta),$.pitchDelta&&(y.pitchDelta=(y.pitchDelta||0)+$.pitchDelta),$.around!==void 0&&(y.around=$.around),$.aroundCoord!==void 0&&(y.aroundCoord=$.aroundCoord),$.pinchAround!==void 0&&(y.pinchAround=$.pinchAround),$.noInertia&&(y.noInertia=$.noInertia),Object.assign(C,G),Object.assign(R,Z);this._updateMapTransform(y,C,R),this._changes=[]}_updateMapTransform(y,C,R){const $=this._map,G=$.transform,Z=jt=>[jt.x,jt.y,jt.z];if((()=>{const jt=this._eventsInProgress.drag;return jt&&!this._handlersById[jt.handlerName].isActive()})()&&!GC(y)){const jt=G.zoom;G.cameraElevationReference="sea",this._originalZoom!=null&&G._orthographicProjectionAtLowPitch&&G.projection.name!=="globe"&&G.pitch===0?(G.cameraElevationReference="ground",G.zoom=this._originalZoom):(G.recenterOnTerrain(),G.cameraElevationReference="ground"),jt!==G.zoom&&this._map._update(!0)}if(G._isCameraConstrained&&$._stop(!0),!GC(y))return void this._fireEvents(C,R,!0);let{panDelta:te,zoomDelta:ue,bearingDelta:xe,pitchDelta:je,around:Re,aroundCoord:Le,pinchAround:Ue}=y;G._isCameraConstrained&&(ue>0&&(ue=0),G._isCameraConstrained=!1),Ue!==void 0&&(Re=Ue),(ue||(jt=>C[jt]&&!this._eventsInProgress[jt])("drag"))&&Re&&(this._dragOrigin=Z(G.pointCoordinate3D(Re)),this._originalZoom=G.zoom,this._trackingEllipsoid.setup(G._camera.position,this._dragOrigin)),G.cameraElevationReference="sea",$._stop(!0),Re=Re||$.transform.centerPoint,xe&&(G.bearing+=xe),je&&(G.pitch+=je),G._updateCameraState();const st=[0,0,0];if(te)if(G.projection.name==="mercator"){const jt=this._trackingEllipsoid.projectRay(G.screenPointToMercatorRay(Re).dir),Tt=this._trackingEllipsoid.projectRay(G.screenPointToMercatorRay(Re.sub(te)).dir);st[0]=Tt[0]-jt[0],st[1]=Tt[1]-jt[1]}else{const jt=G.pointCoordinate(Re);if(G.projection.name==="globe"){te=te.rotate(-G.angle);const Tt=G._pixelsPerMercatorPixel/G.worldSize;st[0]=-te.x*o.eQ(o.bV(jt.y))*Tt,st[1]=-te.y*o.eQ(G.center.lat)*Tt}else{const Tt=G.pointCoordinate(Re.sub(te));jt&&Tt&&(st[0]=Tt.x-jt.x,st[1]=Tt.y-jt.y)}}const Xe=G.zoom,pt=[0,0,0];if(ue){const jt=Z(Le||G.pointCoordinate3D(Re)),Tt={dir:o.ay([],o.ax([],jt,G._camera.position))};if(Tt.dir[2]<0){const xt=G.zoomDeltaToMovement(jt,ue);o.bJ(pt,Tt.dir,xt)}}const mt=o.cT(st,st,pt);G._translateCameraConstrained(mt),ue&&Math.abs(G.zoom-Xe)>1e-4&&G.recenterOnTerrain(),G.cameraElevationReference="ground",this._map._update(),y.noInertia||this._inertia.record(y),this._fireEvents(C,R,!0)}_fireEvents(y,C,R){const $=HC(this._eventsInProgress),G=HC(y),Z={};for(const je in y){const{originalEvent:Re}=y[je];this._eventsInProgress[je]||(Z[`${je}start`]=Re),this._eventsInProgress[je]=y[je]}!$&&G&&this._fireEvent("movestart",G.originalEvent);for(const je in Z)this._fireEvent(je,Z[je]);G&&this._fireEvent("move",G.originalEvent);for(const je in y){const{originalEvent:Re}=y[je];this._fireEvent(je,Re)}const te={};let ue;for(const je in this._eventsInProgress){const{handlerName:Re,originalEvent:Le}=this._eventsInProgress[je];this._handlersById[Re].isActive()||(delete this._eventsInProgress[je],ue=C[Re]||Le,te[`${je}end`]=ue)}for(const je in te)this._fireEvent(je,te[je]);const xe=HC(this._eventsInProgress);if(R&&($||G)&&!xe){this._updatingCamera=!0;const je=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Re=Le=>Le!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new lq("renderFrame",{timeStamp:y})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const tO="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class uq extends o.E{constructor(y,C){super(),this._moving=!1,this._zooming=!1,this.transform=y,this._bearingSnap=C.bearingSnap,this._respectPrefersReducedMotion=C.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(y,C){return this.jumpTo({center:y},C)}panBy(y,C,R){return y=o.P.convert(y).mult(-1),this.panTo(this.transform.center,Object.assign({offset:y},C),R)}panTo(y,C,R){return this.easeTo(Object.assign({center:y},C),R)}getZoom(){return this.transform.zoom}setZoom(y,C){return this.jumpTo({zoom:y},C),this}zoomTo(y,C,R){return this.easeTo(Object.assign({zoom:y},C),R)}zoomIn(y,C){return this.zoomTo(this.getZoom()+1,y,C),this}zoomOut(y,C){return this.zoomTo(this.getZoom()-1,y,C),this}getBearing(){return this.transform.bearing}setBearing(y,C){return this.jumpTo({bearing:y},C),this}getPadding(){return this.transform.padding}setPadding(y,C){return this.jumpTo({padding:y},C),this}rotateTo(y,C,R){return this.easeTo(Object.assign({bearing:y},C),R)}resetNorth(y,C){return this.rotateTo(0,Object.assign({duration:1e3},y),C),this}resetNorthPitch(y,C){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},y),C),this}snapToNorth(y,C){return Math.abs(this.getBearing())y.aspect?R/(2*Math.tan(.5*y.fovX)*y.aspect):$/(2*Math.tan(.5*y.fovY)*y.aspect)}_cameraForBoundsOnGlobe(y,C,R,$,G,Z){const te=y.clone(),ue=this._extendCameraOptions(Z);te.bearing=$,te.pitch=G;const xe=o.aU.convert(C),je=o.aU.convert(R),Re=.5*(xe.lat+je.lat),Le=.5*(xe.lng+je.lng),Ue=o.eT(Re,Le),st=o.ay([],Ue),Xe=o.ay([],o.bh([],st,[0,1,0])),pt=o.bh([],Xe,st),mt=[Xe[0],Xe[1],Xe[2],0,pt[0],pt[1],pt[2],0,st[0],st[1],st[2],0,0,0,0,1],jt=[Ue,o.eT(xe.lat,xe.lng),o.eT(je.lat,xe.lng),o.eT(je.lat,je.lng),o.eT(xe.lat,je.lng),o.eT(Re,xe.lng),o.eT(Re,je.lng),o.eT(xe.lat,Le),o.eT(je.lat,Le)];let Tt=o.cU.fromPoints(jt.map(qs=>[o.bi(Xe,qs),o.bi(pt,qs),o.bi(st,qs)]));const xt=o.ah([],Tt.center,mt);o.eU(xt)===0&&o.eV(xt,0,0,1),o.ay(xt,xt),o.bJ(xt,xt,o.aF),te.center=o.eW(xt);const es=te.getWorldToCameraMatrix(),Ft=o.b7(new Float64Array(16),es);Tt=o.cU.applyTransform(Tt,o.aD([],es,mt));const Jt=this._extendAABB(Tt,te,ue,$);if(!Jt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Tt=Jt,o.ah(xt,xt,es);const At=.5*(Tt.max[2]-Tt.min[2]),Rt=this._minimumAABBFrustumDistance(te,Tt),Wt=o.bJ([],[0,0,1],At),ys=o.cT(Wt,xt,Wt),rs=Rt+(te.pitch===0?0:o.bf(xt,ys)),zs=te.globeCenterInViewSpace,Is=o.ax([],xt,[zs[0],zs[1],zs[2]]);o.ay(Is,Is),o.bJ(Is,Is,rs);const an=o.cT([],xt,Is);o.ah(an,an,Ft);const mn=o.eD/o.aF,js=o.ai(an),ms=o.bU(Math.max(js*mn-o.eD,Number.EPSILON),0),Rs=Math.min(te.zoomFromMercatorZAdjusted(ms),ue.maxZoom);return Rs>.5*(o.cJ+o.cv)?(te.setProjection({name:"mercator"}),te.zoom=Rs,this._cameraForBounds(te,C,R,$,G,Z)):{center:te.center,zoom:Rs,bearing:$,pitch:G}}_extendAABB(y,C,R,$){const G=.5*((R.padding.left||0)+(R.padding.right||0)),Z=.5*((R.padding.top||0)+(R.padding.bottom||0)),te=Z,ue=G,xe=G,je=Z,Re=C.width-(ue+xe),Le=C.height-(te+je),Ue=o.ax([],y.max,y.min),st=Math.min(Re/Ue[0],Le/Ue[1]),Xe=Math.min(C.scaleZoom(C.scale*st),R.maxZoom);if(isNaN(Xe))return null;const pt=C.scale/C.zoomScale(Xe),mt=new o.cU([y.min[0]-ue*pt,y.min[1]-je*pt,y.min[2]],[y.max[0]+xe*pt,y.max[1]+te*pt,y.max[2]]),jt=(typeof R.offset.x=="number"&&typeof R.offset.y=="number"?new o.P(R.offset.x,R.offset.y):o.P.convert(R.offset)).rotate(-o.ap($));return mt.center[0]-=jt.x*pt,mt.center[1]+=jt.y*pt,mt}queryTerrainElevation(y,C){const R=this.transform.elevation;return R?(C=Object.assign({},{exaggerated:!0},C),R.getAtPoint(o.ag.fromLngLat(y),null,C.exaggerated)):null}_cameraForBounds(y,C,R,$,G,Z){if(y.projection.name==="globe")return this._cameraForBoundsOnGlobe(y,C,R,$,G,Z);const te=y.clone(),ue=this._extendCameraOptions(Z);te.bearing=$,te.pitch=G;const xe=o.aU.convert(C),je=o.aU.convert(R),Re=new o.aU(xe.lng,je.lat),Le=new o.aU(je.lng,xe.lat),Ue=te.project(xe),st=te.project(je),Xe=this.queryTerrainElevation(xe),pt=this.queryTerrainElevation(je),mt=this.queryTerrainElevation(Re),jt=this.queryTerrainElevation(Le),Tt=[[Ue.x,Ue.y,Math.min(Xe||0,pt||0,mt||0,jt||0)],[st.x,st.y,Math.max(Xe||0,pt||0,mt||0,jt||0)]];let xt=o.cU.fromPoints(Tt);const es=te.getWorldToCameraMatrix(),Ft=o.b7(new Float64Array(16),es);xt=o.cU.applyTransform(xt,es);const Jt=this._extendAABB(xt,te,ue,$);if(!Jt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");xt=Jt;const At=.5*o.ax([],xt.max,xt.min)[2],Rt=this._minimumAABBFrustumDistance(te,xt),Wt=[0,0,1,0];o.aE(Wt,Wt,es),o.eX(Wt,Wt);const ys=o.bJ([],Wt,Rt+At),rs=o.cT([],xt.center,ys);o.ah(xt.center,xt.center,Ft),o.ah(rs,rs,Ft);const zs=te.unproject(new o.P(xt.center[0],xt.center[1])),Is=o.eY(te.projection,zs),an=Math.pow(2,Is),mn=Math.min(te._zoomFromMercatorZ(rs[2]*te.pixelsPerMeter*an/te.worldSize),ue.maxZoom);return te.mercatorFromTransition&&mn<.5*(o.cJ+o.cv)?(te.setProjection({name:"globe"}),te.zoom=mn,this._cameraForBounds(te,C,R,$,G,Z)):{center:zs,zoom:mn,bearing:$,pitch:G}}fitBounds(y,C,R){const $=this.cameraForBounds(y,C);return this._fitInternal($,C,R)}fitScreenCoordinates(y,C,R,$,G){const Z=o.P.convert(y),te=o.P.convert(C),ue=new o.P(Math.min(Z.x,te.x),Math.min(Z.y,te.y)),xe=new o.P(Math.max(Z.x,te.x),Math.max(Z.y,te.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(Z,te))return this;const je=this.transform.pointLocation3D(ue),Re=this.transform.pointLocation3D(xe),Le=this.transform.pointLocation3D(new o.P(ue.x,xe.y)),Ue=this.transform.pointLocation3D(new o.P(xe.x,ue.y)),st=[Math.min(je.lng,Re.lng,Le.lng,Ue.lng),Math.min(je.lat,Re.lat,Le.lat,Ue.lat)],Xe=[Math.max(je.lng,Re.lng,Le.lng,Ue.lng),Math.max(je.lat,Re.lat,Le.lat,Ue.lat)],pt=$&&$.pitch?$.pitch:this.getPitch(),mt=this._cameraForBounds(this.transform,st,Xe,R,pt,$);return this._fitInternal(mt,$,G)}_fitInternal(y,C,R){return y?(C=Object.assign(y,C)).linear?this.easeTo(C,R):this.flyTo(C,R):this}jumpTo(y,C){this.stop();const R=y.preloadOnly?this.transform.clone():this.transform;let $=!1,G=!1,Z=!1;"zoom"in y&&R.zoom!==+y.zoom&&($=!0,R.zoom=+y.zoom),y.center!==void 0&&(R.center=o.aU.convert(y.center)),"bearing"in y&&R.bearing!==+y.bearing&&(G=!0,R.bearing=+y.bearing),"pitch"in y&&R.pitch!==+y.pitch&&(Z=!0,R.pitch=+y.pitch);const te=typeof y.padding=="number"?this._extendPadding(y.padding):y.padding;if(y.padding!=null&&!R.isPaddingEqual(te))if(y.retainPadding===!1){const ue=R.clone();ue.padding=te,R.setLocationAtPoint(R.center,ue.centerPoint)}else R.padding=te;return y.preloadOnly?(this._preloadTiles(R),this):(this.fire(new o.C("movestart",C)).fire(new o.C("move",C)),$&&this.fire(new o.C("zoomstart",C)).fire(new o.C("zoom",C)).fire(new o.C("zoomend",C)),G&&this.fire(new o.C("rotatestart",C)).fire(new o.C("rotate",C)).fire(new o.C("rotateend",C)),Z&&this.fire(new o.C("pitchstart",C)).fire(new o.C("pitch",C)).fire(new o.C("pitchend",C)),this.fire(new o.C("moveend",C)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(tO),this.transform.getFreeCameraOptions()}setFreeCameraOptions(y,C){const R=this.transform;if(!R.projection.supportsFreeCamera)return o.w(tO),this;this.stop();const $=R.zoom,G=R.pitch,Z=R.bearing;R.setFreeCameraOptions(y);const te=$!==R.zoom,ue=G!==R.pitch,xe=Z!==R.bearing;return this.fire(new o.C("movestart",C)).fire(new o.C("move",C)),te&&this.fire(new o.C("zoomstart",C)).fire(new o.C("zoom",C)).fire(new o.C("zoomend",C)),xe&&this.fire(new o.C("rotatestart",C)).fire(new o.C("rotate",C)).fire(new o.C("rotateend",C)),ue&&this.fire(new o.C("pitchstart",C)).fire(new o.C("pitch",C)).fire(new o.C("pitchend",C)),this.fire(new o.C("moveend",C)),this}easeTo(y,C){this._stop(!1,y.easeId),((y=Object.assign({offset:[0,0],duration:500,easing:o.eP},y)).animate===!1||this._prefersReducedMotion(y))&&(y.duration=0);const R=this.transform,$=this.getZoom(),G=this.getBearing(),Z=this.getPitch(),te=this.getPadding(),ue="zoom"in y?+y.zoom:$,xe="bearing"in y?this._normalizeBearing(y.bearing,G):G,je="pitch"in y?+y.pitch:Z,Re=this._extendPadding(y.padding),Le=o.P.convert(y.offset);let Ue,st,Xe;if(R.projection.name==="globe"){const Wt=o.ag.fromLngLat(R.center),ys=Le.rotate(-R.angle);Wt.x+=ys.x/R.worldSize,Wt.y+=ys.y/R.worldSize;const rs=Wt.toLngLat(),zs=o.aU.convert(y.center||rs);this._normalizeCenter(zs),Ue=R.centerPoint.add(ys),st=new o.P(Wt.x,Wt.y).mult(R.worldSize),Xe=new o.P(o.aH(zs.lng),o.aL(zs.lat)).mult(R.worldSize).sub(st)}else{Ue=R.centerPoint.add(Le);const Wt=R.pointLocation(Ue),ys=o.aU.convert(y.center||Wt);this._normalizeCenter(ys),st=R.project(Wt),Xe=R.project(ys).sub(st)}const pt=R.zoomScale(ue-$);let mt,jt;y.around&&(mt=o.aU.convert(y.around),jt=R.locationPoint(mt));const Tt=this._zooming||ue!==$,xt=this._rotating||G!==xe,es=this._pitching||je!==Z,Ft=!R.isPaddingEqual(Re),Jt=y.retainPadding===!1?R.clone():R,At=Wt=>ys=>{if(Tt&&(Wt.zoom=o.am($,ue,ys)),xt&&(Wt.bearing=o.am(G,xe,ys)),es&&(Wt.pitch=o.am(Z,je,ys)),Ft&&(Jt.interpolatePadding(te,Re,ys),Ue=Jt.centerPoint.add(Le)),mt)Wt.setLocationAtPoint(mt,jt);else{const rs=Wt.zoomScale(Wt.zoom-$),zs=ue>$?Math.min(2,pt):Math.max(.5,pt),Is=Math.pow(zs,1-ys),an=Wt.unproject(st.add(Xe.mult(ys*Is)).mult(rs));Wt.setLocationAtPoint(Wt.renderWorldCopies?an.wrap():an,Ue)}return y.preloadOnly||this._fireMoveEvents(C),Wt};if(y.preloadOnly){const Wt=this._emulate(At,y.duration,R);return this._preloadTiles(Wt),this}const Rt={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Tt,this._rotating=xt,this._pitching=es,this._padding=Ft,this._easeId=y.easeId,this._prepareEase(C,y.noMoveStart,Rt),this._ease(At(R),Wt=>{R.cameraElevationReference==="sea"&&R.recenterOnTerrain(),this._afterEase(C,Wt)},y),this}_prepareEase(y,C,R={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),C||R.moving||this.fire(new o.C("movestart",y)),this._zooming&&!R.zooming&&this.fire(new o.C("zoomstart",y)),this._rotating&&!R.rotating&&this.fire(new o.C("rotatestart",y)),this._pitching&&!R.pitching&&this.fire(new o.C("pitchstart",y))}_fireMoveEvents(y){this.fire(new o.C("move",y)),this._zooming&&this.fire(new o.C("zoom",y)),this._rotating&&this.fire(new o.C("rotate",y)),this._pitching&&this.fire(new o.C("pitch",y))}_afterEase(y,C){if(this._easeId&&C&&this._easeId===C)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const R=this._zooming,$=this._rotating,G=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,R&&this.fire(new o.C("zoomend",y)),$&&this.fire(new o.C("rotateend",y)),G&&this.fire(new o.C("pitchend",y)),this.fire(new o.C("moveend",y))}flyTo(y,C){if(this._prefersReducedMotion(y)){const qs=o.aJ(y,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(qs,C)}this.stop(),y=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},y);const R=this.transform,$=this.getZoom(),G=this.getBearing(),Z=this.getPitch(),te=this.getPadding(),ue="zoom"in y?o.aC(+y.zoom,R.minZoom,R.maxZoom):$,xe="bearing"in y?this._normalizeBearing(y.bearing,G):G,je="pitch"in y?+y.pitch:Z,Re=this._extendPadding(y.padding),Le=R.zoomScale(ue-$),Ue=o.P.convert(y.offset);let st=R.centerPoint.add(Ue);const Xe=R.pointLocation(st),pt=o.aU.convert(y.center||Xe);this._normalizeCenter(pt);const mt=R.project(Xe),jt=R.project(pt).sub(mt);let Tt=y.curve;const xt=Math.max(R.width,R.height),es=xt/Le,Ft=jt.mag();if("minZoom"in y){const qs=o.aC(Math.min(y.minZoom,$,ue),R.minZoom,R.maxZoom),Qs=xt/R.zoomScale(qs-$);Tt=Math.sqrt(Qs/Ft*2)}const Jt=Tt*Tt;function At(qs){const Qs=(es*es-xt*xt+(qs?-1:1)*Jt*Jt*Ft*Ft)/(2*(qs?es:xt)*Jt*Ft);return Math.log(Math.sqrt(Qs*Qs+1)-Qs)}function Rt(qs){return(Math.exp(qs)-Math.exp(-qs))/2}function Wt(qs){return(Math.exp(qs)+Math.exp(-qs))/2}const ys=At(0);let rs=function(qs){return Wt(ys)/Wt(ys+Tt*qs)},zs=function(qs){return xt*((Wt(ys)*(Rt(Qs=ys+Tt*qs)/Wt(Qs))-Rt(ys))/Jt)/Ft;var Qs},Is=(At(1)-ys)/Tt;if(Math.abs(Ft)<1e-6||!isFinite(Is)){if(Math.abs(xt-es)<1e-6)return this.easeTo(y,C);const qs=esy.maxDuration&&(y.duration=0);const an=G!==xe,mn=je!==Z,js=!R.isPaddingEqual(Re),ms=y.retainPadding===!1?R.clone():R,Rs=qs=>Qs=>{const Dn=Qs*Is,Cn=1/rs(Dn);qs.zoom=Qs===1?ue:$+qs.scaleZoom(Cn),an&&(qs.bearing=o.am(G,xe,Qs)),mn&&(qs.pitch=o.am(Z,je,Qs)),js&&(ms.interpolatePadding(te,Re,Qs),st=ms.centerPoint.add(Ue));const Tn=Qs===1?pt:qs.unproject(mt.add(jt.mult(zs(Dn))).mult(Cn));return qs.setLocationAtPoint(qs.renderWorldCopies?Tn.wrap():Tn,st),qs._updateCameraOnTerrain(),y.preloadOnly||this._fireMoveEvents(C),qs};if(y.preloadOnly){const qs=this._emulate(Rs,y.duration,R);return this._preloadTiles(qs),this}return this._zooming=!0,this._rotating=an,this._pitching=mn,this._padding=js,this._prepareEase(C,!1),this._ease(Rs(R),()=>this._afterEase(C),y),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(y){}_cancelRenderFrame(y){}_stop(y,C){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const R=this._onEaseEnd;this._onEaseEnd=void 0,R.call(this,C)}if(!y){const R=this.handlers;R&&R.stop(!1)}return this}_ease(y,C,R){R.animate===!1||R.duration===0?(y(1),C()):(this._easeStart=o.o.now(),this._easeOptions=R,this._onEaseFrame=y,this._onEaseEnd=C,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const y=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),C=this._onEaseFrame;C&&C(this._easeOptions.easing(y)),y<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(y,C){y=o.bs(y,-180,180);const R=Math.abs(y-C);return Math.abs(y-360-C)180?-360:R<-180?360:0}_prefersReducedMotion(y){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(y&&y.essential)}_emulate(y,C,R){const $=Math.ceil(15*C/1e3),G=[],Z=y(R.clone());for(let te=0;te<=$;te++){const ue=Z(te/$);G.push(ue.clone())}return G}_preloadTiles(y,C){}}class sO{constructor(y={}){this.options=y,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(y){const C=this.options&&this.options.compact,R=y._getUIString("AttributionControl.ToggleAttribution");this._map=y,this._container=b("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=b("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",R);const $=b("span","mapboxgl-ctrl-icon",this._compactButton);return $.setAttribute("aria-hidden","true"),$.setAttribute("title",R),this._innerContainer=b("div","mapboxgl-ctrl-attrib-inner",this._container),C&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),C===void 0&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let y=this._editLink;y||(y=this._editLink=this._container.querySelector(".mapbox-improve-map"));const C=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(y){const R=C.reduce(($,G,Z)=>(G.value&&($+=`${G.key}=${G.value}${Z$.length-G.length),y=y.filter(($,G)=>{for(let Z=G+1;Z=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?y=[...this.options.customAttribution,...y]:y.unshift(this.options.customAttribution));const R=y.map($=>function(G){const Z=new DOMParser().parseFromString(G,"text/html");return Array.from(Z.body.querySelectorAll("*")).reverse().forEach(te=>{const ue=te.textContent||"";if(te.tagName!=="A")return void te.replaceWith(...te.childNodes);const xe=te.getAttribute("href");if(!xe||!/^(https?:|mailto:)/i.test(xe))return void te.replaceWith(Z.createTextNode(ue));const je=Z.createElement("a");je.href=xe,je.textContent=ue,je.rel="noopener nofollow";const Re=te.getAttribute("class");Re&&(je.className=Re),te.replaceWith(je)}),Z.body.innerHTML}($)).join(" | ");R!==this._attribHTML&&(this._attribHTML=R,y.length?(this._innerContainer.innerHTML=R,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 nO{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(y){this._map=y,this._container=b("div","mapboxgl-ctrl");const C=b("a","mapboxgl-ctrl-logo");return C.target="_blank",C.rel="noopener nofollow",C.href="https://www.mapbox.com/",C.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),C.setAttribute("rel","noopener nofollow"),this._container.appendChild(C),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(y){y&&y.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const y=this._map.style._sourceCaches;if(Object.entries(y).length===0)return!0;for(const C in y){const R=y[C].getSource();if(R.hasOwnProperty("mapbox_logo")&&!R.mapbox_logo)return!1}return!0}_updateCompact(){const y=this._container.children;if(y.length){const C=y[0];this._map.getCanvasContainer().offsetWidth<250?C.classList.add("mapboxgl-compact"):C.classList.remove("mapboxgl-compact")}}}class hq{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(y){const C=++this._id;return this._queue.push({callback:y,id:C,cancelled:!1}),C}remove(y){const C=this._currentlyRunning,R=C?this._queue.concat(C):this._queue;for(const $ of R)if($.id===y)return void($.cancelled=!0)}run(y=0){const C=this._currentlyRunning=this._queue;this._queue=[];for(const R of C)if(!R.cancelled&&(R.callback(y),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class Sbe{constructor(y){this.jumpTo(y)}getValue(y){if(y<=this._startTime)return this._start;if(y>=this._endTime)return this._end;const C=o.dn((y-this._startTime)/(this._endTime-this._startTime));return this._start*(1-C)+this._end*C}isEasing(y){return y>=this._startTime&&y<=this._endTime}jumpTo(y){this._startTime=-1/0,this._endTime=-1/0,this._start=y,this._end=y}easeTo(y,C,R){this._start=this.getValue(C),this._end=y,this._startTime=C,this._endTime=C+R}}const Cbe={"AttributionControl.ToggleAttribution":"Toggle attribution","FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"Mapbox homepage","Map.Title":"Map","NavigationControl.ResetBearing":"Reset bearing to north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","ScrollZoomBlocker.CtrlMessage":"Use ctrl + scroll to zoom the map","ScrollZoomBlocker.CmdMessage":"Use ⌘ + scroll to zoom the map","TouchPanBlocker.Message":"Use two fingers to move the map"};class Po extends o.C{constructor(y,C,R,$){const{point:G,lngLat:Z,originalEvent:te,target:ue}=y;super(y.type,{point:G,lngLat:Z,originalEvent:te,target:ue}),this.preventDefault=()=>{y.preventDefault()},this.id=C,this.interaction=R,this.feature=$}}class F6{constructor(y){this.map=y,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(y,C){if(this.typeById.has(y))throw new Error(`Interaction id "${y}" already exists.`);const R=C.filter;let $=C.type;R&&this.filters.set(y,o.dg(R)),$==="mouseover"&&($="mouseenter"),$==="mouseout"&&($="mouseleave");const G=this.interactionsByType.get($)||new Map;$==="mouseenter"||$==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(y,C)):G.size===0&&this.map.on($,this.handleType),G.size===0&&this.interactionsByType.set($,G),G.set(y,C),this.typeById.set(y,$)}get(y){const C=this.typeById.get(y);if(!C)return;const R=this.interactionsByType.get(C);return R?R.get(y):void 0}remove(y){const C=this.typeById.get(y);if(!C)return;this.typeById.delete(y),this.filters.delete(y);const R=this.interactionsByType.get(C);R&&(R.delete(y),C==="mouseenter"||C==="mouseleave"?(this.delegatedInteractions.delete(y),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):R.size===0&&this.map.off(C,this.handleType))}queryTargets(y,C){const R=[];for(const[$,G]of C)G.target&&R.push({targetId:$,target:G.target,filter:this.filters.get($)});return this.map.style.queryRenderedTargets(y,R,this.map.transform)}handleMove(y){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const C=this.queryTargets(y.point,Array.from(this.delegatedInteractions).reverse());C.length&&(y.type="mouseenter",this.handleType(y,C));const R=new Map;for(const[$,{feature:G}]of this.prevHoveredFeatures)this.hoveredFeatures.has($)||R.set(G.id,G);R.size&&(y.type="mouseleave",this.handleType(y,Array.from(R.values())))}handleOut(y){const C=Array.from(this.hoveredFeatures.values()).map(({feature:R})=>R);C.length&&(y.type="mouseleave",this.handleType(y,C)),this.hoveredFeatures.clear()}handleType(y,C){const R=y.type==="mouseenter";if(R&&!this.interactionsByType.has(y.type))return void o.w("mouseenter interaction required for mouseleave to work.");const $=Array.from(this.interactionsByType.get(y.type)).reverse(),G=!!C;C=C||this.queryTargets(y.point,$);let Z=!1;const te=new Set;for(const ue of C){for(const[xe,je]of $){if(!je.target)continue;const Re=ue.variants?ue.variants[xe]:null;if(Re){for(const Le of Re){if(_h(Le,ue,te,xe))continue;const Ue=new o.di(ue,Le),st=Ef(Le,ue,xe);G&&Ue.id!==void 0&&(Ue.state=this.map.getFeatureState(Ue));const Xe=R?this.prevHoveredFeatures.get(st):null,pt=new Po(y,xe,je,Ue),mt=Xe?Xe.stop:je.handler(pt);if(R&&this.hoveredFeatures.set(st,{feature:ue,stop:mt}),mt!==!1){Z=!0;break}}if(Z)break}}if(Z)break}if(!Z)for(const[ue,xe]of $){const{handler:je,target:Re}=xe;if(!Re&&je(new Po(y,ue,xe,null))!==!1)break}}}function Tbe(I,y){if(Array.isArray(I)&&Array.isArray(y)){const C=new Set(I),R=new Set(y);return C.size===R.size&&I.every($=>R.has($))}return o.b6(I,y)}const Ebe={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:85,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,performanceMetricsCollection:!0,bearingSnap:7,clickTolerance:3,pitchWithRotate:!0,hash:!1,attributionControl:!0,antialias:!1,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,minTileCacheSize:null,maxTileCacheSize:null,localIdeographFontFamily:"sans-serif",localFontFamily:null,useServerFontComposition:!0,transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1},Abe={showCompass:!0,showZoom:!0,visualizePitch:!1};class WC{constructor(y,C,R=!1){this._clickTolerance=10,this.element=C,this.mouseRotate=new I6({clickTolerance:y.dragRotate._mouseRotate._clickTolerance}),this.map=y,R&&(this.mousePitch=new UC({clickTolerance:y.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),C.addEventListener("mousedown",this.mousedown),C.addEventListener("touchstart",this.touchstart,{passive:!1}),C.addEventListener("touchmove",this.touchmove),C.addEventListener("touchend",this.touchend),C.addEventListener("touchcancel",this.reset)}down(y,C){this.mouseRotate.mousedown(y,C),this.mousePitch&&this.mousePitch.mousedown(y,C),A()}move(y,C){const R=this.map,$=this.mouseRotate.mousemoveWindow(y,C),G=$&&$.bearingDelta;if(G&&R.setBearing(R.getBearing()+G),this.mousePitch){const Z=this.mousePitch.mousemoveWindow(y,C),te=Z&&Z.pitchDelta;te&&R.setPitch(R.getPitch()+te)}}off(){const y=this.element;y.removeEventListener("mousedown",this.mousedown),y.removeEventListener("touchstart",this.touchstart),y.removeEventListener("touchmove",this.touchmove),y.removeEventListener("touchend",this.touchend),y.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){T(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(y){this.down(Object.assign({},y,{button:y.button,type:y.type,ctrlKey:!0,preventDefault:()=>y.preventDefault()}),M(this.element,y)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(y){this.move(y,M(this.element,y))}mouseup(y){this.mouseRotate.mouseupWindow(y),this.mousePitch&&this.mousePitch.mouseupWindow(y),this.offTemp()}touchstart(y){y.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=F(this.element,y.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>y.preventDefault()},this._startPos))}touchmove(y){y.targetTouches.length!==1?this.reset():(this._lastPos=F(this.element,y.targetTouches)[0],this.move({buttons:1,preventDefault:()=>y.preventDefault()},this._lastPos))}touchend(y){y.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)C.width||y.y>C.height;C.locationPoint3D(R).distSqr(y)180;){const R=C.locationPoint3D(I);if(R.x>=0&&R.y>=0&&R.x<=C.width&&R.y<=C.height)break;I.lng>C.center.lng?I.lng-=360:I.lng+=360}return I}const KC={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%)"},Cx={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class jg extends o.E{constructor(y,C){super(),(y instanceof HTMLElement||C)&&(y=Object.assign({element:y},C)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:R="center",color:$="#3FB1CE",scale:G=1,draggable:Z=!1,clickTolerance:te=0,rotation:ue=Cx.rotation,rotationAlignment:xe=Cx.rotationAlignment,pitchAlignment:je=Cx.pitchAlignment,occludedOpacity:Re=Cx.occludedOpacity,altitude:Le=Cx.altitude}=y||{};this._anchor=R,this._color=$,this._scale=G,this._draggable=Z,this._clickTolerance=te,this._rotation=ue,this._rotationAlignment=xe,this._pitchAlignment=je,this._occludedOpacity=Re,this._altitude=Le,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),y&&y.element?(this._element=y.element,this._offset=o.P.convert(y&&y.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(y&&y.offset||[0,-14])),this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label","Map marker"),this._element.hasAttribute("role")||this._element.setAttribute("role","img"),this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",Xe=>{Xe.preventDefault()}),this._element.addEventListener("mousedown",Xe=>{Xe.preventDefault()});const Ue=this._element.classList;for(const Xe in KC)Ue.remove(`mapboxgl-marker-anchor-${Xe}`);Ue.add(`mapboxgl-marker-anchor-${this._anchor}`);const st=y&&y.className?y.className.trim().split(/\s+/):[];Ue.add(...st),this._popup=null}_createDefaultMarker(){const y=b("div"),C=v("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},y);if(this._altitude===0){const R=v("radialGradient",{id:"shadowGradient"},v("defs",{},C));v("stop",{offset:"10%","stop-opacity":.4},R),v("stop",{offset:"100%","stop-opacity":.05},R),v("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},C)}return v("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},C),v("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},C),v("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},C),y}addTo(y){return y===this._map||(this.remove(),this._map=y,y.getCanvasContainer().appendChild(this._element),y.on("move",this._updateMoving),y.on("moveend",this._update),y.on("remove",this._clearFadeTimer),y._addMarker(this),this.setDraggable(this._draggable),this._update(),y.on("click",this._onMapClick)),this}remove(){const y=this._map;return y&&(y.off("click",this._onMapClick),y.off("move",this._updateMoving),y.off("moveend",this._update),y.off("mousedown",this._addDragHandler),y.off("touchstart",this._addDragHandler),y.off("mouseup",this._onUp),y.off("touchend",this._onUp),y.off("mousemove",this._onMove),y.off("touchmove",this._onMove),y.off("remove",this._clearFadeTimer),y._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(y){return this._lngLat=o.aU.convert(y),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(y){return y===this._altitude||(this._defaultMarker&&(this._altitude===0&&y!==0||this._altitude!==0&&y===0)&&(this._element=this._createDefaultMarker()),this._altitude=y||Cx.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(y){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")),y){if(!("offset"in y.options)){const $=Math.sqrt(Math.pow(13.5,2)/2);y.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[$,-1*(38.1-13.5+$)],"bottom-right":[-$,-1*(38.1-13.5+$)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=y,y._marker=this,y._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(y){const C=y.code,R=y.charCode||y.keyCode;C!=="Space"&&C!=="Enter"&&R!==32&&R!==13||this.togglePopup()}_onMapClick(y){const C=y.originalEvent.target,R=this._element;this._popup&&(C===R||R.contains(C))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const y=this._popup;return y?(y.isOpen()?(y.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(y.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const y=this._map,C=this._pos;if(!y||!C)return!1;const R=y.unproject(C,this._altitude),$=y.getFreeCameraOptions();if(!$.position)return!1;const G=$.position.toLngLat();return G.distanceTo(R)<.9*G.distanceTo(this._lngLat)}_evaluateOpacity(){const y=this._map;if(!y)return;const C=this._pos;if(!C||C.x<0||C.x>y.transform.width||C.y<0||C.y>y.transform.height)return void this._clearFadeTimer();const R=y.unproject(C,this._altitude);let $;y._showingGlobe()&&o.e$(y.transform,this._lngLat)?$=0:($=1-y._queryFogOpacity(R),y.transform._terrainEnabled()&&y.getTerrain()&&this._behindTerrain()&&($*=this._occludedOpacity)),this._element.style.opacity=`${$}`,this._element.style.pointerEvents=$>0?"auto":"none",this._popup&&this._popup._setOpacity($),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const y=this._pos;if(!y||!this._map)return;const C=this._offset.mult(this._scale);this._element.style.transform=` translate(${y.x}px,${y.y}px) ${KC[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${C.x}px,${C.y}px) `}_calculateXYTransform(){const y=this._pos,C=this._map,R=this.getPitchAlignment();if(!C||!y||R!=="map")return"";if(!C._showingGlobe()){const ue=C.getPitch();return ue?`rotateX(${ue}deg)`:""}const $=o.cH(o.f0(C.transform,this._lngLat)),G=y.sub(o.f1(C.transform)),Z=Math.abs(G.x)+Math.abs(G.y);if(Z===0)return"";const te=$/Z;return`rotateX(${-G.y*te}deg) rotateY(${G.x*te}deg)`}_calculateZTransform(){const y=this._pos,C=this._map;if(!C||!y)return"";let R=0;const $=this.getRotationAlignment();if($==="map")if(C._showingGlobe()){const G=C.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),Z=C.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(G);R=o.cH(Math.atan2(Z.y,Z.x))-90}else R=-C.getBearing();else if($==="horizon"){const G=o.aj(4,6,C.getZoom()),Z=o.f1(C.transform);Z.y+=G*C.transform.height;const te=y.sub(Z),ue=o.cH(Math.atan2(te.y,te.x));R=(ue>90?ue-270:ue+90)*(1-G)}return R+=this._rotation,R?`rotateZ(${R}deg)`:""}_update(y){cancelAnimationFrame(this._updateFrameId);const C=this._map;C&&(C.transform.renderWorldCopies&&(this._lngLat=rO(this._lngLat,this._pos,C.transform)),this._pos=C.project(this._lngLat,this._altitude),y===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),C._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(C._showingGlobe()||C.getTerrain()||C.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(y){return this._offset=o.P.convert(y),this._update(),this}addClassName(y){return this._element.classList.add(y),this}removeClassName(y){return this._element.classList.remove(y),this}toggleClassName(y){return this._element.classList.toggle(y)}_onMove(y){const C=this._map;if(!C)return;const R=this._pointerdownPos,$=this._positionDelta;if(R&&$){if(!this._isDragging){const G=this._clickTolerance||C._clickTolerance;if(y.point.dist(R)I.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(I.minPitch!=null&&I.maxPitch!=null&&I.minPitch>I.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(I.minPitch!=null&&I.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(I.maxPitch!=null&&I.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");I.antialias&&o.eZ(window)&&(I.antialias=!1,o.w("Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609")),super(new ip(I.minZoom,I.maxZoom,I.minPitch,I.maxPitch,I.renderWorldCopies,null,null),I),this._repaint=!!I.repaint,this._interactive=I.interactive,this._minTileCacheSize=I.minTileCacheSize,this._maxTileCacheSize=I.maxTileCacheSize,this._failIfMajorPerformanceCaveat=I.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=I.preserveDrawingBuffer,this._antialias=I.antialias,this._trackResize=I.trackResize,this._bearingSnap=I.bearingSnap,this._refreshExpiredTiles=I.refreshExpiredTiles,this._fadeDuration=I.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=I.crossSourceCollisions,this._collectResourceTiming=I.collectResourceTiming,this._language=this._parseLanguage(I.language),this._worldview=I.worldview,this._renderTaskQueue=new hq,this._domRenderTaskQueue=new hq,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},Cbe,I.locale),this._clickTolerance=I.clickTolerance,this._cooperativeGestures=I.cooperativeGestures,this._performanceMetricsCollection=I.performanceMetricsCollection,this._tessellationStep=I.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=I.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new Sbe(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=I.scaleFactor,this._requestManager=new Y(I.transformRequest,I.accessToken,I.testMode);const C=ce(I.accessToken||o.g.ACCESS_TOKEN);if(C&&"atlas"in C&&typeof C.atlas=="number"&&(this._tokenExpiration=C.atlas),this._silenceAuthErrors=!!I.testMode,this._contextCreateOptions=I.contextCreateOptions?Object.assign({},I.contextCreateOptions):{},typeof I.container=="string"){const R=document.getElementById(I.container);if(!R)throw new Error(`Container '${I.container.toString()}' not found.`);this._container=R}else{if(!(I.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=I.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."),I.maxBounds&&this.setMaxBounds(I.maxBounds),this._spriteFormat="auto",o.aZ(["_onWindowOnline","_onWindowResize","_onVisibilityChange","_onMapScroll","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),this.painter===void 0)throw new Error("Failed to initialize WebGL.");if(this.on("move",()=>this._update(!1)),this.on("moveend",()=>this._update(!1)),this.on("zoom",()=>this._update(!0)),this._fullscreenchangeEvent="onfullscreenchange"in document?"fullscreenchange":"webkitfullscreenchange",window.addEventListener("online",this._onWindowOnline,!1),window.addEventListener("resize",this._onWindowResize,!1),window.addEventListener("orientationchange",this._onWindowResize,!1),window.addEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.addEventListener("visibilitychange",this._onVisibilityChange,!1),this.handlers=new dq(this,I),this._localFontFamily=I.localFontFamily,this._localIdeographFontFamily=I.localIdeographFontFamily,this._useServerFontComposition=I.useServerFontComposition,(I.style||!I.testMode)&&this.setStyle(I.style||o.g.DEFAULT_STYLE,{config:I.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),I.projection&&this.setProjection(I.projection),I.hash&&(this._hash=new kc(typeof I.hash=="string"&&I.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){y.center==null&&y.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:I.center,zoom:I.zoom,bearing:I.bearing,pitch:I.pitch});const R=I.bounds;R&&(this.resize(),this.fitBounds(R,Object.assign({},I.fitBoundsOptions,{duration:0})))}this.resize(),I.attributionControl&&this.addControl(new sO({customAttribution:I.customAttribution})),this._logoControl=new nO,this.addControl(this._logoControl,I.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",R=>{this._update(R.dataType==="style"),this.fire(new o.C(`${R.dataType}data`,R))}),this.on("dataloading",R=>{this.fire(new o.C(`${R.dataType}dataloading`,R))}),this._interactions=new F6(this)}_getMapId(){return this._mapId}addControl(I,y){if(y===void 0&&(y=I.getDefaultPosition?I.getDefaultPosition():"top-right"),!I||!I.onAdd)return this.fire(new o.B(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const C=I.onAdd(this);this._controls.push(I);const R=this._controlPositions[y];return y.indexOf("bottom")!==-1?R.insertBefore(C,R.firstChild):R.appendChild(C),this}removeControl(I){if(!I||!I.onRemove)return this.fire(new o.B(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const y=this._controls.indexOf(I);return y>-1&&this._controls.splice(y,1),I.onRemove(this),this}hasControl(I){return this._controls.indexOf(I)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(I){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 y=!this._moving;return y&&this.fire(new o.C("movestart",I)).fire(new o.C("move",I)),this.fire(new o.C("resize",I)),y&&this.fire(new o.C("moveend",I)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(I){return this.transform.setMaxBounds(o.aK.convert(I)),this._update()}setMinZoom(I){if((I=I??-2)>=-2&&I<=this.transform.maxZoom)return this.transform.minZoom=I,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=I,this._update(),this.getZoom()>I?this.setZoom(I):this.fire(new o.C("zoomstart")).fire(new o.C("zoom")).fire(new o.C("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(I){if((I=I??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(I>=0&&I<=this.transform.maxPitch)return this.transform.minPitch=I,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(I>=this.transform.minPitch)return this.transform.maxPitch=I,this._update(),this.getPitch()>I?this.setPitch(I):this.fire(new o.C("pitchstart")).fire(new o.C("pitch")).fire(new o.C("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(I){return this._scaleFactor=I,this.painter.scaleFactor=I,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(y=>y.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(I){return this.transform.renderWorldCopies=I,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(I){return I==="auto"?navigator.language:Array.isArray(I)?I.length===0?void 0:I.map(y=>y==="auto"?navigator.language:y):I}setLanguage(I){const y=this._parseLanguage(I);if(!this.style||y===this._language)return this;this._language=y,this.style.reloadSources();for(const C of this._controls)C._setLanguage&&C._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(I){return this.style&&I!==this._worldview?(this._worldview=I,this._styleDirty=!0,this.style.setWorldview(I),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(I){return this._lazyInitEmptyStyle(),I?typeof I=="string"&&(I={name:I}):I=null,this._useExplicitProjection=!!I,this._prioritizeAndUpdateProjection(I,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const I=this.transform,y=I.projection.name;let C;y==="globe"&&I.zoom>=o.cv?(I.setMercatorFromTransition(),C=!0):y==="mercator"&&I.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(I),this.style.applyProjectionUpdate();const R=this.transform.getProjection().name==="mercator"&&C!==this.transform.mercatorFromTransition;return(y||R)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(I,y){return this.transform.locationPoint3D(o.aU.convert(I),y)}unproject(I,y){return this.transform.pointLocation3D(o.P.convert(I),y)}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(I,y,C){const R=$=>{let G=[];if(Array.isArray(y)){const Z=y.filter(te=>this.getLayer(te));G=Z.length?this.queryRenderedFeatures($,{layers:Z}):[]}else G=this.queryRenderedFeatures($,{target:y});return G};if(I==="mouseenter"||I==="mouseover"){let $=!1;return{listener:C,targets:y,delegates:{mousemove:Z=>{const te=R(Z.point);te.length?$||($=!0,C.call(this,new ai(I,this,Z.originalEvent,{features:te}))):$=!1},mouseout:()=>{$=!1}}}}if(I==="mouseleave"||I==="mouseout"){let $=!1;return{listener:C,targets:y,delegates:{mousemove:te=>{R(te.point).length?$=!0:$&&($=!1,C.call(this,new ai(I,this,te.originalEvent)))},mouseout:te=>{$&&($=!1,C.call(this,new ai(I,this,te.originalEvent)))}}}}{const $=G=>{const Z=R(G.point);Z.length&&(G.features=Z,C.call(this,G),delete G.features)};return{listener:C,targets:y,delegates:{[I]:$}}}}on(I,y,C){if(typeof y=="function"||C===void 0)return super.on(I,y);if(typeof y=="string"&&(y=[y]),!this._areTargetsValid(y))return this;const R=this._createDelegatedListener(I,y,C);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[I]=this._delegatedListeners[I]||[],this._delegatedListeners[I].push(R);for(const $ in R.delegates)this.on($,R.delegates[$]);return this}once(I,y,C){if(typeof y=="function"||C===void 0)return super.once(I,y);if(typeof y=="string"&&(y=[y]),!this._areTargetsValid(y))return this;const R=this._createDelegatedListener(I,y,C);for(const $ in R.delegates)this.once($,R.delegates[$]);return this}off(I,y,C){if(typeof y=="function"||C===void 0)return super.off(I,y);if(typeof y=="string"&&(y=[y]),!this._areTargetsValid(y))return this;const R=this._delegatedListeners?this._delegatedListeners[I]:void 0;return R&&($=>{for(let G=0;G<$.length;G++){const Z=$[G];if(Z.listener===C&&Tbe(Z.targets,y)){for(const te in Z.delegates)this.off(te,Z.delegates[te]);return $.splice(G,1),this}}})(R),this}queryRenderedFeatures(I,y){if(!this.style)return[];if(I===void 0||I instanceof o.P||Array.isArray(I)||y!==void 0||(y=I,I=void 0),I=I||[[0,0],[this.transform.width,this.transform.height]],!y){const G=this.style.queryRenderedFeatures(I,void 0,this.transform),Z=this.style.queryRenderedFeatureset(I,void 0,this.transform);return G.concat(Z)}let C=!0;if(y.target&&(C=this._isTargetValid(y.target),C&&!y.layers))return this.style.queryRenderedFeatureset(I,y,this.transform);let R=!0;if(y.layers&&Array.isArray(y.layers)){for(const G of y.layers)if(!this._isValidId(G)){R=!1;break}if(R&&!y.target)return this.style.queryRenderedFeatures(I,y,this.transform)}let $=[];return R&&($=$.concat(this.style.queryRenderedFeatures(I,y,this.transform))),C&&($=$.concat(this.style.queryRenderedFeatureset(I,y,this.transform))),$}querySourceFeatures(I,y){return!I||typeof I=="string"&&!this._isValidId(I)?[]:this.style.querySourceFeatures(I,y)}queryRasterValue(I,y,C){return this._isValidId(I)?this.style.queryRasterValue(I,y,C):Promise.resolve(null)}isPointOnSurface(I){const{name:y}=this.transform.projection;return y!=="globe"&&y!=="mercator"&&o.w(`${y} projection does not support isPointOnSurface, this API may behave unexpectedly.`),this.transform.isPointOnSurface(o.P.convert(I))}addInteraction(I,y){return this._interactions.add(I,y),this}removeInteraction(I){return this._interactions.remove(I),this}getCooperativeGestures(){return this._cooperativeGestures}setCooperativeGestures(I){return this._cooperativeGestures=I,this}setStyle(I,y){return y=Object.assign({},{localIdeographFontFamily:this._localIdeographFontFamily,localFontFamily:this._localFontFamily,useServerFontComposition:this._useServerFontComposition},y),this.style&&I&&y.diff!==!1&&y.localFontFamily===this._localFontFamily&&y.localIdeographFontFamily===this._localIdeographFontFamily&&!y.config?(this.style._diffStyle(I,(C,R)=>{if(C){const $=typeof C=="string"?C:C instanceof Error?C.message:C.error;o.w(`Unable to perform style diff: ${$}. Rebuilding the style from scratch.`),this._updateStyle(I,y)}else R&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=y.localIdeographFontFamily,this._localFontFamily=y.localFontFamily,this._updateStyle(I,y))}_getUIString(I){const y=this._locale[I];if(y==null)throw new Error(`Missing UI string '${I}'`);return y}_updateStyle(I,y){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),I){const C=Object.assign({},y);y&&y.config&&(C.initialConfig=y.config,delete C.config),this.style=new Qc(this,C).load(I),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Qc(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(I){return I==null?(this.fire(new o.B(new Error("IDs can't be empty."))),!1):!o.db(I)||(this.fire(new o.B(new Error(`IDs can't contain special symbols: "${I}".`))),!1)}_isTargetValid(I){return"featuresetId"in I?this._isValidId("importId"in I?I.importId:I.featuresetId):"layerId"in I&&this._isValidId(I.layerId)}_areTargetsValid(I){if(Array.isArray(I)){for(const y of I)if(!this._isValidId(y))return!1;return!0}return this._isTargetValid(I)}addSource(I,y){return this._isValidId(I)?(this._lazyInitEmptyStyle(),this.style.addSource(I,y),this._update(!0)):this}isSourceLoaded(I){return!!this._isValidId(I)&&!!this.style&&this.style._isSourceCacheLoaded(I)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(I,y,C){this._lazyInitEmptyStyle(),this.style.addSourceType(I,y,C)}removeSource(I){return this._isValidId(I)?(this.style.removeSource(I),this._updateTerrain(),this._update(!0)):this}getSource(I){return this._isValidId(I)?this.style.getOwnSource(I):null}addImage(I,y,{pixelRatio:C=1,sdf:R=!1,stretchX:$,stretchY:G,content:Z}={}){this._lazyInitEmptyStyle();const te=o.I.from(I);if(y instanceof HTMLImageElement||ImageBitmap&&y instanceof ImageBitmap){const{width:ue,height:xe,data:je}=o.o.getImageData(y);this.style.addImage(te,{data:new o.q({width:ue,height:xe},je),pixelRatio:C,stretchX:$,stretchY:G,content:Z,sdf:R,version:0,usvg:!1})}else if(y.width===void 0||y.height===void 0)this.fire(new o.B(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));else{const{width:ue,height:xe}=y,je=y;this.style.addImage(te,{data:new o.q({width:ue,height:xe},new Uint8Array(je.data)),pixelRatio:C,stretchX:$,stretchY:G,content:Z,sdf:R,usvg:!1,version:0,userImage:je}),je.onAdd&&je.onAdd(this,I)}}updateImage(I,y){this._lazyInitEmptyStyle();const C=o.I.from(I),R=this.style.getImage(C);if(!R)return void this.fire(new o.B(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const $=y instanceof HTMLImageElement||ImageBitmap&&y instanceof ImageBitmap?o.o.getImageData(y):y,{width:G,height:Z,data:te}=$;if(G===void 0||Z===void 0)return void this.fire(new o.B(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(G!==(R.usvg?R.icon.usvg_tree.width:R.data.width)||Z!==(R.usvg?R.icon.usvg_tree.height:R.data.height))return void this.fire(new o.B(new Error(`The width and height of the updated image (${G}, ${Z}) must be that same as the previous version of the image (${R.data.width}, ${R.data.height})`)));const ue=!(y instanceof HTMLImageElement||ImageBitmap&&y instanceof ImageBitmap);let xe=!1;R.usvg?(R.data=new o.q({width:G,height:Z},new Uint8Array(te)),R.usvg=!1,R.icon=void 0,xe=!0):R.data.replace(te,ue),this.style.updateImage(C,R,xe)}hasImage(I){return I?!!this.style&&!!this.style.getImage(o.I.from(I)):(this.fire(new o.B(new Error("Missing required image id"))),!1)}removeImage(I){this.style.removeImage(o.I.from(I))}loadImage(I,y){o.n(this._requestManager.transformRequest(I,o.R.Image),(C,R)=>{y(C,R)})}listImages(){return this.style.listImages().map(I=>I.name)}addModel(I,y){this._lazyInitEmptyStyle(),this.style.addModel(I,y)}hasModel(I){return I?this.style.hasModel(I):(this.fire(new o.B(new Error("Missing required model id"))),!1)}removeModel(I){this.style.removeModel(I)}listModels(){return this.style.listModels()}addLayer(I,y){return this._isValidId(I.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(I,y),this._update(!0)):this}getSlot(I){const y=this.getLayer(I);return y&&y.slot||null}setSlot(I,y){return this.style.setSlot(I,y),this.style.mergeLayers(),this._update(!0)}addImport(I,y){return this.style.addImport(I,y).catch(C=>this.fire(new o.B(new Error("Failed to add import",C)))),this}updateImport(I,y){return typeof y!="string"&&y.id!==I?(this.removeImport(I),this.addImport(y)):(this.style.updateImport(I,y),this._update(!0))}removeImport(I){return this.style.removeImport(I),this}moveImport(I,y){return this.style.moveImport(I,y),this._update(!0)}moveLayer(I,y){return this._isValidId(I)?(this.style.moveLayer(I,y),this._update(!0)):this}removeLayer(I){return this._isValidId(I)?(this.style.removeLayer(I),this._update(!0)):this}getLayer(I){if(!this._isValidId(I))return null;const y=this.style.getOwnLayer(I);return y?y.type==="custom"?y.implementation:y.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(I,y,C){return this._isValidId(I)?(this.style.setLayerZoomRange(I,y,C),this._update(!0)):this}setFilter(I,y,C={}){return this._isValidId(I)?(this.style.setFilter(I,y,C),this._update(!0)):this}getFilter(I){return this._isValidId(I)?this.style.getFilter(I):null}setPaintProperty(I,y,C,R={}){return this._isValidId(I)?(this.style.setPaintProperty(I,y,C,R),this._update(!0)):this}getPaintProperty(I,y){return this._isValidId(I)?this.style.getPaintProperty(I,y):null}setLayoutProperty(I,y,C,R={}){return this._isValidId(I)?(this.style.setLayoutProperty(I,y,C,R),this._update(!0)):this}getLayoutProperty(I,y){return this._isValidId(I)?this.style.getLayoutProperty(I,y):null}setLayerProperty(I,y,C,R={}){return this._isValidId(I)?(y==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(I,y,C,R),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(I){return this.style.setGlyphsUrl(I),this._update(!0)}getSchema(I){return this.style.getSchema(I)}setSchema(I,y){return this.style.setSchema(I,y),this._update(!0)}getConfig(I){return this.style.getConfig(I)}setConfig(I,y){return this.style.setConfig(I,y),this._update(!0)}getConfigProperty(I,y){return this.style.getConfigProperty(I,y)}setConfigProperty(I,y,C){return this.style.setConfigProperty(I,y,C),this._update(!0)}getFeaturesetDescriptors(I){return this.style.getFeaturesetDescriptors(I)}setLights(I){if(this._lazyInitEmptyStyle(),I&&I.length===1&&I[0].type==="flat"){const y=I[0];y.properties?this.style.setFlatLight(y.properties,y.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(I),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const I=this.style.getLights()||[];return I.length===0&&I.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),I}setLight(I,y={}){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:I}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(I){return this._lazyInitEmptyStyle(),!I&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(I),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(I){return this._lazyInitEmptyStyle(),this.style.setFog(I),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(I){return this._lazyInitEmptyStyle(),this.style.setSnow(I),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(I){return this._lazyInitEmptyStyle(),this.style.setRain(I),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(I){return this._lazyInitEmptyStyle(),this.style.setColorTheme(I),this._update(!0)}setImportColorTheme(I,y){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(I,y),this._update(!0)}setCamera(I){return this.style.setCamera(I),this._triggerCameraUpdate(I)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(I){const y=this.transform.nearClipOffset!==I;return this.transform.nearClipOffset=I,this._update(y)}_triggerCameraUpdate(I){return this._update(this.transform.setOrthographicProjectionAtLowPitch(I["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(I){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aU.convert(I),this.transform):0}setFeatureState(I,y){return I.source&&!this._isValidId(I.source)?this:(this.style.setFeatureState(I,y),this._update())}removeFeatureState(I,y){return I.source&&!this._isValidId(I.source)?this:(this.style.removeFeatureState(I,y),this._update())}getFeatureState(I){return I.source&&!this._isValidId(I.source)?null:this.style.getFeatureState(I)}_selectIndoorFloor(I){this.style.indoorManager.selectFloor(I)}_setIndoorActiveFloorsVisibility(I){this.style.indoorManager.setActiveFloorsVisibility(I)}getIndoorTileOptions(I,y){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(I,y):null}_updateContainerDimensions(){if(!this._container)return;const I=this._container.getBoundingClientRect().width||400,y=this._container.getBoundingClientRect().height||300;let C,R,$,G=this._container;for(;G&&(!R||!$);){const Z=window.getComputedStyle(G).transform;Z&&Z!=="none"&&(C=Z.match(/matrix.*\((.+)\)/)[1].split(", "),C[0]&&C[0]!=="0"&&C[0]!=="1"&&(R=C[0]),C[3]&&C[3]!=="0"&&C[3]!=="1"&&($=C[3])),G=G.parentElement}this._containerWidth=R?Math.abs(I/R):I,this._containerHeight=$?Math.abs(y/$):y}_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 I=this._container;I.classList.add("mapboxgl-map"),(this._missingCSSCanary=b("div","mapboxgl-canary",I)).style.visibility="hidden",this._detectMissingCSS();const y=this._canvasContainer=b("div","mapboxgl-canvas-container",I);this._canvas=b("canvas","mapboxgl-canvas",y),this._interactive&&(y.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const C=this._controlContainer=b("div","mapboxgl-control-container",I),R=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach($=>{R[$]=b("div",`mapboxgl-ctrl-${$}`,C)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(I,y){const C=o.o.devicePixelRatio||1;this._canvas.width=C*Math.ceil(I),this._canvas.height=C*Math.ceil(y),this._canvas.style.width=`${I}px`,this._canvas.style.height=`${y}px`}_addMarker(I){this._markers.push(I)}_removeMarker(I){const y=this._markers.indexOf(I);y!==-1&&this._markers.splice(y,1)}_addPopup(I){this._popups.push(I)}_removePopup(I){const y=this._popups.indexOf(I);y!==-1&&this._popups.splice(y,1)}_setupPainter(){const I=Object.assign({},g.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),y=this._canvas.getContext("webgl2",I);y?($e(y,!0),this.painter=new oo(y,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",C=>{if(C.dataType==="source"){const R=this.transform.elevation?this.transform.elevation._source():null;R&&C.sourceCacheId===R.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(y)):this.fire(new o.B(new Error("Failed to initialize WebGL")))}_contextLost(I){I.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new o.C("webglcontextlost",{originalEvent:I}))}_contextRestored(I){this._setupPainter(),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight)),this._updateTerrain(),this.style&&(this.style.clearLayers(),this.style.imageManager.destroyAtlasTextures(),this.style.imageManager.imageAtlasCache.destroyTextures(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new o.C("webglcontextrestored",{originalEvent:I}))}_onMapScroll(I){if(I.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(I){return this.style?(this._styleDirty=this._styleDirty||I,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(I){return this._update(),this._renderTaskQueue.add(I)}_cancelRenderFrame(I){this._renderTaskQueue.remove(I)}_requestDomTask(I){!this.loaded()||this.loaded()&&!this.isMoving()?I():this._domRenderTaskQueue.add(I)}_render(I){let y;this.fire(new o.C("renderstart")),++this._frameId;const C=this.painter.context.extTimerQuery,R=o.o.now(),$=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(y=$.createQuery(),$.beginQuery(C.TIME_ELAPSED_EXT,y)),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(I),this._domRenderTaskQueue.run(I),this._removed)return;this._updateProjectionTransition();const G=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const ue=this.transform.zoom,xe=this.transform.pitch,je=o.o.now(),Re=new o.ae(ue,{now:je,fadeDuration:G,pitch:xe,transition:this.style.transition,worldview:this._worldview});this.style.update(Re)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let Z=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),Z=this._updateAverageElevation(R),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):Z=this._updateAverageElevation(R),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,G,this._crossSourceCollisions,this.painter.replacementSource)),this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:G,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new o.C("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,u.mark(d.load),this.fire(new o.C("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&(this.style.snow||this.style.rain)&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this.style.modelManager.isLoaded()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),y){const ue=o.o.now()-R;$.endQuery(C.TIME_ELAPSED_EXT),setTimeout(()=>{const xe=$.getQueryParameter(y,$.QUERY_RESULT)/1e6;$.deleteQuery(y),this.fire(new o.C("gpu-timing-frame",{cpuTime:ue,gpuTime:xe}))},50)}if(this.listens("gpu-timing-layer")){const ue=this.painter.collectGpuTimers();setTimeout(()=>{const xe=this.painter.queryGpuTimers(ue);this.fire(new o.C("gpu-timing-layer",{layerTimes:xe}))},50)}if(this.listens("gpu-timing-deferred-render")){const ue=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const xe=this.painter.queryGpuTimeDeferredRender(ue);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:xe}))},50)}const te=this._sourcesDirty||this._styleDirty||this._placementDirty||Z;if(te||this._repaint)this.triggerRepaint();else{const ue=this.idle();if(ue&&(Z=this._updateAverageElevation(R,!0)),Z)this.triggerRepaint();else if(this._triggerFrame(!1),ue&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const xe=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:xe})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||te||(this._fullyLoaded=!0,u.mark(d.fullLoad),this._performanceMetricsCollection&&we(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:!!this.painter.style.getTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate())}_forceMarkerAndPopupUpdate(I){for(const y of this._markers)I&&!this.getRenderWorldCopies()&&(y._lngLat=y._lngLat.wrap()),y._update();for(const y of this._popups)!I||this.getRenderWorldCopies()||y._trackPointer||(y._lngLat=y._lngLat.wrap()),y._update()}_updateAverageElevation(I,y=!1){const C=$=>(this.transform.averageElevation=$,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&C(0);const R=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(R||(y||I-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(I)){const $=this.transform.averageElevation;let G=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(G)?G=0:this._averageElevationLastSampledAt=I;const Z=Math.abs($-G);if(Z>1){if(this._isInitialLoad||R)return this._averageElevation.jumpTo(G),C(G);this._averageElevation.easeTo(G,I,300)}else if(Z>1e-4)return this._averageElevation.jumpTo(G),C(G)}return!!this._averageElevation.isEasing(I)&&C(this._averageElevation.getValue(I))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const I=this.painter.context.gl;$e(I,!1),this._logoControl instanceof nO&&this._logoControl._updateLogo(),I&&I.clear(I.DEPTH_BUFFER_BIT|I.COLOR_BUFFER_BIT|I.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new o.B(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}_authenticate(){Ne(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,I=>{I&&(I.message!==K&&I.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),Ce(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&De(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Fe(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){ve(this._requestManager._customAccessToken)}_updateTerrain(){const I=this._isDragging();this.painter.updateTerrain(this.style,I)}_calculateSpeedIndex(){const I=this.painter.canvasCopy(),y=this.painter.getCanvasCopiesAndTimestamps();y.timeStamps.push(performance.now());const C=this.painter.context.gl,R=C.createFramebuffer();function $(G){C.framebufferTexture2D(C.FRAMEBUFFER,C.COLOR_ATTACHMENT0,C.TEXTURE_2D,G,0);const Z=new Uint8Array(C.drawingBufferWidth*C.drawingBufferHeight*4);return C.readPixels(0,0,C.drawingBufferWidth,C.drawingBufferHeight,C.RGBA,C.UNSIGNED_BYTE,Z),Z}return C.bindFramebuffer(C.FRAMEBUFFER,R),this._canvasPixelComparison($(I),y.canvasCopies.map($),y.timeStamps)}_canvasPixelComparison(I,y,C){let R=C[1]-C[0];const $=I.length/4;for(let G=0;G{const C=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,C&&this._render(y)}))}_preloadTiles(I){const y=this.style?this.style.getSourceCaches():[];return o.t(y,(C,R)=>C._preloadTiles(I,R),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(I){this._trackResize&&this.resize({originalEvent:I})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(I){this._showTileBoundaries!==I&&(this._showTileBoundaries=I,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(I){this._showParseStatus!==I&&(this._showParseStatus=I,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(I){this._showTerrainWireframe!==I&&(this._showTerrainWireframe=I,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(I){this._showLayers2DWireframe!==I&&(this._showLayers2DWireframe=I,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(I){this._showLayers3DWireframe!==I&&(this._showLayers3DWireframe=I,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(I){this._speedIndexTiming!==I&&(this._speedIndexTiming=I,this._update())}get showPadding(){return!!this._showPadding}set showPadding(I){this._showPadding!==I&&(this._showPadding=I,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(I){this._showCollisionBoxes!==I&&(this._showCollisionBoxes=I,this.style&&I?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(I){this._showOverdrawInspector!==I&&(this._showOverdrawInspector=I,this._update())}get repaint(){return!!this._repaint}set repaint(I){this._repaint!==I&&(this._repaint=I,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(I){this._vertices=I,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(I){this._showTileAABBs!==I&&(this._showTileAABBs=I,I&&this._update())}_setCacheLimits(I,y){o.e_(I,y)}get version(){return c}},NavigationControl:class{constructor(I={}){this.options=Object.assign({},Abe,I),this._container=b("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",y=>y.preventDefault()),this.options.showZoom&&(o.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",y=>{this._map&&this._map.zoomIn({},{originalEvent:y})}),b("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",y=>{this._map&&this._map.zoomOut({},{originalEvent:y})}),b("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.aZ(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",y=>{const C=this._map;C&&(this.options.visualizePitch?C.resetNorthPitch({},{originalEvent:y}):C.resetNorth({},{originalEvent:y}))}),this._compassIcon=b("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const I=this._map;if(!I)return;const y=I.getZoom(),C=y===I.getMaxZoom(),R=y===I.getMinZoom();this._zoomInButton.disabled=C,this._zoomOutButton.disabled=R,this._zoomInButton.setAttribute("aria-disabled",C.toString()),this._zoomOutButton.setAttribute("aria-disabled",R.toString())}_rotateCompassArrow(){const I=this._map;if(!I)return;const y=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(I.transform.pitch*(Math.PI/180)),.5)}) rotateX(${I.transform.pitch}deg) rotateZ(${I.transform.angle*(180/Math.PI)}deg)`:`rotate(${I.transform.angle*(180/Math.PI)}deg)`;I._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=y)})}onAdd(I){return this._map=I,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),I.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&I.on("pitch",this._rotateCompassArrow),I.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new WC(I,this._compass,this.options.visualizePitch)),this._container}onRemove(){const I=this._map;I&&(this._container.remove(),this.options.showZoom&&I.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&I.off("pitch",this._rotateCompassArrow),I.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(I,y){const C=b("button",I,this._container);return C.type="button",C.addEventListener("click",y),C}_setButtonTitle(I,y){if(!this._map)return;const C=this._map._getUIString(`NavigationControl.${y}`);I.setAttribute("aria-label",C),I.firstElementChild&&I.firstElementChild.setAttribute("title",C)}},GeolocateControl:class extends o.E{constructor(I={}){super();const y=navigator.geolocation;this.options=Object.assign({geolocation:y},YC,I),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=Ta(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(I){return this._map=I,this._container=b("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(I){const y=(C=!!this.options.geolocation)=>{this._supportsGeolocation=C,I(C)};this._supportsGeolocation!==void 0?I(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(C=>y(C.state!=="denied")).catch(()=>y()):y()}_isOutOfMapMaxBounds(I){const y=this._map.getMaxBounds(),C=I.coords;return!!y&&(C.longitudey.getEast()||C.latitudey.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}}_onSuccess(I){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(I))return this._setErrorState(),this.fire(new o.C("outofmaxbounds",I)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=I,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this.options.followUserLocation?(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active")):(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"));break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(I),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(I),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("geolocate",Object.assign({coords:I.coords,timestamp:I.timestamp},I.toJSON?{toJSON:I.toJSON.bind(I)}:{}))),this._finish()}}_updateCamera(I){const y=new o.aU(I.coords.longitude,I.coords.latitude),C=I.coords.accuracy,R=this._map.getBearing(),$=Object.assign({bearing:R},this.options.fitBoundsOptions);this._map.fitBounds(y.toBounds(C),$,{geolocateSource:!0})}_updateMarker(I){if(I){const y=new o.aU(I.coords.longitude,I.coords.latitude);this._accuracyCircleMarker.setLngLat(y).addTo(this._map),this._userLocationDotMarker.setLngLat(y).addTo(this._map),this._accuracy=I.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const I=this._map.transform,y=o.bU(1,I._center.lat)*I.worldSize,C=Math.ceil(2*this._accuracy*y);this._circleElement.style.width=`${C}px`,this._circleElement.style.height=`${C}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&typeof this._heading=="number"?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(I){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(I.code===1){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const y=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",y),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",y),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(I.code===3&&this._noTimeout)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("error",{code:I.code,message:I.message,PERMISSION_DENIED:I.PERMISSION_DENIED,POSITION_UNAVAILABLE:I.POSITION_UNAVAILABLE,TIMEOUT:I.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const I=this.options.positionOptions.timeout;I&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},I))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(I){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",y=>y.preventDefault()),this._geolocateButton=b("button","mapboxgl-ctrl-geolocate",this._container),b("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",I===!1){o.w("Geolocation support is not available so the GeolocateControl will be disabled.");const y=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",y),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",y)}else{const y=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",y),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",y)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=b("div","mapboxgl-user-location"),this._dotElement.appendChild(b("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(b("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new jg({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=b("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new jg({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.showButton||(this._container.style.display="none"),this.options.trackUserLocation&&this._map.on("movestart",y=>{y.geolocateSource||this._watchState!=="ACTIVE_LOCK"||y.originalEvent&&y.originalEvent.type==="resize"||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this.fire(new o.C("trackuserlocationend")))})}}_onDeviceOrientation(I){this._userLocationDotMarker&&(I.webkitCompassHeading?this._heading=I.webkitCompassHeading:I.absolute===!0&&(this._heading=-1*I.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return o.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new o.C("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new o.C("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.C("trackuserlocationstart"))}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let I;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(I={maximumAge:6e5,timeout:0},this._noTimeout=!0):(I=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,I),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(I){return this.options.followUserLocation=I??YC.followUserLocation,this.options.trackUserLocation&&this._watchState!=="OFF"&&(this.options.followUserLocation?this._watchState!=="BACKGROUND"&&this._watchState!=="BACKGROUND_ERROR"||(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.C("trackuserlocationstart"))):this._watchState!=="ACTIVE_LOCK"&&this._watchState!=="ACTIVE_ERROR"||(this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this.fire(new o.C("trackuserlocationend")))),this}_addDeviceOrientationListener(){const I=()=>{const y="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(y,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(y=>{y==="granted"&&I()}).catch(console.error):I()}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:sO,ScaleControl:class{constructor(I={}){this.options=Object.assign({},ud,I),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const I=this.options.maxWidth||100,y=this._map,C=y._containerHeight/2,R=y._containerWidth/2-I/2,$=y.unproject([R,C]),G=y.unproject([R+I,C]),Z=$.distanceTo(G);if(this.options.unit==="imperial"){const te=3.2808*Z;te>5280?this._setScale(I,te/5280,"mile"):this._setScale(I,te,"foot")}else this.options.unit==="nautical"?this._setScale(I,Z/1852,"nautical-mile"):Z>=1e3?this._setScale(I,Z/1e3,"kilometer"):this._setScale(I,Z,"meter")}_setScale(I,y,C){this._map._requestDomTask(()=>{const R=function(G){const Z=Math.pow(10,`${Math.floor(G)}`.length-1);let te=G/Z;return te=te>=10?10:te>=5?5:te>=3?3:te>=2?2:te>=1?1:function(ue){const xe=Math.pow(10,Math.ceil(-Math.log(ue)/Math.LN10));return Math.round(ue*xe)/xe}(te),Z*te}(y),$=R/y;this._container.innerHTML=C!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:C}).format(R):`${R} ${Ng[C]}`,this._container.style.width=I*$+"px"})}onAdd(I){return this._map=I,this._language=I.getLanguage(),this._container=b("div","mapboxgl-ctrl mapboxgl-ctrl-scale",I.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(I){this._language=I,this._update()}setUnit(I){this.options.unit=I,this._update()}},FullscreenControl:class{constructor(I={}){this._fullscreen=!1,I&&I.container&&(I.container instanceof HTMLElement?this._container=I.container:o.w("Full screen control 'container' must be a DOM element.")),o.aZ(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(I){return this._map=I,this._container||(this._container=this._map.getContainer()),this._controlContainer=b("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 I=this._fullscreenButton=b("button","mapboxgl-ctrl-fullscreen",this._controlContainer);b("span","mapboxgl-ctrl-icon",I).setAttribute("aria-hidden","true"),I.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const I=this._getTitle();this._fullscreenButton.setAttribute("aria-label",I),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",I)}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle())}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen()}},IndoorControl:class{constructor(){o.aZ(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(I){return this._map=I,this._container=b("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const I=this._map.style.indoorManager;I.off("selector-update",this._onIndoorUpdate),I.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(I.getControlState())}}_createButton(I,y){const C=b("button",I,this._container);return C.type="button",C.addEventListener("click",y),C}_setButtonTitle(I,y){I.setAttribute("aria-label",y),I.textContent=y}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.style&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(I){if(!I||!I.floors||I.floors.length===0)return this._model=I,void(this._container.style.display="none");const y=this._model;this._model=I,this._container.style.display="inline-block";const C=!y||y.floors.length!==I.floors.length||y.floors.some((R,$)=>R.id!==I.floors[$].id);if(C&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),I.selectedFloorId){if(I.selectedFloorId!==this._lastSelectedFloorId||C){const R=I.floors.findIndex($=>$.id===I.selectedFloorId);if(R!==-1){const $=I.floors.length;let G,Z;$<=5?(G=0,Z=$-1):this._visibleFloorStart===0?(G=0,Z=3):this._visibleFloorStart>=$-3?(G=$-3-1,Z=$-1):(G=this._visibleFloorStart,Z=this._visibleFloorStart+3-1),RZ&&(this._visibleFloorStart=R-2)}}this._lastSelectedFloorId=I.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const I=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);b("span","mapboxgl-ctrl-icon",I).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||I.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(I);const y=this._model.floors,C=y.length;if(C<=5)return void y.forEach(Z=>this._createFloorButton(Z));const R=this._visibleFloorStart===0,$=this._visibleFloorStart>=C-3;if(R)this._createFloorButton(y[0]);else{const Z=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);b("span","mapboxgl-ctrl-icon",Z).setAttribute("aria-hidden","true"),this._container.appendChild(Z)}let G=[];if(G=R?y.slice(1,4):$?y.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):y.slice(this._visibleFloorStart,this._visibleFloorStart+3),G.forEach(Z=>this._createFloorButton(Z)),$)this._createFloorButton(y[C-1]);else{const Z=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);b("span","mapboxgl-ctrl-icon",Z).setAttribute("aria-hidden","true"),this._container.appendChild(Z)}}_createFloorButton(I){const y=this._createButton("mapboxgl-ctrl-level-button",()=>{const G=I.id;this._model&&this._model.selectedFloorId===G&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(G))}),C=(I.name||"").trim(),R=I.zIndex.toString(),$=C?Array.from(C).slice(0,3).join(""):R;this._setButtonTitle(y,$),this._model&&this._model.activeFloorsVisible&&I.id===this._model.selectedFloorId&&y.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(y)}_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 I=this._model&&this._model.floors||[];if(I.length>3){const y=I.length-3;this._visibleFloorStart===y-1&&(this._visibleFloorStart=y-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const I=this._model.floors.length-3;this._visibleFloorStartI&&(this._visibleFloorStart=I),this._render())}}},Popup:class extends o.E{constructor(I){super(),this.options=Object.assign(Object.create(ZC),I),this._altitude=this.options.altitude,o.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(I&&I.className?I.className.trim().split(/\s+/):[])}addTo(I){return this._map&&this.remove(),this._map=I,this.options.closeOnClick&&I.on("preclick",this._onClose),this.options.closeOnMove&&I.on("move",this._onClose),I.on("remove",this.remove),this._update(),I._addPopup(this),this._focusFirstElement(),this._trackPointer?(I.on("mousemove",this._onMouseEvent),I.on("mouseup",this._onMouseEvent),I._canvasContainer.classList.add("mapboxgl-track-pointer")):I.on("move",this._update),this.fire(new o.C("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const I=this._map;return I&&(I.off("move",this._update),I.off("move",this._onClose),I.off("preclick",this._onClose),I.off("click",this._onClose),I.off("remove",this.remove),I.off("mousemove",this._onMouseEvent),I.off("mouseup",this._onMouseEvent),I.off("drag",this._onMouseEvent),I._canvasContainer&&I._canvasContainer.classList.remove("mapboxgl-track-pointer"),I._removePopup(this),this._map=void 0),this.fire(new o.C("close")),this}getLngLat(){return this._lngLat}setLngLat(I){this._lngLat=o.aU.convert(I),this._pos=null,this._trackPointer=!1,this._update();const y=this._map;return y&&(y.on("move",this._update),y.off("mousemove",this._onMouseEvent),y._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(I){return this._altitude=I,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const I=this._map;return I&&(I.off("move",this._update),I.on("mousemove",this._onMouseEvent),I.on("drag",this._onMouseEvent),I._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(I){return this.setDOMContent(document.createTextNode(I))}setHTML(I){const y=document.createDocumentFragment(),C=document.createElement("body");let R;for(C.innerHTML=I;R=C.firstChild,R;)y.appendChild(R);return this.setDOMContent(y)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(I){return this.options.maxWidth=I,this._update(),this}setDOMContent(I){let y=this._content;if(y)for(;y.hasChildNodes();)y.firstChild&&y.removeChild(y.firstChild);else y=this._content=b("div","mapboxgl-popup-content",this._container||void 0);if(y.appendChild(I),this.options.closeButton){const C=this._closeButton=b("button","mapboxgl-popup-close-button",y);C.type="button",C.setAttribute("aria-label","Close popup"),C.innerHTML='',C.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(I){return this._classList.add(I),this._updateClassList(),this}removeClassName(I){return this._classList.delete(I),this._updateClassList(),this}setOffset(I){return this.options.offset=I,this._update(),this}toggleClassName(I){let y;return this._classList.delete(I)?y=!1:(this._classList.add(I),y=!0),this._updateClassList(),y}_onMouseEvent(I){this._update(I.point)}_getAnchor(I){if(this.options.anchor)return this.options.anchor;const y=this._map,C=this._container,R=this._pos;if(!y||!C||!R)return"bottom";const $=C.offsetWidth,G=C.offsetHeight,Z=R.x<$/2,te=R.x>y.transform.width-$/2;if(R.y+Iy.transform.height-G){if(Z)return"bottom-left";if(te)return"bottom-right"}return Z?"left":te?"right":"bottom"}_updateClassList(){const I=this._container;if(!I)return;const y=[...this._classList];y.push("mapboxgl-popup"),this._anchor&&y.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&y.push("mapboxgl-popup-track-pointer"),I.className=y.join(" ")}_update(I){const y=this._map,C=this._content;if(!y||!this._lngLat&&!this._trackPointer||!C)return;let R=this._container;if(R||(R=this._container=b("div","mapboxgl-popup",y.getContainer()),this._tip=b("div","mapboxgl-popup-tip",R),R.appendChild(C)),this.options.maxWidth&&R.style.maxWidth!==this.options.maxWidth&&(R.style.maxWidth=this.options.maxWidth),y.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=rO(this._lngLat,this._pos,y.transform)),!this._trackPointer||I){const $=this._pos=this._trackPointer&&I instanceof o.P?I:y.project(this._lngLat,this._altitude),G=z6(this.options.offset),Z=this._anchor=this._getAnchor(G.y),te=z6(this.options.offset,Z),ue=$.add(te).round();y._requestDomTask(()=>{this._container&&Z&&(this._container.style.transform=`${KC[Z]} translate(${ue.x}px,${ue.y}px)`)})}if(!this._marker&&y._showingGlobe()){const $=o.e$(y.transform,this._lngLat)?0:1;this._setOpacity($)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const I=this._container.querySelector(Mbe);I&&I.focus()}_onClose(){this.remove()}_setOpacity(I){this._container&&(this._container.style.opacity=`${I}`),this._content&&(this._content.style.pointerEvents=I?"auto":"none")}},Marker:jg,Style:Qc,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:Zb,Evented:o.E,config:o.g,prewarm:function(){Qt().acquire(at)},clearPrewarmedResources:function(){const I=Bt;I&&(I.isPreloaded()&&I.numActive()===1?(I.release(at),Bt=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},get accessToken(){return o.g.ACCESS_TOKEN},set accessToken(I){o.g.ACCESS_TOKEN=I},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(I){o.g.API_URL=I},get workerCount(){return Ge.workerCount},set workerCount(I){Ge.workerCount=I},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(I){o.g.MAX_PARALLEL_IMAGE_REQUESTS=I},clearStorage(I){o.f7(I)},get workerUrl(){return rt.workerUrl},set workerUrl(I){rt.workerUrl=I},get workerClass(){return rt.workerClass},set workerClass(I){rt.workerClass=I},get workerParams(){return rt.workerParams},set workerParams(I){rt.workerParams=I},get dracoUrl(){return o.f6()},set dracoUrl(I){o.g.DRACO_URL=o.o.resolveURL(I)},get meshoptUrl(){return o.f5()},set meshoptUrl(I){const y=o.o.resolveURL(I);o.g.MESHOPT_URL=y,o.g.MESHOPT_SIMD_URL=y},get buildingGenUrl(){return o.f4()},set buildingGenUrl(I){o.g.BUILDING_GEN_URL=o.o.resolveURL(I)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})(bct);var kzt=bct.exports;const ml=jl(kzt),hBe={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},mBe={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 Szt(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function Czt({listings:s,isLoading:t}){const n=In(),r=N.useRef(null),a=N.useRef(null),i=N.useRef([]),[l,o]=N.useState(""),[c,d]=N.useState(!0);return N.useEffect(()=>{(async()=>{d(!0);try{const{data:p}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();p!=null&&p.value&&o(p.value)}catch(p){console.error("Error fetching mapbox token:",p)}d(!1)})()},[]),N.useEffect(()=>{if(!r.current||!l||a.current)return;ml.accessToken=l;const h=s.filter(g=>g.latitude!=null&&g.longitude!=null);let p=[-98.5795,39.8283],f=4;if(h.length>0){const g=h.reduce((v,j)=>v+j.longitude,0)/h.length,b=h.reduce((v,j)=>v+j.latitude,0)/h.length;p=[g,b],f=h.length===1?12:10}return a.current=new ml.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:f,center:p}),a.current.addControl(new ml.NavigationControl,"top-right"),()=>{var g;(g=a.current)==null||g.remove(),a.current=null}},[l]),N.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(p=>p.remove()),i.current=[];const h=s.filter(p=>p.latitude!=null&&p.longitude!=null);if(h.forEach(p=>{var A,T,D;const f=hBe[p.status]||"#10B981",g=((A=p.photos)==null?void 0:A.find(L=>L.is_primary))||((T=p.photos)==null?void 0:T[0]),v=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${p.slug||p.id}`:`/public/listing/${p.slug||p.id}`,j=document.createElement("div");j.className="cursor-pointer",j.innerHTML=`
`;const _=new ml.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${g!=null&&g.photo_url?``:""}
${Szt(p.price)}
${p.property_address||""}
${p.city}, ${p.state}
${mBe[p.status]||p.status} ${p.bedrooms?`${p.bedrooms} bed`:""} ${p.bathrooms?`${p.bathrooms} bath`:""}
${(D=p.agent)!=null&&D.name?`
Listed by ${p.agent.name}
`:""}
Click to view details →
`),S=new ml.Marker(j).setLngLat([p.longitude,p.latitude]).setPopup(_).addTo(a.current);i.current.push(S)}),h.length>1){const p=new ml.LngLatBounds;h.forEach(f=>p.extend([f.longitude,f.latitude])),a.current.fitBounds(p,{padding:60,maxZoom:13})}else h.length===1&&a.current.flyTo({center:[h[0].longitude,h[0].latitude],zoom:12})},[s,l]),N.useEffect(()=>(window.__navigateToPublicListing__=h=>{n(h)},()=>{delete window.__navigateToPublicListing__}),[n]),c||t?e.jsx(Ws,{className:"w-full h-[500px] rounded-lg"}):!l||s.filter(h=>h.latitude!=null&&h.longitude!=null).length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:Object.entries(hBe).map(([h,p])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:p}}),e.jsx("span",{className:"text-xs text-gray-600",children:mBe[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const uje={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},Tzt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},_I="#0d0d0d",pBe="#1a1a1a",_l="#c9a84c",kk="#f0d78c";function wct(){const[s,t]=N.useState(""),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(-1),u=N.useRef(null),[h,p]=N.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:f}=yzt(),g=N.useMemo(()=>{if(!f)return[];const V=s.trim().toLowerCase(),W=[...f.cities.map(Y=>({label:Y.label,value:Y.city,type:"city",count:Y.count})),...f.neighborhoods.map(Y=>({label:Y.label,value:Y.neighborhood,type:"neighborhood",count:Y.count})),...f.zips.map(Y=>({label:`ZIP ${Y.label}`,value:Y.zip,type:"zip",count:Y.count}))];return(V?W.filter(Y=>Y.label.toLowerCase().includes(V)||Y.value.toLowerCase().includes(V)):W).slice(0,8)},[f,s]);N.useEffect(()=>{const V=W=>{u.current&&!u.current.contains(W.target)&&o(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[]);const{data:b,isLoading:v}=gzt({city:s||void 0,status:h.status||void 0,propertyType:h.propertyType||void 0,minPrice:h.minPrice?Number(h.minPrice):void 0,maxPrice:h.maxPrice?Number(h.maxPrice):void 0}),j=V=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(V),_=()=>{p({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},S=s||h.status||h.propertyType||h.minPrice||h.maxPrice,A=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),T=V=>A?`/${V.slug||V.id}`:`/public/listing/${V.slug||V.id}`,{featured:D,restListings:L,luxeCount:M,cities:F,activeCount:z}=N.useMemo(()=>{const V=b||[],W=V.filter(Me=>Me.status==="active"),K=W.length>0?W:V,Y=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[ee,ne,oe]=Y.split("-").map(Number),pe=Math.floor(Date.UTC(ee,ne-1,oe)/864e5),ce=K.length>0?K[pe%K.length]:void 0,de=V.filter(Me=>!ce||Me.id!==ce.id),ie=Array.from(new Set(V.map(Me=>Me.city).filter(Boolean))).slice(0,8),ye=V.filter(Me=>(Me.price||0)>=1e6).length,_e=W.length;return{featured:ce,restListings:de,luxeCount:ye,cities:ie,activeCount:_e}},[b]);return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"LevelUp Listings — Curated Homes for Sale"}),e.jsx("meta",{name:"description",content:"A curated collection of exclusive properties from LevelUp real estate agents. Discover luxury homes, coming soon listings, and market-defining architecture."}),e.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),e.jsx("meta",{property:"og:title",content:"LevelUp Listings — Curated Homes for Sale"}),e.jsx("meta",{property:"og:description",content:"A curated collection of exclusive properties from LevelUp real estate agents."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com"})})]}),e.jsxs("div",{className:"min-h-screen text-white",style:{backgroundColor:_I,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: ${_l}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${_l}, 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(Ln,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:dfe,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(Ln,{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 ${_l}`,color:_l},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i(V=>!V),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${_l}`,color:_l},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(Fn,{className:"w-5 h-5"}):e.jsx(n4,{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(Ln,{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 ${_l}`,color:_l},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:Nzt,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:_l}}),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:kk},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 ${_l}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_r,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:_l}}),e.jsx(ge,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:V=>{t(V.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:V=>{if(!(!l||g.length===0))if(V.key==="ArrowDown")V.preventDefault(),d(W=>Math.min(W+1,g.length-1));else if(V.key==="ArrowUp")V.preventDefault(),d(W=>Math.max(W-1,0));else if(V.key==="Enter"&&c>=0){V.preventDefault();const W=g[c];t(W.value),o(!1)}else V.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(c4,{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:_l,color:_I},onClick:()=>o(!1),children:[e.jsx(_r,{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:_l},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:g.map((V,W)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(W),onClick:()=>{t(V.value),o(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:c===W?"rgba(201,168,76,0.12)":"transparent"},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[V.type==="city"&&e.jsx(Ca,{className:"h-4 w-4 shrink-0",style:{color:_l}}),V.type==="neighborhood"&&e.jsx(Ga,{className:"h-4 w-4 shrink-0",style:{color:_l}}),V.type==="zip"&&e.jsx(zr,{className:"h-4 w-4 shrink-0",style:{color:_l}}),e.jsx("span",{className:"text-white/90 truncate",children:V.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[V.count," ",V.count===1?"listing":"listings"]})]})},`${V.type}-${V.value}-${W}`))})]}),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(us,{value:h.status||"all",onValueChange:V=>p({...h,status:V==="all"?"":V}),children:[e.jsx(cs,{className:"lu-input-dark",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"Any status"}),Object.entries(uje).map(([V,W])=>e.jsx(Ze,{value:V,children:W},V))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(us,{value:h.propertyType||"all",onValueChange:V=>p({...h,propertyType:V==="all"?"":V}),children:[e.jsx(cs,{className:"lu-input-dark",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"Any type"}),Object.entries(Tzt).map(([V,W])=>e.jsx(Ze,{value:V,children:W},V))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(ge,{type:"number",placeholder:"No min",value:h.minPrice,onChange:V=>p({...h,minPrice:V.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(ge,{type:"number",placeholder:"No max",value:h.maxPrice,onChange:V=>p({...h,maxPrice:V.target.value}),className:"lu-input-dark"})]}),S&&e.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:_,className:"text-white/70 hover:text-white gap-1",children:[e.jsx(Fn,{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:((b==null?void 0:b.length)??0).toString()},{label:"Active Now",value:z.toString()},{label:"Luxury $1M+",value:M.toString()}].map(V=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:kk},children:V.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:V.label})]},V.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(io,{className:"h-4 w-4 animate-bounce"})]})]})]}),F.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:pBe,borderTop:"1px solid rgba(201,168,76,0.15)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:e.jsx("div",{className:"lu-marquee whitespace-nowrap",children:[...F,...F,...F].map((V,W)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[V,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:_l}})]},W))})}),D&&e.jsx("section",{id:"featured",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx(un,{className:"h-4 w-4",style:{color:_l}}),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:kk},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(Ln,{to:T(D),className:"group block",children:e.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[e.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var W,K;const V=((W=D.photos)==null?void 0:W.find(Y=>Y.is_primary))||((K=D.photos)==null?void 0:K[0]);return V?e.jsx("img",{src:V.photo_url,alt:D.property_address||D.city,className:"w-full h-full object-cover lu-img-zoom"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(zr,{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:_l,color:_I},children:uje[D.status]||"Featured"})]}),e.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[e.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[e.jsx(Ca,{className:"h-3.5 w-3.5",style:{color:_l}}),D.city,D.state?`, ${D.state}`:""]}),D.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:D.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:kk},children:j(D.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[D.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ny,{className:"h-4 w-4",style:{color:_l}}),D.bedrooms," bd"]}),D.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Tp,{className:"h-4 w-4",style:{color:_l}}),D.bathrooms," ba"]}),D.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(cy,{className:"h-4 w-4",style:{color:_l}}),D.square_footage.toLocaleString()," sf"]})]}),D.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:D.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:_l},children:["View Residence ",e.jsx(za,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:pBe},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:_l}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:_l}})]}),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:kk},children:"carefully considered"}),"."]}),e.jsx("p",{className:"text-white/60 max-w-2xl mx-auto",children:"Browse the full catalogue of LevelUp-represented properties. Filter, refine, and find the one that feels like yours."})]}),v?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((V,W)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ws,{className:"aspect-[4/5] bg-white/5"}),e.jsx(Ws,{className:"h-6 w-32 bg-white/5"}),e.jsx(Ws,{className:"h-4 w-full bg-white/5"})]},W))}):L.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:L.map(V=>{var K,Y,ee,ne,oe;const W=((K=V.photos)==null?void 0:K.find(pe=>pe.is_primary))||((Y=V.photos)==null?void 0:Y[0]);return e.jsxs(Ln,{to:T(V),className:"group lu-card-hover block",children:[e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[W?e.jsx("img",{src:W.photo_url,alt:V.property_address||V.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(zr,{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:_l,border:`1px solid ${_l}`},children:uje[V.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:[V.bedrooms&&e.jsxs("span",{children:[V.bedrooms," bd"]}),V.bathrooms&&e.jsxs("span",{children:[V.bathrooms," ba"]}),V.square_footage&&e.jsxs("span",{children:[V.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(Ca,{className:"h-3 w-3",style:{color:_l}}),V.city,V.state?`, ${V.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:kk},children:j(V.price)}),V.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:V.property_address}),((ee=V.agent)==null?void 0:ee.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(Ga,{className:"h-3 w-3"}),V.agent.name,(((ne=V.agent.brokerage)==null?void 0:ne.name)||V.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((oe=V.agent.brokerage)==null?void 0:oe.name)||V.agent.brokerage_name]})]})]})]},V.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 ${_l}`},children:e.jsx(zr,{className:"h-8 w-8",style:{color:_l}})}),e.jsx("h3",{className:"lu-serif text-2xl mb-2",children:"No listings match yet"}),e.jsx("p",{className:"text-white/60 mb-6",children:"Adjust your search — or check back soon for new arrivals."}),S&&e.jsx(B,{onClick:_,style:{background:_l,color:_I},className:"hover:brightness-110",children:"Clear filters"})]})]})}),b&&b.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:_l}}),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:kk},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(Czt,{listings:b,isLoading:v})})]})}),e.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${_I} 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:_l}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:_l}})]}),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:kk},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:_l,color:_I},children:["Explore LevelUp",e.jsx(za,{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:dfe,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(y9t,{}),e.jsx(v9t,{})]})}const Ezt=N.lazy(()=>vi(()=>import("./PublicHomeValue-iaJNarTJ.js"),[]));function Azt(){const s=Jl(),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(wct,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(N.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(Ezt,{})}):r.startsWith("public/")?null:e.jsx(vct,{slugOverride:r})}function mye({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 jct=s=>lt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:n}=await q.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(n)throw n;const{data:r}=await q.from("profiles").select("name, email, phone, brokerage_id").eq("id",t.user_id).single();let a=null;if(r!=null&&r.brokerage_id){const{data:o}=await q.from("brokerages").select("name").eq("id",r.brokerage_id).single();a=(o==null?void 0:o.name)||null}let i=null;try{const{data:o}=await q.from("profiles").select("avatar_url").eq("id",t.user_id).single();if(o!=null&&o.avatar_url)i=o.avatar_url;else{const{data:c}=await q.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=q.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...r||{name:null,email:null,phone:null,brokerage_id:null},email:t.display_email||(r==null?void 0:r.email)||null};return{...t,social_links:t.social_links||[],profile:l,brokerage_name:t.brokerage_display_name||a,avatar_url:i}},enabled:!!s}),Mzt=()=>lt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await q.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),Izt=s=>lt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),Nct=()=>{const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("agent_cards").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ae.success("Agent card created")},onError:t=>ae.error(t.message)})},kct=()=>{const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("agent_cards").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ae.success("Agent card updated")},onError:t=>ae.error(t.message)})},pl=async(s,t,n,r)=>{const a=new URLSearchParams(window.location.search);await q.from("agent_card_interactions").insert({card_id:s,interaction_type:t,interaction_detail:n||null,referrer:document.referrer||null,user_agent:navigator.userAgent||null,utm_source:a.get("utm_source")||null,utm_medium:a.get("utm_medium")||null,utm_campaign:a.get("utm_campaign")||null,metadata:{}})},Pzt=async(s,t)=>{const{error:n}=await q.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},Sct=s=>lt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(n)throw n;const{data:r,error:a}=await q.from("agent_card_leads").select("*").eq("card_id",s).order("created_at",{ascending:!1});if(a)throw a;const i=(t==null?void 0:t.filter(c=>c.interaction_type==="card_view").length)||0,l=(t==null?void 0:t.filter(c=>c.interaction_type==="button_click").length)||0,o=(t==null?void 0:t.filter(c=>c.interaction_type==="contact_saved").length)||0;return{views:i,clicks:l,saves:o,leads:r||[],interactions:t||[]}},enabled:!!s});function pye({open:s,onOpenChange:t,cardId:n,type:r,agentName:a}){const[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(""),[b,v]=N.useState(!1),j=async _=>{if(_.preventDefault(),!i.trim()){ae.error("Please enter your name");return}v(!0);try{await Pzt(n,{lead_type:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}),pl(n,"lead_submitted",r),q.functions.invoke("card-lead-notify",{body:{cardId:n,leadType:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}}).catch(S=>console.error("Card lead notify failed:",S)),ae.success(r==="booking"?"Request sent! They'll be in touch soon.":r==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),p(""),g("")}catch{ae.error("Something went wrong. Please try again.")}finally{v(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Qn,{children:r==="booking"?`Let ${a} know you'd like to connect.`:r==="connect"?`Share your info and ${a} will reach out.`:`Know someone who could use ${a}'s help?`})]}),e.jsxs("form",{onSubmit:j,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-name",children:"Name *"}),e.jsx(ge,{id:"lead-name",value:i,onChange:_=>l(_.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(ge,{id:"lead-phone",type:"tel",value:d,onChange:_=>u(_.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-email",children:"Email"}),e.jsx(ge,{id:"lead-email",type:"email",value:o,onChange:_=>c(_.target.value),placeholder:"you@example.com"})]}),r==="booking"&&e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select one"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"buy",children:"Buy a home"}),e.jsx(Ze,{value:"sell",children:"Sell my home"}),e.jsx(Ze,{value:"both",children:"Buy & Sell"}),e.jsx(Ze,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(ge,{id:"lead-message",value:f,onChange:_=>g(_.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(B,{type:"submit",className:"w-full rounded-2xl",disabled:b,children:b?"Sending...":"Submit"})]})]})})}const Lzt=s=>lt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("card_blocks").select("*").eq("card_id",s).eq("is_visible",!0).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),Dzt=s=>lt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),Rzt=()=>{const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("card_blocks").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["card-blocks",n.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",n.card_id]}),ae.success("Block added")},onError:t=>ae.error(t.message)})},Ozt=()=>{const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("card_blocks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ae.success("Block updated")},onError:t=>ae.error(t.message)})},Fzt=()=>{const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("card_blocks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ae.success("Block removed")},onError:t=>ae.error(t.message)})};function zzt(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 Bzt(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 $zt={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 Uzt({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=Bzt(n.video_url),i=r||!!a,l=r?zzt(n.video_url):a||n.video_url;return e.jsx("div",{className:$zt[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 qzt={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 Vzt({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=N.useState(0);if(r.length===0)return null;const l=qzt[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(yb,{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(fl,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex gap-1.5",children:r.map((c,d)=>e.jsx("div",{className:`h-1.5 w-1.5 rounded-full transition-colors cursor-pointer ${d===a?l.dot:l.dotInactive}`,onClick:()=>i(d)},d))}),e.jsx("button",{onClick:()=>i(c=>(c+1)%r.length),className:l.nav,children:e.jsx(ga,{className:"h-4 w-4"})})]})]})}const Hzt={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 Gzt({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=Hzt[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const Wzt={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 Kzt({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=Wzt[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:()=>pl(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(tr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const F4e={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 Yzt({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 Zzt={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 Qzt({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=Zzt[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=F4e[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>pl(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(Yzt,{path:c.icon,color:c.color})},o)})})]})}function fye({cardId:s,variant:t}){const{data:n}=Lzt(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(Uzt,{block:l,variant:t},l.id);case"testimonials":return e.jsx(Vzt,{block:l,variant:t},l.id);case"specialties":return e.jsx(Gzt,{block:l,variant:t},l.id);case"custom_links":return e.jsx(Kzt,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(Qzt,{block:i,cardId:s,variant:t})]})}async function Xzt(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 Jzt(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 xye(s){const{first:t,last:n}=Jzt(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 Xzt(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 eBt({card:s}){var j;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(_=>_[0]).join("").toUpperCase().slice(0,2),o=(_,S)=>{pl(s.id,"button_click",_),S()},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),pl(s.id,"button_click","book"))},p=()=>{var _,S;pl(s.id,"contact_saved"),xye({name:i,phone:(_=s.profile)==null?void 0:_.phone,email:(S=s.profile)==null?void 0:S.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{pl(s.id,"share_event");const _=`https://cards.relevelup.com/${s.slug}`,S="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:S,url:_})}catch{}else await navigator.clipboard.writeText(_),ae.success("Link copied!")},g=()=>{a("referral"),n(!0),pl(s.id,"button_click","refer")},b=()=>{a("connect"),n(!0),pl(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(aa,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(ri,{src:s.avatar_url||void 0,alt:i}),e.jsx(ia,{className:"text-2xl font-semibold bg-primary text-primary-foreground",children:l})]}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900 mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-medium text-primary mb-1",children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-medium text-slate-500 mb-1",children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-medium text-slate-400 mb-3",children:s.team_name}),s.positioning_statement&&e.jsxs("p",{className:"text-base text-slate-600 italic leading-relaxed max-w-xs mx-auto",children:['"',s.positioning_statement,'"']})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs(B,{onClick:c,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Pr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs(B,{onClick:d,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Ci,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs(B,{onClick:u,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Hs,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs(B,{onClick:h,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(yr,{className:"h-5 w-5 mr-2"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm text-slate-600",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(ua,{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(mye,{card:s,variant:"standard"}),e.jsx(fye,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs(B,{variant:"ghost",onClick:p,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Da,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs(B,{variant:"ghost",onClick:()=>{pl(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(ua,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(B,{variant:"ghost",onClick:g,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(_n,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(B,{variant:"ghost",onClick:b,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Fo,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(B,{variant:"ghost",onClick:f,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Hl,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((_,S)=>e.jsx("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>pl(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:v[_.platform.toLowerCase()]||"🔗"},S))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(pye,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function tBt({card:s}){var j;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(_=>_[0]).join("").toUpperCase().slice(0,2),o=(_,S)=>{pl(s.id,"button_click",_),S()},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),pl(s.id,"button_click","book"))},p=()=>{var _,S;pl(s.id,"contact_saved"),xye({name:i,phone:(_=s.profile)==null?void 0:_.phone,email:(S=s.profile)==null?void 0:S.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{pl(s.id,"share_event");const _=`https://cards.relevelup.com/${s.slug}`,S="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:S,url:_})}catch{}else await navigator.clipboard.writeText(_),ae.success("Link copied!")},g=()=>{a("referral"),n(!0),pl(s.id,"button_click","refer")},b=()=>{a("connect"),n(!0),pl(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(aa,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(ri,{src:s.avatar_url||void 0,alt:i}),e.jsx(ia,{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:Pr,label:"Call",handler:c},{icon:Ci,label:"Text",handler:d},{icon:Hs,label:"Email",handler:u}].map(({icon:_,label:S,handler:A})=>e.jsxs("button",{onClick:A,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[e.jsx(_,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:S})]},S))}),e.jsxs("button",{onClick:h,className:"w-full h-12 text-base font-semibold rounded-xl mb-6 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] text-[#0f1419] hover:opacity-90 transition-opacity flex items-center justify-center gap-2",children:[e.jsx(yr,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(ua,{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(mye,{card:s,variant:"luxury"}),e.jsx(fye,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Da,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{pl(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(ua,{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(_n,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),e.jsxs("button",{onClick:b,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Fo,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Hl,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((_,S)=>e.jsx("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>pl(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:v[_.platform.toLowerCase()]||"🔗"},S))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(pye,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function sBt({card:s}){var S,A,T,D;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((S=s.profile)==null?void 0:S.name)||"Agent",l=i.split(" ").map(L=>L[0]).join("").toUpperCase().slice(0,2),o={accent:((A=s.bold_theme_colors)==null?void 0:A.accent)||"#ff5722",dark:((T=s.bold_theme_colors)==null?void 0:T.dark)||"#1a1a2e",button:((D=s.bold_theme_colors)==null?void 0:D.button)||"#ff5722"},c=(L,M)=>{const F=parseInt(L.replace("#",""),16),z=Math.max(0,(F>>16)-M),V=Math.max(0,(F>>8&255)-M),W=Math.max(0,(F&255)-M);return`#${(z<<16|V<<8|W).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(L,M)=>{pl(s.id,"button_click",L),M()},u=()=>d("call",()=>{var L;(L=s.profile)!=null&&L.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),h=()=>d("text",()=>{var L;(L=s.profile)!=null&&L.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),p=()=>d("email",()=>{var L;(L=s.profile)!=null&&L.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),f=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),pl(s.id,"button_click","book"))},g=()=>{var L,M;pl(s.id,"contact_saved"),xye({name:i,phone:(L=s.profile)==null?void 0:L.phone,email:(M=s.profile)==null?void 0:M.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},b=async()=>{pl(s.id,"share_event");const L=`https://cards.relevelup.com/${s.slug}`,M="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:M,url:L})}catch{}else await navigator.clipboard.writeText(L),ae.success("Link copied!")},v=()=>{a("referral"),n(!0),pl(s.id,"button_click","refer")},j=()=>{a("connect"),n(!0),pl(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(aa,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(ri,{src:s.avatar_url||void 0,alt:i}),e.jsx(ia,{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:Pr,label:"Call",handler:u},{icon:Ci,label:"Text",handler:h},{icon:Hs,label:"Email",handler:p}].map(({icon:L,label:M,handler:F})=>e.jsxs("button",{onClick:F,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:o.dark},children:[e.jsx(L,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:M})]},M))}),e.jsxs("button",{onClick:f,className:"w-full h-14 text-base font-black rounded-2xl mb-6 text-white transition-opacity hover:opacity-90 flex items-center justify-center gap-2 uppercase tracking-wide",style:{backgroundColor:o.button},children:[e.jsx(yr,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-5 mb-6",children:s.review_snippet&&e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(ua,{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(mye,{card:s,variant:"bold"}),e.jsx(fye,{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(Da,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{pl(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(ua,{className:"h-4 w-4",style:{color:o.accent}})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:v,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(_n,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:j,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Fo,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),e.jsxs("button",{onClick:b,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Hl,{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((L,M)=>e.jsx("a",{href:L.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>pl(s.id,"button_click",`social_${L.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:_[L.platform.toLowerCase()]||"🔗"},M))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(pye,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function nBt({card:s}){var j;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(_=>_[0]).join("").toUpperCase().slice(0,2),o=(_,S)=>{pl(s.id,"button_click",_),S()},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),pl(s.id,"button_click","book"))},p=()=>{var _,S;pl(s.id,"contact_saved"),xye({name:i,phone:(_=s.profile)==null?void 0:_.phone,email:(S=s.profile)==null?void 0:S.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{pl(s.id,"share_event");const _=`https://cards.relevelup.com/${s.slug}`,S="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:S,url:_})}catch{}else await navigator.clipboard.writeText(_),ae.success("Link copied!")},g=()=>{a("referral"),n(!0),pl(s.id,"button_click","refer")},b=()=>{a("connect"),n(!0),pl(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[e.jsx("div",{className:"bg-[#1b3a4b] h-2"}),e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(aa,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(ri,{src:s.avatar_url||void 0,alt:i}),e.jsx(ia,{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:Pr,label:"Call",handler:c},{icon:Ci,label:"Text",handler:d},{icon:Hs,label:"Email",handler:u}].map(({icon:_,label:S,handler:A})=>e.jsxs("button",{onClick:A,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[e.jsx(_,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:S})]},S))}),e.jsxs("button",{onClick:h,className:"w-full h-12 text-base font-semibold rounded-lg mb-6 bg-[#1b3a4b] hover:bg-[#264d61] text-white transition-colors flex items-center justify-center gap-2 shadow-sm",children:[e.jsx(yr,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:e.jsx("div",{className:"flex items-center justify-center gap-6",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(ua,{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(mye,{card:s,variant:"classic"}),e.jsx(fye,{cardId:s.id,variant:"classic"}),e.jsxs("div",{className:"bg-white rounded-lg border border-[#d4cfc5] shadow-sm divide-y divide-[#e8e3db] mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Da,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{pl(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(ua,{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(_n,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),e.jsxs("button",{onClick:b,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Fo,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Hl,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((_,S)=>e.jsx("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>pl(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:v[_.platform.toLowerCase()]||"🔗"},S))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(pye,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function aMe({card:s}){switch(s.theme){case"luxury":return e.jsx(tBt,{card:s});case"bold":return e.jsx(sBt,{card:s});case"classic":return e.jsx(nBt,{card:s});case"standard":default:return e.jsx(eBt,{card:s})}}function rBt(){const s=Jl();N.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Agent Cards"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific agent's card URL to view their digital business card."})]})}):e.jsx(aBt,{slug:t})}function aBt({slug:s}){return e.jsx(iBt,{slug:s})}function iBt({slug:s}){var i;const{data:t,isLoading:n,error:r}=jct(s);if(N.useEffect(()=>{t!=null&&t.id&&pl(t.id,"card_view")},[t==null?void 0:t.id]),n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Ws,{className:"h-28 w-28 rounded-full"}),e.jsx(Ws,{className:"h-6 w-48"}),e.jsx(Ws,{className:"h-4 w-36"})]}),e.jsx(Ws,{className:"h-12 w-full"}),e.jsx(Ws,{className:"h-12 w-full"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsxs("title",{children:[a," | Real Estate Agent"]}),e.jsx("meta",{name:"description",content:t.positioning_statement||`Connect with ${a}, your trusted real estate professional.`}),e.jsx("meta",{property:"og:title",content:`${a} | Real Estate Agent`}),e.jsx("meta",{property:"og:description",content:t.positioning_statement||`Connect with ${a}`}),t.avatar_url&&e.jsx("meta",{property:"og:image",content:t.avatar_url})]}),e.jsx(aMe,{card:t})]})}function Cct({presentationId:s,ctaLabel:t,agentName:n,prefillName:r,prefillEmail:a,prefillPhone:i}){const[l,o]=N.useState(r||""),[c,d]=N.useState(a||""),[u,h]=N.useState(i||""),[p,f]=N.useState(""),[g,b]=N.useState(""),[v,j]=N.useState(!1),[_,S]=N.useState(!1),A=async T=>{if(T.preventDefault(),!l.trim()){ae.error("Please enter your name");return}j(!0);try{const{error:D}=await q.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:p||null,message:g.trim()||null});if(D)throw D;try{await q.rpc("log_presentation_view",{p_presentation_id:s,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}q.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:p||void 0,message:g.trim()||void 0}}).catch(L=>console.error("Presentation lead notify failed:",L)),S(!0)}catch{ae.error("Something went wrong. Please try again.")}finally{j(!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(Lr,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),e.jsx("p",{className:"text-gray-500",children:n?`${n} will be in touch soon.`:"We'll be in touch soon."})]}):e.jsxs("form",{onSubmit:A,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(ge,{id:"pres-lead-name",value:l,onChange:T=>o(T.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(ge,{id:"pres-lead-phone",type:"tel",value:u,onChange:T=>h(T.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(ge,{id:"pres-lead-email",type:"email",value:c,onChange:T=>d(T.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(us,{value:p,onValueChange:f,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select one"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"buy",children:"Buy a home"}),e.jsx(Ze,{value:"sell",children:"Sell my home"}),e.jsx(Ze,{value:"both",children:"Buy & Sell"}),e.jsx(Ze,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(ge,{id:"pres-lead-message",value:g,onChange:T=>b(T.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx(B,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:v,children:v?"Sending...":t})]})}function oBt(){const s=Jl();N.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Smart Presentations"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific presentation URL to view it."})]})}):e.jsx(lBt,{shareToken:t})}function lBt({shareToken:s}){var g;const[t,n]=N.useState(null),[r,a]=N.useState(!0),[i,l]=N.useState(0),[o,c]=N.useState(!1);N.useEffect(()=>{d()},[s]);const d=async()=>{const{data:b,error:v}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(v||!b){c(!0),a(!1);return}const{data:j}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",b.owner_user_id).single();let _;if(j!=null&&j.brokerage_id){const{data:A}=await q.from("brokerages").select("name").eq("id",j.brokerage_id).single();_=(A==null?void 0:A.name)||void 0}let S=null;if(b.contact_id){const{data:A}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",b.contact_id).single();S=A}n({...b,owner_name:j==null?void 0:j.name,owner_email:j==null?void 0:j.email,owner_phone:j==null?void 0:j.phone,owner_avatar:j==null?void 0:j.avatar_url,owner_title:(j==null?void 0:j.title)||void 0,brokerage_name:_,contact_name:S?[S.first_name,S.last_name].filter(Boolean).join(" "):void 0,contact_email:(S==null?void 0:S.email)||void 0,contact_phone:(S==null?void 0:S.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:b.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}},h=b=>{const v=b.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(v)return`https://www.youtube.com/embed/${v[1]}?rel=0`;if(b.includes("iframe.mediadelivery.net/play/")){const S=b.replace("/play/","/embed/"),A=S.includes("?")?"&":"?";return`${S}${A}responsive=true`}if(b.includes("iframe.mediadelivery.net")){const S=b.includes("?")?"&":"?";return`${b}${S}responsive=true`}const j=b.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(j)return`https://www.loom.com/embed/${j[1]}`;const _=b.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return _?`https://iframe.mediadelivery.net/embed/${_[1]}/${_[2]}?responsive=true`:b};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(Ws,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const p=t.sections.filter(b=>b.is_visible!==!1),f=p[i];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[f!=null&&f.video_url?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:h(f.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):f!=null&&f.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:f.image_url,alt:f.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:f==null?void 0:f.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:f==null?void 0:f.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:f==null?void 0:f.description})]}),(f==null?void 0:f.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:f.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:p.map((b,v)=>e.jsx("button",{onClick:()=>l(v),className:Et("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:b.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:b.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:b.description})]})]})},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=t.cta_url)!=null&&g.trim()?e.jsxs(B,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(tr,{className:"h-5 w-5 ml-2"})]}):e.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:e.jsx(Cct,{presentationId:t.id,ctaLabel:t.cta_label,agentName:t.owner_name||void 0,prefillName:t.contact_name,prefillEmail:t.contact_email,prefillPhone:t.contact_phone})})]})]}),e.jsx("footer",{className:"border-t border-gray-100 bg-white mt-12 py-6 text-center text-xs text-gray-400",children:"Powered by LevelUp"})]})}const Xv=()=>{const s=fa();return lt({queryKey:["user-team",s],queryFn:async()=>{const{data:t,error:n}=await q.from("team_members").select("id, team_id, role").eq("user_id",s).maybeSingle();if(console.log("[useUserTeam] membership query:",{userId:s,membership:t,error:n}),n)throw n;if(!t)return null;const{data:r,error:a}=await q.from("teams").select("*").eq("id",t.team_id).single();if(a)throw a;return{membershipId:t.id,teamId:t.team_id,role:t.role,team:r}},enabled:!!s,staleTime:5*60*1e3})};function cBt(){const{user:s}=gs(),t=fa(),{data:n}=Xv();return lt({queryKey:["open-houses",t,n==null?void 0:n.teamId,n==null?void 0:n.role],queryFn:async()=>{const{data:r,error:a}=await q.from("open_houses").select("*").eq("agent_id",t).order("event_date",{ascending:!1});if(a)throw a;let i=r||[];if((n==null?void 0:n.role)==="team_leader"&&n.teamId){const{data:l,error:o}=await q.rpc("get_team_open_houses",{_user_id:t});if(!o&&l){const c=[...new Set(l.map(h=>h.agent_id))],d={};if(c.length>0){const{data:h}=await q.from("profiles").select("id, name").in("id",c);h==null||h.forEach(p=>{p.name&&(d[p.id]=p.name)})}const u=l.map(h=>({...h,agent_name:d[h.agent_id]||void 0}));i=[...i,...u]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function Vxn(s){const{user:t}=gs();return lt({queryKey:["open-house",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_houses").select("*").eq("id",s).single();if(r)throw r;return n},enabled:!!t&&!!s})}function Tct(s){const{user:t}=gs(),n=Gt();return N.useEffect(()=>{if(!s)return;const r=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=q.channel(r).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${s}`},()=>{n.invalidateQueries({queryKey:["open-house-visitors",s]}),n.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{q.removeChannel(a)}},[s,n]),lt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:r,error:a}=await q.from("open_house_visitors").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(a)throw a;return r},enabled:!!t&&!!s})}function dBt(){const s=Gt(),t=fa();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("open_houses").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),Dr({title:"Open house created!"})},onError:n=>{Dr({title:"Error",description:n.message,variant:"destructive"})}})}function Ect(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{error:r}=await q.from("open_houses").update(n).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-houses"]}),s.invalidateQueries({queryKey:["open-house",n.id]})}})}function uBt(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("open_houses").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),Dr({title:"Open house deleted"})}})}function hBt(s){return lt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",s).eq("is_active",!0).single();if(n)throw n;let r=null;if(t.agent_id){const{data:a}=await q.from("agent_cards").select("slug").eq("user_id",t.agent_id).eq("is_published",!0).maybeSingle();a&&(r=a.slug)}return{...t,agent_card_slug:r}},enabled:!!s})}function mBt(s){const{user:t}=gs();return lt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;return n},enabled:!!t&&!!s})}function pBt(s){return lt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).eq("is_active",!0).order("sort_order");if(n)throw n;return t},enabled:!!s})}function fBt(){return gt({mutationFn:async s=>{const{error:t}=await q.from("open_house_survey_responses").insert(s);if(t)throw t}})}function xBt(s){const{user:t}=gs();return lt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;const a=(n||[]).map(o=>o.id);if(a.length===0)return{questions:[],responses:[]};const{data:i,error:l}=await q.from("open_house_survey_responses").select("*").in("question_id",a).order("created_at",{ascending:!1});if(l)throw l;return{questions:n,responses:i||[]}},enabled:!!t&&!!s})}function gBt(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("open_house_survey_questions").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function yBt(){const s=Gt();return gt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await q.from("open_house_survey_questions").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function vBt(){const s=Gt();return gt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_survey_questions").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function bBt(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.rpc("seed_default_survey_questions",{_open_house_id:t});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n]})}})}function _Bt(){return gt({mutationFn:async s=>{const{data:t,error:n}=await q.from("open_house_visitors").insert(s).select("id").single();if(n)throw n;return t}})}function wBt(){return gt({mutationFn:async({visitor_id:s,...t})=>{const{error:n}=await q.from("open_house_visitors").update(t).eq("id",s);if(n)throw n}})}function jBt(){return gt({mutationFn:async s=>{await q.rpc("increment_open_house_scan",{_slug:s})}})}async function Act(s){const{data:t,error:n}=await q.from("open_house_rooms").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(c=>c.id),{data:i,error:l}=await q.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var u;const d=c;(o[u=d.room_id]||(o[u]=[])).push(d)}),r.map(c=>({...c,media:o[c.id]||[]}))}function NBt(s){const{user:t}=gs();return lt({queryKey:["open-house-rooms",s],queryFn:()=>Act(s),enabled:!!t&&!!s})}function kBt(s){return lt({queryKey:["public-open-house-rooms",s],queryFn:()=>Act(s),enabled:!!s})}function SBt(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("open_house_rooms").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function CBt(){const s=Gt();return gt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await q.from("open_house_rooms").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function TBt(){const s=Gt();return gt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_rooms").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function EBt(){const s=Gt();return gt({mutationFn:async({open_house_id:t,...n})=>{const{data:r,error:a}=await q.from("open_house_room_media").insert(n).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function ABt(){const s=Gt();return gt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_room_media").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function MBt(s){const{user:t}=gs();return lt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_leads").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n||[]},enabled:!!t&&!!s})}function IBt(){const s=Gt();return gt({mutationFn:async({id:t,status:n,open_house_id:r})=>{const{error:a}=await q.from("open_house_leads").update({status:n}).eq("id",t);if(a)throw a;return{open_house_id:r}},onSuccess:t=>{s.invalidateQueries({queryKey:["open-house-leads",t.open_house_id]})}})}var gye="Switch",[PBt,Hxn]=gu(gye),[LBt,DBt]=PBt(gye),Mct=N.forwardRef((s,t)=>{const{__scopeSwitch:n,name:r,checked:a,defaultChecked:i,required:l,disabled:o,value:c="on",onCheckedChange:d,form:u,...h}=s,[p,f]=N.useState(null),g=Ti(t,S=>f(S)),b=N.useRef(!1),v=p?u||!!p.closest("form"):!0,[j,_]=mm({prop:a,defaultProp:i??!1,onChange:d,caller:gye});return e.jsxs(LBt,{scope:n,checked:j,disabled:o,children:[e.jsx(sa.button,{type:"button",role:"switch","aria-checked":j,"aria-required":l,"data-state":Dct(j),"data-disabled":o?"":void 0,disabled:o,value:c,...h,ref:g,onClick:wr(s.onClick,S=>{_(A=>!A),v&&(b.current=S.isPropagationStopped(),b.current||S.stopPropagation())})}),v&&e.jsx(Lct,{control:p,bubbles:!b.current,name:r,value:c,checked:j,required:l,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});Mct.displayName=gye;var Ict="SwitchThumb",Pct=N.forwardRef((s,t)=>{const{__scopeSwitch:n,...r}=s,a=DBt(Ict,n);return e.jsx(sa.span,{"data-state":Dct(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});Pct.displayName=Ict;var RBt="SwitchBubbleInput",Lct=N.forwardRef(({__scopeSwitch:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=N.useRef(null),o=Ti(l,i),c=rU(n),d=q$(t);return N.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&f){const g=new Event("click",{bubbles:r});f.call(u,n),u.dispatchEvent(g)}},[c,n,r]),e.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Lct.displayName=RBt;function Dct(s){return s?"checked":"unchecked"}var Rct=Mct,OBt=Pct;const vn=N.forwardRef(({className:s,...t},n)=>e.jsx(Rct,{className:Et("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(OBt,{className:Et("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")})}));vn.displayName=Rct.displayName;function ti(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 Ic(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Ul(s,t){const n=ti(s);return isNaN(t)?Ic(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function kf(s,t){const n=ti(s);if(isNaN(t))return Ic(s,NaN);if(!t)return n;const r=n.getDate(),a=Ic(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 Oct(s,t){const n=+ti(s);return Ic(s,n+t)}const iMe=6048e5,FBt=864e5,yye=6e4,vye=36e5,zBt=1e3,nH=43200,fBe=1440;function xBe(s,t){return Oct(s,t*vye)}let BBt={};function Q4(){return BBt}function Km(s,t){var o,c,d,u;const n=Q4(),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=ti(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function Sf(s){const t=ti(s);return t.setHours(0,0,0,0),t}function P4(s){const t=ti(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 Wx(s,t){const n=Sf(s),r=Sf(t),a=+n-P4(n),i=+r-P4(r);return Math.round((a-i)/FBt)}function $Bt(s){const t=Fct(s),n=Ic(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),fN(n)}function CP(s,t){return Oct(s,t*yye)}function F2(s,t){const n=t*7;return Ul(s,n)}function UBt(s,t){return kf(s,t*12)}function qBt(s){let t;return s.forEach(function(n){const r=ti(n);(t===void 0||t{const r=ti(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function Lme(s,t){const n=ti(s),r=ti(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function bye(s){return Ic(s,Date.now())}function Rl(s,t){const n=Sf(s),r=Sf(t);return+n==+r}function oMe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function z4e(s){if(!oMe(s)&&typeof s!="number")return!1;const t=ti(s);return!isNaN(Number(t))}function N8(s,t){const n=ti(s),r=ti(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function HBt(s,t,n){const r=Km(s,n),a=Km(t,n),i=+r-P4(r),l=+a-P4(a);return Math.round((i-l)/iMe)}function Yv(s,t){const n=ti(s),r=ti(t),a=gBe(n,r),i=Math.abs(Wx(n,r));n.setDate(n.getDate()-a*i);const l=+(gBe(n,r)===-a),o=a*(i-l);return o===0?0:o}function gBe(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 GBt(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function WBt(s,t){return+ti(s)-+ti(t)}function KBt(s){const t=ti(s);return t.setHours(23,59,59,999),t}function H0(s){const t=ti(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function YBt(s){const t=ti(s);return+KBt(t)==+H0(t)}function ZBt(s,t){const n=ti(s),r=ti(t),a=Lme(n,r),i=Math.abs(N8(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=Lme(n,r)===-a;YBt(ti(s))&&i===1&&Lme(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function QBt(s,t,n){const r=WBt(s,t)/1e3;return GBt(n==null?void 0:n.roundingMethod)(r)}function B4e(s,t){const n=ti(s.start),r=ti(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(ti(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function Bd(s){const t=ti(s);return t.setDate(1),t.setHours(0,0,0,0),t}function zct(s){const t=ti(s),n=Ic(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function k8(s,t){var o,c,d,u;const n=Q4(),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=ti(s),i=a.getDay(),l=(i{let r;const a=XBt[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 hje(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const e$t={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},t$t={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},s$t={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},n$t={date:hje({formats:e$t,defaultWidth:"full"}),time:hje({formats:t$t,defaultWidth:"full"}),dateTime:hje({formats:s$t,defaultWidth:"full"})},r$t={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},a$t=(s,t,n,r)=>r$t[s];function lF(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 i$t={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},o$t={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},l$t={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"]},c$t={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"]},d$t={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"}},u$t={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"}},h$t=(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"},m$t={ordinalNumber:h$t,era:lF({values:i$t,defaultWidth:"wide"}),quarter:lF({values:o$t,defaultWidth:"wide",argumentCallback:s=>s-1}),month:lF({values:l$t,defaultWidth:"wide"}),day:lF({values:c$t,defaultWidth:"wide"}),dayPeriod:lF({values:d$t,defaultWidth:"wide",formattingValues:u$t,defaultFormattingWidth:"wide"})};function cF(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)?f$t(o,h=>h.test(l)):p$t(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 p$t(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function f$t(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 g$t=/^(\d+)(th|st|nd|rd)?/i,y$t=/\d+/i,v$t={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},b$t={any:[/^b/i,/^(a|c)/i]},_$t={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},w$t={any:[/1/i,/2/i,/3/i,/4/i]},j$t={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},N$t={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]},k$t={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},S$t={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]},C$t={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},T$t={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}},E$t={ordinalNumber:x$t({matchPattern:g$t,parsePattern:y$t,valueCallback:s=>parseInt(s,10)}),era:cF({matchPatterns:v$t,defaultMatchWidth:"wide",parsePatterns:b$t,defaultParseWidth:"any"}),quarter:cF({matchPatterns:_$t,defaultMatchWidth:"wide",parsePatterns:w$t,defaultParseWidth:"any",valueCallback:s=>s+1}),month:cF({matchPatterns:j$t,defaultMatchWidth:"wide",parsePatterns:N$t,defaultParseWidth:"any"}),day:cF({matchPatterns:k$t,defaultMatchWidth:"wide",parsePatterns:S$t,defaultParseWidth:"any"}),dayPeriod:cF({matchPatterns:C$t,defaultMatchWidth:"any",parsePatterns:T$t,defaultParseWidth:"any"})},_ye={code:"en-US",formatDistance:JBt,formatLong:n$t,formatRelative:a$t,localize:m$t,match:E$t,options:{weekStartsOn:0,firstWeekContainsDate:1}};function A$t(s){const t=ti(s);return Wx(t,zct(t))+1}function lMe(s){const t=ti(s),n=+fN(t)-+$Bt(t);return Math.round(n/iMe)+1}function cMe(s,t){var u,h,p,f;const n=ti(s),r=n.getFullYear(),a=Q4(),i=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??a.firstWeekContainsDate??((f=(p=a.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,l=Ic(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=Km(l,t),c=Ic(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=Km(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function M$t(s,t){var o,c,d,u;const n=Q4(),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=cMe(s,t),i=Ic(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),Km(i,t)}function dMe(s,t){const n=ti(s),r=+Km(n,t)-+M$t(n,t);return Math.round(r/iMe)+1}function Tc(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const Sk={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return Tc(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):Tc(n+1,2)},d(s,t){return Tc(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 Tc(s.getHours()%12||12,t.length)},H(s,t){return Tc(s.getHours(),t.length)},m(s,t){return Tc(s.getMinutes(),t.length)},s(s,t){return Tc(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return Tc(a,t.length)}},wI={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},yBe={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 Sk.y(s,t)},Y:function(s,t,n,r){const a=cMe(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return Tc(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Tc(i,t.length)},R:function(s,t){const n=Fct(s);return Tc(n,t.length)},u:function(s,t){const n=s.getFullYear();return Tc(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 Tc(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 Tc(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 Sk.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 Tc(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=dMe(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):Tc(a,t.length)},I:function(s,t,n){const r=lMe(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Tc(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):Sk.d(s,t)},D:function(s,t,n){const r=A$t(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Tc(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 Tc(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 Tc(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 Tc(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=wI.noon:r===0?a=wI.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=wI.evening:r>=12?a=wI.afternoon:r>=4?a=wI.morning:a=wI.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 Sk.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):Sk.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Tc(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Tc(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):Sk.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):Sk.s(s,t)},S:function(s,t){return Sk.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return bBe(r);case"XXXX":case"XX":return ME(r);case"XXXXX":case"XXX":default:return ME(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return bBe(r);case"xxxx":case"xx":return ME(r);case"xxxxx":case"xxx":default:return ME(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+vBe(r,":");case"OOOO":default:return"GMT"+ME(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+vBe(r,":");case"zzzz":default:return"GMT"+ME(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return Tc(r,t.length)},T:function(s,t,n){const r=s.getTime();return Tc(r,t.length)}};function vBe(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+Tc(i,2)}function bBe(s,t){return s%60===0?(s>0?"-":"+")+Tc(Math.abs(s)/60,2):ME(s,t)}function ME(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Tc(Math.trunc(r/60),2),i=Tc(r%60,2);return n+a+t+i}const _Be=(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"})}},$ct=(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"})}},I$t=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return _Be(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}}",_Be(r,t)).replace("{{time}}",$ct(a,t))},$4e={p:$ct,P:I$t},P$t=/^D+$/,L$t=/^Y+$/,D$t=["D","DD","YY","YYYY"];function Uct(s){return P$t.test(s)}function qct(s){return L$t.test(s)}function U4e(s,t,n){const r=R$t(s,t,n);if(console.warn(r),D$t.includes(s))throw new RangeError(r)}function R$t(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 O$t=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,F$t=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,z$t=/^'([^]*?)'?$/,B$t=/''/g,$$t=/[a-zA-Z]/;function ks(s,t,n){var u,h,p,f,g,b,v,j;const r=Q4(),a=(n==null?void 0:n.locale)??r.locale??_ye,i=(n==null?void 0:n.firstWeekContainsDate)??((h=(u=n==null?void 0:n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((f=(p=r.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,l=(n==null?void 0:n.weekStartsOn)??((b=(g=n==null?void 0:n.locale)==null?void 0:g.options)==null?void 0:b.weekStartsOn)??r.weekStartsOn??((j=(v=r.locale)==null?void 0:v.options)==null?void 0:j.weekStartsOn)??0,o=ti(s);if(!z4e(o))throw new RangeError("Invalid time value");let c=t.match(F$t).map(_=>{const S=_[0];if(S==="p"||S==="P"){const A=$4e[S];return A(_,a.formatLong)}return _}).join("").match(O$t).map(_=>{if(_==="''")return{isToken:!1,value:"'"};const S=_[0];if(S==="'")return{isToken:!1,value:U$t(_)};if(yBe[S])return{isToken:!0,value:_};if(S.match($$t))throw new RangeError("Format string contains an unescaped latin alphabet character `"+S+"`");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 S=_.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&qct(S)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&Uct(S))&&U4e(S,t,String(s));const A=yBe[S[0]];return A(o,S,a.localize,d)}).join("")}function U$t(s){const t=s.match(z$t);return t?t[1].replace(B$t,"'"):s}function q$t(s,t,n){const r=Q4(),a=(n==null?void 0:n.locale)??r.locale??_ye,i=2520,l=Lme(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=ti(t),d=ti(s)):(c=ti(s),d=ti(t));const u=QBt(d,c),h=(P4(d)-P4(c))/1e3,p=Math.round((u-h)/60);let f;if(p<2)return n!=null&&n.includeSeconds?u<5?a.formatDistance("lessThanXSeconds",5,o):u<10?a.formatDistance("lessThanXSeconds",10,o):u<20?a.formatDistance("lessThanXSeconds",20,o):u<40?a.formatDistance("halfAMinute",0,o):u<60?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",1,o):p===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",p,o);if(p<45)return a.formatDistance("xMinutes",p,o);if(p<90)return a.formatDistance("aboutXHours",1,o);if(pr.getTime()}function jb(s,t){const n=ti(s),r=ti(t);return+n<+r}function Z$t(s){return+ti(s)>Date.now()}function Q$t(s,t){const n=t instanceof Date?Ic(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 X$t=10;class Vct{constructor(){Pa(this,"subPriority",0)}validate(t,n){return!0}}class J$t extends Vct{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 eUt extends Vct{constructor(){super(...arguments);Pa(this,"priority",X$t);Pa(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:Ic(n,Q$t(n,Date))}}class dc{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new J$t(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class tUt extends dc{constructor(){super(...arguments);Pa(this,"priority",140);Pa(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 Lh={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}/},tw={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 Dh(s,t){return s&&{value:t(s.value),rest:s.rest}}function Ru(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function sw(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*vye+i*yye+l*zBt),rest:t.slice(n[0].length)}}function Hct(s){return Ru(Lh.anyDigitsSigned,s)}function xh(s,t){switch(s){case 1:return Ru(Lh.singleDigit,t);case 2:return Ru(Lh.twoDigits,t);case 3:return Ru(Lh.threeDigits,t);case 4:return Ru(Lh.fourDigits,t);default:return Ru(new RegExp("^\\d{1,"+s+"}"),t)}}function ufe(s,t){switch(s){case 1:return Ru(Lh.singleDigitSigned,t);case 2:return Ru(Lh.twoDigitsSigned,t);case 3:return Ru(Lh.threeDigitsSigned,t);case 4:return Ru(Lh.fourDigitsSigned,t);default:return Ru(new RegExp("^-?\\d{1,"+s+"}"),t)}}function uMe(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 Gct(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 Wct(s){return s%400===0||s%4===0&&s%100!==0}class sUt extends dc{constructor(){super(...arguments);Pa(this,"priority",130);Pa(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 Dh(xh(4,n),i);case"yo":return Dh(a.ordinalNumber(n,{unit:"year"}),i);default:return Dh(xh(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=Gct(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 nUt extends dc{constructor(){super(...arguments);Pa(this,"priority",130);Pa(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 Dh(xh(4,n),i);case"Yo":return Dh(a.ordinalNumber(n,{unit:"year"}),i);default:return Dh(xh(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=cMe(n,i);if(a.isTwoDigitYear){const c=Gct(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),Km(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),Km(n,i)}}class rUt extends dc{constructor(){super(...arguments);Pa(this,"priority",130);Pa(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return ufe(r==="R"?4:r.length,n)}set(n,r,a){const i=Ic(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),fN(i)}}class aUt extends dc{constructor(){super(...arguments);Pa(this,"priority",130);Pa(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return ufe(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class iUt extends dc{constructor(){super(...arguments);Pa(this,"priority",120);Pa(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 xh(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 oUt extends dc{constructor(){super(...arguments);Pa(this,"priority",120);Pa(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 xh(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 lUt extends dc{constructor(){super(...arguments);Pa(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Pa(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return Dh(Ru(Lh.month,n),i);case"MM":return Dh(xh(2,n),i);case"Mo":return Dh(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 cUt extends dc{constructor(){super(...arguments);Pa(this,"priority",110);Pa(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 Dh(Ru(Lh.month,n),i);case"LL":return Dh(xh(2,n),i);case"Lo":return Dh(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 dUt(s,t,n){const r=ti(s),a=dMe(r,n)-t;return r.setDate(r.getDate()-a*7),r}class uUt extends dc{constructor(){super(...arguments);Pa(this,"priority",100);Pa(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return Ru(Lh.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return xh(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return Km(dUt(n,a,i),i)}}function hUt(s,t){const n=ti(s),r=lMe(n)-t;return n.setDate(n.getDate()-r*7),n}class mUt extends dc{constructor(){super(...arguments);Pa(this,"priority",100);Pa(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 Ru(Lh.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return xh(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return fN(hUt(n,a))}}const pUt=[31,28,31,30,31,30,31,31,30,31,30,31],fUt=[31,29,31,30,31,30,31,31,30,31,30,31];class xUt extends dc{constructor(){super(...arguments);Pa(this,"priority",90);Pa(this,"subPriority",1);Pa(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return Ru(Lh.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return xh(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=Wct(a),l=n.getMonth();return i?r>=1&&r<=fUt[l]:r>=1&&r<=pUt[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class gUt extends dc{constructor(){super(...arguments);Pa(this,"priority",90);Pa(this,"subpriority",1);Pa(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 Ru(Lh.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return xh(r.length,n)}}validate(n,r){const a=n.getFullYear();return Wct(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 hMe(s,t,n){var h,p,f,g;const r=Q4(),a=(n==null?void 0:n.weekStartsOn)??((p=(h=n==null?void 0:n.locale)==null?void 0:h.options)==null?void 0:p.weekStartsOn)??r.weekStartsOn??((g=(f=r.locale)==null?void 0:f.options)==null?void 0:g.weekStartsOn)??0,i=ti(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 Ul(i,u)}class yUt extends dc{constructor(){super(...arguments);Pa(this,"priority",90);Pa(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=hMe(n,a,i),n.setHours(0,0,0,0),n}}class vUt extends dc{constructor(){super(...arguments);Pa(this,"priority",90);Pa(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 Dh(xh(r.length,n),l);case"eo":return Dh(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=hMe(n,a,i),n.setHours(0,0,0,0),n}}class bUt extends dc{constructor(){super(...arguments);Pa(this,"priority",90);Pa(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 Dh(xh(r.length,n),l);case"co":return Dh(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=hMe(n,a,i),n.setHours(0,0,0,0),n}}function _Ut(s,t){const n=ti(s),r=G$t(n),a=t-r;return Ul(n,a)}class wUt extends dc{constructor(){super(...arguments);Pa(this,"priority",90);Pa(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 xh(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return Dh(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 Dh(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return Dh(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return Dh(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=_Ut(n,a),n.setHours(0,0,0,0),n}}class jUt extends dc{constructor(){super(...arguments);Pa(this,"priority",80);Pa(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(uMe(a),0,0,0),n}}class NUt extends dc{constructor(){super(...arguments);Pa(this,"priority",80);Pa(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(uMe(a),0,0,0),n}}class kUt extends dc{constructor(){super(...arguments);Pa(this,"priority",80);Pa(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(uMe(a),0,0,0),n}}class SUt extends dc{constructor(){super(...arguments);Pa(this,"priority",70);Pa(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Ru(Lh.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return xh(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 CUt extends dc{constructor(){super(...arguments);Pa(this,"priority",70);Pa(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return Ru(Lh.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return xh(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class TUt extends dc{constructor(){super(...arguments);Pa(this,"priority",70);Pa(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Ru(Lh.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return xh(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 EUt extends dc{constructor(){super(...arguments);Pa(this,"priority",70);Pa(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return Ru(Lh.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return xh(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 AUt extends dc{constructor(){super(...arguments);Pa(this,"priority",60);Pa(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Ru(Lh.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return xh(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class MUt extends dc{constructor(){super(...arguments);Pa(this,"priority",50);Pa(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Ru(Lh.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return xh(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class IUt extends dc{constructor(){super(...arguments);Pa(this,"priority",30);Pa(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return Dh(xh(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class PUt extends dc{constructor(){super(...arguments);Pa(this,"priority",10);Pa(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return sw(tw.basicOptionalMinutes,n);case"XX":return sw(tw.basic,n);case"XXXX":return sw(tw.basicOptionalSeconds,n);case"XXXXX":return sw(tw.extendedOptionalSeconds,n);case"XXX":default:return sw(tw.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Ic(n,n.getTime()-P4(n)-a)}}class LUt extends dc{constructor(){super(...arguments);Pa(this,"priority",10);Pa(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return sw(tw.basicOptionalMinutes,n);case"xx":return sw(tw.basic,n);case"xxxx":return sw(tw.basicOptionalSeconds,n);case"xxxxx":return sw(tw.extendedOptionalSeconds,n);case"xxx":default:return sw(tw.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Ic(n,n.getTime()-P4(n)-a)}}class DUt extends dc{constructor(){super(...arguments);Pa(this,"priority",40);Pa(this,"incompatibleTokens","*")}parse(n){return Hct(n)}set(n,r,a){return[Ic(n,a*1e3),{timestampIsSet:!0}]}}class RUt extends dc{constructor(){super(...arguments);Pa(this,"priority",20);Pa(this,"incompatibleTokens","*")}parse(n){return Hct(n)}set(n,r,a){return[Ic(n,a),{timestampIsSet:!0}]}}const OUt={G:new tUt,y:new sUt,Y:new nUt,R:new rUt,u:new aUt,Q:new iUt,q:new oUt,M:new lUt,L:new cUt,w:new uUt,I:new mUt,d:new xUt,D:new gUt,E:new yUt,e:new vUt,c:new bUt,i:new wUt,a:new jUt,b:new NUt,B:new kUt,h:new SUt,H:new CUt,K:new TUt,k:new EUt,m:new AUt,s:new MUt,S:new IUt,X:new PUt,x:new LUt,t:new DUt,T:new RUt},FUt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,zUt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,BUt=/^'([^]*?)'?$/,$Ut=/''/g,UUt=/\S/,qUt=/[a-zA-Z]/;function mMe(s,t,n,r){var b,v,j,_;const a=H$t(),i=a.locale??_ye,l=a.firstWeekContainsDate??((v=(b=a.locale)==null?void 0:b.options)==null?void 0:v.firstWeekContainsDate)??1,o=a.weekStartsOn??((_=(j=a.locale)==null?void 0:j.options)==null?void 0:_.weekStartsOn)??0;if(t==="")return s===""?ti(n):Ic(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new eUt],u=t.match(zUt).map(S=>{const A=S[0];if(A in $4e){const T=$4e[A];return T(S,i.formatLong)}return S}).join("").match(FUt),h=[];for(let S of u){qct(S)&&U4e(S,t,s),Uct(S)&&U4e(S,t,s);const A=S[0],T=OUt[A];if(T){const{incompatibleTokens:D}=T;if(Array.isArray(D)){const M=h.find(F=>D.includes(F.token)||F.token===A);if(M)throw new RangeError(`The format string mustn't contain \`${M.fullToken}\` and \`${S}\` at the same time`)}else if(T.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${S}\` and any other token at the same time`);h.push({token:A,fullToken:S});const L=T.run(s,S,i.match,c);if(!L)return Ic(n,NaN);d.push(L.setter),s=L.rest}else{if(A.match(qUt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+A+"`");if(S==="''"?S="'":A==="'"&&(S=VUt(S)),s.indexOf(S)===0)s=s.slice(S.length);else return Ic(n,NaN)}}if(s.length>0&&UUt.test(s))return Ic(n,NaN);const p=d.map(S=>S.priority).sort((S,A)=>A-S).filter((S,A,T)=>T.indexOf(S)===A).map(S=>d.filter(A=>A.priority===S).sort((A,T)=>T.subPriority-A.subPriority)).map(S=>S[0]);let f=ti(n);if(isNaN(f.getTime()))return Ic(n,NaN);const g={};for(const S of p){if(!S.validate(f,c))return Ic(n,NaN);const A=S.set(f,g,c);Array.isArray(A)?(f=A[0],Object.assign(g,A[1])):f=A}return Ic(n,f)}function VUt(s){return s.match(BUt)[1].replace($Ut,"'")}function jw(s){return+ti(s)i-l);return n>=r&&n<=a}function Y9(s,t){return Ul(s,-t)}function Lu(s,t){const r=XUt(s);let a;if(r.date){const c=JUt(r.date,2);a=eqt(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=tqt(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=sqt(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 rH={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},YUt=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,ZUt=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,QUt=/^([+-])(\d{2})(?::?(\d{2}))?$/;function XUt(s){const t={},n=s.split(rH.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],rH.timeZoneDelimiter.test(t.date)&&(t.date=s.split(rH.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=rH.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function JUt(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 eqt(s,t){if(t===null)return new Date(NaN);const n=s.match(YUt);if(!n)return new Date(NaN);const r=!!n[4],a=dF(n[1]),i=dF(n[2])-1,l=dF(n[3]),o=dF(n[4]),c=dF(n[5])-1;if(r)return oqt(t,o,c)?nqt(t,o,c):new Date(NaN);{const d=new Date(0);return!aqt(t,i,l)||!iqt(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function dF(s){return s?parseInt(s):1}function tqt(s){const t=s.match(ZUt);if(!t)return NaN;const n=mje(t[1]),r=mje(t[2]),a=mje(t[3]);return lqt(n,r,a)?n*vye+r*yye+a*1e3:NaN}function mje(s){return s&&parseFloat(s.replace(",","."))||0}function sqt(s){if(s==="Z")return 0;const t=s.match(QUt);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return cqt(r,a)?n*(r*vye+a*yye):NaN}function nqt(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 rqt=[31,null,31,30,31,30,31,31,30,31,30,31];function Kct(s){return s%400===0||s%4===0&&s%100!==0}function aqt(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(rqt[t]||(Kct(s)?29:28))}function iqt(s,t){return t>=1&&t<=(Kct(s)?366:365)}function oqt(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function lqt(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function cqt(s,t){return t>=0&&t<=59}function pje(s,t){const n=ti(s),r=n.getFullYear(),a=n.getDate(),i=Ic(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=V$t(i);return n.setMonth(t,Math.min(a,l)),n}function Z9(s,t){const n=ti(s);return n.setHours(t),n}function Q9(s,t){const n=ti(s);return n.setMinutes(t),n}function jBe(s,t){const n=ti(s);return isNaN(+n)?Ic(s,NaN):(n.setFullYear(t),n)}function WE(s,t){return kf(s,-t)}var NBe;function fr(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 LL 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"}}(NBe=globalThis).__zod_globalConfig??(NBe.__zod_globalConfig={});const pMe=globalThis.__zod_globalConfig;function vM(s){return pMe}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 q4e(s,t){return typeof t=="bigint"?t.toString():t}function fMe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function xMe(s){return s==null}function gMe(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function dqt(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 hfe(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const hqt=fMe(()=>{var s;if(pMe.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 mB(s){if(hfe(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(hfe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Xct(s){return mB(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const mqt=new Set(["string","number","symbol"]);function S8(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J4(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 Ri(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 pqt(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const fqt={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 xqt(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=X4(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 WM(this,"shape",l),l},checks:[]});return J4(s,i)}function gqt(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=X4(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 WM(this,"shape",l),l},checks:[]});return J4(s,i)}function yqt(s,t){if(!mB(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=X4(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return WM(this,"shape",i),i}});return J4(s,a)}function vqt(s,t){if(!mB(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=X4(s._zod.def,{get shape(){const r={...s._zod.def.shape,...t};return WM(this,"shape",r),r}});return J4(s,n)}function bqt(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=X4(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return WM(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return J4(s,n)}function _qt(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=X4(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 WM(this,"shape",c),c},checks:[]});return J4(t,l)}function wqt(s,t,n){const r=X4(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 WM(this,"shape",i),i}});return J4(t,r)}function TP(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 aH(s){return typeof s=="string"?s:s==null?void 0:s.message}function bM(s,t,n){var c,d,u,h,p,f;const r=s.message?s.message:aH((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??aH((h=t==null?void 0:t.error)==null?void 0:h.call(t,s))??aH((p=n.customError)==null?void 0:p.call(n,s))??aH((f=n.localeError)==null?void 0:f.call(n,s))??"Invalid input",{inst:a,continue:i,input:l,...o}=s;return o.path??(o.path=[]),o.message=r,t!=null&&t.reportInput&&(o.input=l),o}function yMe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function pB(...s){const[t,n,r]=s;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const edt=(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,q4e,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},tdt=fr("$ZodError",edt),sdt=fr("$ZodError",edt,{Parent:Error});function Nqt(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 kqt(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 LL;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>bM(c,i,vM())));throw Qct(o,a==null?void 0:a.callee),o}return l.value},bMe=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=>bM(c,i,vM())));throw Qct(o,a==null?void 0:a.callee),o}return l.value},wye=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 LL;return i.issues.length?{success:!1,error:new(s??tdt)(i.issues.map(l=>bM(l,a,vM())))}:{success:!0,data:i.value}},Sqt=wye(sdt),jye=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=>bM(l,a,vM())))}:{success:!0,data:i.value}},Cqt=jye(sdt),Tqt=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return vMe(s)(t,n,a)},Eqt=s=>(t,n,r)=>vMe(s)(t,n,r),Aqt=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return bMe(s)(t,n,a)},Mqt=s=>async(t,n,r)=>bMe(s)(t,n,r),Iqt=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return wye(s)(t,n,a)},Pqt=s=>(t,n,r)=>wye(s)(t,n,r),Lqt=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return jye(s)(t,n,a)},Dqt=s=>async(t,n,r)=>jye(s)(t,n,r),Rqt=/^[cC][0-9a-z]{6,}$/,Oqt=/^[0-9a-z]+$/,Fqt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,zqt=/^[0-9a-vA-V]{20}$/,Bqt=/^[A-Za-z0-9]{27}$/,$qt=/^[a-zA-Z0-9_-]{21}$/,Uqt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,qqt=/^([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})$/,CBe=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)$/,Vqt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Hqt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Gqt(){return new RegExp(Hqt,"u")}const Wqt=/^(?:(?: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])$/,Kqt=/^(([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}|:))$/,Yqt=/^((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])$/,Zqt=/^(([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])$/,Qqt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ndt=/^[A-Za-z0-9_-]*$/,Xqt=/^https?$/,Jqt=/^\+[1-9]\d{6,14}$/,rdt="(?:(?:\\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])))",eVt=new RegExp(`^${rdt}$`);function adt(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 tVt(s){return new RegExp(`^${adt(s)}$`)}function sVt(s){const t=adt({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(`^${rdt}T(?:${r})$`)}const nVt=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}$`)},rVt=/^-?\d+$/,aVt=/^-?\d+(?:\.\d+)?$/,iVt=/^(?:true|false)$/i,oVt=/^[^A-Z]*$/,lVt=/^[^a-z]*$/,n0=fr("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),idt={number:"number",bigint:"bigint",object:"date"},odt=fr("$ZodCheckLessThan",(s,t)=>{n0.init(s,t);const n=idt[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{n0.init(s,t);const n=idt[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})}}),cVt=fr("$ZodCheckMultipleOf",(s,t)=>{n0.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):dqt(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})}}),dVt=fr("$ZodCheckNumberFormat",(s,t)=>{var l;n0.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]=fqt[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=rVt)}),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})}}),uVt=fr("$ZodCheckMaxLength",(s,t)=>{var n;n0.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!xMe(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=yMe(a);r.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),hVt=fr("$ZodCheckMinLength",(s,t)=>{var n;n0.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!xMe(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=yMe(a);r.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),mVt=fr("$ZodCheckLengthEquals",(s,t)=>{var n;n0.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!xMe(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=yMe(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})}}),Nye=fr("$ZodCheckStringFormat",(s,t)=>{var n,r;n0.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=()=>{})}),pVt=fr("$ZodCheckRegex",(s,t)=>{Nye.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})}}),fVt=fr("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=oVt),Nye.init(s,t)}),xVt=fr("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=lVt),Nye.init(s,t)}),gVt=fr("$ZodCheckIncludes",(s,t)=>{n0.init(s,t);const n=S8(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})}}),yVt=fr("$ZodCheckStartsWith",(s,t)=>{n0.init(s,t);const n=new RegExp(`^${S8(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})}}),vVt=fr("$ZodCheckEndsWith",(s,t)=>{n0.init(s,t);const n=new RegExp(`.*${S8(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})}}),bVt=fr("$ZodCheckOverwrite",(s,t)=>{n0.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class _Vt{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 wVt={major:4,minor:4,patch:3},yh=fr("$ZodType",(s,t)=>{var a;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=wVt;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=TP(o),h;for(const p of c){if(p._zod.def.when){if(jqt(o)||!p._zod.def.when(o))continue}else if(u)continue;const f=o.issues.length,g=p._zod.check(o);if(g instanceof Promise&&(d==null?void 0:d.async)===!1)throw new LL;if(h||g instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await g,o.issues.length!==f&&(u||(u=TP(o,f)))});else{if(o.issues.length===f)continue;u||(u=TP(o,f))}}return h?h.then(()=>o):o},l=(o,c,d)=>{if(TP(o))return o.aborted=!0,o;const u=i(c,r,d);if(u instanceof Promise){if(d.async===!1)throw new LL;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 LL;return d.then(u=>i(u,r,c))}return i(d,r,c)}}Kc(s,"~standard",()=>({validate:i=>{var l;try{const o=Sqt(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return Cqt(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}))}),_Me=fr("$ZodString",(s,t)=>{var n;yh.init(s,t),s._zod.pattern=[...((n=s==null?void 0:s._zod.bag)==null?void 0:n.patterns)??[]].pop()??nVt(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}}),yu=fr("$ZodStringFormat",(s,t)=>{Nye.init(s,t),_Me.init(s,t)}),jVt=fr("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=qqt),yu.init(s,t)}),NVt=fr("$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=CBe(r))}else t.pattern??(t.pattern=CBe());yu.init(s,t)}),kVt=fr("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=Vqt),yu.init(s,t)}),SVt=fr("$ZodURL",(s,t)=>{yu.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)===Xqt.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})}}}),CVt=fr("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=Gqt()),yu.init(s,t)}),TVt=fr("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=$qt),yu.init(s,t)}),EVt=fr("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=Rqt),yu.init(s,t)}),AVt=fr("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=Oqt),yu.init(s,t)}),MVt=fr("$ZodULID",(s,t)=>{t.pattern??(t.pattern=Fqt),yu.init(s,t)}),IVt=fr("$ZodXID",(s,t)=>{t.pattern??(t.pattern=zqt),yu.init(s,t)}),PVt=fr("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=Bqt),yu.init(s,t)}),LVt=fr("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=sVt(t)),yu.init(s,t)}),DVt=fr("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=eVt),yu.init(s,t)}),RVt=fr("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=tVt(t)),yu.init(s,t)}),OVt=fr("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=Uqt),yu.init(s,t)}),FVt=fr("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=Wqt),yu.init(s,t),s._zod.bag.format="ipv4"}),zVt=fr("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=Kqt),yu.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})}}}),BVt=fr("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=Yqt),yu.init(s,t)}),$Vt=fr("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=Zqt),yu.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 cdt(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const UVt=fr("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=Qqt),yu.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=n=>{cdt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}});function qVt(s){if(!ndt.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return cdt(n)}const VVt=fr("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=ndt),yu.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=n=>{qVt(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),HVt=fr("$ZodE164",(s,t)=>{t.pattern??(t.pattern=Jqt),yu.init(s,t)});function GVt(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 WVt=fr("$ZodJWT",(s,t)=>{yu.init(s,t),s._zod.check=n=>{GVt(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),ddt=fr("$ZodNumber",(s,t)=>{yh.init(s,t),s._zod.pattern=s._zod.bag.pattern??aVt,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}}),KVt=fr("$ZodNumberFormat",(s,t)=>{dVt.init(s,t),ddt.init(s,t)}),YVt=fr("$ZodBoolean",(s,t)=>{yh.init(s,t),s._zod.pattern=iVt,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}}),ZVt=fr("$ZodUnknown",(s,t)=>{yh.init(s,t),s._zod.parse=n=>n}),QVt=fr("$ZodNever",(s,t)=>{yh.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function TBe(s,t,n){s.issues.length&&t.issues.push(...Jct(n,s.issues)),t.value[n]=s.value}const XVt=fr("$ZodArray",(s,t)=>{yh.init(s,t),s._zod.parse=(n,r)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:s}),n;n.value=Array(a.length);const i=[];for(let l=0;lTBe(d,n,l))):TBe(c,n,l)}return i.length?Promise.all(i).then(()=>n):n}});function mfe(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 udt(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=pqt(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function hdt(s,t,n,r,a,i){const l=[],o=a.keySet,c=a.catchall._zod,d=c.def.type,u=c.optin==="optional",h=c.optout==="optional";for(const p in t){if(p==="__proto__"||o.has(p))continue;if(d==="never"){l.push(p);continue}const f=c.run({value:t[p],issues:[]},r);f instanceof Promise?s.push(f.then(g=>mfe(g,n,p,t,u,h))):mfe(f,n,p,t,u,h)}return l.length&&n.issues.push({code:"unrecognized_keys",keys:l,input:t,inst:i}),s.length?Promise.all(s).then(()=>n):n}const JVt=fr("$ZodObject",(s,t)=>{yh.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=fMe(()=>udt(t));Kc(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=hfe,i=t.catchall;let l;s._zod.parse=(o,c)=>{l??(l=r.value);const d=o.value;if(!a(d))return o.issues.push({expected:"object",code:"invalid_type",input:d,inst:s}),o;o.value={};const u=[],h=l.shape;for(const p of l.keys){const f=h[p],g=f._zod.optin==="optional",b=f._zod.optout==="optional",v=f._zod.run({value:d[p],issues:[]},c);v instanceof Promise?u.push(v.then(j=>mfe(j,o,p,d,g,b))):mfe(v,o,p,d,g,b)}return i?hdt(u,d,o,c,r.value,s):u.length?Promise.all(u).then(()=>o):o}}),eHt=fr("$ZodObjectJIT",(s,t)=>{JVt.init(s,t);const n=s._zod.parse,r=fMe(()=>udt(t)),a=p=>{var S,A;const f=new _Vt(["shape","payload","ctx"]),g=r.value,b=T=>{const D=SBe(T);return`shape[${D}]._zod.run({ value: input[${D}], issues: [] }, ctx)`};f.write("const input = payload.value;");const v=Object.create(null);let j=0;for(const T of g.keys)v[T]=`key_${j++}`;f.write("const newResult = {};");for(const T of g.keys){const D=v[T],L=SBe(T),M=p[T],F=((S=M==null?void 0:M._zod)==null?void 0:S.optin)==="optional",z=((A=M==null?void 0:M._zod)==null?void 0:A.optout)==="optional";f.write(`const ${D} = ${b(T)};`),F&&z?f.write(` if (${D}.issues.length) { if (${L} in input) { payload.issues = payload.issues.concat(${D}.issues.map(iss => ({ ...iss, path: iss.path ? [${L}, ...iss.path] : [${L}] }))); } } if (${D}.value === undefined) { if (${L} in input) { newResult[${L}] = undefined; } } else { newResult[${L}] = ${D}.value; } `):F?f.write(` if (${D}.issues.length) { payload.issues = payload.issues.concat(${D}.issues.map(iss => ({ ...iss, path: iss.path ? [${L}, ...iss.path] : [${L}] }))); } if (${D}.value === undefined) { if (${L} in input) { newResult[${L}] = undefined; } } else { newResult[${L}] = ${D}.value; } `):f.write(` const ${D}_present = ${L} in input; if (${D}.issues.length) { payload.issues = payload.issues.concat(${D}.issues.map(iss => ({ ...iss, path: iss.path ? [${L}, ...iss.path] : [${L}] }))); } if (!${D}_present && !${D}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${L}] }); } if (${D}_present) { if (${D}.value === undefined) { newResult[${L}] = undefined; } else { newResult[${L}] = ${D}.value; } } `)}f.write("payload.value = newResult;"),f.write("return payload;");const _=f.compile();return(T,D)=>_(p,T,D)};let i;const l=hfe,o=!pMe.jitless,d=o&&hqt.value,u=t.catchall;let h;s._zod.parse=(p,f)=>{h??(h=r.value);const g=p.value;return l(g)?o&&d&&(f==null?void 0:f.async)===!1&&f.jitless!==!0?(i||(i=a(t.shape)),p=i(p,f),u?hdt([],g,p,f,h,s):p):n(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:g,inst:s}),p)}});function EBe(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=>!TP(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=>bM(l,r,vM())))}),t)}const tHt=fr("$ZodUnion",(s,t)=>{yh.init(s,t),Kc(s._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Kc(s._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Kc(s._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Kc(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=>gMe(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=>EBe(o,r,s,a)):EBe(l,r,s,a)}}),sHt=fr("$ZodIntersection",(s,t)=>{yh.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])=>ABe(n,c,d)):ABe(n,i,l)}});function V4e(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(mB(s)&&mB(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=V4e(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}),TP(s))return s;const l=V4e(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 nHt=fr("$ZodEnum",(s,t)=>{yh.init(s,t);const n=Zct(t.entries),r=new Set(n);s._zod.values=r,s._zod.pattern=new RegExp(`^(${n.filter(a=>mqt.has(typeof a)).map(a=>typeof a=="string"?S8(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}}),rHt=fr("$ZodLiteral",(s,t)=>{if(yh.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"?S8(r):r?S8(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}}),aHt=fr("$ZodTransform",(s,t)=>{yh.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 LL;return n.value=a,n.fallback=!0,n}});function MBe(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const mdt=fr("$ZodOptional",(s,t)=>{yh.init(s,t),s._zod.optin="optional",s._zod.optout="optional",Kc(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Kc(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${gMe(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=>MBe(l,a)):MBe(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),iHt=fr("$ZodExactOptional",(s,t)=>{mdt.init(s,t),Kc(s._zod,"values",()=>t.innerType._zod.values),Kc(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),oHt=fr("$ZodNullable",(s,t)=>{yh.init(s,t),Kc(s._zod,"optin",()=>t.innerType._zod.optin),Kc(s._zod,"optout",()=>t.innerType._zod.optout),Kc(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${gMe(n.source)}|null)$`):void 0}),Kc(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)}),lHt=fr("$ZodDefault",(s,t)=>{yh.init(s,t),s._zod.optin="optional",Kc(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=>IBe(i,t)):IBe(a,t)}});function IBe(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const cHt=fr("$ZodPrefault",(s,t)=>{yh.init(s,t),s._zod.optin="optional",Kc(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))}),dHt=fr("$ZodNonOptional",(s,t)=>{yh.init(s,t),Kc(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=>PBe(i,s)):PBe(a,s)}});function PBe(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 uHt=fr("$ZodCatch",(s,t)=>{yh.init(s,t),s._zod.optin="optional",Kc(s._zod,"optout",()=>t.innerType._zod.optout),Kc(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=>bM(l,r,vM()))},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=>bM(i,r,vM()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),hHt=fr("$ZodPipe",(s,t)=>{yh.init(s,t),Kc(s._zod,"values",()=>t.in._zod.values),Kc(s._zod,"optin",()=>t.in._zod.optin),Kc(s._zod,"optout",()=>t.out._zod.optout),Kc(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=>iH(l,t.in,r)):iH(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>iH(i,t.out,r)):iH(a,t.out,r)}});function iH(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 mHt=fr("$ZodReadonly",(s,t)=>{yh.init(s,t),Kc(s._zod,"propValues",()=>t.innerType._zod.propValues),Kc(s._zod,"values",()=>t.innerType._zod.values),Kc(s._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),Kc(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(LBe):LBe(a)}});function LBe(s){return s.value=Object.freeze(s.value),s}const pHt=fr("$ZodCustom",(s,t)=>{n0.init(s,t),yh.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=>DBe(i,n,r,s));DBe(a,n,r,s)}});function DBe(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(pB(a))}}var RBe;class fHt{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 xHt(){return new fHt}(RBe=globalThis).__zod_globalRegistry??(RBe.__zod_globalRegistry=xHt());const f7=globalThis.__zod_globalRegistry;function gHt(s,t){return new s({type:"string",...Ri(t)})}function yHt(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...Ri(t)})}function OBe(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...Ri(t)})}function vHt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...Ri(t)})}function bHt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ri(t)})}function _Ht(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ri(t)})}function wHt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ri(t)})}function jHt(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...Ri(t)})}function NHt(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...Ri(t)})}function kHt(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ri(t)})}function SHt(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...Ri(t)})}function CHt(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ri(t)})}function THt(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...Ri(t)})}function EHt(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...Ri(t)})}function AHt(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ri(t)})}function MHt(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ri(t)})}function IHt(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ri(t)})}function PHt(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ri(t)})}function LHt(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ri(t)})}function DHt(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...Ri(t)})}function RHt(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...Ri(t)})}function OHt(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...Ri(t)})}function FHt(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...Ri(t)})}function zHt(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ri(t)})}function BHt(s,t){return new s({type:"string",format:"date",check:"string_format",...Ri(t)})}function $Ht(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...Ri(t)})}function UHt(s,t){return new s({type:"string",format:"duration",check:"string_format",...Ri(t)})}function qHt(s,t){return new s({type:"number",checks:[],...Ri(t)})}function VHt(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...Ri(t)})}function HHt(s,t){return new s({type:"boolean",...Ri(t)})}function GHt(s){return new s({type:"unknown"})}function WHt(s,t){return new s({type:"never",...Ri(t)})}function FBe(s,t){return new odt({check:"less_than",...Ri(t),value:s,inclusive:!1})}function fje(s,t){return new odt({check:"less_than",...Ri(t),value:s,inclusive:!0})}function zBe(s,t){return new ldt({check:"greater_than",...Ri(t),value:s,inclusive:!1})}function xje(s,t){return new ldt({check:"greater_than",...Ri(t),value:s,inclusive:!0})}function BBe(s,t){return new cVt({check:"multiple_of",...Ri(t),value:s})}function pdt(s,t){return new uVt({check:"max_length",...Ri(t),maximum:s})}function pfe(s,t){return new hVt({check:"min_length",...Ri(t),minimum:s})}function fdt(s,t){return new mVt({check:"length_equals",...Ri(t),length:s})}function KHt(s,t){return new pVt({check:"string_format",format:"regex",...Ri(t),pattern:s})}function YHt(s){return new fVt({check:"string_format",format:"lowercase",...Ri(s)})}function ZHt(s){return new xVt({check:"string_format",format:"uppercase",...Ri(s)})}function QHt(s,t){return new gVt({check:"string_format",format:"includes",...Ri(t),includes:s})}function XHt(s,t){return new yVt({check:"string_format",format:"starts_with",...Ri(t),prefix:s})}function JHt(s,t){return new vVt({check:"string_format",format:"ends_with",...Ri(t),suffix:s})}function GD(s){return new bVt({check:"overwrite",tx:s})}function eGt(s){return GD(t=>t.normalize(s))}function tGt(){return GD(s=>s.trim())}function sGt(){return GD(s=>s.toLowerCase())}function nGt(){return GD(s=>s.toUpperCase())}function rGt(){return GD(s=>uqt(s))}function aGt(s,t,n){return new s({type:"array",element:t,...Ri(n)})}function iGt(s,t,n){return new s({type:"custom",check:"custom",fn:t,...Ri(n)})}function oGt(s,t){const n=lGt(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(pB(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(pB(i))}},s(r.value,r)),t);return n}function lGt(s,t){const n=new n0({check:"custom",...Ri(t)});return n._zod.check=s,n}function xdt(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)??f7,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 Cf(s,t,n={path:[],schemaPath:[]}){var u,h;var r;const a=s._zod.def,i=t.seen.get(s);if(i)return i.count++,n.schemaPath.includes(s)&&(i.cycle=n.path),i.schema;const l={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(s,l);const o=(h=(u=s._zod).toJSONSchema)==null?void 0:h.call(u);if(o)l.schema=o;else{const p={...n,schemaPath:[...n.schemaPath,s],path:n.path};if(s._zod.processJSONSchema)s._zod.processJSONSchema(t,l.schema,p);else{const g=l.schema,b=t.processors[a.type];if(!b)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);b(s,t,g,p)}const f=s._zod.parent;f&&(l.ref||(l.ref=f),Cf(f,t,p),t.seen.get(f).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&Object.assign(l.schema,c),t.io==="input"&&Ox(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 gdt(s,t){var l,o,c,d;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of s.seen.entries()){const h=(l=s.metadataRegistry.get(u[0]))==null?void 0:l.id;if(h){const p=r.get(h);if(p&&p!==u[0])throw new Error(`Duplicate schema id "${h}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(h,u[0])}}const a=u=>{var b;const h=s.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const v=(b=s.external.registry.get(u[0]))==null?void 0:b.id,j=s.external.uri??(S=>S);if(v)return{ref:j(v)};const _=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=_,{defId:_,ref:`${j("__shared")}#/${h}/${_}`}}if(u[1]===n)return{ref:"#"};const f=`#/${h}/`,g=u[1].schema.id??`__schema${s.counter++}`;return{defId:g,ref:f+g}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:p,defId:f}=a(u);h.def={...h.schema},f&&(h.defId=f);const g=h.schema;for(const b in g)delete g[b];g.$ref=p};if(s.cycles==="throw")for(const u of s.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${(o=h.cycle)==null?void 0:o.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of s.seen.entries()){const h=u[1];if(t===u[0]){i(u);continue}if(s.external){const f=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&f){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&s.reused==="ref"){i(u);continue}}}function ydt(s,t){var o,c,d,u;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=h=>{const p=s.seen.get(h);if(p.ref===null)return;const f=p.def??p.schema,g={...f},b=p.ref;if(p.ref=null,b){r(b);const j=s.seen.get(b),_=j.schema;if(_.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(_)):Object.assign(f,_),Object.assign(f,g),h._zod.parent===b)for(const A in f)A==="$ref"||A==="allOf"||A in g||delete f[A];if(_.$ref&&j.def)for(const A in f)A==="$ref"||A==="allOf"||A in j.def&&JSON.stringify(f[A])===JSON.stringify(j.def[A])&&delete f[A]}const v=h._zod.parent;if(v&&v!==b){r(v);const j=s.seen.get(v);if(j!=null&&j.schema.$ref&&(f.$ref=j.schema.$ref,j.def))for(const _ in f)_==="$ref"||_==="allOf"||_ in j.def&&JSON.stringify(f[_])===JSON.stringify(j.def[_])&&delete f[_]}s.override({zodSchema:h,jsonSchema:f,path:p.path??[]})};for(const h of[...s.seen.entries()].reverse())r(h[0]);const a={};if(s.target==="draft-2020-12"?a.$schema="https://json-schema.org/draft/2020-12/schema":s.target==="draft-07"?a.$schema="http://json-schema.org/draft-07/schema#":s.target==="draft-04"?a.$schema="http://json-schema.org/draft-04/schema#":s.target,(o=s.external)!=null&&o.uri){const h=(c=s.external.registry.get(t))==null?void 0:c.id;if(!h)throw new Error("Schema is missing an `id` property");a.$id=s.external.uri(h)}Object.assign(a,n.def??n.schema);const i=(d=s.metadataRegistry.get(t))==null?void 0:d.id;i!==void 0&&a.id===i&&delete a.id;const l=((u=s.external)==null?void 0:u.defs)??{};for(const h of s.seen.entries()){const p=h[1];p.def&&p.defId&&(p.def.id===p.defId&&delete p.def.id,l[p.defId]=p.def)}s.external||Object.keys(l).length>0&&(s.target==="draft-2020-12"?a.$defs=l:a.definitions=l);try{const h=JSON.parse(JSON.stringify(a));return Object.defineProperty(h,"~standard",{value:{...t["~standard"],jsonSchema:{input:ffe(t,"input",s.processors),output:ffe(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function Ox(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 Ox(r.element,n);if(r.type==="set")return Ox(r.valueType,n);if(r.type==="lazy")return Ox(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 Ox(r.innerType,n);if(r.type==="intersection")return Ox(r.left,n)||Ox(r.right,n);if(r.type==="record"||r.type==="map")return Ox(r.keyType,n)||Ox(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:Ox(r.in,n)||Ox(r.out,n);if(r.type==="object"){for(const a in r.shape)if(Ox(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(Ox(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(Ox(a,n))return!0;return!!(r.rest&&Ox(r.rest,n))}return!1}const cGt=(s,t={})=>n=>{const r=xdt({...n,processors:t});return Cf(s,r),gdt(r,s),ydt(r,s)},ffe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=xdt({...a??{},target:i,io:t,processors:n});return Cf(s,l),gdt(l,s),ydt(l,s)},dGt={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},uGt=(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=dGt[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}))])}},hGt=(s,t,n,r)=>{const a=n,{minimum:i,maximum:l,format:o,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=s._zod.bag;typeof o=="string"&&o.includes("int")?a.type="integer":a.type="number";const h=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof d=="number"&&d<=(l??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";h?f?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:typeof i=="number"&&(a.minimum=i),p?f?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d:typeof l=="number"&&(a.maximum=l),typeof c=="number"&&(a.multipleOf=c)},mGt=(s,t,n,r)=>{n.type="boolean"},pGt=(s,t,n,r)=>{n.not={}},fGt=(s,t,n,r)=>{},xGt=(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},gGt=(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},yGt=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},vGt=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},bGt=(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=Cf(i.element,t,{...r,path:[...r.path,"items"]})},_Gt=(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]=Cf(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=Cf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},wGt=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>Cf(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},jGt=(s,t,n,r)=>{const a=s._zod.def,i=Cf(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=Cf(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},NGt=(s,t,n,r)=>{const a=s._zod.def,i=Cf(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"}]},kGt=(s,t,n,r)=>{const a=s._zod.def;Cf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},SGt=(s,t,n,r)=>{const a=s._zod.def;Cf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},CGt=(s,t,n,r)=>{const a=s._zod.def;Cf(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)))},TGt=(s,t,n,r)=>{const a=s._zod.def;Cf(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},EGt=(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;Cf(l,t,r);const o=t.seen.get(s);o.ref=l},AGt=(s,t,n,r)=>{const a=s._zod.def;Cf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},vdt=(s,t,n,r)=>{const a=s._zod.def;Cf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},MGt=fr("ZodISODateTime",(s,t)=>{LVt.init(s,t),Gu.init(s,t)});function IGt(s){return zHt(MGt,s)}const PGt=fr("ZodISODate",(s,t)=>{DVt.init(s,t),Gu.init(s,t)});function LGt(s){return BHt(PGt,s)}const DGt=fr("ZodISOTime",(s,t)=>{RVt.init(s,t),Gu.init(s,t)});function RGt(s){return $Ht(DGt,s)}const OGt=fr("ZodISODuration",(s,t)=>{OVt.init(s,t),Gu.init(s,t)});function FGt(s){return UHt(OGt,s)}const bdt=(s,t)=>{tdt.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:n=>kqt(s,n)},flatten:{value:n=>Nqt(s,n)},addIssue:{value:n=>{s.issues.push(n),s.message=JSON.stringify(s.issues,q4e,2)}},addIssues:{value:n=>{s.issues.push(...n),s.message=JSON.stringify(s.issues,q4e,2)}},isEmpty:{get(){return s.issues.length===0}}})},zGt=fr("ZodError",bdt),Jv=fr("ZodError",bdt,{Parent:Error}),BGt=vMe(Jv),$Gt=bMe(Jv),UGt=wye(Jv),qGt=jye(Jv),VGt=Tqt(Jv),HGt=Eqt(Jv),GGt=Aqt(Jv),WGt=Mqt(Jv),KGt=Iqt(Jv),YGt=Pqt(Jv),ZGt=Lqt(Jv),QGt=Dqt(Jv),$Be=new WeakMap;function iU(s,t,n){const r=Object.getPrototypeOf(s);let a=$Be.get(r);if(a||(a=new Set,$Be.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 vh=fr("ZodType",(s,t)=>(yh.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:ffe(s,"input"),output:ffe(s,"output")}}),s.toJSONSchema=cGt(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(n,r)=>BGt(s,n,r,{callee:s.parse}),s.safeParse=(n,r)=>UGt(s,n,r),s.parseAsync=async(n,r)=>$Gt(s,n,r,{callee:s.parseAsync}),s.safeParseAsync=async(n,r)=>qGt(s,n,r),s.spa=s.safeParseAsync,s.encode=(n,r)=>VGt(s,n,r),s.decode=(n,r)=>HGt(s,n,r),s.encodeAsync=async(n,r)=>GGt(s,n,r),s.decodeAsync=async(n,r)=>WGt(s,n,r),s.safeEncode=(n,r)=>KGt(s,n,r),s.safeDecode=(n,r)=>YGt(s,n,r),s.safeEncodeAsync=async(n,r)=>ZGt(s,n,r),s.safeDecodeAsync=async(n,r)=>QGt(s,n,r),iU(s,"ZodType",{check(...n){const r=this.def;return this.clone(X4(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 J4(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(GWt(n,r))},superRefine(n,r){return this.check(WWt(n,r))},overwrite(n){return this.check(GD(n))},optional(){return HBe(this)},exactOptional(){return PWt(this)},nullable(){return GBe(this)},nullish(){return HBe(GBe(this))},nonoptional(n){return zWt(this,n)},array(){return jWt(this)},or(n){return SWt([this,n])},and(n){return TWt(this,n)},transform(n){return WBe(this,MWt(n))},default(n){return RWt(this,n)},prefault(n){return FWt(this,n)},catch(n){return $Wt(this,n)},pipe(n){return WBe(this,n)},readonly(){return VWt(this)},describe(n){const r=this.clone();return f7.add(r,{description:n}),r},meta(...n){if(n.length===0)return f7.get(this);const r=this.clone();return f7.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=f7.get(s))==null?void 0:n.description},configurable:!0}),s)),_dt=fr("_ZodString",(s,t)=>{_Me.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(r,a,i)=>uGt(s,r,a);const n=s._zod.bag;s.format=n.format??null,s.minLength=n.minimum??null,s.maxLength=n.maximum??null,iU(s,"_ZodString",{regex(...r){return this.check(KHt(...r))},includes(...r){return this.check(QHt(...r))},startsWith(...r){return this.check(XHt(...r))},endsWith(...r){return this.check(JHt(...r))},min(...r){return this.check(pfe(...r))},max(...r){return this.check(pdt(...r))},length(...r){return this.check(fdt(...r))},nonempty(...r){return this.check(pfe(1,...r))},lowercase(r){return this.check(YHt(r))},uppercase(r){return this.check(ZHt(r))},trim(){return this.check(tGt())},normalize(...r){return this.check(eGt(...r))},toLowerCase(){return this.check(sGt())},toUpperCase(){return this.check(nGt())},slugify(){return this.check(rGt())}})}),XGt=fr("ZodString",(s,t)=>{_Me.init(s,t),_dt.init(s,t),s.email=n=>s.check(yHt(JGt,n)),s.url=n=>s.check(jHt(eWt,n)),s.jwt=n=>s.check(FHt(fWt,n)),s.emoji=n=>s.check(NHt(tWt,n)),s.guid=n=>s.check(OBe(UBe,n)),s.uuid=n=>s.check(vHt(oH,n)),s.uuidv4=n=>s.check(bHt(oH,n)),s.uuidv6=n=>s.check(_Ht(oH,n)),s.uuidv7=n=>s.check(wHt(oH,n)),s.nanoid=n=>s.check(kHt(sWt,n)),s.guid=n=>s.check(OBe(UBe,n)),s.cuid=n=>s.check(SHt(nWt,n)),s.cuid2=n=>s.check(CHt(rWt,n)),s.ulid=n=>s.check(THt(aWt,n)),s.base64=n=>s.check(DHt(hWt,n)),s.base64url=n=>s.check(RHt(mWt,n)),s.xid=n=>s.check(EHt(iWt,n)),s.ksuid=n=>s.check(AHt(oWt,n)),s.ipv4=n=>s.check(MHt(lWt,n)),s.ipv6=n=>s.check(IHt(cWt,n)),s.cidrv4=n=>s.check(PHt(dWt,n)),s.cidrv6=n=>s.check(LHt(uWt,n)),s.e164=n=>s.check(OHt(pWt,n)),s.datetime=n=>s.check(IGt(n)),s.date=n=>s.check(LGt(n)),s.time=n=>s.check(RGt(n)),s.duration=n=>s.check(FGt(n))});function go(s){return gHt(XGt,s)}const Gu=fr("ZodStringFormat",(s,t)=>{yu.init(s,t),_dt.init(s,t)}),JGt=fr("ZodEmail",(s,t)=>{kVt.init(s,t),Gu.init(s,t)}),UBe=fr("ZodGUID",(s,t)=>{jVt.init(s,t),Gu.init(s,t)}),oH=fr("ZodUUID",(s,t)=>{NVt.init(s,t),Gu.init(s,t)}),eWt=fr("ZodURL",(s,t)=>{SVt.init(s,t),Gu.init(s,t)}),tWt=fr("ZodEmoji",(s,t)=>{CVt.init(s,t),Gu.init(s,t)}),sWt=fr("ZodNanoID",(s,t)=>{TVt.init(s,t),Gu.init(s,t)}),nWt=fr("ZodCUID",(s,t)=>{EVt.init(s,t),Gu.init(s,t)}),rWt=fr("ZodCUID2",(s,t)=>{AVt.init(s,t),Gu.init(s,t)}),aWt=fr("ZodULID",(s,t)=>{MVt.init(s,t),Gu.init(s,t)}),iWt=fr("ZodXID",(s,t)=>{IVt.init(s,t),Gu.init(s,t)}),oWt=fr("ZodKSUID",(s,t)=>{PVt.init(s,t),Gu.init(s,t)}),lWt=fr("ZodIPv4",(s,t)=>{FVt.init(s,t),Gu.init(s,t)}),cWt=fr("ZodIPv6",(s,t)=>{zVt.init(s,t),Gu.init(s,t)}),dWt=fr("ZodCIDRv4",(s,t)=>{BVt.init(s,t),Gu.init(s,t)}),uWt=fr("ZodCIDRv6",(s,t)=>{$Vt.init(s,t),Gu.init(s,t)}),hWt=fr("ZodBase64",(s,t)=>{UVt.init(s,t),Gu.init(s,t)}),mWt=fr("ZodBase64URL",(s,t)=>{VVt.init(s,t),Gu.init(s,t)}),pWt=fr("ZodE164",(s,t)=>{HVt.init(s,t),Gu.init(s,t)}),fWt=fr("ZodJWT",(s,t)=>{WVt.init(s,t),Gu.init(s,t)}),wdt=fr("ZodNumber",(s,t)=>{ddt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(r,a,i)=>hGt(s,r,a),iU(s,"ZodNumber",{gt(r,a){return this.check(zBe(r,a))},gte(r,a){return this.check(xje(r,a))},min(r,a){return this.check(xje(r,a))},lt(r,a){return this.check(FBe(r,a))},lte(r,a){return this.check(fje(r,a))},max(r,a){return this.check(fje(r,a))},int(r){return this.check(qBe(r))},safe(r){return this.check(qBe(r))},positive(r){return this.check(zBe(0,r))},nonnegative(r){return this.check(xje(0,r))},negative(r){return this.check(FBe(0,r))},nonpositive(r){return this.check(fje(0,r))},multipleOf(r,a){return this.check(BBe(r,a))},step(r,a){return this.check(BBe(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 X9(s){return qHt(wdt,s)}const xWt=fr("ZodNumberFormat",(s,t)=>{KVt.init(s,t),wdt.init(s,t)});function qBe(s){return VHt(xWt,s)}const gWt=fr("ZodBoolean",(s,t)=>{YVt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>mGt(s,n,r)});function yWt(s){return HHt(gWt,s)}const vWt=fr("ZodUnknown",(s,t)=>{ZVt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>fGt()});function VBe(){return GHt(vWt)}const bWt=fr("ZodNever",(s,t)=>{QVt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>pGt(s,n,r)});function _Wt(s){return WHt(bWt,s)}const wWt=fr("ZodArray",(s,t)=>{XVt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>bGt(s,n,r,a),s.element=t.element,iU(s,"ZodArray",{min(n,r){return this.check(pfe(n,r))},nonempty(n){return this.check(pfe(1,n))},max(n,r){return this.check(pdt(n,r))},length(n,r){return this.check(fdt(n,r))},unwrap(){return this.element}})});function jWt(s,t){return aGt(wWt,s,t)}const NWt=fr("ZodObject",(s,t)=>{eHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>_Gt(s,n,r,a),Kc(s,"shape",()=>t.shape),iU(s,"ZodObject",{keyof(){return wMe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:VBe()})},loose(){return this.clone({...this._zod.def,catchall:VBe()})},strict(){return this.clone({...this._zod.def,catchall:_Wt()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return yqt(this,n)},safeExtend(n){return vqt(this,n)},merge(n){return bqt(this,n)},pick(n){return xqt(this,n)},omit(n){return gqt(this,n)},partial(...n){return _qt(jdt,this,n[0])},required(...n){return wqt(Ndt,this,n[0])}})});function Zw(s,t){const n={type:"object",shape:s??{},...Ri(t)};return new NWt(n)}const kWt=fr("ZodUnion",(s,t)=>{tHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>wGt(s,n,r,a),s.options=t.options});function SWt(s,t){return new kWt({type:"union",options:s,...Ri(t)})}const CWt=fr("ZodIntersection",(s,t)=>{sHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>jGt(s,n,r,a)});function TWt(s,t){return new CWt({type:"intersection",left:s,right:t})}const H4e=fr("ZodEnum",(s,t)=>{nHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(r,a,i)=>xGt(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 H4e({...t,checks:[],...Ri(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 H4e({...t,checks:[],...Ri(a),entries:i})}});function wMe(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new H4e({type:"enum",entries:n,...Ri(t)})}const EWt=fr("ZodLiteral",(s,t)=>{rHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>gGt(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 Np(s,t){return new EWt({type:"literal",values:Array.isArray(s)?s:[s],...Ri(t)})}const AWt=fr("ZodTransform",(s,t)=>{aHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>vGt(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(pB(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(pB(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 MWt(s){return new AWt({type:"transform",transform:s})}const jdt=fr("ZodOptional",(s,t)=>{mdt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>vdt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function HBe(s){return new jdt({type:"optional",innerType:s})}const IWt=fr("ZodExactOptional",(s,t)=>{iHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>vdt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function PWt(s){return new IWt({type:"optional",innerType:s})}const LWt=fr("ZodNullable",(s,t)=>{oHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>NGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function GBe(s){return new LWt({type:"nullable",innerType:s})}const DWt=fr("ZodDefault",(s,t)=>{lHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>SGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function RWt(s,t){return new DWt({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():Xct(t)}})}const OWt=fr("ZodPrefault",(s,t)=>{cHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>CGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function FWt(s,t){return new OWt({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():Xct(t)}})}const Ndt=fr("ZodNonOptional",(s,t)=>{dHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>kGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function zWt(s,t){return new Ndt({type:"nonoptional",innerType:s,...Ri(t)})}const BWt=fr("ZodCatch",(s,t)=>{uHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>TGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function $Wt(s,t){return new BWt({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const UWt=fr("ZodPipe",(s,t)=>{hHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>EGt(s,n,r,a),s.in=t.in,s.out=t.out});function WBe(s,t){return new UWt({type:"pipe",in:s,out:t})}const qWt=fr("ZodReadonly",(s,t)=>{mHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>AGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function VWt(s){return new qWt({type:"readonly",innerType:s})}const HWt=fr("ZodCustom",(s,t)=>{pHt.init(s,t),vh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>yGt(s,n)});function GWt(s,t={}){return iGt(HWt,s,t)}function WWt(s,t){return oGt(s,t)}const KWt=["Excellent","Good","Neutral","Bad","Very Bad"],YWt=[5,4,3,2,1];function ZWt({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=fBt(),[i,l]=N.useState({}),o=s.filter(p=>p.question_type==="rating"),c=s.filter(p=>p.question_type!=="rating"),d=(p,f)=>{l(g=>({...g,[p]:{rating_value:f}}))},u=(p,f)=>{l(g=>({...g,[p]:{text_value:f}}))},h=async()=>{const p=Object.entries(i).filter(([,f])=>f.rating_value!=null||f.text_value&&f.text_value.trim()).map(([f,g])=>{var b;return{visitor_id:t,question_id:f,rating_value:g.rating_value??null,text_value:((b=g.text_value)==null?void 0:b.trim())||null}});if(p.length>0)try{await a.mutateAsync(p)}catch{}n()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),e.jsx("button",{onClick:r,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),e.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"flex-1"}),KWt.map(p=>e.jsx("div",{className:"w-12 text-center",children:e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:p})},p))]}),o.map(p=>e.jsxs("div",{className:"flex items-center gap-1 py-1.5 border-b border-slate-100 last:border-0",children:[e.jsx("span",{className:"flex-1 text-sm text-slate-700 pr-2",children:p.question_text}),YWt.map(f=>{var g;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(p.id,f),className:`w-6 h-6 rounded-full border-2 transition-all ${((g=i[p.id])==null?void 0:g.rating_value)===f?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},f)})]},p.id))]}),c.map(p=>{var f;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:p.question_text}),e.jsx(Ts,{value:((f=i[p.id])==null?void 0:f.text_value)||"",onChange:g=>u(p.id,g.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},p.id)}),e.jsx(B,{onClick:h,disabled:a.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:a.isPending?e.jsx(ss,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}var kye="Checkbox",[QWt,Gxn]=gu(kye),[XWt,jMe]=QWt(kye);function JWt(s){const{__scopeCheckbox:t,checked:n,children:r,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:h}=s,[p,f]=mm({prop:n,defaultProp:a??!1,onChange:c,caller:kye}),[g,b]=N.useState(null),[v,j]=N.useState(null),_=N.useRef(!1),S=g?!!l||!!g.closest("form"):!0,A={checked:p,disabled:i,setChecked:f,control:g,setControl:b,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:_,required:d,defaultChecked:x4(a)?!1:a,isFormControl:S,bubbleInput:v,setBubbleInput:j};return e.jsx(XWt,{scope:t,...A,children:eKt(h)?h(A):r})}var kdt="CheckboxTrigger",Sdt=N.forwardRef(({__scopeCheckbox:s,onKeyDown:t,onClick:n,...r},a)=>{const{control:i,value:l,disabled:o,checked:c,required:d,setControl:u,setChecked:h,hasConsumerStoppedPropagationRef:p,isFormControl:f,bubbleInput:g}=jMe(kdt,s),b=Ti(a,u),v=N.useRef(c);return N.useEffect(()=>{const j=i==null?void 0:i.form;if(j){const _=()=>h(v.current);return j.addEventListener("reset",_),()=>j.removeEventListener("reset",_)}},[i,h]),e.jsx(sa.button,{type:"button",role:"checkbox","aria-checked":x4(c)?"mixed":c,"aria-required":d,"data-state":Mdt(c),"data-disabled":o?"":void 0,disabled:o,value:l,...r,ref:b,onKeyDown:wr(t,j=>{j.key==="Enter"&&j.preventDefault()}),onClick:wr(n,j=>{h(_=>x4(_)?!0:!_),g&&f&&(p.current=j.isPropagationStopped(),p.current||j.stopPropagation())})})});Sdt.displayName=kdt;var NMe=N.forwardRef((s,t)=>{const{__scopeCheckbox:n,name:r,checked:a,defaultChecked:i,required:l,disabled:o,value:c,onCheckedChange:d,form:u,...h}=s;return e.jsx(JWt,{__scopeCheckbox:n,checked:a,defaultChecked:i,disabled:o,required:l,onCheckedChange:d,name:r,form:u,value:c,internal_do_not_use_render:({isFormControl:p})=>e.jsxs(e.Fragment,{children:[e.jsx(Sdt,{...h,ref:t,__scopeCheckbox:n}),p&&e.jsx(Adt,{__scopeCheckbox:n})]})})});NMe.displayName=kye;var Cdt="CheckboxIndicator",Tdt=N.forwardRef((s,t)=>{const{__scopeCheckbox:n,forceMount:r,...a}=s,i=jMe(Cdt,n);return e.jsx(Bh,{present:r||x4(i.checked)||i.checked===!0,children:e.jsx(sa.span,{"data-state":Mdt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});Tdt.displayName=Cdt;var Edt="CheckboxBubbleInput",Adt=N.forwardRef(({__scopeCheckbox:s,...t},n)=>{const{control:r,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:l,required:o,disabled:c,name:d,value:u,form:h,bubbleInput:p,setBubbleInput:f}=jMe(Edt,s),g=Ti(n,f),b=rU(i),v=q$(r);N.useEffect(()=>{const _=p;if(!_)return;const S=window.HTMLInputElement.prototype,T=Object.getOwnPropertyDescriptor(S,"checked").set,D=!a.current;if(b!==i&&T){const L=new Event("click",{bubbles:D});_.indeterminate=x4(i),T.call(_,x4(i)?!1:i),_.dispatchEvent(L)}},[p,b,i,a]);const j=N.useRef(x4(i)?!1:i);return e.jsx(sa.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??j.current,required:o,disabled:c,name:d,value:u,form:h,...t,tabIndex:-1,ref:g,style:{...t.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});Adt.displayName=Edt;function eKt(s){return typeof s=="function"}function x4(s){return s==="indeterminate"}function Mdt(s){return x4(s)?"indeterminate":s?"checked":"unchecked"}const hi=N.forwardRef(({className:s,...t},n)=>e.jsx(NMe,{ref:n,className:Et("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(Tdt,{className:Et("flex items-center justify-center text-current"),children:e.jsx(Lr,{className:"h-4 w-4"})})}));hi.displayName=NMe.displayName;const ug=aye,oU=ZAe,tKt=iye,Idt=N.forwardRef(({className:s,...t},n)=>e.jsx(UD,{className:Et("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}));Idt.displayName=UD.displayName;const sKt=qM("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"}}),ox=N.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(tKt,{children:[e.jsx(Idt,{}),e.jsxs(qD,{ref:a,className:Et(sKt({side:s}),t),...r,children:[n,e.jsxs(sU,{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(Fn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));ox.displayName=qD.displayName;const r0=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col space-y-2 text-center sm:text-left",s),...t});r0.displayName="SheetHeader";const Pdt=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Pdt.displayName="SheetFooter";const a0=N.forwardRef(({className:s,...t},n)=>e.jsx(eU,{ref:n,className:Et("text-lg font-semibold text-foreground",s),...t}));a0.displayName=eU.displayName;const lU=N.forwardRef(({className:s,...t},n)=>e.jsx(tU,{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));lU.displayName=tU.displayName;function G4e(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function nKt({rooms:s}){var h;const[t,n]=N.useState(((h=s[0])==null?void 0:h.id)||""),[r,a]=N.useState(null),i=s.find(p=>p.id===t)||s[0],l=r!==null?i==null?void 0:i.media[r]:null,o=(i==null?void 0:i.media.length)??0,c=()=>a(null),d=()=>a(p=>p===null||o===0?p:(p-1+o)%o),u=()=>a(p=>p===null||o===0?p:(p+1)%o);return N.useEffect(()=>{if(r===null)return;const p=f=>{f.key==="Escape"?c():f.key==="ArrowLeft"?d():f.key==="ArrowRight"&&u()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,o]),s.length?e.jsxs("div",{className:"hidden md:block",children:[e.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(p=>e.jsxs("button",{onClick:()=>n(p.id),className:Et("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===p.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[p.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:p.media.length})]},p.id))})}),i&&e.jsxs("div",{className:"mt-6",children:[e.jsx("h3",{className:"text-2xl font-bold",children:i.name}),i.description&&e.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:i.description}),i.media.length===0?e.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):e.jsx("div",{className:"mt-5 grid grid-cols-2 lg:grid-cols-3 gap-3",children:i.media.map((p,f)=>e.jsx("button",{onClick:()=>a(f),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:p.kind==="video"?e.jsxs(e.Fragment,{children:[G4e(p.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:p.url,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/50 transition",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(vr,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:p.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},p.id))})]}),l&&i&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:c,children:[e.jsxs("div",{className:"absolute top-5 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-xs font-medium",children:[i.name," — ",(r??0)+1," / ",o]}),e.jsx("button",{onClick:p=>{p.stopPropagation(),c()},className:"absolute top-5 right-5 h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 text-white text-xl flex items-center justify-center transition","aria-label":"Close",children:"×"}),o>1&&e.jsx("button",{onClick:p=>{p.stopPropagation(),d()},className:"absolute left-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Previous",children:e.jsx(fl,{className:"h-6 w-6"})}),l.kind==="video"?G4e(l.url)?e.jsx("iframe",{src:`${l.url}?autoplay=true`,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full max-w-5xl aspect-video rounded-lg",onClick:p=>p.stopPropagation()},l.url):e.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:p=>p.stopPropagation()},l.url):e.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:p=>p.stopPropagation()}),o>1&&e.jsx("button",{onClick:p=>{p.stopPropagation(),u()},className:"absolute right-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Next",children:e.jsx(ga,{className:"h-6 w-6"})})]})]}):null}function rKt({rooms:s}){var o;const t=[];s.forEach(c=>{t.push({type:"cover",roomId:c.id,roomName:c.name,description:c.description,mediaCount:c.media.length}),c.media.forEach((d,u)=>{t.push({type:"media",roomId:c.id,roomName:c.name,url:d.url,kind:d.kind,index:u,total:c.media.length})})});const n=N.useRef(null),[r,a]=N.useState(0);N.useEffect(()=>{const c=n.current;if(!c)return;let d=0;const u=()=>{cancelAnimationFrame(d),d=requestAnimationFrame(()=>{const h=Math.round(c.scrollLeft/c.clientWidth);a(h)})};return c.addEventListener("scroll",u,{passive:!0}),()=>{c.removeEventListener("scroll",u),cancelAnimationFrame(d)}},[]);const i=c=>{const d=n.current;d&&d.scrollTo({left:c*d.clientWidth,behavior:"smooth"})};if(!t.length)return null;const l=(o=t[r])==null?void 0:o.roomId;return e.jsxs("div",{className:"md:hidden -mx-5",children:[e.jsx("div",{className:"px-5 py-3 overflow-x-auto sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md border-b border-white/10",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(c=>{const d=t.findIndex(h=>h.roomId===c.id),u=l===c.id;return e.jsx("button",{onClick:()=>i(d),className:Et("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"?G4e(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(fl,{className:"h-4 w-4"})," Prev"]}),e.jsxs("span",{className:"text-xs text-white/50",children:[r+1," / ",t.length]}),e.jsxs("button",{onClick:()=>i(Math.min(t.length-1,r+1)),disabled:r===t.length-1,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:["Next ",e.jsx(ga,{className:"h-4 w-4"})]})]})]})}const gje={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:Ci},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:yr},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:Nr},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:Zl}},aKt=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function iKt(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 oKt({openHouse:s,visitorId:t,visitorName:n,visitorEmail:r,visitorPhone:a,previewMode:i=!1}){var qe;const l=s.profiles,o=((qe=l==null?void 0:l.name)==null?void 0:qe.split(" ").map(ve=>ve[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=N.useState(null),[h,p]=N.useState(""),[f,g]=N.useState(r||""),[b,v]=N.useState(a||""),[j,_]=N.useState(!1),[S,A]=N.useState(null),[T,D]=N.useState(""),[L,M]=N.useState(""),[F,z]=N.useState(""),[V,W]=N.useState([]),[K,Y]=N.useState(""),[ee,ne]=N.useState(""),[oe,pe]=N.useState(""),[ce,de]=N.useState(""),ie=iKt(s.price),ye=s.tour_mode==="rooms",{data:_e=[]}=kBt(ye?s.id:void 0),Me=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),Te=ve=>{u(ve),p(""),D(""),M(""),z(""),W([]),Y(""),ne(""),pe(""),de("")},Ce=()=>{u(null)},Ee=ve=>{W(Je=>Je.includes(ve)?Je.filter(we=>we!==ve):[...Je,ve])},De=ve=>ve==="showing"?{preferred_date:T||null,preferred_time:L||null,alternate_date:F||null}:ve==="disclosure"?{requested_documents:V}:ve==="offer"?{offer_amount:K||null,financing:ee||null,timeline:oe||null,pre_approved:ce||null}:{},Ie=d?d==="showing"?!!T:d==="question"?h.trim().length>0:!0:!1,Fe=async()=>{if(d){if(i){Dr({title:"Preview mode",description:"Lead not sent — this is just a preview."}),A(d),setTimeout(()=>{u(null),A(null)},1500);return}_(!0);try{const ve=De(d),{error:Je}=await q.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:h.trim()||null,email:f.trim()||null,phone:b.trim()||null,visitor_name:n,...ve}});if(Je)throw Je;q.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:h.trim()||null,visitor_name:n,visitor_email:f.trim()||null,visitor_phone:b.trim()||null,extras:ve}}).catch(()=>{}),A(d),Dr({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{Ce(),A(null)},1400)}catch(ve){Dr({title:"Something went wrong",description:ve.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(Ca,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),ie&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:ie}),e.jsxs("div",{className:"flex flex-wrap gap-4 mt-4 text-sm text-white/80",children:[s.beds!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ny,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Tp,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(cy,{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(aa,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(ri,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(ia,{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(Pr,{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(Hs,{className:"h-4 w-4"})})]})]}),ye&&_e.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(nKt,{rooms:_e}),e.jsx(rKt,{rooms:_e})]}),Me.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:Me.map(ve=>{const Je=gje[ve],we=Je.icon;return e.jsxs("button",{onClick:()=>Te(ve),className:"flex items-center gap-3 p-4 rounded-xl bg-white text-slate-900 hover:bg-white/90 transition-colors text-left",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:c?{backgroundColor:`${c}1a`,color:c}:{backgroundColor:"#f1f5f9",color:"#334155"},children:e.jsx(we,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Je.label})]},ve)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(ug,{open:!!d,onOpenChange:ve=>!ve&&Ce(),children:e.jsx(ox,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(r0,{className:"text-left",children:[e.jsx(a0,{children:gje[d].title}),e.jsxs(lU,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),S===d?e.jsxs("div",{className:"py-10 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-green-100 flex items-center justify-center",children:e.jsx(xr,{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(se,{className:"text-xs",children:"Email"}),e.jsx(ge,{type:"email",value:f,onChange:ve=>g(ve.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(ge,{type:"tel",value:b,onChange:ve=>v(ve.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),d==="showing"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Preferred date *"}),e.jsx(ge,{type:"date",value:T,onChange:ve=>D(ve.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Preferred time"}),e.jsx(ge,{type:"time",value:L,onChange:ve=>M(ve.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(ge,{type:"date",value:F,onChange:ve=>z(ve.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:aKt.map(ve=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(hi,{checked:V.includes(ve),onCheckedChange:()=>Ee(ve)}),e.jsx("span",{children:ve})]},ve))})]}),d==="offer"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Estimated offer"}),e.jsx(ge,{value:K,onChange:ve=>Y(ve.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Financing"}),e.jsxs(us,{value:ee,onValueChange:ne,children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{placeholder:"Select..."})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"Cash",children:"Cash"}),e.jsx(Ze,{value:"Conventional",children:"Conventional"}),e.jsx(Ze,{value:"FHA",children:"FHA"}),e.jsx(Ze,{value:"VA",children:"VA"}),e.jsx(Ze,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Timeline"}),e.jsxs(us,{value:oe,onValueChange:pe,children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{placeholder:"Select..."})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"ASAP",children:"ASAP"}),e.jsx(Ze,{value:"30 days",children:"30 days"}),e.jsx(Ze,{value:"60 days",children:"60 days"}),e.jsx(Ze,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(us,{value:ce,onValueChange:de,children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{placeholder:"Select..."})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"Yes",children:"Yes"}),e.jsx(Ze,{value:"No",children:"No"}),e.jsx(Ze,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Ts,{value:h,onChange:ve=>p(ve.target.value),placeholder:gje[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(B,{onClick:Fe,disabled:j||!Ie,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:j?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const lKt=Zw({first_name:go().trim().min(1,"First name is required").max(50),last_name:go().trim().max(50).optional(),email:go().trim().email("Please enter a valid email").max(255).optional().or(Np("")),phone:go().trim().max(20).optional().or(Np(""))}),cKt=[{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 Ldt({slug:s}={}){var $e;const t=_i(),n=s||t.slug,[r]=yl(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=hBt(n),d=_Bt(),u=wBt(),h=jBt(),p=N.useRef(!1),[f,g]=N.useState("welcome"),[b,v]=N.useState(null),[j,_]=N.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[S,A]=N.useState(""),[T,D]=N.useState(!1),[L,M]=N.useState(!1),[F,z]=N.useState(""),[V,W]=N.useState(""),[K,Y]=N.useState(i),ee=N.useCallback(()=>{v(null),_({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),A(""),D(!1),M(!1),z(""),W(""),Y(i),g(a?"info":"welcome")},[a]),ne=N.useCallback((Ye,Ke)=>{l!=null&&l.id&&q.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:Ye,first_name:Ke.first_name??j.first_name,last_name:Ke.last_name??j.last_name,email:Ke.email??j.email,phone:Ke.phone??j.phone,visitor_intent:Ke.visitor_intent??S,message:Ke.message,wants_market_updates:Ke.wants_market_updates??T,has_agent:Ke.has_agent??L,working_with_agent_name:Ke.working_with_agent_name??F,visitor_address:Ke.visitor_address??j.visitor_address}}).catch(rt=>console.error("Guest book lead notify failed:",rt))},[l==null?void 0:l.id,j,S,T,L,F]);N.useEffect(()=>{if(!a||f!=="done")return;Y(i);const Ye=setInterval(()=>{Y(Ke=>Ke<=1?(clearInterval(Ye),ee(),0):Ke-1)},1e3);return()=>clearInterval(Ye)},[a,f,ee]),N.useEffect(()=>{if(!a)return;g(Ke=>Ke==="welcome"?"info":Ke);let Ye=null;return(async()=>{var Ke,rt;try{Ye=await((rt=(Ke=navigator.wakeLock)==null?void 0:Ke.request)==null?void 0:rt.call(Ke,"screen"))}catch{}})(),()=>{var Ke;try{(Ke=Ye==null?void 0:Ye.release)==null||Ke.call(Ye)}catch{}}},[a]);const oe=N.useCallback(()=>{var Ke;const Ye=document.documentElement;document.fullscreenElement||(Ke=Ye.requestFullscreen||Ye.webkitRequestFullscreen)==null||Ke.call(Ye).catch(()=>{})},[]),{data:pe,isLoading:ce}=pBt(l==null?void 0:l.id),de=!!(l!=null&&l.enable_survey),ie=(l==null?void 0:l.ask_visitor_intent)!==!1,ye=(l==null?void 0:l.ask_visitor_address)===!0;N.useEffect(()=>{if(!n||!(l!=null&&l.id)||p.current)return;const Ye=`oh_scan_${l.id}`;if(sessionStorage.getItem(Ye)){p.current=!0;return}p.current=!0,sessionStorage.setItem(Ye,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),N.useEffect(()=>{f==="pending_survey"&&(ce||g(de&&((pe==null?void 0:pe.length)??0)>0?"survey":"done"))},[f,ce,de,pe]);const _e=Ye=>{if(!Ye)return"";const[Ke,rt]=Ye.split(":"),tt=parseInt(Ke),at=tt>=12?"PM":"AM";return`${tt>12?tt-12:tt||12}:${rt} ${at}`},Me=async()=>{W("");const Ye=lKt.safeParse(j);if(!Ye.success){W(Ye.error.issues[0].message);return}if(!j.email&&!j.phone){W("Please provide either an email or phone number");return}const Ke=(l==null?void 0:l.kind)==="virtual";let rt=null;if(!b&&(l!=null&&l.id))try{const tt=await d.mutateAsync({open_house_id:l.id,first_name:j.first_name.trim(),last_name:j.last_name.trim()||void 0,email:j.email.trim()||void 0,phone:j.phone.trim()||void 0,visitor_address:ye&&j.visitor_address.trim()?j.visitor_address.trim():void 0,wants_market_updates:T,has_agent:L,working_with_agent_name:L&&F.trim()?F.trim():void 0,partial_signin:Ke?!1:ie});rt=tt.id,v(tt.id)}catch{if(Ke){W("We could not start the virtual tour. Please try again.");return}}if(Ke){ie?g("intent"):(rt&&ne(rt,{}),g("done"));return}if(!ie){rt&&ne(rt,{}),de?!ce&&pe&&pe.length>0?g("survey"):g("pending_survey"):g("done");return}g("intent")},Te=async Ye=>{A(Ye);try{let Ke=b;if(Ke?await u.mutateAsync({visitor_id:Ke,visitor_intent:Ye,wants_market_updates:T,has_agent:L,working_with_agent_name:L&&F.trim()?F.trim():null,partial_signin:!1}):(Ke=(await d.mutateAsync({open_house_id:l.id,first_name:j.first_name.trim(),last_name:j.last_name.trim()||void 0,email:j.email.trim()||void 0,phone:j.phone.trim()||void 0,visitor_address:ye&&j.visitor_address.trim()?j.visitor_address.trim():void 0,visitor_intent:Ye,wants_market_updates:T,has_agent:L,working_with_agent_name:L&&F.trim()?F.trim():void 0,partial_signin:!1})).id,v(Ke)),Ke&&ne(Ke,{visitor_intent:Ye,wants_market_updates:T,has_agent:L,working_with_agent_name:L&&F.trim()?F.trim():null}),(l==null?void 0:l.kind)==="virtual"){g("done");return}de?!ce&&pe&&pe.length>0?g("survey"):g("pending_survey"):g("done")}catch{W("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(zr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),e.jsx("p",{className:"text-white/60",children:"This sign-in page doesn't exist or is no longer active."})]})});const Ce=l.profiles,Ee=(($e=Ce==null?void 0:Ce.name)==null?void 0:$e.split(" ").map(Ye=>Ye[0]).join("").slice(0,2))||"?",De=l.event_type==="community",Ie=l.kind==="virtual",Fe=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Ie&&(Fe||f==="done"))return!Fe&&!b?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})}):e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsxs("title",{children:["Virtual Tour | ",l.property_address]}),e.jsx("meta",{name:"description",content:`Take a virtual tour of ${l.property_address}`}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),Fe&&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(oKt,{openHouse:l,visitorId:Fe?"preview":b,visitorName:Fe?"Preview Visitor":`${j.first_name} ${j.last_name}`.trim(),visitorEmail:Fe?"":j.email,visitorPhone:Fe?"":j.phone,previewMode:Fe})]});const ve=`${Ie?"Virtual Open House":De?"Community Event":"Open House"} — ${l.property_address}`,we=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?ks(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,Ce!=null&&Ce.name?`Hosted by ${Ce.name}`:null].filter(Boolean).join(" · "),it=l.photo_url||"",Ne=it&&it.includes("/storage/v1/object/public/")?it.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":it||"https://dashboard.relevelup.com/og-image.png",He=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${n}`;return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsx("title",{children:ve}),e.jsx("meta",{name:"description",content:we||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:ve}),e.jsx("meta",{property:"og:description",content:we||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:image",content:Ne}),e.jsx("meta",{property:"og:image:width",content:"1200"}),e.jsx("meta",{property:"og:image:height",content:"630"}),e.jsx("meta",{property:"og:url",content:He}),e.jsx("meta",{property:"og:site_name",content:"ReLevel Up"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ve}),e.jsx("meta",{name:"twitter:description",content:we||`Sign in to ${l.property_address}`}),e.jsx("meta",{name:"twitter:image",content:Ne}),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(aa,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(ri,{src:(Ce==null?void 0:Ce.avatar_url)||"",alt:(Ce==null?void 0:Ce.name)||""}),e.jsx(ia,{className:"bg-white/10 text-white text-lg",children:Ee})]}),e.jsx("p",{className:"text-white/60 text-sm",children:Ce==null?void 0:Ce.name}),(Ce==null?void 0:Ce.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:Ce.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[l.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{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(yr,{className:"h-3 w-3"}),ks(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(gr,{className:"h-3 w-3"}),_e(l.start_time),l.end_time?` – ${_e(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:De?e.jsx(Ga,{className:"h-5 w-5 text-white"}):e.jsx(zr,{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(Ca,{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(yr,{className:"h-3 w-3"}),ks(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(gr,{className:"h-3 w-3"}),_e(l.start_time),l.end_time?` – ${_e(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[f==="welcome"&&e.jsxs("div",{className:"text-center space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:l.agent_greeting||"Please sign in below."})]}),e.jsxs(B,{onClick:()=>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(za,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),f==="info"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>g("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(Wr,{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(se,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(ge,{value:j.first_name,onChange:Ye=>_(Ke=>({...Ke,first_name:Ye.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(ge,{value:j.last_name,onChange:Ye=>_(Ke=>({...Ke,last_name:Ye.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(ge,{type:"email",value:j.email,onChange:Ye=>_(Ke=>({...Ke,email:Ye.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(ge,{type:"tel",value:j.phone,onChange:Ye=>_(Ke=>({...Ke,phone:Ye.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),ye&&e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(ge,{value:j.visitor_address,onChange:Ye=>_(Ke=>({...Ke,visitor_address:Ye.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:T,onChange:Ye=>D(Ye.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:L?"Yes":"No"}),e.jsx(vn,{checked:L,onCheckedChange:M})]})]}),L&&e.jsx(ge,{value:F,onChange:Ye=>z(Ye.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),V&&e.jsx("p",{className:"text-destructive text-sm",children:V}),e.jsxs(B,{onClick:Me,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(za,{className:"h-5 w-5 ml-2"})]})]}),f==="intent"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>g("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(Wr,{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:cKt.map(Ye=>e.jsxs("button",{onClick:()=>Te(Ye.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:Ye.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Ye.label})]},Ye.value))}),V&&e.jsx("p",{className:"text-destructive text-sm text-center",children:V})]}),f==="pending_survey"&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),f==="survey"&&b&&pe&&e.jsx(ZWt,{questions:pe,visitorId:b,onComplete:()=>g("done"),onSkip:()=>g("done")}),f==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:e.jsx(xr,{className:"h-8 w-8 text-green-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"You're all set!"}),e.jsxs("p",{className:"text-slate-500 text-sm mt-1",children:["Thanks for signing in, ",j.first_name,". ",De?"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(Nr,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(Ce==null?void 0:Ce.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:Ce.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx(B,{onClick:ee,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),e.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",K,"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(jL,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:oe,className:"inline-flex items-center gap-1 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10 hover:bg-white/20",title:"Enter full screen",children:e.jsx(p9,{className:"h-3 w-3"})})]})]})})]})}function Wxn(s){const{user:t}=gs();return lt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_cohost_tokens").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n},enabled:!!t&&!!s})}function Kxn(){const s=Gt(),{user:t}=gs();return gt({mutationFn:async({openHouseId:n,label:r})=>{const{data:a,error:i}=await q.from("open_house_cohost_tokens").insert({open_house_id:n,label:r||null,created_by:t.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function Yxn(){const s=Gt();return gt({mutationFn:async({id:t,openHouseId:n})=>{const{error:r}=await q.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function dKt(s){return lt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(n)throw n;if(t.expires_at&&new Date(t.expires_at)t[n][r]??n,s)}var kMe="ScrollArea",[Ddt,Zxn]=gu(kMe),[hKt,e1]=Ddt(kMe),Rdt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,g]=N.useState(null),[b,v]=N.useState(null),[j,_]=N.useState(0),[S,A]=N.useState(0),[T,D]=N.useState(!1),[L,M]=N.useState(!1),F=Ti(t,V=>c(V)),z=kN(a);return e.jsx(hKt,{scope:n,type:r,dir:z,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:u,content:h,onContentChange:p,scrollbarX:f,onScrollbarXChange:g,scrollbarXEnabled:T,onScrollbarXEnabledChange:D,scrollbarY:b,onScrollbarYChange:v,scrollbarYEnabled:L,onScrollbarYEnabledChange:M,onCornerWidthChange:_,onCornerHeightChange:A,children:e.jsx(sa.div,{dir:z,...l,ref:F,style:{position:"relative","--radix-scroll-area-corner-width":j+"px","--radix-scroll-area-corner-height":S+"px",...s.style}})})});Rdt.displayName=kMe;var Odt="ScrollAreaViewport",Fdt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=s,l=e1(Odt,n),o=N.useRef(null),c=Ti(t,o,l.onViewportChange);return e.jsxs(e.Fragment,{children:[e.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:a}),e.jsx(sa.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:l.scrollbarXEnabled?"scroll":"hidden",overflowY:l.scrollbarYEnabled?"scroll":"hidden",...s.style},children:e.jsx("div",{ref:l.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Fdt.displayName=Odt;var Qw="ScrollAreaScrollbar",SMe=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=e1(Qw,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return N.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(mKt,{...r,ref:t,forceMount:n}):a.type==="scroll"?e.jsx(pKt,{...r,ref:t,forceMount:n}):a.type==="auto"?e.jsx(zdt,{...r,ref:t,forceMount:n}):a.type==="always"?e.jsx(CMe,{...r,ref:t}):null});SMe.displayName=Qw;var mKt=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=e1(Qw,s.__scopeScrollArea),[i,l]=N.useState(!1);return N.useEffect(()=>{const o=a.scrollArea;let c=0;if(o){const d=()=>{window.clearTimeout(c),l(!0)},u=()=>{c=window.setTimeout(()=>l(!1),a.scrollHideDelay)};return o.addEventListener("pointerenter",d),o.addEventListener("pointerleave",u),()=>{window.clearTimeout(c),o.removeEventListener("pointerenter",d),o.removeEventListener("pointerleave",u)}}},[a.scrollArea,a.scrollHideDelay]),e.jsx(Bh,{present:n||i,children:e.jsx(zdt,{"data-state":i?"visible":"hidden",...r,ref:t})})}),pKt=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=e1(Qw,s.__scopeScrollArea),i=s.orientation==="horizontal",l=Cye(()=>c("SCROLL_END"),100),[o,c]=uKt("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return N.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),N.useEffect(()=>{const d=a.viewport,u=i?"scrollLeft":"scrollTop";if(d){let h=d[u];const p=()=>{const f=d[u];h!==f&&(c("SCROLL"),l()),h=f};return d.addEventListener("scroll",p),()=>d.removeEventListener("scroll",p)}},[a.viewport,i,c,l]),e.jsx(Bh,{present:n||o!=="hidden",children:e.jsx(CMe,{"data-state":o==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:wr(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:wr(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),zdt=N.forwardRef((s,t)=>{const n=e1(Qw,s.__scopeScrollArea),{forceMount:r,...a}=s,[i,l]=N.useState(!1),o=s.orientation==="horizontal",c=Cye(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=s,a=e1(Qw,s.__scopeScrollArea),i=N.useRef(null),l=N.useRef(0),[o,c]=N.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Vdt(o.viewport,o.content),u={...r,sizes:o,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:p=>i.current=p,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:p=>l.current=p};function h(p,f){return bKt(p,l.current,o,f)}return n==="horizontal"?e.jsx(fKt,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const p=a.viewport.scrollLeft,f=KBe(p,o,a.dir);i.current.style.transform=`translate3d(${f}px, 0, 0)`}},onWheelScroll:p=>{a.viewport&&(a.viewport.scrollLeft=p)},onDragScroll:p=>{a.viewport&&(a.viewport.scrollLeft=h(p,a.dir))}}):n==="vertical"?e.jsx(xKt,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const p=a.viewport.scrollTop,f=KBe(p,o);i.current.style.transform=`translate3d(0, ${f}px, 0)`}},onWheelScroll:p=>{a.viewport&&(a.viewport.scrollTop=p)},onDragScroll:p=>{a.viewport&&(a.viewport.scrollTop=h(p))}}):null}),fKt=N.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=e1(Qw,s.__scopeScrollArea),[l,o]=N.useState(),c=N.useRef(null),d=Ti(t,c,i.onScrollbarXChange);return N.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx($dt,{"data-orientation":"horizontal",...a,ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Sye(n)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.x),onDragScroll:u=>s.onDragScroll(u.x),onWheelScroll:(u,h)=>{if(i.viewport){const p=i.viewport.scrollLeft+u.deltaX;s.onWheelScroll(p),Gdt(p,h)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:gfe(l.paddingLeft),paddingEnd:gfe(l.paddingRight)}})}})}),xKt=N.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=e1(Qw,s.__scopeScrollArea),[l,o]=N.useState(),c=N.useRef(null),d=Ti(t,c,i.onScrollbarYChange);return N.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx($dt,{"data-orientation":"vertical",...a,ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Sye(n)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.y),onDragScroll:u=>s.onDragScroll(u.y),onWheelScroll:(u,h)=>{if(i.viewport){const p=i.viewport.scrollTop+u.deltaY;s.onWheelScroll(p),Gdt(p,h)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:gfe(l.paddingTop),paddingEnd:gfe(l.paddingBottom)}})}})}),[gKt,Bdt]=Ddt(Qw),$dt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:a,onThumbChange:i,onThumbPointerUp:l,onThumbPointerDown:o,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:u,onResize:h,...p}=s,f=e1(Qw,n),[g,b]=N.useState(null),v=Ti(t,F=>b(F)),j=N.useRef(null),_=N.useRef(""),S=f.viewport,A=r.content-r.viewport,T=dh(u),D=dh(c),L=Cye(h,10);function M(F){if(j.current){const z=F.clientX-j.current.left,V=F.clientY-j.current.top;d({x:z,y:V})}}return N.useEffect(()=>{const F=z=>{const V=z.target;(g==null?void 0:g.contains(V))&&T(z,A)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[S,g,A,T]),N.useEffect(D,[r,D]),C8(g,L),C8(f.content,L),e.jsx(gKt,{scope:n,scrollbar:g,hasThumb:a,onThumbChange:dh(i),onThumbPointerUp:dh(l),onThumbPositionChange:D,onThumbPointerDown:dh(o),children:e.jsx(sa.div,{...p,ref:v,style:{position:"absolute",...p.style},onPointerDown:wr(s.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),j.current=g.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",f.viewport&&(f.viewport.style.scrollBehavior="auto"),M(F))}),onPointerMove:wr(s.onPointerMove,M),onPointerUp:wr(s.onPointerUp,F=>{const z=F.target;z.hasPointerCapture(F.pointerId)&&z.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=_.current,f.viewport&&(f.viewport.style.scrollBehavior=""),j.current=null})})})}),xfe="ScrollAreaThumb",Udt=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Bdt(xfe,s.__scopeScrollArea);return e.jsx(Bh,{present:n||a.hasThumb,children:e.jsx(yKt,{ref:t,...r})})}),yKt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,style:r,...a}=s,i=e1(xfe,n),l=Bdt(xfe,n),{onThumbPositionChange:o}=l,c=Ti(t,h=>l.onThumbChange(h)),d=N.useRef(void 0),u=Cye(()=>{d.current&&(d.current(),d.current=void 0)},100);return N.useEffect(()=>{const h=i.viewport;if(h){const p=()=>{if(u(),!d.current){const f=_Kt(h,o);d.current=f,o()}};return o(),h.addEventListener("scroll",p),()=>h.removeEventListener("scroll",p)}},[i.viewport,u,o]),e.jsx(sa.div,{"data-state":l.hasThumb?"visible":"hidden",...a,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:wr(s.onPointerDownCapture,h=>{const f=h.target.getBoundingClientRect(),g=h.clientX-f.left,b=h.clientY-f.top;l.onThumbPointerDown({x:g,y:b})}),onPointerUp:wr(s.onPointerUp,l.onThumbPointerUp)})});Udt.displayName=xfe;var TMe="ScrollAreaCorner",qdt=N.forwardRef((s,t)=>{const n=e1(TMe,s.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?e.jsx(vKt,{...s,ref:t}):null});qdt.displayName=TMe;var vKt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,...r}=s,a=e1(TMe,n),[i,l]=N.useState(0),[o,c]=N.useState(0),d=!!(i&&o);return C8(a.scrollbarX,()=>{var h;const u=((h=a.scrollbarX)==null?void 0:h.offsetHeight)||0;a.onCornerHeightChange(u),c(u)}),C8(a.scrollbarY,()=>{var h;const u=((h=a.scrollbarY)==null?void 0:h.offsetWidth)||0;a.onCornerWidthChange(u),l(u)}),d?e.jsx(sa.div,{...r,ref:t,style:{width:i,height:o,position:"absolute",right:a.dir==="ltr"?0:void 0,left:a.dir==="rtl"?0:void 0,bottom:0,...s.style}}):null});function gfe(s){return s?parseInt(s,10):0}function Vdt(s,t){const n=s/t;return isNaN(n)?0:n}function Sye(s){const t=Vdt(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}function bKt(s,t,n,r="ltr"){const a=Sye(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 Hdt([c,d],h)(s)}function KBe(s,t,n="ltr"){const r=Sye(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=hB(s,c);return Hdt([0,l],[0,o])(d)}function Hdt(s,t){return n=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(s[1]-s[0]);return t[0]+r*(n-s[0])}}function Gdt(s,t){return s>0&&s{})=>{let n={left:s.scrollLeft,top:s.scrollTop},r=0;return function a(){const i={left:s.scrollLeft,top:s.scrollTop},l=n.left!==i.left,o=n.top!==i.top;(l||o)&&t(),n=i,r=window.requestAnimationFrame(a)}(),()=>window.cancelAnimationFrame(r)};function Cye(s,t){const n=dh(s),r=N.useRef(0);return N.useEffect(()=>()=>window.clearTimeout(r.current),[]),N.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function C8(s,t){const n=dh(t);fh(()=>{let r=0;if(s){const a=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return a.observe(s),()=>{window.cancelAnimationFrame(r),a.unobserve(s)}}},[s,n])}var Wdt=Rdt,wKt=Fdt,jKt=qdt;const mi=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Wdt,{ref:r,className:Et("relative overflow-hidden",s),...n,children:[e.jsx(wKt,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(cU,{}),e.jsx(jKt,{})]}));mi.displayName=Wdt.displayName;const cU=N.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(SMe,{ref:r,orientation:t,className:Et("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(Udt,{className:"relative flex-1 rounded-full bg-border"})}));cU.displayName=SMe.displayName;const EMe=N.createContext({});function AMe(s){const t=N.useRef(null);return t.current===null&&(t.current=s()),t.current}const NKt=typeof window<"u",Kdt=NKt?N.useLayoutEffect:N.useEffect,Tye=N.createContext(null);function MMe(s,t){s.indexOf(t)===-1&&s.push(t)}function yfe(s,t){const n=s.indexOf(t);n>-1&&s.splice(n,1)}const Pw=(s,t,n)=>n>t?t:n{},T8=()=>{};const L4={},Ydt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function Zdt(s){return typeof s=="object"&&s!==null}const Qdt=s=>/^0[^.\s]+$/u.test(s);function Xdt(s){let t;return()=>(t===void 0&&(t=s()),t)}const qv=s=>s,kKt=(s,t)=>n=>t(s(n)),dU=(...s)=>s.reduce(kKt),fB=(s,t,n)=>{const r=t-s;return r===0?1:(n-s)/r};class IMe{constructor(){this.subscriptions=[]}add(t){return MMe(this.subscriptions,t),()=>yfe(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,Iv=s=>s/1e3;function Jdt(s,t){return t?s*(1e3/t):0}const eut=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,SKt=1e-7,CKt=12;function TKt(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=eut(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>SKt&&++oTKt(i,0,1,s,n);return i=>i===0||i===1?i:eut(a(i),t,r)}const tut=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,sut=s=>t=>1-s(1-t),nut=uU(.33,1.53,.69,.99),PMe=sut(nut),rut=tut(PMe),aut=s=>s>=1?1:(s*=2)<1?.5*PMe(s):.5*(2-Math.pow(2,-10*(s-1))),LMe=s=>1-Math.sin(Math.acos(s)),iut=sut(LMe),out=tut(LMe),EKt=uU(.42,0,1,1),AKt=uU(0,0,.58,1),lut=uU(.42,0,.58,1),MKt=s=>Array.isArray(s)&&typeof s[0]!="number",cut=s=>Array.isArray(s)&&typeof s[0]=="number",YBe={linear:qv,easeIn:EKt,easeInOut:lut,easeOut:AKt,circIn:LMe,circInOut:out,circOut:iut,backIn:PMe,backInOut:rut,backOut:nut,anticipate:aut},IKt=s=>typeof s=="string",ZBe=s=>{if(cut(s)){T8(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,r,a]=s;return uU(t,n,r,a)}else if(IKt(s))return T8(YBe[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),YBe[s];return s},lH=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],QBe={value:null,addProjectionMetrics:null};function PKt(s,t){let n=new Set,r=new Set,a=!1,i=!1;const l=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1},c=0;function d(h){l.has(h)&&(u.schedule(h),s()),c++,h(o)}const u={schedule:(h,p=!1,f=!1)=>{const b=f&&a?n:r;return p&&l.add(h),b.add(h),h},cancel:h=>{r.delete(h),l.delete(h)},process:h=>{if(o=h,a){i=!0;return}a=!0;const p=n;n=r,r=p,n.forEach(d),t&&QBe.value&&QBe.value.frameloop[t].push(c),c=0,n.clear(),a=!1,i&&(i=!1,u.process(h))}};return u}const LKt=40;function dut(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=lH.reduce((S,A)=>(S[A]=PKt(i,t?A:void 0),S),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:p,render:f,postRender:g}=l,b=()=>{const S=L4.useManualTiming,A=S?a.timestamp:performance.now();n=!1,S||(a.delta=r?1e3/60:Math.max(Math.min(A-a.timestamp,LKt),1)),a.timestamp=A,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),p.process(a),f.process(a),g.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(b))},v=()=>{n=!0,r=!0,a.isProcessing||s(b)};return{schedule:lH.reduce((S,A)=>{const T=l[A];return S[A]=(D,L=!1,M=!1)=>(n||v(),T.schedule(D,L,M)),S},{}),cancel:S=>{for(let A=0;A(Dme===void 0&&Kx.set(sf.isProcessing||L4.useManualTiming?sf.timestamp:performance.now()),Dme),set:s=>{Dme=s,queueMicrotask(DKt)}},uut=s=>t=>typeof t=="string"&&t.startsWith(s),hut=uut("--"),RKt=uut("var(--"),DMe=s=>RKt(s)?OKt.test(s.split("/*")[0].trim()):!1,OKt=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function XBe(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const WD={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},xB={...WD,transform:s=>Pw(0,1,s)},cH={...WD,default:1},J9=s=>Math.round(s*1e5)/1e5,RMe=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function FKt(s){return s==null}const zKt=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,OMe=(s,t)=>n=>!!(typeof n=="string"&&zKt.test(n)&&n.startsWith(s)||t&&!FKt(n)&&Object.prototype.hasOwnProperty.call(n,t)),mut=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(RMe);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},BKt=s=>Pw(0,255,s),vje={...WD,transform:s=>Math.round(BKt(s))},KE={test:OMe("rgb","red"),parse:mut("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+vje.transform(s)+", "+vje.transform(t)+", "+vje.transform(n)+", "+J9(xB.transform(r))+")"};function $Kt(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 W4e={test:OMe("#"),parse:$Kt,transform:KE.transform},hU=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),$k=hU("deg"),Nw=hU("%"),ci=hU("px"),UKt=hU("vh"),qKt=hU("vw"),JBe={...Nw,parse:s=>Nw.parse(s)/100,transform:s=>Nw.transform(s*100)},EP={test:OMe("hsl","hue"),parse:mut("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+Nw.transform(J9(t))+", "+Nw.transform(J9(n))+", "+J9(xB.transform(r))+")"},Xh={test:s=>KE.test(s)||W4e.test(s)||EP.test(s),parse:s=>KE.test(s)?KE.parse(s):EP.test(s)?EP.parse(s):W4e.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?KE.transform(s):EP.transform(s),getAnimatableNone:s=>{const t=Xh.parse(s);return t.alpha=0,Xh.transform(t)}},VKt=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function HKt(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(RMe))==null?void 0:t.length)||0)+(((n=s.match(VKt))==null?void 0:n.length)||0)>0}const put="number",fut="color",GKt="var",WKt="var(",e$e="${}",KKt=/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 E8(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(KKt,c=>(Xh.test(c)?(r.color.push(i),a.push(fut),n.push(Xh.parse(c))):c.startsWith(WKt)?(r.var.push(i),a.push(GKt),n.push(c)):(r.number.push(i),a.push(put),n.push(parseFloat(c))),++i,e$e)).split(e$e);return{values:n,split:o,indexes:r,types:a}}function YKt(s){return E8(s).values}function xut({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:Xh.test(s)?Xh.getAnimatableNone(s):s,XKt=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:QKt(s);function JKt(s){const t=E8(s);return xut(t)(t.values.map((r,a)=>XKt(r,t.split[a])))}const Nb={test:HKt,parse:YKt,createTransformer:ZKt,getAnimatableNone:JKt};function bje(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 eYt({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=bje(c,o,s+1/3),i=bje(c,o,s),l=bje(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function vfe(s,t){return n=>n>0?t:s}const $d=(s,t,n)=>s+(t-s)*n,_je=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},tYt=[W4e,KE,EP],sYt=s=>tYt.find(t=>t.test(s));function t$e(s){const t=sYt(s);if(Eye(!!t,`'${s}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(s);return t===EP&&(n=eYt(n)),n}const s$e=(s,t)=>{const n=t$e(s),r=t$e(t);if(!n||!r)return vfe(s,t);const a={...n};return i=>(a.red=_je(n.red,r.red,i),a.green=_je(n.green,r.green,i),a.blue=_je(n.blue,r.blue,i),a.alpha=$d(n.alpha,r.alpha,i),KE.transform(a))},K4e=new Set(["none","hidden"]);function nYt(s,t){return K4e.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function rYt(s,t){return n=>$d(s,t,n)}function FMe(s){return typeof s=="number"?rYt:typeof s=="string"?DMe(s)?vfe:Xh.test(s)?s$e:oYt:Array.isArray(s)?gut:typeof s=="object"?Xh.test(s)?s$e:aYt:vfe}function gut(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>FMe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function iYt(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=Nb.createTransformer(t),r=E8(s),a=E8(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?K4e.has(s)&&!a.values.length||K4e.has(t)&&!r.values.length?nYt(s,t):dU(gut(iYt(r,a),a.values),n):(Eye(!0,`Complex values '${s}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),vfe(s,t))};function yut(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?$d(s,t,n):FMe(s)(s,t)}const lYt=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>rd.update(t,n),stop:()=>D4(t),now:()=>sf.isProcessing?sf.timestamp:Kx.now()}},vut=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=bfe?1/0:t}function cYt(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(zMe(r),bfe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:Iv(a)}}const Eu={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 Y4e(s,t){return s*Math.sqrt(1-t*t)}const dYt=12;function uYt(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,p=u-n,f=Y4e(d,l),g=Math.exp(-h);return wje-p/f*g},i=d=>{const h=d*l*s,p=h*n+n,f=Math.pow(l,2)*Math.pow(d,2)*s,g=Math.exp(-h),b=Y4e(Math.pow(d,2),l);return(-a(d)+wje>0?-1:1)*((p-f)*g)/b}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-wje+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=uYt(a,i,o);if(s=Kg(s),isNaN(c))return{stiffness:Eu.stiffness,damping:Eu.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const mYt=["duration","bounce"],pYt=["stiffness","damping","mass"];function n$e(s,t){return t.some(n=>s[n]!==void 0)}function fYt(s){let t={velocity:Eu.velocity,stiffness:Eu.stiffness,damping:Eu.damping,mass:Eu.mass,isResolvedFromDuration:!1,...s};if(!n$e(s,pYt)&&n$e(s,mYt))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*Pw(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:Eu.mass,stiffness:a,damping:i}}else{const n=hYt({...s,velocity:0});t={...t,...n,mass:Eu.mass},t.isResolvedFromDuration=!0}return t}function _fe(s=Eu.visualDuration,t=Eu.bounce){const n=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:r,restDelta:a}=n;const i=n.keyframes[0],l=n.keyframes[n.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:u,duration:h,velocity:p,isResolvedFromDuration:f}=fYt({...n,velocity:-Iv(n.velocity||0)}),g=p||0,b=d/(2*Math.sqrt(c*u)),v=l-i,j=Iv(Math.sqrt(c/u)),_=Math.abs(v)<5;r||(r=_?Eu.restSpeed.granular:Eu.restSpeed.default),a||(a=_?Eu.restDelta.granular:Eu.restDelta.default);let S,A,T,D,L,M;if(b<1)T=Y4e(j,b),D=(g+b*j*v)/T,S=z=>{const V=Math.exp(-b*j*z);return l-V*(D*Math.sin(T*z)+v*Math.cos(T*z))},L=b*j*D+v*T,M=b*j*v-D*T,A=z=>Math.exp(-b*j*z)*(L*Math.sin(T*z)+M*Math.cos(T*z));else if(b===1){S=V=>l-Math.exp(-j*V)*(v+(g+j*v)*V);const z=g+j*v;A=V=>Math.exp(-j*V)*(j*z*V-g)}else{const z=j*Math.sqrt(b*b-1);S=Y=>{const ee=Math.exp(-b*j*Y),ne=Math.min(z*Y,300);return l-ee*((g+b*j*v)*Math.sinh(ne)+z*v*Math.cosh(ne))/z};const V=(g+b*j*v)/z,W=b*j*V-v*z,K=b*j*v-V*z;A=Y=>{const ee=Math.exp(-b*j*Y),ne=Math.min(z*Y,300);return ee*(W*Math.sinh(ne)+K*Math.cosh(ne))}}const F={calculatedDuration:f&&h||null,velocity:z=>Kg(A(z)),next:z=>{if(!f&&b<1){const W=Math.exp(-b*j*z),K=Math.sin(T*z),Y=Math.cos(T*z),ee=l-W*(D*K+v*Y),ne=Kg(W*(L*K+M*Y));return o.done=Math.abs(ne)<=r&&Math.abs(l-ee)<=a,o.value=o.done?l:ee,o}const V=S(z);if(f)o.done=z>=h;else{const W=Kg(A(z));o.done=Math.abs(W)<=r&&Math.abs(l-V)<=a}return o.value=o.done?l:V,o},toString:()=>{const z=Math.min(zMe(F),bfe),V=vut(W=>F.next(z*W).value,z,30);return z+"ms "+V},toTransition:()=>{}};return F}_fe.applyToOptions=s=>{const t=cYt(s,100,_fe);return s.ease=t.ease,s.duration=Kg(t.duration),s.type="keyframes",s};const xYt=5;function but(s,t,n){const r=Math.max(t-xYt,0);return Jdt(n-s(r),t-r)}function Z4e({keyframes:s,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:u}){const h=s[0],p={done:!1,value:h},f=M=>o!==void 0&&Mc,g=M=>o===void 0?c:c===void 0||Math.abs(o-M)-b*Math.exp(-M/r),S=M=>j+_(M),A=M=>{const F=_(M),z=S(M);p.done=Math.abs(F)<=d,p.value=p.done?j:z};let T,D;const L=M=>{f(p.value)&&(T=M,D=_fe({keyframes:[p.value,g(p.value)],velocity:but(S,M,p.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return L(0),{calculatedDuration:null,next:M=>{let F=!1;return!D&&T===void 0&&(F=!0,A(M),L(M)),T!==void 0&&M>=T?D.next(M-T):(!F&&A(M),p)}}}function gYt(s,t,n){const r=[],a=n||L4.mix||yut,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=gYt(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(Pw(s[0],s[i-1],u)):d}function vYt(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=fB(0,t,r);s.push($d(n,1,a))}}function bYt(s){const t=[0];return vYt(t,s.length-1),t}function _Yt(s,t){return s.map(n=>n*t)}function wYt(s,t){return s.map(()=>t||lut).splice(0,s.length-1)}function ez({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=MKt(r)?r.map(ZBe):ZBe(r),i={done:!1,value:t[0]},l=_Yt(n&&n.length===t.length?n:bYt(t),s),o=yYt(l,t,{ease:Array.isArray(a)?a:wYt(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const jYt=s=>s!==null;function Aye(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(jYt),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const NYt={decay:Z4e,inertia:Z4e,tween:ez,keyframes:ez,spring:_fe};function _ut(s){typeof s.type=="string"&&(s.type=NYt[s.type])}class BMe{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 kYt=s=>s/100;class wfe extends BMe{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!==Kx.now()&&this.tick(Kx.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;_ut(t);const{type:n=ez,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||ez;c!==ez&&typeof o[0]!="number"&&(this.mixKeyframes=dU(kYt,yut(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=zMe(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+a,this.totalDuration=this.resolvedDuration*(r+1)-a,this.generator=d}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:r,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:u,repeat:h,repeatType:p,repeatDelay:f,type:g,onUpdate:b,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-a/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const j=this.currentTime-d*(this.playbackSpeed>=0?1:-1),_=this.playbackSpeed>=0?j<0:j>a;this.currentTime=Math.max(j,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let S=this.currentTime,A=r;if(h){const M=Math.min(this.currentTime,a)/o;let F=Math.floor(M),z=M%1;!z&&M>=1&&(z=1),z===1&&F--,F=Math.min(F,h+1),!!(F%2)&&(p==="reverse"?(z=1-z,f&&(z-=f/o)):p==="mirror"&&(A=l)),S=Pw(0,1,z)*o}let T;_?(this.delayState.value=u[0],T=this.delayState):T=A.next(S),i&&!_&&(T.value=i(T.value));let{done:D}=T;!_&&c!==null&&(D=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const L=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return L&&g!==Z4e&&(T.value=Aye(u,this.options,v,this.speed)),b&&b(T.value),L&&this.finish(),T}then(t,n){return this.finished.then(t,n)}get duration(){return Iv(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Iv(t)}get time(){return Iv(this.currentTime)}set time(t){t=Kg(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 but(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(Kx.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=Iv(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=lYt,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(Kx.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 SYt(s){for(let t=1;ts*180/Math.PI,Q4e=s=>{const t=YE(Math.atan2(s[1],s[0]));return X4e(t)},CYt={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:Q4e,rotateZ:Q4e,skewX:s=>YE(Math.atan(s[1])),skewY:s=>YE(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},X4e=s=>(s=s%360,s<0&&(s+=360),s),r$e=Q4e,a$e=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),i$e=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),TYt={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:a$e,scaleY:i$e,scale:s=>(a$e(s)+i$e(s))/2,rotateX:s=>X4e(YE(Math.atan2(s[6],s[5]))),rotateY:s=>X4e(YE(Math.atan2(-s[2],s[0]))),rotateZ:r$e,rotate:r$e,skewX:s=>YE(Math.atan(s[4])),skewY:s=>YE(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function J4e(s){return s.includes("scale")?1:0}function eCe(s,t){if(!s||s==="none")return J4e(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=TYt,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=CYt,a=o}if(!a)return J4e(t);const i=r[t],l=a[1].split(",").map(AYt);return typeof i=="function"?i(l):l[i]}const EYt=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return eCe(n,t)};function AYt(s){return parseFloat(s.trim())}const KD=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],YD=new Set(KD),o$e=s=>s===WD||s===ci,MYt=new Set(["x","y","z"]),IYt=KD.filter(s=>!MYt.has(s));function PYt(s){const t=[];return IYt.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const IS={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})=>eCe(t,"x"),y:(s,{transform:t})=>eCe(t,"y")};IS.translateX=IS.x;IS.translateY=IS.y;const HA=new Set;let tCe=!1,sCe=!1,nCe=!1;function wut(){if(sCe){const s=Array.from(HA).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=PYt(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)})}sCe=!1,tCe=!1,HA.forEach(s=>s.complete(nCe)),HA.clear()}function jut(){HA.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(sCe=!0)})}function LYt(){nCe=!0,jut(),wut(),nCe=!1}class $Me{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?(HA.add(this),tCe||(tCe=!0,rd.read(jut),rd.resolveKeyframes(wut))):(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])}SYt(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),HA.delete(this)}cancel(){this.state==="scheduled"&&(HA.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const DYt=s=>s.startsWith("--");function Nut(s,t,n){DYt(t)?s.style.setProperty(t,n):s.style[t]=n}const RYt={};function kut(s,t){const n=Xdt(s);return()=>RYt[t]??n()}const OYt=kut(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),Sut=kut(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),x7=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,l$e={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:x7([0,.65,.55,1]),circOut:x7([.55,0,1,.45]),backIn:x7([.31,.01,.66,-.59]),backOut:x7([.33,1.53,.69,.99])};function Cut(s,t){if(s)return typeof s=="function"?Sut()?vut(s,t):"ease-out":cut(s)?x7(s):Array.isArray(s)?s.map(n=>Cut(n,t)||l$e.easeOut):l$e[s]}function FYt(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=Cut(o,a);Array.isArray(h)&&(u.easing=h);const p={delay:r,duration:a,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(p.pseudoElement=d),s.animate(u,p)}function Tut(s){return typeof s=="function"&&"applyToOptions"in s}function zYt({type:s,...t}){return Tut(s)&&Sut()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Eut extends BMe{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,T8(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=zYt(t);this.animation=FYt(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=Aye(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),Nut(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 Iv(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Iv(t)}get time(){return Iv(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Kg(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&&OYt()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),qv):a(this)}}const Aut={anticipate:aut,backInOut:rut,circInOut:out};function BYt(s){return s in Aut}function $Yt(s){typeof s.ease=="string"&&BYt(s.ease)&&(s.ease=Aut[s.ease])}const jje=10;class UYt extends Eut{constructor(t){$Yt(t),_ut(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 wfe({...l,autoplay:!1}),c=Math.max(jje,Kx.now()-this.startTime),d=Pw(0,jje,c-jje),u=o.sample(c).value,{name:h}=this.options;i&&h&&Nut(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const c$e=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(Nb.test(s)||s==="0")&&!s.startsWith("url("));function qYt(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function YYt(s){var h;const{motionValue:t,name:n,repeatDelay:r,repeatType:a,damping:i,type:l,keyframes:o}=s;if(!(((h=t==null?void 0:t.owner)==null?void 0:h.current)instanceof HTMLElement))return!1;const{onUpdate:d,transformTemplate:u}=t.owner.getProps();return KYt()&&n&&(Mut.has(n)||WYt.has(n)&&GYt(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const ZYt=40;class QYt extends BMe{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 b,v;this._animation&&(this._animation.stop(),(b=this.stopTimeline)==null||b.call(this)),(v=this.keyframeResolver)==null||v.cancel()},this.createdAt=Kx.now();const p={autoplay:t,delay:n,type:r,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:u,...h},f=(u==null?void 0:u.KeyframeResolver)||$Me;this.keyframeResolver=new f(o,(b,v,j)=>this.onKeyframesResolved(b,v,p,!j),c,d,u),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(t,n,r,a){var j,_;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=Kx.now();let h=!0;VYt(t,i,l,o)||(h=!1,(L4.instantAnimations||!c)&&(u==null||u(Aye(t,r,n))),t[0]=t[t.length-1],rCe(r),r.repeat=0);const f={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>ZYt?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},g=h&&!d&&YYt(f),b=(_=(j=f.motionValue)==null?void 0:j.owner)==null?void 0:_.current;let v;if(g)try{v=new UYt({...f,element:b})}catch{v=new wfe(f)}else v=new wfe(f);v.finished.then(()=>{this.notifyFinished()}).catch(qv),this.pendingTimeline&&(this.stopTimeline=v.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=v}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),LYt()),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 Iut(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 XYt=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function JYt(s){const t=XYt.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}const eZt=4;function Put(s,t,n=1){T8(n<=eZt,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[r,a]=JYt(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return Ydt(l)?parseFloat(l):l}return DMe(a)?Put(a,t,n+1):a}const tZt={type:"spring",stiffness:500,damping:25,restSpeed:10},sZt=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),nZt={type:"keyframes",duration:.8},rZt={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},aZt=(s,{keyframes:t})=>t.length>2?nZt:YD.has(s)?s.startsWith("scale")?sZt(t[1]):tZt:rZt;function Lut(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function UMe(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?Lut(n,s):n}const iZt=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function oZt(s){for(const t in s)if(!iZt.has(t))return!0;return!1}const qMe=(s,t,n,r={},a,i)=>l=>{const o=UMe(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Kg(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:p=>{t.set(p),o.onUpdate&&o.onUpdate(p)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};oZt(o)||Object.assign(u,aZt(s,u)),u.duration&&(u.duration=Kg(u.duration)),u.repeatDelay&&(u.repeatDelay=Kg(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(rCe(u),u.delay===0&&(h=!0)),(L4.instantAnimations||L4.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(h=!0,rCe(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const p=Aye(u.keyframes,o);if(p!==void 0){rd.update(()=>{u.onUpdate(p),u.onComplete()});return}}return o.isSync?new wfe(u):new QYt(u)};function d$e(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function VMe(s,t,n,r){if(typeof t=="function"){const[a,i]=d$e(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]=d$e(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function GA(s,t,n){const r=s.getProps();return VMe(r,t,n!==void 0?n:r.custom,s)}const Dut=new Set(["width","height","top","left","right","bottom",...KD]),u$e=30,lZt=s=>!isNaN(parseFloat(s));class cZt{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=Kx.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=Kx.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=lZt(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 IMe);const r=this.events[t].add(n);return t==="change"?()=>{r(),rd.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=Kx.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>u$e)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,u$e);return Jdt(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 A8(s,t){return new cZt(s,t)}const aCe=s=>Array.isArray(s);function dZt(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,A8(n))}function uZt(s){return aCe(s)?s[s.length-1]||0:s}function hZt(s,t){const n=GA(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=uZt(i[l]);dZt(s,l,o)}}const uf=s=>!!(s&&s.getVelocity);function mZt(s){return!!(uf(s)&&s.add)}function iCe(s,t){const n=s.getValue("willChange");if(mZt(n))return n.add(t);if(!n&&L4.WillChange){const r=new L4.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function HMe(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const pZt="framerAppearId",Rut="data-"+HMe(pZt);function Out(s){return s.props[Rut]}function fZt({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function Fut(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?Lut(i,c):c;const d=i==null?void 0:i.reduceMotion;r&&(i=r);const u=[],h=a&&s.animationState&&s.animationState.getState()[a];for(const p in o){const f=s.getValue(p,s.latestValues[p]??null),g=o[p];if(g===void 0||h&&fZt(h,p))continue;const b={delay:n,...UMe(i||{},p)},v=f.get();if(v!==void 0&&!f.isAnimating()&&!Array.isArray(g)&&g===v&&!b.velocity){rd.update(()=>f.set(g));continue}let j=!1;if(window.MotionHandoffAnimation){const A=Out(s);if(A){const T=window.MotionHandoffAnimation(A,p,rd);T!==null&&(b.startTime=T,j=!0)}}iCe(s,p);const _=d??s.shouldReduceMotion;f.start(qMe(p,f,g,_&&Dut.has(p)?{type:!1}:b,s,j));const S=f.animation;S&&u.push(S)}if(l){const p=()=>rd.update(()=>{l&&hZt(s,l)});u.length?Promise.all(u).then(p):p()}return u}function oCe(s,t,n={}){var c;const r=GA(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(Fut(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:p}=a;return xZt(s,t,d,u,h,p,n)}:()=>Promise.resolve(),{when:o}=a;if(o){const[d,u]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>u())}else return Promise.all([i(),l(n.delay)])}function xZt(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(oCe(c,t,{...l,delay:n+(typeof r=="function"?0:r)+Iut(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function gZt(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>oCe(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=oCe(s,t,n);else{const a=typeof t=="function"?GA(s,t,n.custom):t;r=Promise.all(Fut(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const yZt={test:s=>s==="auto",parse:s=>s},zut=s=>t=>t.test(s),But=[WD,ci,Nw,$k,qKt,UKt,yZt],h$e=s=>But.find(zut(s));function vZt(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||Qdt(s):!0}const bZt=new Set(["brightness","contrast","saturate","opacity"]);function _Zt(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(RMe)||[];if(!r)return s;const a=n.replace(r,"");let i=bZt.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const wZt=/\b([a-z-]*)\(.*?\)/gu,lCe={...Nb,getAnimatableNone:s=>{const t=s.match(wZt);return t?t.map(_Zt).join(" "):s}},cCe={...Nb,getAnimatableNone:s=>{const t=Nb.parse(s);return Nb.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},m$e={...WD,transform:Math.round},jZt={rotate:$k,rotateX:$k,rotateY:$k,rotateZ:$k,scale:cH,scaleX:cH,scaleY:cH,scaleZ:cH,skew:$k,skewX:$k,skewY:$k,distance:ci,translateX:ci,translateY:ci,translateZ:ci,x:ci,y:ci,z:ci,perspective:ci,transformPerspective:ci,opacity:xB,originX:JBe,originY:JBe,originZ:ci},GMe={borderWidth:ci,borderTopWidth:ci,borderRightWidth:ci,borderBottomWidth:ci,borderLeftWidth:ci,borderRadius:ci,borderTopLeftRadius:ci,borderTopRightRadius:ci,borderBottomRightRadius:ci,borderBottomLeftRadius:ci,width:ci,maxWidth:ci,height:ci,maxHeight:ci,top:ci,right:ci,bottom:ci,left:ci,inset:ci,insetBlock:ci,insetBlockStart:ci,insetBlockEnd:ci,insetInline:ci,insetInlineStart:ci,insetInlineEnd:ci,padding:ci,paddingTop:ci,paddingRight:ci,paddingBottom:ci,paddingLeft:ci,paddingBlock:ci,paddingBlockStart:ci,paddingBlockEnd:ci,paddingInline:ci,paddingInlineStart:ci,paddingInlineEnd:ci,margin:ci,marginTop:ci,marginRight:ci,marginBottom:ci,marginLeft:ci,marginBlock:ci,marginBlockStart:ci,marginBlockEnd:ci,marginInline:ci,marginInlineStart:ci,marginInlineEnd:ci,fontSize:ci,backgroundPositionX:ci,backgroundPositionY:ci,...jZt,zIndex:m$e,fillOpacity:xB,strokeOpacity:xB,numOctaves:m$e},NZt={...GMe,color:Xh,backgroundColor:Xh,outlineColor:Xh,fill:Xh,stroke:Xh,borderColor:Xh,borderTopColor:Xh,borderRightColor:Xh,borderBottomColor:Xh,borderLeftColor:Xh,filter:lCe,WebkitFilter:lCe,mask:cCe,WebkitMask:cCe},$ut=s=>NZt[s],kZt=new Set([lCe,cCe]);function Uut(s,t){let n=$ut(s);return kZt.has(n)||(n=Nb),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const SZt=new Set(["auto","none","0"]);function CZt(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function WMe(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 qut=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function Rme(s){return Zdt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:KMe,cancel:Qxn}=dut(queueMicrotask,!1),V1={x:!1,y:!1};function Vut(){return V1.x||V1.y}function EZt(s){return s==="x"||s==="y"?V1[s]?null:(V1[s]=!0,()=>{V1[s]=!1}):V1.x||V1.y?null:(V1.x=V1.y=!0,()=>{V1.x=V1.y=!1})}function Hut(s,t){const n=WMe(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function AZt(s){return!(s.pointerType==="touch"||Vut())}function MZt(s,t,n={}){const[r,a,i]=Hut(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",g)},h=v=>{d&&(d(v),d=void 0),u()},p=v=>{o=!1,window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),c&&(c=!1,h(v))},f=()=>{o=!0,window.addEventListener("pointerup",p,a),window.addEventListener("pointercancel",p,a)},g=v=>{if(v.pointerType!=="touch"){if(o){c=!0;return}h(v)}},b=v=>{if(!AZt(v))return;c=!1;const j=t(l,v);typeof j=="function"&&(d=j,l.addEventListener("pointerleave",g,a))};l.addEventListener("pointerenter",b,a),l.addEventListener("pointerdown",f,a)}),i}const Gut=(s,t)=>t?s===t?!0:Gut(s,t.parentElement):!1,YMe=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,IZt=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function PZt(s){return IZt.has(s.tagName)||s.isContentEditable===!0}const LZt=new Set(["INPUT","SELECT","TEXTAREA"]);function DZt(s){return LZt.has(s.tagName)||s.isContentEditable===!0}const Ome=new WeakSet;function p$e(s){return t=>{t.key==="Enter"&&s(t)}}function Nje(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const RZt=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=p$e(()=>{if(Ome.has(n))return;Nje(n,"down");const a=p$e(()=>{Nje(n,"up")}),i=()=>Nje(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 f$e(s){return YMe(s)&&!Vut()}const x$e=new WeakSet;function OZt(s,t,n={}){const[r,a,i]=Hut(s,n),l=o=>{const c=o.currentTarget;if(!f$e(o)||x$e.has(o))return;Ome.add(c),n.stopPropagation&&x$e.add(o);const d=t(c,o),u=(f,g)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",p),Ome.has(c)&&Ome.delete(c),f$e(f)&&typeof d=="function"&&d(f,{success:g})},h=f=>{u(f,c===window||c===document||n.useGlobalTarget||Gut(c,f.target))},p=f=>{u(f,!1)};window.addEventListener("pointerup",h,a),window.addEventListener("pointercancel",p,a)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),Rme(o)&&(o.addEventListener("focus",d=>RZt(d,a)),!PZt(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function ZMe(s){return Zdt(s)&&"ownerSVGElement"in s}const Fme=new WeakMap;let Uk;const Wut=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:ZMe(r)&&"getBBox"in r?r.getBBox()[t]:r[n],FZt=Wut("inline","width","offsetWidth"),zZt=Wut("block","height","offsetHeight");function BZt({target:s,borderBoxSize:t}){var n;(n=Fme.get(s))==null||n.forEach(r=>{r(s,{get width(){return FZt(s,t)},get height(){return zZt(s,t)}})})}function $Zt(s){s.forEach(BZt)}function UZt(){typeof ResizeObserver>"u"||(Uk=new ResizeObserver($Zt))}function qZt(s,t){Uk||UZt();const n=WMe(s);return n.forEach(r=>{let a=Fme.get(r);a||(a=new Set,Fme.set(r,a)),a.add(t),Uk==null||Uk.observe(r)}),()=>{n.forEach(r=>{const a=Fme.get(r);a==null||a.delete(t),a!=null&&a.size||Uk==null||Uk.unobserve(r)})}}const zme=new Set;let AP;function VZt(){AP=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};zme.forEach(t=>t(s))},window.addEventListener("resize",AP)}function HZt(s){return zme.add(s),AP||VZt(),()=>{zme.delete(s),!zme.size&&typeof AP=="function"&&(window.removeEventListener("resize",AP),AP=void 0)}}function g$e(s,t){return typeof s=="function"?HZt(s):qZt(s,t)}function GZt(s){return ZMe(s)&&s.tagName==="svg"}const WZt=[...But,Xh,Nb],KZt=s=>WZt.find(zut(s)),y$e=()=>({translate:0,scale:1,origin:0,originPoint:0}),MP=()=>({x:y$e(),y:y$e()}),v$e=()=>({min:0,max:0}),Am=()=>({x:v$e(),y:v$e()}),YZt=new WeakMap;function Mye(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function gB(s){return typeof s=="string"||Array.isArray(s)}const QMe=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],XMe=["initial",...QMe];function Iye(s){return Mye(s.animate)||XMe.some(t=>gB(s[t]))}function Kut(s){return!!(Iye(s)||s.variants)}function ZZt(s,t,n){for(const r in t){const a=t[r],i=n[r];if(uf(a))s.addValue(r,a);else if(uf(i))s.addValue(r,A8(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,A8(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const dCe={current:null},Yut={current:!1},QZt=typeof window<"u";function XZt(){if(Yut.current=!0,!!QZt)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>dCe.current=s.matches;s.addEventListener("change",t),t()}else dCe.current=!1}const b$e=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let jfe={};function Zut(s){jfe=s}function JZt(){return jfe}class eQt{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=$Me,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=Kx.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(Yut.current||XZt(),this.shouldReduceMotion=dCe.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(),D4(this.notifyUpdate),D4(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&&Mut.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new Eut({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:Kg(u)}),p=l(h);this.valueSubscriptions.set(t,()=>{p(),h.cancel()});return}const r=YD.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&rd.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;typeof window<"u"&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{a(),i&&i(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in jfe){const n=jfe[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):Am()}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=A8(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"&&(Ydt(r)||Qdt(r))?r=parseFloat(r):!KZt(r)&&Nb.test(n)&&(r=Uut(t,n)),this.setBaseTarget(t,uf(r)?r.get():r)),uf(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=VMe(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&&!uf(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 IMe),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){KMe.render(this.render)}}class Qut extends eQt{constructor(){super(...arguments),this.KeyframeResolver=TZt}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;uf(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class eC{constructor(t){this.isMounted=!1,this.node=t}update(){}}function Xut({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function tQt({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function sQt(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 kje(s){return s===void 0||s===1}function uCe({scale:s,scaleX:t,scaleY:n}){return!kje(s)||!kje(t)||!kje(n)}function IE(s){return uCe(s)||Jut(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function Jut(s){return _$e(s.x)||_$e(s.y)}function _$e(s){return s&&s!=="0%"}function Nfe(s,t,n){const r=s-n,a=t*r;return n+a}function w$e(s,t,n,r,a){return a!==void 0&&(s=Nfe(s,a,r)),Nfe(s,n,r)+t}function hCe(s,t=0,n=1,r,a){s.min=w$e(s.min,t,n,r,a),s.max=w$e(s.max,t,n,r,a)}function eht(s,{x:t,y:n}){hCe(s.x,t.translate,t.scale,t.originPoint),hCe(s.y,n.translate,n.scale,n.originPoint)}const j$e=.999999999999,N$e=1.0000000000001;function nQt(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;cj$e&&(t.x=1),t.yj$e&&(t.y=1)}function Q_(s,t){s.min+=t,s.max+=t}function k$e(s,t,n,r,a=.5){const i=$d(s.min,s.max,a);hCe(s,t,n,i,r)}function S$e(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function Bme(s,t,n){const r=n??s;k$e(s.x,S$e(t.x,r.x),t.scaleX,t.scale,t.originX),k$e(s.y,S$e(t.y,r.y),t.scaleY,t.scale,t.originY)}function tht(s,t){return Xut(sQt(s.getBoundingClientRect(),t))}function rQt(s,t,n){const r=tht(s,n),{scroll:a}=t;return a&&(Q_(r.x,a.offset.x),Q_(r.y,a.offset.y)),r}const aQt={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},iQt=KD.length;function oQt(s,t,n){let r="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(ci.test(s))s=parseFloat(s);else return s;const n=C$e(s,t.target.x),r=C$e(s,t.target.y);return`${n}% ${r}%`}},lQt={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=Nb.parse(s);if(a.length>5)return r;const i=Nb.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=$d(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},mCe={borderRadius:{...uF,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:uF,borderTopRightRadius:uF,borderBottomLeftRadius:uF,borderBottomRightRadius:uF,boxShadow:lQt};function nht(s,{layout:t,layoutId:n}){return YD.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!mCe[s]||s==="opacity")}function e6e(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)(uf(r[o])||a&&uf(a[o])||nht(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function cQt(s){return window.getComputedStyle(s)}class dQt extends Qut{constructor(){super(...arguments),this.type="html",this.renderInstance=sht}readValueFromInstance(t,n){var r;if(YD.has(n))return(r=this.projection)!=null&&r.isProjecting?J4e(n):EYt(t,n);{const a=cQt(t),i=(hut(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return tht(t,n)}build(t,n,r){JMe(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return e6e(t,n,r)}}const uQt={offset:"stroke-dashoffset",array:"stroke-dasharray"},hQt={offset:"strokeDashoffset",array:"strokeDasharray"};function mQt(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?uQt:hQt;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const pQt=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function rht(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(JMe(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:h,style:p}=s;h.transform&&(p.transform=h.transform,delete h.transform),(p.transform||h.transformOrigin)&&(p.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),p.transform&&(p.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete h.transformBox);for(const f of pQt)h[f]!==void 0&&(p[f]=h[f],delete h[f]);t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),a!==void 0&&mQt(h,a,i,l,!1)}const aht=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"]),iht=s=>typeof s=="string"&&s.toLowerCase()==="svg";function fQt(s,t,n,r){sht(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(aht.has(a)?a:HMe(a),t.attrs[a])}function oht(s,t,n){const r=e6e(s,t,n);for(const a in s)if(uf(s[a])||uf(t[a])){const i=KD.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class xQt extends Qut{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Am}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(YD.has(n)){const r=$ut(n);return r&&r.default||0}return n=aht.has(n)?n:HMe(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return oht(t,n,r)}build(t,n,r){rht(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){fQt(t,n,r,a)}mount(t){this.isSVGTag=iht(t.tagName),super.mount(t)}}const gQt=XMe.length;function lht(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?lht(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})=>gZt(s,n,r)))}function _Qt(s){let t=bQt(s),n=T$e(),r=!0,a=!1;const i=d=>(u,h)=>{var f;const p=GA(s,h,d==="exit"?(f=s.presenceContext)==null?void 0:f.custom:void 0);if(p){const{transition:g,transitionEnd:b,...v}=p;u={...u,...v,...b}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=lht(s.parent)||{},p=[],f=new Set;let g={},b=1/0;for(let j=0;jb&&T,z=!1;const V=Array.isArray(A)?A:[A];let W=V.reduce(i(_),{});D===!1&&(W={});const{prevResolvedValues:K={}}=S,Y={...K,...W},ee=pe=>{F=!0,f.has(pe)&&(z=!0,f.delete(pe)),S.needsAnimating[pe]=!0;const ce=s.getValue(pe);ce&&(ce.liveStyle=!1)};for(const pe in Y){const ce=W[pe],de=K[pe];if(g.hasOwnProperty(pe))continue;let ie=!1;aCe(ce)&&aCe(de)?ie=!cht(ce,de):ie=ce!==de,ie?ce!=null?ee(pe):f.add(pe):ce!==void 0&&f.has(pe)?ee(pe):S.protectedKeys[pe]=!0}S.prevProp=A,S.prevResolvedValues=W,S.isActive&&(g={...g,...W}),(r||a)&&s.blockInitialAnimation&&(F=!1);const ne=L&&M;F&&(!ne||z)&&p.push(...V.map(pe=>{const ce={type:_};if(typeof pe=="string"&&(r||a)&&!ne&&s.manuallyAnimateOnMount&&s.parent){const{parent:de}=s,ie=GA(de,pe);if(de.enteringChildren&&ie){const{delayChildren:ye}=ie.transition||{};ce.delay=Iut(de.enteringChildren,s,ye)}}return{animation:pe,options:ce}}))}if(f.size){const j={};if(typeof u.initial!="boolean"){const _=GA(s,Array.isArray(u.initial)?u.initial[0]:u.initial);_&&_.transition&&(j.transition=_.transition)}f.forEach(_=>{const S=s.getBaseTarget(_),A=s.getValue(_);A&&(A.liveStyle=!0),j[_]=S??null}),p.push({animation:j})}let v=!!p.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(v=!1),r=!1,a=!1,v?t(p):Promise.resolve()}function c(d,u){var p;if(n[d].isActive===u)return Promise.resolve();(p=s.variantChildren)==null||p.forEach(f=>{var g;return(g=f.animationState)==null?void 0:g.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const f in n)n[f].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=T$e(),a=!0}}}function wQt(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!cht(t,s):!1}function u3(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function T$e(){return{animate:u3(!0),whileInView:u3(),whileHover:u3(),whileTap:u3(),whileDrag:u3(),whileFocus:u3(),exit:u3()}}function pCe(s,t){s.min=t.min,s.max=t.max}function z1(s,t){pCe(s.x,t.x),pCe(s.y,t.y)}function E$e(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const dht=1e-4,jQt=1-dht,NQt=1+dht,uht=.01,kQt=0-uht,SQt=0+uht;function Yx(s){return s.max-s.min}function CQt(s,t,n){return Math.abs(s-t)<=n}function A$e(s,t,n,r=.5){s.origin=r,s.originPoint=$d(t.min,t.max,s.origin),s.scale=Yx(n)/Yx(t),s.translate=$d(n.min,n.max,s.origin)-s.originPoint,(s.scale>=jQt&&s.scale<=NQt||isNaN(s.scale))&&(s.scale=1),(s.translate>=kQt&&s.translate<=SQt||isNaN(s.translate))&&(s.translate=0)}function tz(s,t,n,r){A$e(s.x,t.x,n.x,r?r.originX:void 0),A$e(s.y,t.y,n.y,r?r.originY:void 0)}function M$e(s,t,n,r=0){const a=r?$d(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+Yx(t)}function TQt(s,t,n,r){M$e(s.x,t.x,n.x,r==null?void 0:r.x),M$e(s.y,t.y,n.y,r==null?void 0:r.y)}function I$e(s,t,n,r=0){const a=r?$d(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+Yx(t)}function kfe(s,t,n,r){I$e(s.x,t.x,n.x,r==null?void 0:r.x),I$e(s.y,t.y,n.y,r==null?void 0:r.y)}function P$e(s,t,n,r,a){return s-=t,s=Nfe(s,1/n,r),a!==void 0&&(s=Nfe(s,1/a,r)),s}function EQt(s,t=0,n=1,r=.5,a,i=s,l=s){if(Nw.test(t)&&(t=parseFloat(t),t=$d(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=$d(i.min,i.max,r);s===i&&(o-=t),s.min=P$e(s.min,t,n,o,a),s.max=P$e(s.max,t,n,o,a)}function L$e(s,t,[n,r,a],i,l){EQt(s,t[n],t[r],t[a],t.scale,i,l)}const AQt=["x","scaleX","originX"],MQt=["y","scaleY","originY"];function D$e(s,t,n,r){L$e(s.x,t,AQt,n?n.x:void 0,r?r.x:void 0),L$e(s.y,t,MQt,n?n.y:void 0,r?r.y:void 0)}function R$e(s){return s.translate===0&&s.scale===1}function hht(s){return R$e(s.x)&&R$e(s.y)}function O$e(s,t){return s.min===t.min&&s.max===t.max}function IQt(s,t){return O$e(s.x,t.x)&&O$e(s.y,t.y)}function F$e(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function mht(s,t){return F$e(s.x,t.x)&&F$e(s.y,t.y)}function z$e(s){return Yx(s.x)/Yx(s.y)}function B$e(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function B_(s){return[s("x"),s("y")]}function PQt(s,t,n){let r="";const a=s.x.translate/t.x,i=s.y.translate/t.y,l=(n==null?void 0:n.z)||0;if((a||i||l)&&(r=`translate3d(${a}px, ${i}px, ${l}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:d,rotate:u,rotateX:h,rotateY:p,skewX:f,skewY:g}=n;d&&(r=`perspective(${d}px) ${r}`),u&&(r+=`rotate(${u}deg) `),h&&(r+=`rotateX(${h}deg) `),p&&(r+=`rotateY(${p}deg) `),f&&(r+=`skewX(${f}deg) `),g&&(r+=`skewY(${g}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 pht=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],LQt=pht.length,$$e=s=>typeof s=="string"?parseFloat(s):s,U$e=s=>typeof s=="number"||ci.test(s);function DQt(s,t,n,r,a,i){a?(s.opacity=$d(0,n.opacity??1,RQt(r)),s.opacityExit=$d(t.opacity??1,0,OQt(r))):i&&(s.opacity=$d(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(fB(s,t,r))}function FQt(s,t,n){const r=uf(s)?s:A8(s);return r.start(qMe("",r,t,n)),r.animation}function yB(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n)}const zQt=(s,t)=>s.depth-t.depth;class BQt{constructor(){this.children=[],this.isDirty=!1}add(t){MMe(this.children,t),this.isDirty=!0}remove(t){yfe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(zQt),this.isDirty=!1,this.children.forEach(t)}}function $Qt(s,t){const n=Kx.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(D4(r),s(i-t))};return rd.setup(r,!0),()=>D4(r)}function $me(s){return uf(s)?s.get():s}class UQt{constructor(){this.members=[]}add(t){MMe(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&&(yfe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(yfe(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 Ume={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Sje=["","X","Y","Z"],qQt=1e3;let VQt=0;function Cje(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function xht(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=Out(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",rd,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&xht(r)}function ght({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=VQt++,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(WQt),this.nodes.forEach(JQt),this.nodes.forEach(eXt),this.nodes.forEach(KQt)},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;rd.read(()=>{h=window.innerWidth}),s(l,()=>{const f=window.innerWidth;f!==h&&(h=f,this.root.updateBlockedByResize=!0,u&&u(),u=$Qt(p,250),Ume.hasAnimatedSinceResize&&(Ume.hasAnimatedSinceResize=!1,this.nodes.forEach(G$e)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:p,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||aXt,{onLayoutAnimationStart:b,onLayoutAnimationComplete:v}=d.getProps(),j=!this.targetLayout||!mht(this.targetLayout,f),_=!h&&p;if(this.options.layoutRoot||this.resumeFrom||_||h&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const S={...UMe(g,"layout"),onPlay:b,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(S.delay=0,S.type=!1),this.startAnimation(S),this.setAnimationOrigin(u,_)}else h||G$e(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),D4(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(tXt),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&&xht(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&&!Yx(this.snapshot.measuredBox.x)&&!Yx(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 T=A/1e3;W$e(h.x,l.x,T),W$e(h.y,l.y,T),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(kfe(p,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),nXt(this.relativeTarget,this.relativeTargetOrigin,p,T),S&&IQt(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=Am()),z1(S,this.relativeTarget)),b&&(this.animationValues=u,DQt(u,d,this.latestValues,T,_,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=T},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&&(D4(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=rd.update(()=>{Ume.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=A8(0)),this.motionValue.jump(0,!1),this.currentAnimation=FQt(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),l.onUpdate&&l.onUpdate(u)},onStop:()=>{},onComplete:()=>{l.onComplete&&l.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(qQt),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&&yht(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Am();const h=Yx(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const p=Yx(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+p}z1(o,c),Bme(o,u),tz(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new UQt),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&&Cje("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(V$e),this.root.sharedNodes.clear()}}}function HQt(s){s.updateLayout()}function GQt(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")B_(h=>{const p=l?t.measuredBox[h]:t.layoutBox[h],f=Yx(p);p.min=r[h].min,p.max=p.min+f});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";pCe(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else yht(i,t.layoutBox,r)&&B_(h=>{const p=l?t.measuredBox[h]:t.layoutBox[h],f=Yx(r[h]);p.max=p.min+f,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[h].max=s.relativeTarget[h].min+f)});const o=MP();tz(o,r,t.layoutBox);const c=MP();l?tz(c,s.applyTransform(a,!0),t.measuredBox):tz(c,r,t.layoutBox);const d=!hht(o);let u=!1;if(!s.resumeFrom){const h=s.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:p,layout:f}=h;if(p&&f){const g=s.options.layoutAnchor||void 0,b=Am();kfe(b,t.layoutBox,p.layoutBox,g);const v=Am();kfe(v,r,f.layoutBox,g),mht(b,v)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=v,s.relativeTargetOrigin=b,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 WQt(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 KQt(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function YQt(s){s.clearSnapshot()}function V$e(s){s.clearMeasurements()}function ZQt(s){s.isLayoutDirty=!0,s.updateLayout()}function H$e(s){s.isLayoutDirty=!1}function QQt(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function XQt(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function G$e(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function JQt(s){s.resolveTargetDelta()}function eXt(s){s.calcProjection()}function tXt(s){s.resetSkewAndRotation()}function sXt(s){s.removeLeadSnapshot()}function W$e(s,t,n){s.translate=$d(t.translate,0,n),s.scale=$d(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function K$e(s,t,n,r){s.min=$d(t.min,n.min,r),s.max=$d(t.max,n.max,r)}function nXt(s,t,n,r){K$e(s.x,t.x,n.x,r),K$e(s.y,t.y,n.y,r)}function rXt(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const aXt={duration:.45,ease:[.4,0,.1,1]},Y$e=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),Z$e=Y$e("applewebkit/")&&!Y$e("chrome/")?Math.round:qv;function Q$e(s){s.min=Z$e(s.min),s.max=Z$e(s.max)}function iXt(s){Q$e(s.x),Q$e(s.y)}function yht(s,t,n){return s==="position"||s==="preserve-aspect"&&!CQt(z$e(t),z$e(n),.2)}function oXt(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const lXt=ght({attachResizeListener:(s,t)=>yB(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}),Tje={current:void 0},vht=ght({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!Tje.current){const s=new lXt({});s.mount(window),s.setOptions({layoutScroll:!0}),Tje.current=s}return Tje.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),t6e=N.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function X$e(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function cXt(...s){return t=>{let n=!1;const r=s.map(a=>{const i=X$e(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:f,height:g,top:b,left:v,right:j,bottom:_}=c.current;if(t||i===!1||!o.current||!f||!g)return;const S=n==="left"?`left: ${v}`:`right: ${j}`,A=r==="bottom"?`bottom: ${_}`:`top: ${b}`;o.current.dataset.motionPopId=l;const T=document.createElement("style");d&&(T.nonce=d);const D=a??document.head;return D.appendChild(T),T.sheet&&T.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${f}px !important; height: ${g}px !important; ${S}px !important; ${A}px !important; } `),()=>{var L;(L=o.current)==null||L.removeAttribute("data-motion-pop-id"),D.contains(T)&&D.removeChild(T)}},[t]),e.jsx(uXt,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:N.cloneElement(s,{ref:h})})}const mXt=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=AMe(pXt),h=N.useId();let p=!0,f=N.useMemo(()=>(p=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:g=>{u.set(g,!0);for(const b of u.values())if(!b)return;r&&r()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,r]);return i&&p&&(f={...f}),N.useMemo(()=>{u.forEach((g,b)=>u.set(b,!1))},[n]),N.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(hXt,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(Tye.Provider,{value:f,children:s})};function pXt(){return new Map}function bht(s=!0){const t=N.useContext(Tye);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:a}=t,i=N.useId();N.useEffect(()=>{if(s)return a(i)},[s]);const l=N.useCallback(()=>s&&r&&r(i),[i,r,s]);return!n&&r?[!1,l]:[!0]}const dH=s=>s.key||"";function J$e(s){const t=[];return N.Children.forEach(s,n=>{N.isValidElement(n)&&t.push(n)}),t}const Pye=({children:s,custom:t,initial:n=!0,onExitComplete:r,presenceAffectsLayout:a=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",anchorY:c="top",root:d})=>{const[u,h]=bht(l),p=N.useMemo(()=>J$e(s),[s]),f=l&&!u?[]:p.map(dH),g=N.useRef(!0),b=N.useRef(p),v=AMe(()=>new Map),j=N.useRef(new Set),[_,S]=N.useState(p),[A,T]=N.useState(p);Kdt(()=>{g.current=!1,b.current=p;for(let M=0;M{const F=dH(M),z=l&&!u?!1:p===A||f.includes(F),V=()=>{if(j.current.has(F))return;if(v.has(F))j.current.add(F),v.set(F,!0);else return;let W=!0;v.forEach(K=>{K||(W=!1)}),W&&(L==null||L(),T(b.current),l&&(h==null||h()),r&&r())};return e.jsx(mXt,{isPresent:z,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:z?void 0:V,anchorX:o,anchorY:c,children:M},F)})})},_ht=N.createContext({strict:!1}),eUe={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 tUe=!1;function fXt(){if(tUe)return;const s={};for(const t in eUe)s[t]={isEnabled:n=>eUe[t].some(r=>!!n[r])};Zut(s),tUe=!0}function wht(){return fXt(),JZt()}function xXt(s){const t=wht();for(const n in s)t[n]={...t[n],...s[n]};Zut(t)}const gXt=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 Sfe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||gXt.has(s)}let jht=s=>!Sfe(s);function yXt(s){typeof s=="function"&&(jht=t=>t.startsWith("on")?!Sfe(t):s(t))}try{yXt(require("@emotion/is-prop-valid").default)}catch{}function vXt(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||uf(s[a])||(jht(a)||n===!0&&Sfe(a)||!t&&!Sfe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const Lye=N.createContext({});function bXt(s,t){if(Iye(s)){const{initial:n,animate:r}=s;return{initial:n===!1||gB(n)?n:void 0,animate:gB(r)?r:void 0}}return s.inherit!==!1?t:{}}function _Xt(s){const{initial:t,animate:n}=bXt(s,N.useContext(Lye));return N.useMemo(()=>({initial:t,animate:n}),[sUe(t),sUe(n)])}function sUe(s){return Array.isArray(s)?s.join(" "):s}const s6e=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Nht(s,t,n){for(const r in t)!uf(t[r])&&!nht(r,n)&&(s[r]=t[r])}function wXt({transformTemplate:s},t){return N.useMemo(()=>{const n=s6e();return JMe(n,t,s),Object.assign({},n.vars,n.style)},[t])}function jXt(s,t){const n=s.style||{},r={};return Nht(r,n,s),Object.assign(r,wXt(s,t)),r}function NXt(s,t){const n={},r=jXt(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 kht=()=>({...s6e(),attrs:{}});function kXt(s,t,n,r){const a=N.useMemo(()=>{const i=kht();return rht(i,t,iht(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};Nht(i,s.style,s),a.style={...i,...a.style}}return a}const SXt=["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 n6e(s){return typeof s!="string"||s.includes("-")?!1:!!(SXt.indexOf(s)>-1||/[A-Z]/u.test(s))}function CXt(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??n6e(s)?kXt:NXt)(t,r,a,s),d=vXt(t,typeof s=="string",i),u=s!==N.Fragment?{...d,...c,ref:n}:{},{children:h}=t,p=N.useMemo(()=>uf(h)?h.get():h,[h]);return N.createElement(s,{...u,children:p})}function TXt({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:EXt(n,r,a,s),renderState:t()}}function EXt(s,t,n,r){const a={},i=r(s,{});for(const p in i)a[p]=$me(i[p]);let{initial:l,animate:o}=s;const c=Iye(s),d=Kut(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"&&!Mye(h)){const p=Array.isArray(h)?h:[h];for(let f=0;f(t,n)=>{const r=N.useContext(Lye),a=N.useContext(Tye),i=()=>TXt(s,t,r,a);return n?i():AMe(i)},AXt=Sht({scrapeMotionValuesFromProps:e6e,createRenderState:s6e}),MXt=Sht({scrapeMotionValuesFromProps:oht,createRenderState:kht}),IXt=Symbol.for("motionComponentSymbol");function PXt(s,t,n){const r=N.useRef(n);N.useInsertionEffect(()=>{r.current=n});const a=N.useRef(null);return N.useCallback(i=>{var o;i&&((o=s.onMount)==null||o.call(s,i));const l=r.current;if(typeof l=="function")if(i){const c=l(i);typeof c=="function"&&(a.current=c)}else a.current?(a.current(),a.current=null):l(i);else l&&(l.current=i);t&&(i?t.mount(i):t.unmount())},[t])}const Cht=N.createContext({});function iP(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function LXt(s,t,n,r,a,i){var S,A;const{visualElement:l}=N.useContext(Lye),o=N.useContext(_ht),c=N.useContext(Tye),d=N.useContext(t6e),u=d.reducedMotion,h=d.skipAnimations,p=N.useRef(null),f=N.useRef(!1);r=r||o.renderer,!p.current&&r&&(p.current=r(s,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:i}),f.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const g=p.current,b=N.useContext(Cht);g&&!g.projection&&a&&(g.type==="html"||g.type==="svg")&&DXt(p.current,n,a,b);const v=N.useRef(!1);N.useInsertionEffect(()=>{g&&v.current&&g.update(n,c)});const j=n[Rut],_=N.useRef(!!j&&typeof window<"u"&&!((S=window.MotionHandoffIsComplete)!=null&&S.call(window,j))&&((A=window.MotionHasOptimisedAnimation)==null?void 0:A.call(window,j)));return Kdt(()=>{f.current=!0,g&&(v.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),_.current&&g.animationState&&g.animationState.animateChanges())}),N.useEffect(()=>{g&&(!_.current&&g.animationState&&g.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var T;(T=window.MotionHandoffMarkAsComplete)==null||T.call(window,j)}),_.current=!1),g.enteringChildren=void 0)}),g}function DXt(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:Tht(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&iP(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function Tht(s){if(s)return s.options.allowProjection!==!1?s.projection:Tht(s.parent)}function Eje(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&xXt(r);const i=n?n==="svg":n6e(s),l=i?MXt:AXt;function o(d,u){let h;const p={...N.useContext(t6e),...d,layoutId:RXt(d)},{isStatic:f}=p,g=_Xt(d),b=l(d,f);if(!f&&typeof window<"u"){OXt();const v=FXt(p);h=v.MeasureLayout,g.visualElement=LXt(s,b,p,a,v.ProjectionNode,i)}return e.jsxs(Lye.Provider,{value:g,children:[h&&g.visualElement?e.jsx(h,{visualElement:g.visualElement,...p}):null,CXt(s,d,PXt(b,g.visualElement,u),b,f,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=N.forwardRef(o);return c[IXt]=s,c}function RXt({layoutId:s}){const t=N.useContext(EMe).id;return t&&s!==void 0?t+"-"+s:s}function OXt(s,t){N.useContext(_ht).strict}function FXt(s){const t=wht(),{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 zXt(s,t){if(typeof Proxy>"u")return Eje;const n=new Map,r=(i,l)=>Eje(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,Eje(l,void 0,s,t)),n.get(l))})}const BXt=(s,t)=>t.isSVG??n6e(s)?new xQt(t):new dQt(t,{allowProjection:s!==N.Fragment});class $Xt extends eC{constructor(t){super(t),t.animationState||(t.animationState=_Qt(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Mye(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 UXt=0;class qXt extends eC{constructor(){super(...arguments),this.id=UXt++,this.isExitComplete=!1}update(){var i;if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===r)return;if(t&&r===!1){if(this.isExitComplete){const{initial:l,custom:o}=this.node.getProps();if(typeof l=="string"){const c=GA(this.node,l,o);if(c){const{transition:d,transitionEnd:u,...h}=c;for(const p in h)(i=this.node.getValue(p))==null||i.jump(h[p])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const a=this.node.animationState.setActive("exit",!t);n&&!t&&a.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const VXt={animation:{Feature:$Xt},exit:{Feature:qXt}};function mU(s){return{point:{x:s.pageX,y:s.pageY}}}const HXt=s=>t=>YMe(t)&&s(t,mU(t));function sz(s,t,n,r){return yB(s,t,HXt(n),r)}const Eht=({current:s})=>s?s.ownerDocument.defaultView:null,nUe=(s,t)=>Math.abs(s-t);function GXt(s,t){const n=nUe(s.x,t.x),r=nUe(s.y,t.y);return Math.sqrt(n**2+r**2)}const rUe=new Set(["auto","scroll"]);class Aht{constructor(t,n,{transformPagePoint:r,contextWindow:a=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=f=>{this.handleScroll(f.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=uH(this.lastRawMoveEventInfo,this.transformPagePoint));const f=Aje(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,b=GXt(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!b)return;const{point:v}=f,{timestamp:j}=sf;this.history.push({...v,timestamp:j});const{onStart:_,onMove:S}=this.handlers;g||(_&&_(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastRawMoveEventInfo=g,this.lastMoveEventInfo=uH(g,this.transformPagePoint),rd.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:b,onSessionEnd:v,resumeAnimation:j}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&j&&j(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const _=Aje(f.type==="pointercancel"?this.lastMoveEventInfo:uH(g,this.transformPagePoint),this.history);this.startEvent&&b&&b(f,_),v&&v(f,_)},!YMe(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=mU(t),d=uH(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=sf;this.history=[{...u,timestamp:h}];const{onSessionStart:p}=n;p&&p(t,Aje(d,this.history)),this.removeListeners=dU(sz(this.contextWindow,"pointermove",this.handlePointerMove),sz(this.contextWindow,"pointerup",this.handlePointerUp),sz(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(rUe.has(r.overflowX)||rUe.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),rd.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),D4(this.updatePoint)}}function uH(s,t){return t?{point:t(s.point)}:s}function aUe(s,t){return{x:s.x-t.x,y:s.y-t.y}}function Aje({point:s},t){return{point:s,delta:aUe(s,Mht(t)),offset:aUe(s,WXt(t)),velocity:KXt(t,.1)}}function WXt(s){return s[0]}function Mht(s){return s[s.length-1]}function KXt(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=Mht(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>Kg(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>Kg(t)*2&&(r=s[1]);const i=Iv(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 YXt(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?$d(n,s,r.max):Math.min(s,n)),s}function iUe(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 ZXt(s,{top:t,left:n,bottom:r,right:a}){return{x:iUe(s.x,n,a),y:iUe(s.y,t,r)}}function oUe(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=fB(t.min,t.max-r,s.min):r>a&&(n=fB(s.min,s.max-a,t.min)),Pw(0,1,n)}function JXt(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 fCe=.35;function eJt(s=fCe){return s===!1?s=0:s===!0&&(s=fCe),{x:lUe(s,"left","right"),y:lUe(s,"top","bottom")}}function lUe(s,t,n){return{min:cUe(s,t),max:cUe(s,n)}}function cUe(s,t){return typeof s=="number"?s:s[t]||0}const tJt=new WeakMap;class sJt{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=Am(),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(mU(h).point),this.stopAnimation()},l=(h,p)=>{const{drag:f,dragPropagation:g,onDragStart:b}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=EZt(f),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=p,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),B_(j=>{let _=this.getAxisMotionValue(j).get()||0;if(Nw.test(_)){const{projection:S}=this.visualElement;if(S&&S.layout){const A=S.layout.layoutBox[j];A&&(_=Yx(A)*(parseFloat(_)/100))}}this.originPoint[j]=_}),b&&rd.update(()=>b(h,p),!1,!0),iCe(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},o=(h,p)=>{this.latestPointerEvent=h,this.latestPanInfo=p;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:b,onDrag:v}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:j}=p;if(g&&this.currentDirection===null){this.currentDirection=rJt(j),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",p.point,j),this.updateAxis("y",p.point,j),this.visualElement.render(),v&&rd.update(()=>v(h,p),!1,!0)},c=(h,p)=>{this.latestPointerEvent=h,this.latestPanInfo=p,this.stop(h,p),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new Aht(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:Eht(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&&rd.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||!hH(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=YXt(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&&iP(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=ZXt(r.layoutBox,t):this.constraints=!1,this.elastic=eJt(n),a!==this.constraints&&!iP(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&B_(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=JXt(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!iP(t))return!1;const r=t.current;T8(r!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:a}=this.visualElement;if(!a||!a.layout)return!1;const i=rQt(r,a.root,this.visualElement.getTransformPagePoint());let l=QXt(a.layout.layoutBox,i);if(n){const o=n(tQt(l));this.hasMutatedConstraints=!!o,o&&(l=Xut(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=B_(u=>{if(!hH(u,n,this.currentDirection))return;let h=c&&c[u]||{};(l===!0||l===u)&&(h={min:0,max:0});const p=a?200:1e6,f=a?40:1e7,g={type:"inertia",velocity:r?t[u]:0,bounceStiffness:p,bounceDamping:f,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 iCe(this.visualElement,t),r.start(qMe(t,r,0,n,this.visualElement,!1))}stopAnimation(){B_(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,r=this.visualElement.getProps(),a=r[n];return a||this.visualElement.getValue(t,(r.initial?r.initial[t]:void 0)||0)}snapToCursor(t){B_(n=>{const{drag:r}=this.getProps();if(!hH(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]-$d(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!iP(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};B_(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=XXt({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(),B_(l=>{if(!hH(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set($d(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;tJt.set(this.visualElement,this);const t=this.visualElement.current,n=sz(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),p=d.target,f=p!==t&&DZt(p);u&&h&&!f&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();iP(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=nJt(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),rd.read(a);const o=yB(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(B_(h=>{const p=this.getAxisMotionValue(h);p&&(this.originPoint[h]+=d[h].translate,p.set(p.get()+d[h].translate))}),this.visualElement.render())});return()=>{o(),n(),l(),c&&c(),r&&r()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:a=!1,dragConstraints:i=!1,dragElastic:l=fCe,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function dUe(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function nJt(s,t,n){const r=g$e(s,dUe(n)),a=g$e(t,dUe(n));return()=>{r(),a()}}function hH(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function rJt(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class aJt extends eC{constructor(t){super(t),this.removeGroupControls=qv,this.removeListeners=qv,this.controls=new sJt(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||qv}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 Mje=s=>(t,n)=>{s&&rd.update(()=>s(t,n),!1,!0)};class iJt extends eC{constructor(){super(...arguments),this.removePointerDownListener=qv}onPointerDown(t){this.session=new Aht(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Eht(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:Mje(t),onStart:Mje(n),onMove:Mje(r),onEnd:(i,l)=>{delete this.session,a&&rd.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=sz(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 Ije=!1;class oJt extends N.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:a}=this.props,{projection:i}=t;i&&(n.group&&n.group.add(i),r&&r.register&&a&&r.register(i),Ije&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Ume.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}),Ije=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||rd.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(),KMe.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;Ije=!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 Iht(s){const[t,n]=bht(),r=N.useContext(EMe);return e.jsx(oJt,{...s,layoutGroup:r,switchLayoutGroup:N.useContext(Cht),isPresent:t,safeToRemove:n})}const lJt={pan:{Feature:iJt},drag:{Feature:aJt,ProjectionNode:vht,MeasureLayout:Iht}};function uUe(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&&rd.postRender(()=>i(t,mU(t)))}class cJt extends eC{mount(){const{current:t}=this.node;t&&(this.unmount=MZt(t,(n,r)=>(uUe(this.node,r,"Start"),a=>uUe(this.node,a,"End"))))}unmount(){}}class dJt extends eC{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=dU(yB(this.node.current,"focus",()=>this.onFocus()),yB(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function hUe(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&&rd.postRender(()=>i(t,mU(t)))}class uJt extends eC{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=OZt(t,(a,i)=>(hUe(this.node,i,"Start"),(l,{success:o})=>hUe(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const xCe=new WeakMap,Pje=new WeakMap,hJt=s=>{const t=xCe.get(s.target);t&&t(s)},mJt=s=>{s.forEach(hJt)};function pJt({root:s,...t}){const n=s||document;Pje.has(n)||Pje.set(n,{});const r=Pje.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(mJt,{root:s,...t})),r[a]}function fJt(s,t,n){const r=pJt(t);return xCe.set(s,n),r.observe(s),()=>{xCe.delete(s),r.unobserve(s)}}const xJt={some:0,all:1};class gJt extends eC{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:xJt[a]},o=d=>{const{isIntersecting:u}=d;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:h,onViewportLeave:p}=this.node.getProps(),f=u?h:p;f&&f(d)};this.stopObserver=fJt(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(yJt(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function yJt({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const vJt={inView:{Feature:gJt},tap:{Feature:uJt},focus:{Feature:dJt},hover:{Feature:cJt}},bJt={layout:{ProjectionNode:vht,MeasureLayout:Iht}},_Jt={...VXt,...vJt,...lJt,...bJt},Zn=zXt(_Jt,BXt),wJt={some:0,all:1};function jJt(s,t,{root:n,margin:r,amount:a="some"}={}){const i=WMe(s),l=new WeakMap,o=d=>{d.forEach(u=>{const h=l.get(u.target);if(u.isIntersecting!==!!h)if(u.isIntersecting){const p=t(u.target,u);typeof p=="function"?l.set(u.target,p):c.unobserve(u.target)}else typeof h=="function"&&(h(u),l.delete(u.target))})},c=new IntersectionObserver(o,{root:n,rootMargin:r,threshold:typeof a=="number"?a:wJt[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function NJt(s,{root:t,margin:n,amount:r,once:a=!1,initial:i=!1}={}){const[l,o]=N.useState(i);return N.useEffect(()=>{if(!s.current||a&&l)return;const c=()=>(o(!0),a?void 0:()=>o(!1)),d={root:t&&t.current||void 0,margin:n,amount:r};return jJt(s.current,c,d)},[t,s,n,a,r]),l}function kJt(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 mUe(s){return s.visitor_intent==="buying"&&!s.has_agent}function SJt({token:s}={}){var g;const t=_i(),n=s||t.token,{data:r,isLoading:a,isError:i}=dKt(n),l=Gt(),o=(g=r==null?void 0:r.open_houses)==null?void 0:g.id,{data:c}=lt({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:b,error:v}=await q.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(v)throw v;return b},enabled:!!o});if(N.useEffect(()=>{if(!o)return;const b=q.channel(`cohost-visitors-${o}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${o}`},()=>{l.invalidateQueries({queryKey:["cohost-visitors",o]})}).subscribe();return()=>{q.removeChannel(b)}},[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(b=>b.visitor_intent==="buying").length)||0,p=(c==null?void 0:c.filter(mUe).length)||0,f=b=>{if(!b)return"";const[v,j]=b.split(":"),_=parseInt(v);return`${_>12?_-12:_||12}:${j} ${_>=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(_n,{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(_c,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:p})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(zr,{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:ks(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[f(d.start_time),d.end_time?` – ${f(d.end_time)}`:""]})]}),e.jsx(mi,{className:"flex-1 p-4 sm:p-6",children:c!=null&&c.length?e.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:e.jsx(Pye,{children:c.map((b,v)=>{var S;const j=kJt(b.visitor_intent),_=mUe(b);return e.jsxs(Zn.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:v*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${_?"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:(S=b.first_name[0])==null?void 0:S.toUpperCase()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-semibold text-white truncate",children:[b.first_name," ",b.last_name||""]}),_&&e.jsx(ze,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),b.has_agent&&e.jsx(ze,{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(ze,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${j.color}`,children:[j.emoji," ",j.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:ks(new Date(b.created_at),"h:mm a")})]})]})]},b.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(wf,{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 CJt(){const t=Jl().pathname.slice(1);if(N.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),t.startsWith("live/")){const n=t.slice(5);if(n)return e.jsx(SJt,{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(Ldt,{slug:t})}function TJt({dealData:s,agentProfile:t,welcomeMessage:n,isWon:r,branding:a}){var d;const i=s!=null&&s.property_address?`${s.property_address}, ${s.city||""}, ${s.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,l=(a==null?void 0:a.logo_url)||null,o=(a==null?void 0:a.cover_photo_url)||null,c=(a==null?void 0:a.tagline)||"Your Real Estate Concierge";return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[o&&e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${o})`,backgroundSize:"cover",backgroundPosition:"center",filter:"grayscale(0.4) brightness(0.45)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:o?"linear-gradient(180deg, hsl(0 0% 3% / 0.85) 0%, hsl(0 0% 5% / 0.75) 50%, hsl(0 0% 5%) 100%)":"radial-gradient(ellipse 100% 70% at 50% 0%, hsl(var(--portal-gold) / 0.12), transparent 60%), linear-gradient(180deg, hsl(0 0% 7%), hsl(0 0% 4%))"}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, hsl(var(--portal-gold)) 1px, transparent 1px)",backgroundSize:"32px 32px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[l&&e.jsx(Zn.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},transition:{duration:.5},className:"mb-6 flex justify-center",children:e.jsx("div",{className:"rounded-xl px-4 py-2.5",style:{background:"hsl(0 0% 100% / 0.06)",backdropFilter:"blur(8px)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:l,alt:"Brand",className:"h-9 max-w-[160px] object-contain"})})}),t&&e.jsxs(Zn.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[t.avatar_url?e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 rounded-full flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"hsl(var(--portal-gold))"},children:((d=t.name)==null?void 0:d.charAt(0))||"?"}),e.jsx("p",{className:"portal-serif text-lg",style:{color:"hsl(var(--portal-ink))"},children:t.name}),e.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:c})]}),e.jsxs(Zn.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.2em] uppercase mb-4",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.25)",color:"hsl(var(--portal-gold))"},children:[e.jsx(zr,{className:"w-3 h-3"}),(s==null?void 0:s.deal_type)==="listing"?"Sale":(s==null?void 0:s.deal_type)==="buy-side"?"Purchase":"Transaction",r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif text-[2.5rem] leading-[1.05] mb-3",style:{color:"hsl(var(--portal-ink))"},children:(s==null?void 0:s.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),i&&e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:[e.jsx(Ca,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}),e.jsx("span",{children:i})]}),n&&e.jsxs("p",{className:"mt-6 text-sm leading-relaxed max-w-md mx-auto italic portal-serif",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1.05rem"},children:["“",n,"”"]})]})]})]}),t&&e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-10 relative z-10",children:e.jsx("div",{className:"rounded-2xl p-3",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.2)",boxShadow:"var(--portal-shadow-tile)"},children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[t.phone&&e.jsxs("a",{href:`tel:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"hsl(var(--portal-gold))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Pr,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),t.email&&e.jsxs("a",{href:`mailto:${t.email}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"hsl(var(--portal-gold))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Hs,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),t.phone&&e.jsxs("a",{href:`sms:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"hsl(var(--portal-gold))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Ql,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function Pht({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=Yv(a,new Date);if(jw(a)&&!df(a))return null;const o=df(a),c=o?"0":String(Math.max(0,l)),d=Math.max(4,Math.min(100,(60-Math.min(60,l))/60*100));return e.jsxs("div",{className:"portal-tile p-8 text-center",children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:o?"The Moment Has Arrived":"Countdown to Closing"}),o?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"portal-serif text-5xl mb-2",style:{color:"hsl(var(--portal-gold))"},children:"Closing Day"}),e.jsxs("p",{className:"text-sm mt-3",style:{color:"hsl(var(--portal-ink-muted))"},children:["Congratulations",n?`, ${n.split(" ")[0]}`:"","."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-baseline justify-center gap-3",children:[e.jsx(Zn.span,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6},className:"portal-serif tabular-nums leading-none",style:{fontSize:"5.5rem",color:"hsl(var(--portal-gold))",textShadow:"0 0 40px hsl(var(--portal-gold) / 0.4)"},children:c}),e.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:l===1?"day":"days"})]}),e.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),e.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:"Until you hold the keys"}),e.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:e.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:e.jsx(Zn.div,{initial:{width:0},animate:{width:`${d}%`},transition:{duration:1.2,ease:"easeOut"},className:"h-full rounded-full",style:{background:"var(--portal-gradient-gold)",boxShadow:"0 0 12px hsl(var(--portal-gold) / 0.6)"}})})})]})]})}function Lht({journeyStages:s,currentIndex:t}){return s.length===0?null:e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"The Journey"}),e.jsx("h2",{className:"portal-serif text-2xl mb-6",style:{color:"hsl(var(--portal-ink))"},children:"Your path to the keys"}),e.jsx("div",{className:"relative",children:s.map((n,r)=>{const a=rt;return e.jsxs(Zn.div,{initial:{opacity:0,x:-6},animate:{opacity:1,x:0},transition:{duration:.35,delay:r*.05},className:"flex items-start gap-4 relative",children:[r{var l,o;if(i.includes("youtube.com/watch")){const c=new URL(i).searchParams.get("v");return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("youtu.be/")){const c=(l=i.split("youtu.be/")[1])==null?void 0:l.split("?")[0];return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("loom.com/share/")){const c=(o=i.split("loom.com/share/")[1])==null?void 0:o.split("?")[0];return c?`https://www.loom.com/embed/${c}`:null}return i};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Right Now"}),e.jsx("h4",{className:"portal-serif text-3xl mb-2 portal-gold-underline",style:{color:"hsl(var(--portal-ink))"},children:s.label}),e.jsx("p",{className:"text-sm leading-relaxed mt-4",style:{color:"hsl(var(--portal-ink-muted))"},children:s.description}),t&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Note From Your Agent"}),e.jsxs("p",{className:"text-sm leading-relaxed portal-serif italic",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:["“",t,"”"]})]}),n&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"linear-gradient(135deg, hsl(var(--portal-gold) / 0.08), hsl(var(--portal-gold) / 0.02))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"What’s Next"}),e.jsx("p",{className:"text-sm leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:n})]}),r&&e.jsx("div",{className:"mt-5 rounded-xl overflow-hidden aspect-video relative group",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("iframe",{src:a(r)||r,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})}function ll(s){const t=s.split(/[-/T]/);if(t.length>=3){const n=Number(t[0]);return n>99?new Date(n,Number(t[1])-1,Number(t[2])):new Date(Number(t[2]),Number(t[0])-1,Number(t[1]))}return new Date(`${s}T12:00:00`)}function EJt(s,t){const n=ks(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 AJt(s,t){const n=ks(t,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${n} DTEND;VALUE=DATE:${n} SUMMARY:${s} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function Rht({targetCloseDate:s,contractDate:t,inspectionDate:n,appraisalDate:r,actualCloseDate:a}){const i=[{label:"Contract",date:t,icon:W2},{label:"Inspection",date:n,icon:_r},{label:"Appraisal",date:r,icon:zr},{label:a?"Closed":"Target Close",date:a||s,icon:yr}].filter(o=>o.date);if(i.length===0)return null;const l=(o,c,d)=>{const u=ll(c);if(d==="google")window.open(EJt(o,u),"_blank");else{const h=AJt(o,u),p=document.createElement("a");p.href=h,p.download=`${o.replace(/\s+/g,"-").toLowerCase()}.ics`,p.click()}};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),e.jsxs("div",{className:"space-y-4 relative",children:[e.jsx("div",{className:"absolute left-[7px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.15)"}}),i.map(({label:o,date:c,icon:d})=>{const u=ll(c),h=jw(u)&&!df(u),p=df(u),f=!h&&!p;return e.jsxs("div",{className:"flex items-start gap-3 relative",children:[e.jsx("div",{className:"w-[15px] h-[15px] rounded-full mt-1 flex-shrink-0 relative z-10",style:{background:h?"hsl(var(--portal-gold) / 0.4)":p?"hsl(var(--portal-gold))":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold))",boxShadow:p?"0 0 12px hsl(var(--portal-gold) / 0.6)":"none"}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:o}),e.jsxs("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:h?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:[ks(u,"MMM d, yyyy"),p&&e.jsx("span",{className:"ml-2 text-[10px] tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-gold))"},children:"Today"})]})]}),f&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>l(o,c,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:g=>{g.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:g=>{g.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:e.jsx(Fg,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>l(o,c,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},o)})]})]})}function Oht({documents:s}){const t=r=>r<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(0)} KB`:`${(r/1048576).toFixed(1)} MB`,n=async r=>{const{data:a}=await q.storage.from("deal-files").createSignedUrl(r.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsxs("button",{onClick:()=>n(r),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx(Nr,{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(Da,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function Fht({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(sm,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(lm,{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:ks(new Date(n.created_at),"MMM d")})]}),n.content&&e.jsx("p",{className:`text-sm mt-2 leading-relaxed ${r===0?"italic portal-serif":""}`,style:{color:"hsl(var(--portal-ink-muted))",fontSize:r===0?"1rem":"0.875rem"},children:r===0?`“${n.content}”`:n.content}),n.video_url&&e.jsx("div",{className:"mt-3 rounded-xl overflow-hidden aspect-video",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:e.jsx("iframe",{src:t(n.video_url)||n.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:n.title})})]})]})},n.id))})]})}const fe=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));fe.displayName="Card";const Mt=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("flex flex-col space-y-1.5 p-6",s),...t}));Mt.displayName="CardHeader";const Pt=N.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Et("text-2xl font-semibold leading-none tracking-tight",s),...t}));Pt.displayName="CardTitle";const Hn=N.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));Hn.displayName="CardDescription";const Ae=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("p-6 pt-0",s),...t}));Ae.displayName="CardContent";const nz=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("flex items-center p-6 pt-0",s),...t}));nz.displayName="CardFooter";const ZD=[{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"}],MJt=[{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 IJt(s){return lt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function PJt(){const s=fa(),{brokerageId:t}=gs();return lt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let n=q.from("vendors").select("*");t?n=n.or(`and(owner_type.eq.agent,owner_user_id.eq.${s}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${t})`):n=n.eq("owner_type","agent").eq("owner_user_id",s);const[{data:r,error:a},{data:i,error:l}]=await Promise.all([n.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("*").eq("agent_user_id",s)]);if(a)throw a;if(l)throw l;return{vendors:r||[],selections:i||[]}},enabled:!!s})}function LJt(){const s=Gt();return gt({mutationFn:async t=>{if(t.id){const{id:n,created_at:r,...a}=t,{data:i,error:l}=await q.from("vendors").update(a).eq("id",n).select().single();if(l)throw l;return i}else{const{data:n,error:r}=await q.from("vendors").insert(t).select().single();if(r)throw r;return n}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function zht(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function DJt(){const s=fa(),t=Gt();return gt({mutationFn:async({vendorId:n,isVisible:r})=>{if(!s)throw new Error("No user");const{data:a}=await q.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",n).maybeSingle();if(a){const{error:i}=await q.from("agent_vendor_selections").update({is_visible:r}).eq("id",a.id);if(i)throw i}else{const{error:i}=await q.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:n,is_visible:r});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function Bht(s){return lt({queryKey:["portal-vendors",s==null?void 0:s.id,s==null?void 0:s.owner_user_id],queryFn:async()=>{if(!(s!=null&&s.id)||!(s!=null&&s.owner_user_id))return[];const t=s.owner_user_id,{data:n}=await q.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),r=n==null?void 0:n.brokerage_id,a=q.from("vendors").select("*").eq("is_active",!0),i=r?a.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${r})`):a.eq("owner_type","agent").eq("owner_user_id",t),[{data:l,error:o},{data:c},{data:d}]=await Promise.all([i.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]);if(o)throw o;const u=new Map;(c||[]).forEach(f=>u.set(f.vendor_id,{display_order:f.display_order,is_visible:f.is_visible}));const h=new Map;return(d||[]).forEach(f=>h.set(f.vendor_id,f.is_visible)),(l||[]).filter(f=>{if(h.get(f.id)===!1)return!1;const g=u.get(f.id);return!(g&&g.is_visible===!1&&!f.is_required)}).map(f=>{var g;return{...f,display_order:((g=u.get(f.id))==null?void 0:g.display_order)??f.sort_order??0}}).sort((f,g)=>(f.display_order||0)-(g.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function pUe(s){try{await q.from("vendor_clicks").insert({vendor_id:s.vendorId,portal_id:s.portalId||null,agent_user_id:s.agentUserId||null,action_taken:s.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(t){console.warn("vendor click track failed",t)}}function $ht(s,t){return lt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:n}=await q.from("vendors").select("id").eq(s==="agent"?"owner_user_id":"owner_brokerage_id",t).eq("owner_type",s),r=(n||[]).map(l=>l.id);if(r.length===0)return{};const{data:a}=await q.from("vendor_clicks").select("vendor_id").in("vendor_id",r),i={};return(a||[]).forEach(l=>{i[l.vendor_id]=(i[l.vendor_id]||0)+1}),i},enabled:!!t})}function Uht({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=Bht({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=(_,S)=>{switch(S){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 S=d(_,_.action_type);pUe({vendorId:_.id,portalId:s,agentUserId:t,actionTaken:_.action_type}),S&&window.open(S,_.action_type==="call"||_.action_type==="email"||_.action_type==="quote"?"_self":"_blank")},h=_=>{const S=d(_,_.action_type);return[{action:"website",label:"Website",icon:e.jsx(lc,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(Hs,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(Pr,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(yr,{className:"w-3.5 h-3.5"})}].filter(T=>T.action!==_.action_type).map(T=>{const D=d(_,T.action);return!D||D===S?null:e.jsxs("button",{onClick:()=>{pUe({vendorId:_.id,portalId:s,agentUserId:t,actionTaken:T.action}),window.open(D,T.action==="call"||T.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:T.label,children:[T.icon,e.jsx("span",{className:"text-xs",children:T.label})]},T.action)}).filter(Boolean)},p=_=>{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"}},f=_=>{switch(_.action_type){case"book":return e.jsx(yr,{className:"w-3.5 h-3.5"});case"call":return e.jsx(Pr,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(Hs,{className:"w-3.5 h-3.5"});case"website":return e.jsx(lc,{className:"w-3.5 h-3.5"})}},g=_=>{var S;return((S=ZD.find(A=>A.value===_))==null?void 0:S.label)||_},b=e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${c}15`,color:c},children:e.jsx(un,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),e.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),v=o.some(_=>_.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(fe,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[b,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(B,{size:"sm",onClick:()=>u(_),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[f(_),e.jsx("span",{className:"ml-1.5 text-xs",children:p(_)})]}),h(_).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:h(_)})]})]},_.id))}),v]});const j=o.reduce((_,S)=>((_[S.category]=_[S.category]||[]).push(S),_),{});return e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[b,e.jsx("div",{className:"space-y-4",children:Object.entries(j).map(([_,S])=>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:S.map(A=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-white border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:A.logo_url?e.jsx("img",{src:A.logo_url,alt:A.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:A.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:A.company||A.name}),A.company&&A.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:A.description})]}),e.jsxs(B,{size:"sm",onClick:()=>u(A),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[f(A),e.jsx("span",{className:"ml-1.5 text-xs",children:p(A)})]})]},A.id))})]},_))}),v]})}function RJt(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 OJt(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 qht({portalId:s,portalSlug:t,ownerUserId:n,rewardText:r,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,u]=N.useState(!1),h=N.useRef(!1),p=RJt(t);N.useEffect(()=>{h.current||(h.current=!0,q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,n]);const f=async D=>{await q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:D,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: ${p}`,b=async()=>{await navigator.clipboard.writeText(p),u(!0),f("copy_link"),setTimeout(()=>u(!1),2e3)},v=()=>{f("share_sms");const D=encodeURIComponent(g());window.location.href=`sms:?&body=${D}`},j=()=>{f("share_email");const D=encodeURIComponent("A referral you'll thank me for"),L=encodeURIComponent(g());window.location.href=`mailto:?subject=${D}&body=${L}`},_=()=>{f("open_form"),window.open(p,"_blank")},S=a||"Know someone buying or selling?",A=c?OJt(c):null,T=A==null?void 0:A.match(/\.(mp4|webm|mov)(\?|$)/i);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gradient-to-br from-emerald-50 via-teal-50 to-cyan-50 rounded-2xl p-6 border border-emerald-100 text-center",children:[e.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),e.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",l?`, ${l.split(" ")[0]}`:"","!"]}),e.jsx("p",{className:"text-sm text-emerald-700/80",children:"Your transaction is complete. We're so proud to have been part of your journey."})]}),A&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 pt-4 pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"w-4 h-4 text-[#406E71]"}),e.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",i||"your agent"]})]})}),e.jsx("div",{className:"aspect-video bg-slate-900",children:T?e.jsx("video",{src:A,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:A,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white shadow-xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.07]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"20px 20px"}}),e.jsxs("div",{className:"relative p-6",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium mb-3",children:[e.jsx(Bi,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:S}),r&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",r]}),e.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",i||"us"," is sending a friend or family member."]}),e.jsxs("button",{onClick:_,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(za,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:v,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Ql,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:j,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Hs,{className:"w-3.5 h-3.5"}),"Email"]}),e.jsxs("button",{onClick:b,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[d?e.jsx(Lr,{className:"w-3.5 h-3.5"}):e.jsx(ta,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>f("review_click"),className:"block bg-white border border-slate-200 hover:border-amber-300 hover:bg-amber-50/30 rounded-2xl p-4 transition-colors",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-2xl",children:"⭐"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),e.jsx(za,{className:"w-4 h-4 text-slate-400"})]})})]})}function FJt(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function zJt(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 BJt={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. 🎉"}},Vht=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function Dye(s){return Vht.map(t=>{if(t==="Active")return{key:"Active",label:FJt(s),description:zJt(s)};const n=BJt[t];return{key:t,label:n.label,description:n.description}})}function Cfe(s){if(!s)return 0;const t=Vht.indexOf(s);return t>=0?t:0}function $Jt({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var ee,ne,oe;const d=(l==null?void 0:l.cover_photo_url)||null,u=(l==null?void 0:l.logo_url)||null,h=(l==null?void 0:l.tagline)||"Your Real Estate Concierge",p=n==null?void 0:n.deal_pipeline,f=p==null?void 0:p.deal_pipeline_stages,g=f==null?void 0:f.is_won_stage,b=p==null?void 0:p.deal_type,v=n==null?void 0:n.stage_mapping;let j=Dye(b);v&&v.length>0&&(j=v.map((pe,ce)=>{var de,ie;return{key:`custom-${ce}`,label:pe.label||((de=j[ce])==null?void 0:de.label)||`Stage ${ce+1}`,description:pe.description||((ie=j[ce])==null?void 0:ie.description)||"",video_url:pe.video_url||void 0}}));const _=v&&v.length>0?Math.min(Cfe(f==null?void 0:f.name),j.length-1):Cfe(f==null?void 0:f.name),S=j[_],A=S==null?void 0:S.video_url,T=g&&n.show_post_close_tips!==!1&&n.referral_enabled!==!1,D=p!=null&&p.property_address?`${p.property_address}, ${p.city||""}, ${p.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,L=!!t,M=(ee=s==null?void 0:s.deal_pipeline)==null?void 0:ee.deal_type,F=(ne=t==null?void 0:t.deal_pipeline)==null?void 0:ne.deal_type,z=pe=>pe==="listing"?"Your Sale":pe==="buy-side"?"Your Purchase":"Transaction",V=j.length>1?Math.round((_+1)/j.length*100):0,{data:W=[]}=Bht({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),K=W.some(pe=>!pe.stage_filter||pe.stage_filter.length===0||!(f!=null&&f.name)?!0:pe.stage_filter.includes(f.name)),Y=()=>{var pe;(pe=document.getElementById("trusted-vendors"))==null||pe.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[600px] opacity-70",style:{background:"radial-gradient(ellipse 70% 100% at 50% 0%, hsl(var(--portal-gold) / 0.08), transparent 60%)"}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[e.jsxs(Zn.div,{initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.4},className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[u?e.jsx("div",{className:"rounded-lg px-3 py-1.5",style:{background:"hsl(0 0% 100% / 0.04)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:u,alt:"Brand",className:"h-8 max-w-[140px] object-contain"})}):e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center portal-serif text-xl",style:{background:"var(--portal-gradient-gold)",color:"hsl(var(--portal-bg))"},children:"✦"}),e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow",children:"Private Client Portal"}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:n!=null&&n.client_name?`Welcome, ${n.client_name.split(" ")[0]}`:"Your transaction"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(hh,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(Zn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.6,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl mb-8",style:{minHeight:380,border:"1px solid hsl(var(--portal-gold) / 0.25)",boxShadow:"var(--portal-shadow-luxe)"},children:[d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${d})`,backgroundSize:"cover",backgroundPosition:"center",filter:"grayscale(0.3) brightness(0.55)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, hsl(0 0% 3% / 0.4) 0%, hsl(0 0% 3% / 0.7) 55%, hsl(0 0% 5%) 100%)"}})]}):e.jsx("div",{className:"absolute inset-0",style:{background:"radial-gradient(ellipse 80% 60% at 20% 20%, hsl(var(--portal-gold) / 0.15), transparent 60%), radial-gradient(ellipse 80% 60% at 80% 80%, hsl(var(--portal-gold) / 0.08), transparent 60%), hsl(var(--portal-surface))"}}),e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.6), transparent)"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",children:[e.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.22em] uppercase mb-6 self-start",style:{background:"hsl(var(--portal-gold) / 0.1)",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"hsl(var(--portal-gold))"},children:[e.jsx(zr,{className:"w-3 h-3"}),b==="listing"?"Sale":b==="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:"hsl(var(--portal-ink))"},children:(p==null?void 0:p.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-32 mb-5"}),D&&e.jsxs("div",{className:"flex items-center gap-2",style:{color:"hsl(var(--portal-ink-muted))"},children:[e.jsx(Ca,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}}),e.jsx("span",{className:"text-base",children:D})]}),(n==null?void 0:n.welcome_message)&&e.jsxs("p",{className:"mt-6 portal-serif italic leading-relaxed max-w-2xl",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1.15rem"},children:["“",n.welcome_message,"”"]})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(UJt,{pct:V}),e.jsx("p",{className:"portal-eyebrow mt-4",children:"Journey Progress"}),e.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:["Stage ",_+1," of ",j.length]})]})]}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.4), transparent)"}})]}),L&&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(pe=>{const ce=pe==="primary"?M:F,de=r===pe;return e.jsx("button",{onClick:()=>a(pe),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:de?"hsl(var(--portal-surface-3))":"transparent",color:de?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:de?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:z(ce)},pe)})}),e.jsxs(Zn.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.06}}},className:"grid grid-cols-12 gap-5",children:[e.jsx("aside",{className:"col-span-3 space-y-5",children:e.jsxs("div",{className:"sticky top-6 space-y-5",children:[e.jsxs(Ck,{children:[e.jsxs("div",{className:"text-center pt-2 pb-1",children:[i!=null&&i.avatar_url?e.jsx("div",{className:"w-24 h-24 mx-auto relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.4)",color:"hsl(var(--portal-gold))"},children:((oe=i==null?void 0:i.name)==null?void 0:oe.charAt(0))||"?"}),e.jsx("h3",{className:"mt-4 portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink))"},children:i==null?void 0:i.name}),e.jsx("div",{className:"portal-hairline w-12 mx-auto my-2"}),e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:h})]}),e.jsxs("div",{className:"mt-5 space-y-2",children:[(i==null?void 0:i.phone)&&e.jsx(Lje,{href:`tel:${i.phone}`,icon:Pr,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(Lje,{href:`sms:${i.phone}`,icon:Ql,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(Lje,{href:`mailto:${i.email}`,icon:Hs,label:"Email",sub:i.email})]})]}),e.jsxs(Ck,{children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:"At a Glance"}),e.jsxs("div",{className:"space-y-4",children:[(p==null?void 0:p.target_close_date)&&e.jsx(Dje,{icon:yr,label:"Target close",value:fUe(p.target_close_date)}),(p==null?void 0:p.contract_date)&&e.jsx(Dje,{icon:gr,label:"Under contract",value:fUe(p.contract_date)}),e.jsx(Dje,{icon:io,label:"Progress",value:`${V}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[T&&e.jsx(qht,{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(Pht,{targetCloseDate:p==null?void 0:p.target_close_date,actualCloseDate:p==null?void 0:p.actual_close_date,clientName:n.client_name}),S&&e.jsx(Ck,{children:e.jsx(Dht,{currentStage:S,nextStepText:n.next_step_text,nextStepVideoUrl:A||n.next_step_video_url})}),e.jsx(Ck,{children:e.jsx(Lht,{journeyStages:j,currentIndex:_})}),o&&o.length>0&&e.jsx(Ck,{children:e.jsx(Fht,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-5",children:[e.jsx(Ck,{children:e.jsx(Rht,{targetCloseDate:p==null?void 0:p.target_close_date,contractDate:p==null?void 0:p.contract_date,inspectionDate:n.inspection_date,appraisalDate:n.appraisal_date,actualCloseDate:p==null?void 0:p.actual_close_date})}),c&&c.length>0&&e.jsx(Ck,{children:e.jsx(Oht,{documents:c})}),K&&e.jsx(Ck,{children:e.jsxs("button",{onClick:Y,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:pe=>{pe.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:pe=>{pe.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(I9,{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(io,{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(Uht,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:f==null?void 0:f.name,brandingColor:"#c9a84c",layout:"grid"})})]})]})}function Ck({children:s}){return e.jsx(Zn.div,{variants:{hidden:{opacity:0,y:10},show:{opacity:1,y:0,transition:{duration:.45,ease:"easeOut"}}},className:"portal-tile p-6",children:s})}function Lje({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 Dje({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 UJt({pct:s}){const a=2*Math.PI*78,i=a-s/100*a;return e.jsxs("div",{className:"relative",style:{width:170,height:170},children:[e.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(44, 51%, 54%)"}),e.jsx("stop",{offset:"100%",stopColor:"hsl(44, 74%, 74%)"})]})}),e.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(44, 40%, 55%, 0.15)",strokeWidth:2,fill:"none"}),e.jsx(Zn.circle,{cx:170/2,cy:170/2,r:78,stroke:"url(#portal-progress-gold)",strokeWidth:3,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:a},animate:{strokeDashoffset:i},transition:{duration:1.4,ease:"easeOut"},strokeDasharray:a,style:{filter:"drop-shadow(0 0 6px hsl(44, 74%, 74%, 0.6))"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"portal-serif tabular-nums leading-none",style:{fontSize:"3rem",color:"hsl(var(--portal-gold))"},children:s}),e.jsx("span",{className:"text-[10px] tracking-[0.25em] uppercase mt-1",style:{color:"hsl(var(--portal-ink-dim))"},children:"percent"})]})]})}function fUe(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 qJt({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var v,j;const[l,o]=N.useState({first_name:((v=s.client_name)==null?void 0:v.split(" ")[0])||"",last_name:((j=s.client_name)==null?void 0:j.split(" ").slice(1).join(" "))||"",email:s.client_email||"",phone:s.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[c,d]=N.useState({}),[u,h]=N.useState(!1),p=gt({mutationFn:async()=>{const{error:_}=await q.from("portal_onboarding_submissions").insert({portal_id:s.id,first_name:l.first_name,last_name:l.last_name||null,email:l.email||null,phone:l.phone||null,preferred_contact_method:l.preferred_contact_method,client_role:l.client_role,notes:l.notes||null,device_fingerprint:a,custom_answers:Object.keys(c).length>0?c:null,spouse_first_name:u&&l.spouse_first_name||null,spouse_last_name:u&&l.spouse_last_name||null,spouse_email:u&&l.spouse_email||null,spouse_phone:u&&l.spouse_phone||null});if(_)throw _},onSuccess:i,onError:_=>{console.error("[PortalOnboarding] Submit failed:",_),ae.error("Something went wrong. Please try again.")}}),f=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",b="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return e.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[(n==null?void 0:n.avatar_url)&&e.jsx("img",{src:n.avatar_url,alt:n.name,className:"w-16 h-16 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),f&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(Ca,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:f.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:_=>{_.preventDefault(),p.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(ge,{required:!0,value:l.first_name,onChange:_=>o(S=>({...S,first_name:_.target.value})),className:g,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(ge,{value:l.last_name,onChange:_=>o(S=>({...S,last_name:_.target.value})),className:g,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(ge,{type:"email",value:l.email,onChange:_=>o(S=>({...S,email:_.target.value})),className:g,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(ge,{type:"tel",value:l.phone,onChange:_=>o(S=>({...S,phone:_.target.value})),className:g,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{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(S=>({...S,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(se,{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(S=>({...S,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(se,{className:"text-xs font-medium text-slate-700",children:[_.question_text," ",_.is_required&&"*"]}),_.field_type==="text"&&e.jsx(ge,{required:_.is_required,value:c[_.id]||"",onChange:S=>d(A=>({...A,[_.id]:S.target.value})),className:g}),_.field_type==="textarea"&&e.jsx("textarea",{required:_.is_required,value:c[_.id]||"",onChange:S=>d(A=>({...A,[_.id]:S.target.value})),className:`${b} min-h-[80px]`}),_.field_type==="dropdown"&&e.jsxs("select",{required:_.is_required,value:c[_.id]||"",onChange:S=>d(A=>({...A,[_.id]:S.target.value})),className:`${b} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(_.options||[]).map(S=>e.jsx("option",{value:S,children:S},S))]}),_.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(S=>e.jsx("button",{type:"button",onClick:()=>d(A=>({...A,[_.id]:S})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[_.id]===S?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:S},S))})]},_.id)),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:_=>o(S=>({...S,notes:_.target.value})),className:`${b} 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(se,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(ge,{value:l.spouse_first_name,onChange:_=>o(S=>({...S,spouse_first_name:_.target.value})),className:g})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(ge,{value:l.spouse_last_name,onChange:_=>o(S=>({...S,spouse_last_name:_.target.value})),className:g})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(ge,{type:"email",value:l.spouse_email,onChange:_=>o(S=>({...S,spouse_email:_.target.value})),className:g})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(ge,{type:"tel",value:l.spouse_phone,onChange:_=>o(S=>({...S,spouse_phone:_.target.value})),className:g})]})]})]}),e.jsx(B,{type:"submit",disabled:p.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:p.isPending?"Submitting...":"Access My Portal"})]})]})})}function VJt(s,t){const n=(r,a)=>a!=null&&a!==""?a:r!=null&&r!==""?r:null;return{logo_url:n(s==null?void 0:s.logo_url,t==null?void 0:t.logo_url),cover_photo_url:n(s==null?void 0:s.cover_photo_url,t==null?void 0:t.cover_photo_url),brand_color:n(s==null?void 0:s.brand_color,t==null?void 0:t.brand_color),accent_color:n(s==null?void 0:s.accent_color,t==null?void 0:t.accent_color),tagline:n(s==null?void 0:s.tagline,t==null?void 0:t.tagline),welcome_message:n(s==null?void 0:s.welcome_message,t==null?void 0:t.welcome_message)}}function Hht(){const s=fa();return lt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function HJt(s){return lt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function GJt(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("agent_portal_branding").upsert({user_id:s,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-portal-branding",s]}),t.invalidateQueries({queryKey:["agent-portal-branding-public",s]})}})}async function Ght(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=q.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function WJt(s,t){return lt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:n,error:r}=await q.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("slug",s).eq("is_enabled",!0).maybeSingle();if(r)throw r;return n},enabled:t})}function KJt(s){return lt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("id",s).eq("is_enabled",!0).maybeSingle();if(n)throw n;return t},enabled:!!s})}function Wht({slug:s}){var oe,pe,ce,de,ie,ye;const[t,n]=N.useState(!1),[r,a]=N.useState("primary"),[i]=N.useState(()=>{const _e=`portal_fp_${s}`;let Me=localStorage.getItem(_e);return Me||(Me=localStorage.getItem("portal_fp"),Me?localStorage.setItem(_e,Me):(Me=crypto.randomUUID(),localStorage.setItem(_e,Me),localStorage.setItem("portal_fp",Me))),Me});N.useEffect(()=>(document.body.classList.add("client-portal-page","portal-theme-noir"),()=>document.body.classList.remove("client-portal-page","portal-theme-noir")),[]);const{data:l,isLoading:o,error:c}=WJt(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=KJt(d),h=(oe=l==null?void 0:l.deal_pipeline)==null?void 0:oe.owner_user_id;lt({queryKey:["portal-stages",h],queryFn:async()=>{const{data:_e,error:Me}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(Me)throw Me;return _e},enabled:!!h});const{data:p}=lt({queryKey:["portal-agent",h],queryFn:async()=>{const{data:_e,error:Me}=await q.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(Me)throw Me;return _e},enabled:!!h}),{data:f}=HJt(h),g=r==="linked"&&u?u:l,b=g==null?void 0:g.id,v=VJt(f,g==null?void 0:g.branding_override),{data:j}=lt({queryKey:["portal-updates-public",b],queryFn:async()=>{const{data:_e,error:Me}=await q.from("portal_updates").select("*").eq("portal_id",b).order("created_at",{ascending:!1});if(Me)throw Me;return _e},enabled:!!b}),_=(pe=g==null?void 0:g.deal_pipeline)==null?void 0:pe.id,{data:S}=lt({queryKey:["portal-documents",_],queryFn:async()=>{const{data:_e,error:Me}=await q.from("deal_files").select("*").eq("deal_id",_).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(Me)throw Me;return _e},enabled:!!_}),A=l==null?void 0:l.id,T=A?`portal_onboarded_${A}_${i}`:null,D=T?localStorage.getItem(T)==="1":!1,{data:L,isLoading:M}=lt({queryKey:["portal-onboarding-check",A,i],queryFn:async()=>{const{data:_e,error:Me}=await q.from("portal_onboarding_submissions").select("id").eq("portal_id",A).eq("device_fingerprint",i).maybeSingle();if(Me)throw Me;return _e&&T&&localStorage.setItem(T,"1"),_e},enabled:!!A&&!!(l!=null&&l.require_onboarding)&&!D,staleTime:5*60*1e3}),F=!!(l!=null&&l.require_onboarding)&&!D&&!L&&!t,{data:z}=lt({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:_e,error:Me}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(Me)throw Me;return _e},enabled:!!h&&F}),V=D||!!L||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!D&&M)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(ss,{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(hh,{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(!V){const _e=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(qJt,{portal:l,dealData:_e,agentProfile:p,customQuestions:z||[],deviceFingerprint:i,onComplete:()=>{T&&localStorage.setItem(T,"1"),n(!0)}})})}const W=(ce=l==null?void 0:l.deal_pipeline)==null?void 0:ce.deal_type,K=(de=u==null?void 0:u.deal_pipeline)==null?void 0:de.deal_type,Y=!!u,ee=_e=>_e==="listing"?"Your Sale":_e==="buy-side"?"Your Purchase":"Transaction",ne=_e=>_e==="listing"?e.jsx(zr,{className:"w-3.5 h-3.5"}):e.jsx(Gg,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx($Jt,{portal:l,linkedPortal:u,activePortal:g,activeTab:r,onTabChange:a,agentProfile:p,branding:v,updates:j,documents:S})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(TJt,{dealData:g==null?void 0:g.deal_pipeline,agentProfile:p,welcomeMessage:(g==null?void 0:g.welcome_message)||v.welcome_message,isWon:(ye=(ie=g==null?void 0:g.deal_pipeline)==null?void 0:ie.deal_pipeline_stages)==null?void 0:ye.is_won_stage,branding:v}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[Y&&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(_e=>{const Me=r===_e,Te=_e==="primary"?W:K;return e.jsxs("button",{onClick:()=>a(_e),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:Me?"hsl(var(--portal-surface-3))":"transparent",color:Me?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:Me?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[ne(Te),e.jsx("span",{style:{fontSize:"1rem"},children:ee(Te)})]},_e)})}),e.jsx(YJt,{portal:g,updates:j,documents:S,agentProfile:p}),e.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[e.jsx("div",{className:"portal-hairline w-16 mx-auto"}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(hh,{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 YJt({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=Dye(c);d&&d.length>0&&(u=d.map((b,v)=>{var j,_;return{key:`custom-${v}`,label:b.label||((j=u[v])==null?void 0:j.label)||`Stage ${v+1}`,description:b.description||((_=u[v])==null?void 0:_.description)||"",video_url:b.video_url||void 0}}));const h=d&&d.length>0?Math.min(Cfe(l==null?void 0:l.name),u.length-1):Cfe(l==null?void 0:l.name),p=u[h],f=p==null?void 0:p.video_url,g=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[g&&e.jsx(qht,{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(Pht,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(Lht,{journeyStages:u,currentIndex:h}),p&&e.jsx(Dht,{currentStage:p,nextStepText:s.next_step_text,nextStepVideoUrl:f||s.next_step_video_url}),e.jsx(Rht,{targetCloseDate:i==null?void 0:i.target_close_date,contractDate:i==null?void 0:i.contract_date,inspectionDate:s.inspection_date,appraisalDate:s.appraisal_date,actualCloseDate:i==null?void 0:i.actual_close_date}),n&&n.length>0&&e.jsx(Oht,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(Uht,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(Fht,{updates:t})]})}function Kht({slug:s}){const t=_i(),n=s||t.slug,[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(""),[b,v]=N.useState(""),[j,_]=N.useState("buying"),[S,A]=N.useState("");N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:T,isLoading:D,error:L}=lt({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:z,error:V}=await q.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",n).eq("is_enabled",!0).maybeSingle();if(V)throw V;return z},enabled:!!n}),{data:M}=lt({queryKey:["portal-referral-agent",T==null?void 0:T.owner_user_id],queryFn:async()=>{const{data:z}=await q.from("profiles").select("id, name, avatar_url").eq("id",T.owner_user_id).single();return z},enabled:!!(T!=null&&T.owner_user_id)}),F=async z=>{if(z.preventDefault(),!T||!h.trim()){ae.error("Please enter your friend's name");return}if(!f.trim()&&!b.trim()){ae.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:V}=await q.from("portal_referrals").insert({portal_id:T.id,owner_user_id:T.owner_user_id,referrer_name:o.trim()||T.client_name||null,referrer_email:d.trim()||null,friend_name:h.trim(),friend_email:f.trim()||null,friend_phone:b.trim()||null,friend_interest:j,friend_message:S.trim()||null});if(V)throw V;l(!0)}catch(V){ae.error(V.message||"Could not submit referral")}finally{a(!1)}};return D?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(Ws,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):L||!T||!T.referral_enabled?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("span",{className:"text-2xl",children:"🔒"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Referral Page Unavailable"}),e.jsx("p",{className:"text-slate-500",children:"This referral link is no longer active."})]})}):i?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-emerald-50 via-teal-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Lr,{className:"w-8 h-8 text-emerald-600"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2 font-serif",children:"Thank you! 🙏"}),e.jsxs("p",{className:"text-sm text-slate-600 leading-relaxed mb-6",children:["Your referral has been sent to ",(M==null?void 0:M.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(Wr,{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:[M!=null&&M.avatar_url?e.jsx("img",{src:M.avatar_url,alt:M.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(Bi,{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(Bi,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:T.referral_cta_headline||"Refer a Friend"}),e.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(M==null?void 0:M.name)||"your agent"," someone you trust."]}),T.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:T.referral_reward_text})," when they close."]})]})]}),e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-6 relative z-10",children:e.jsxs("form",{onSubmit:F,className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Tell us about your friend"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ge,{id:"friend_name",value:h,onChange:z=>p(z.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(ge,{id:"friend_email",type:"email",value:f,onChange:z=>g(z.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(ge,{id:"friend_phone",type:"tel",value:b,onChange:z=>v(z.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm",children:"They're interested in..."}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[{v:"buying",l:"Buying"},{v:"selling",l:"Selling"},{v:"both",l:"Both"},{v:"unsure",l:"Not sure"}].map(z=>e.jsx("button",{type:"button",onClick:()=>_(z.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${j===z.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:z.l},z.v))})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:S,onChange:z=>A(z.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(ge,{id:"referrer_name",value:o,onChange:z=>c(z.target.value),placeholder:T.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(ge,{id:"referrer_email",type:"email",value:d,onChange:z=>u(z.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),e.jsxs("button",{type:"submit",disabled:r,className:"w-full bg-[#406E71] hover:bg-[#345e7a] disabled:opacity-60 text-white font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 transition-colors",children:[r?e.jsx(ss,{className:"w-4 h-4 animate-spin"}):e.jsx(Bi,{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 ZJt(){const t=Jl().pathname.slice(1).replace(/\/$/,"");if(N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>{document.body.classList.remove("client-portal-page")}),[]),!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Client Portal"}),e.jsx("p",{className:"text-slate-500",children:"Visit your personalized portal link to view your transaction details."})]})});const n=t.match(/^([^/]+)\/refer$/);return n?e.jsx(Kht,{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(Wht,{slug:t})}function QJt(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 Tfe({photos:s,alt:t="",className:n="w-full h-full",imgClassName:r="w-full h-full object-cover",iconClassName:a="w-8 h-8"}){const i=N.useMemo(()=>QJt(Array.isArray(s)?s:[]),[s]),[l,o]=N.useState(0);return N.useEffect(()=>{o(0)},[i.join("|")]),!i.length||l>=i.length?e.jsx("div",{className:`${n} bg-muted flex items-center justify-center text-muted-foreground`,children:e.jsx(zr,{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 Yht({comp:s,open:t,onClose:n}){var d;const[r,a]=N.useState(0);if(!s)return null;const i=Array.isArray(s.photos)?s.photos.filter(Boolean):[],l=s.soldPrice||s.price,o=s.sqft&&l?Math.round(l/s.sqft):null,c=u=>{if(!u)return null;const[h,p,f]=u.split(/[-/T]/);return h?`${p}/${f}/${h}`:null};return e.jsx(bs,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(ws,{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(Ca,{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(Tfe,{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(Tfe,{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(zr,{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(Zl,{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(ze,{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(Rje,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(Rje,{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(Rje,{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(mH,{icon:e.jsx(ny,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(mH,{icon:e.jsx(Tp,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(mH,{icon:e.jsx(eN,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(mH,{icon:e.jsx(yr,{className:"w-4 h-4"}),label:"Year Built",value:s.yearBuilt??"—"})]}),e.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[e.jsx(Rx,{label:"MLS #",value:s.mlsNumber}),e.jsx(Rx,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(Rx,{label:"Lot Size",value:s.lotSize}),e.jsx(Rx,{label:"Garage",value:s.garageSpaces}),e.jsx(Rx,{label:"Stories",value:s.stories}),e.jsx(Rx,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(Rx,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(Rx,{label:"Heating",value:s.heating}),e.jsx(Rx,{label:"Cooling",value:s.cooling}),e.jsx(Rx,{label:"Parking",value:s.parking}),e.jsx(Rx,{label:"Elementary",value:s.elementarySchool}),e.jsx(Rx,{label:"Middle",value:s.middleSchool}),e.jsx(Rx,{label:"High",value:s.highSchool}),e.jsx(Rx,{label:"Listed By",value:s.listAgentFullName}),e.jsx(Rx,{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 mH({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 Rx({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 Rje({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 pH({to:s,durationMs:t=1400,prefix:n="",suffix:r="",className:a,delayMs:i=0}){const[l,o]=N.useState(0),c=N.useRef(null);return N.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,h=f=>1-Math.pow(1-f,3),p=setTimeout(()=>{const f=g=>{d||(d=g);const b=g-d,v=Math.min(1,b/t);o(Math.round(u+(s-u)*h(v))),v<1&&(c.current=requestAnimationFrame(f))};c.current=requestAnimationFrame(f)},i);return()=>{clearTimeout(p),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[n,l.toLocaleString(),r]})}function XJt({low:s,likely:t,high:n,defaultMortgage:r=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=N.useState(t),[c,d]=N.useState(r),[u,h]=N.useState(a),[p,f]=N.useState(i),{commission:g,closing:b,net:v}=N.useMemo(()=>{const S=Math.round(l*u/100),A=Math.round(l*p/100);return{commission:S,closing:A,net:Math.max(0,l-S-A-(c||0))}},[l,u,p,c]),j=S=>`$${S.toLocaleString()}`,_=n>s?(l-s)/(n-s)*100:50;return e.jsxs(fe,{className:"overflow-hidden border-primary/20",children:[e.jsxs("div",{className:"bg-gradient-to-br from-primary/5 to-primary/10 px-6 pt-6 pb-4 border-b border-primary/10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(mo,{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(Ae,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-end justify-between mb-3",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"List price"}),e.jsx("span",{className:"text-3xl font-bold tabular-nums",children:j(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx($m,{value:[l],min:s,max:n,step:1e3,onValueChange:([S])=>o(S)}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[e.jsx("span",{children:j(s)}),e.jsxs("span",{children:["Suggested ",j(t)]}),e.jsx("span",{children:j(n)})]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-500 via-primary to-amber-500 transition-all",style:{width:`${Math.min(100,Math.max(0,_))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(ge,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:S=>d(Number(S.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Commission %"}),e.jsx(ge,{type:"number",step:"0.25",value:u,onChange:S=>h(Number(S.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Closing costs %"}),e.jsx(ge,{type:"number",step:"0.25",value:p,onChange:S=>f(Number(S.target.value)||0)})]})]}),e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-4 grid grid-cols-2 gap-y-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sale price"}),e.jsx("span",{className:"text-right tabular-nums font-medium",children:j(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",j(g)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",p,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",j(b)]}),c>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"Mortgage payoff"}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",j(c)]})]})]}),e.jsxs("div",{className:"bg-gradient-to-r from-emerald-500/10 to-primary/10 px-5 py-4 border-t flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(SL,{className:"w-5 h-5 text-emerald-600"}),e.jsx("span",{className:"font-semibold",children:"Your estimated walk-away"})]}),e.jsx("span",{className:"text-2xl font-bold tabular-nums text-emerald-700",children:j(v)})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"This is a rough estimate to help you think through pricing. Actual proceeds depend on title fees, prorations, repairs, and other items your agent will walk through in detail."})]})]})}function Zht({tokenOverride:s}={}){var Fe,qe,ve,Je,we,it,Ne,He,$e,Ye,Ke,rt;const t=_i(),n=s??t.token,[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState([]),[d,u]=N.useState(!0),[h,p]=N.useState(""),[f,g]=N.useState(""),[b,v]=N.useState(""),[j,_]=N.useState(!1),[S,A]=N.useState(!1),[T,D]=N.useState(null),[L,M]=N.useState(null),[F,z]=N.useState(!1),{toast:V}=Ua();N.useEffect(()=>{n&&(async()=>{const{data:tt}=await q.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!tt){u(!1);return}a(tt);const[{data:at},{data:Ge}]=await Promise.all([q.from("cma_comps").select("*").eq("cma_id",tt.id).order("position"),q.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",tt.agent_id).maybeSingle()]);c((at||[]).filter(Bt=>Bt.selected)),l(Ge);const dt=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",dt),await q.from("cma_views").insert({cma_id:tt.id,visitor_token:dt,user_agent:navigator.userAgent}),u(!1)})()},[n]);const W=async tt=>{if(!r)return;const at=localStorage.getItem("cma_visitor_token")||"";await q.from("cma_views").insert({cma_id:r.id,visitor_token:at,reactions:{[tt]:!0}}),q.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:tt,visitorToken:at}}).catch(()=>{}),V({title:"Thanks — your agent just got notified ✨"})},K=!(r!=null&&r.contact_id),Y=async()=>{if(!r||!h.trim())return;if(K&&(!f.trim()||!b.trim())){V({title:"Please add your name and email",variant:"destructive"});return}_(!0);const tt=localStorage.getItem("cma_visitor_token")||"",{data:at,error:Ge}=await q.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:tt,viewerName:f.trim()||void 0,viewerEmail:b.trim()||void 0}});if(_(!1),Ge||!(at!=null&&at.success)){V({title:"Could not send",description:(Ge==null?void 0:Ge.message)||(at==null?void 0:at.error),variant:"destructive"});return}p(""),A(!0),V({title:"Message sent to your agent"})},ee=N.useMemo(()=>{const tt=o.map(at=>{const Ge=at.snapshot,dt=(Ge==null?void 0:Ge.soldPrice)||(Ge==null?void 0:Ge.price);return dt&&(Ge!=null&&Ge.sqft)?dt/Ge.sqft:null}).filter(at=>!!at).sort((at,Ge)=>at-Ge);return tt.length?Math.round(tt[Math.floor(tt.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(ss,{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(zr,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const ne=r.subject||{},oe=(Fe=r.settings)==null?void 0:Fe.personalVideo,pe=(qe=ne.photos)==null?void 0:qe[0],ce=r.contact_first_name?r.contact_first_name:null,de=((i==null?void 0:i.name)||"A").split(" ").map(tt=>tt[0]).slice(0,2).join("").toUpperCase(),ie=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,ye=i!=null&&i.email?`mailto:${i.email}`:null,_e=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,Me=r.price_low??null,Te=r.price_likely??null,Ce=r.price_high??null,Ee=Me&&Te&&Ce,De=Te&&ne.sqft?Math.round(Te/ne.sqft):null,Ie=De&&ee?Math.round((De-ee)/ee*100):null;return e.jsxs("div",{className:"min-h-screen bg-background pb-28 md:pb-0",children:[i&&e.jsx("div",{className:"border-b bg-card sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-6 py-3 flex items-center gap-3",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-10 h-10 rounded-full object-cover ring-2 ring-primary/20"}):e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center font-semibold text-primary text-sm",children:de}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-semibold leading-tight truncate text-sm",children:i.name}),(i.title||i.brokerage_name)&&e.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1 truncate",children:[i.brokerage_name&&e.jsx(Ga,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"truncate",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")})]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[ie&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ie,children:[e.jsx(Pr,{className:"w-4 h-4 mr-1"}),"Call"]})}),ye&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ye,children:[e.jsx(Hs,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[pe?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:pe,alt:ne.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),e.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),e.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[e.jsxs("div",{className:`${oe!=null&&oe.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs(ze,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(un,{className:"w-3 h-3 mr-1"}),ce?`Prepared for ${ce}`:r.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:ne.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(Ca,{className:"w-4 h-4"}),ne.city,", ",ne.state," ",ne.zip]}),Ee&&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(pH,{to:Te,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(pH,{to:Me,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(pH,{to:Te,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(pH,{to:Ce,prefix:"$",delayMs:800})})]})]})]})]}),(oe==null?void 0:oe.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>z(!0),className:"group relative w-full aspect-[4/5] md:aspect-[4/5] rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/20 bg-black",children:[oe.thumb?e.jsx("img",{src:oe.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:oe.url,className:"w-full h-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-black/10 group-hover:from-black/40 transition-colors"}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white",children:[e.jsx("div",{className:"w-16 h-16 md:w-20 md:h-20 rounded-full bg-white/95 text-primary flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform",children:e.jsx(Al,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),e.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((ve=i==null?void 0:i.name)==null?void 0:ve.split(" ")[0])||"your agent"]})]})]})})]})})]}),F&&(oe==null?void 0:oe.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>z(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:tt=>tt.stopPropagation(),children:[e.jsx("video",{src:oe.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),e.jsx(B,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>z(!1),children:"Close"})]})}),e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:ne.bedrooms??"—"},{label:"Baths",value:ne.bathrooms??"—"},{label:"Sq Ft",value:((Je=ne.sqft)==null?void 0:Je.toLocaleString())??"—"},{label:"Year Built",value:ne.yearBuilt??"—"}].map((tt,at)=>e.jsx(fe,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${at*80}ms`},children:e.jsxs(Ae,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:tt.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:tt.label})]})},at))}),((it=(we=r.settings)==null?void 0:we.priceOverride)==null?void 0:it.enabled)&&((He=(Ne=r.settings)==null?void 0:Ne.priceOverride)==null?void 0:He.note)&&e.jsx(fe,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Ae,{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})]})}),Ee&&e.jsx(XJt,{low:Me,likely:Te,high:Ce}),ee&&De&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(fe,{className:"md:col-span-2",children:e.jsxs(Ae,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),e.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",e.jsxs("strong",{className:"text-foreground",children:[o.length," comparable ",o.length===1?"home":"homes"]})," in ",ne.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",ee,"/sqft"]}),". Applied to your home's ",($e=ne.sqft)==null?void 0:$e.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(ee*(ne.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(fe,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Ae,{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:["$",De,e.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",e.jsxs("span",{className:"font-medium text-foreground",children:["$",ee,"/sqft"]})]}),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(ze,{variant:"outline",className:"text-xs",children:[o.length," comps"]})]}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:o.map((tt,at)=>{var Bt;const Ge=tt.snapshot,dt=Ge.soldPrice||Ge.price;return e.jsxs(fe,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${L===at?"ring-2 ring-primary":""}`,style:{animationDelay:`${at*60}ms`},onClick:()=>D(at),onMouseEnter:()=>M(at),onMouseLeave:()=>M(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(Tfe,{photos:Ge.photos,className:"w-full h-44"}),e.jsxs(ze,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",at+1]}),e.jsx(ze,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:Ge.status})]}),e.jsxs(Ae,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:Ge.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ge.city,", ",Ge.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[Ge.bedrooms??"?","bd · ",Ge.bathrooms??"?","ba · ",((Bt=Ge.sqft)==null?void 0:Bt.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:["$",dt==null?void 0:dt.toLocaleString()]}),Ge.sqft&&dt?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(dt/Ge.sqft),"/sqft"]}):null]})]})]},at)})})]}),e.jsx(Yht,{comp:T!==null?(Ye=o[T])==null?void 0:Ye.snapshot:null,open:T!==null,onClose:()=>D(null)}),e.jsx(fe,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(Ae,{className:"p-6 md:p-8 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),e.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",ce?`, ${ce}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((Ke=i==null?void 0:i.name)==null?void 0:Ke.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:yi,label:"I love this price"},{kind:"fair",icon:Hm,label:"Seems fair"},{kind:"lower",icon:bb,label:"I'd price lower"},{kind:"higher",icon:mo,label:"I'd price higher"},{kind:"ready_to_list",icon:fb,label:"Ready to list"},{kind:"want_walkthrough",icon:Ir,label:"Want a walkthrough"},{kind:"need_time",icon:yr,label:"Need more time"},{kind:"have_questions",icon:Y_,label:"I have questions"}].map(({kind:tt,icon:at,label:Ge})=>e.jsxs(B,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>W(tt),children:[e.jsx(at,{className:"w-4 h-4 mr-2"}),Ge]},tt))}),e.jsxs("div",{className:"pt-4 border-t",children:[e.jsxs("p",{className:"text-sm font-medium mb-2 flex items-center gap-1",children:[e.jsx(Ql,{className:"w-4 h-4"}),"Ask your agent a question"]}),S?e.jsxs("div",{className:"rounded-md bg-emerald-50 border border-emerald-200 p-4 text-sm text-emerald-800 animate-fade-in",children:["✓ Sent! ",((rt=i==null?void 0:i.name)==null?void 0:rt.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[K&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[e.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:f,onChange:tt=>g(tt.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:b,onChange:tt=>v(tt.target.value)})]}),e.jsx("textarea",{className:"w-full border rounded-md p-3 text-sm min-h-[100px] bg-background",placeholder:"What questions do you have about this analysis?",value:h,onChange:tt=>p(tt.target.value)}),e.jsx(B,{onClick:Y,disabled:!h.trim()||j,className:"mt-2",children:j?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(fe,{className:"overflow-hidden border-primary/20",children:e.jsx("div",{className:"bg-gradient-to-br from-primary/10 to-primary/5 p-6 md:p-10",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl object-cover ring-4 ring-background shadow-lg"}):e.jsx("div",{className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl bg-primary/20 flex items-center justify-center text-3xl font-bold text-primary ring-4 ring-background shadow-lg",children:de}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:i.name}),(i.title||i.brokerage_name)&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")}),i.bio&&e.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:i.bio}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[ie&&e.jsx(B,{asChild:!0,children:e.jsxs("a",{href:ie,children:[e.jsx(Pr,{className:"w-4 h-4 mr-2"}),i.phone]})}),ye&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:ye,children:[e.jsx(Hs,{className:"w-4 h-4 mr-2"}),"Email"]})}),i.website_url&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(lc,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(ie||_e||ye)&&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:[ie&&e.jsx(B,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ie,children:[e.jsx(Pr,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),_e&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:_e,children:[e.jsx(Ql,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),ye&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ye,children:[e.jsx(Hs,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function JJt(){const t=Jl().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(Zht,{tokenOverride:t})}const gCe="levelup_affiliate_ref",ees=30,tes=()=>{const[s]=yl();N.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(gCe,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},ses=()=>{try{const s=localStorage.getItem(gCe);if(!s)return null;const t=JSON.parse(s),n=ees*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(gCe),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},Efe="/assets/levelup-logo-header-_ZX7DvlA.png",nes="/assets/scale-your-team-ku4MPatU.png";function res({open:s,onOpenChange:t}){return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(ws,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:e.jsx(Ga,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(_s,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Qn,{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 fp={individual_agent:{name:"Individual Agent",price:"$39",period:"/month",description:"Perfect for independent agents ready to level up",features:["Full dashboard access","300+ professional templates","Academy training library","Community & networking","Live events & workshops","Social media content","Newsletter resources","Email support"],trial:"7-day free trial",popular:!1},brokerage_under_25:{name:"Brokerage",subtitle:"Under 25 Agents",price:"$299",period:"/month",description:"Empower your entire team to succeed",features:["Everything in Individual","Brokerage manager dashboard","Invite & manage up to 25 agents","Exclusive brokerage resources","Team performance analytics","Agent onboarding tools","Resource sharing","Priority support"],popular:!0},brokerage_over_25:{name:"Brokerage",subtitle:"Over 25 Agents",price:"$499",period:"/month",description:"Scale your brokerage without limits",features:["Everything in Brokerage","Unlimited agents","Advanced team analytics","Dedicated account manager","Custom onboarding sessions","White-glove support"],popular:!1}},aes=[{icon:Pu,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:xl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:yr,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ql,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Nr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Bi,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],ies=[{icon:_n,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:un,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Pr,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:hu,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Ca,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:yo,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:yi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:ph,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],oes=[{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."}],les=()=>{const{user:s,loading:t}=gs(),n=In(),[r]=yl();N.useEffect(()=>{const L=window.location.host==="listings.relevelup.com",M=window.location.pathname==="/";if(L&&M){n("/public/listings",{replace:!0});return}},[n]);const[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,b]=N.useState(""),[v,j]=N.useState(!1),[_,S]=N.useState(!1),A=(L,M=!1)=>{o({tier:L,skipTrial:M}),d(!0)};tes(),N.useEffect(()=>{const L=window.location.host==="listings.relevelup.com",M=location.pathname.startsWith("/public/");!t&&s&&!L&&!M&&n("/dashboard")},[s,t,n,location.pathname]),N.useEffect(()=>{r.get("canceled")==="true"&&ae.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const T=async(L,M=!1)=>{if(!u){ae.error("Please enter your email address");return}if(!p.trim()){ae.error("Please enter your full name");return}j(!0),i(L+(M?"_direct":""));const F=ses();try{const{data:z,error:V}=await q.functions.invoke("create-checkout",{body:{tier:L,email:u,name:p.trim(),couponCode:g.trim()||void 0,skipTrial:M,referralCode:F}});if(V)throw V;if(z!=null&&z.url)window.open(z.url,"_blank","noopener,noreferrer"),ae.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(z){console.error("Checkout error:",z),ae.error(z.message||"Failed to start checkout. Please try again.")}finally{j(!1),i(null),d(!1),o(null)}},D=()=>{l&&T(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:Efe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var L;return(L=document.getElementById("features"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var L;return(L=document.getElementById("pricing"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx(B,{onClick:()=>n("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-5xl mx-auto text-center space-y-8",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-[136px] md:h-[164px] drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("p",{className:"text-lg text-white/80 max-w-3xl mx-auto leading-relaxed font-sans font-bold md:text-4xl",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-4",children:[e.jsxs(B,{size:"lg",onClick:()=>{var L;return(L=document.getElementById("free-trial"))==null?void 0:L.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(za,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(B,{size:"lg",variant:"outline",onClick:()=>{var L;return(L=document.getElementById("features"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#1e3a4c] rounded-full",children:"See What's Included"})]})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[e.jsxs(B,{size:"lg",variant:"outline",onClick:()=>{var L;return(L=document.getElementById("brokerage"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Ga,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(B,{size:"lg",onClick:()=>{var L;return(L=document.getElementById("pricing"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(Xi,{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:aes.map((L,M)=>e.jsxs(fe,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Mt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(L.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Pt,{className:"text-xl font-sans",children:L.title})]}),e.jsx(Ae,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:L.description})})]},M))})]})}),e.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(un,{className:"w-4 h-4"}),"Included with Membership"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:ies.map((L,M)=>e.jsxs(fe,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(L.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Pt,{className:"text-lg font-semibold text-white",children:L.title})]}),e.jsx(Ae,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:L.description})})]},M))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(B,{size:"lg",onClick:()=>{var L;return(L=document.getElementById("pricing"))==null?void 0:L.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(za,{className:"ml-2 w-5 h-5"})]})})]})]}),e.jsx("section",{id:"brokerage",className:"py-20 bg-[#4a6b6d]/5",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsx("div",{className:"max-w-6xl mx-auto",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium",children:[e.jsx(Ga,{className:"w-4 h-4"}),"For Brokerages"]}),e.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Give every agent on your team access to world-class training and resources. Track performance, streamline onboarding, and watch your brokerage thrive."}),e.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((L,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Lr,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:L})]},M))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(B,{size:"lg",onClick:()=>{var L;return(L=document.getElementById("pricing"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(ga,{className:"ml-2 w-5 h-5"})]}),e.jsxs(B,{size:"lg",variant:"outline",onClick:()=>S(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(yr,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:nes,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:oes.map((L,M)=>e.jsx(fe,{className:"bg-muted/30 border-0",children:e.jsxs(Ae,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(F=>e.jsx(ua,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},F))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',L.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:L.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:L.role})]})]})},M))})]})}),e.jsxs("section",{id:"free-trial",className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center space-y-8",children:[e.jsxs("h2",{className:"text-3xl md:text-5xl font-bold text-white",children:["Start Your Free Trial ",e.jsx("span",{className:"italic",children:"Today"})]}),e.jsx("p",{className:"text-lg md:text-xl text-white/80 leading-relaxed",children:"Get instant access to 7 days of trainings, templates, and tools — designed to give you quick wins now and resources you'll keep forever."}),e.jsx("div",{className:"pt-4",children:e.jsxs(B,{size:"lg",className:"px-12 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",onClick:()=>A("individual_agent"),children:["Start Free Trial",e.jsx(za,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),e.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),e.jsx("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto",children:"Choose the plan that fits your needs. All plans include everything you need to succeed."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:[e.jsxs(fe,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Mt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Xi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(Pt,{className:"text-xl font-sans",children:fp.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:fp.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:fp.individual_agent.period})]}),e.jsx(Hn,{className:"text-base mt-2",children:fp.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(gr,{className:"w-4 h-4"}),fp.individual_agent.trial]})]}),e.jsx(Ae,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:fp.individual_agent.features.map((L,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Lr,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:L})]},M))})}),e.jsxs(nz,{className:"flex flex-col gap-3 pt-4",children:[e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("individual_agent"),children:"Start Free Trial"}),e.jsx(B,{variant:"outline",className:"w-full rounded-full border-2 border-[#4a6b6d] text-[#4a6b6d] bg-white hover:bg-[#4a6b6d]/5 uppercase text-sm font-medium tracking-wide",onClick:()=>A("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(fe,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl scale-105 bg-background",children:[e.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 px-6 py-2 bg-[#4a6b6d] text-white text-sm font-semibold rounded-full shadow-lg",children:"Most Popular"}),e.jsxs(Mt,{className:"pb-4 pt-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/20 flex items-center justify-center",children:e.jsx(Ga,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-xl font-sans",children:fp.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:fp.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:fp.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:fp.brokerage_under_25.period})]}),e.jsx(Hn,{className:"text-base mt-2",children:fp.brokerage_under_25.description})]}),e.jsx(Ae,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:fp.brokerage_under_25.features.map((L,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Lr,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:L})]},M))})}),e.jsx(nz,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(fe,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Mt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Ga,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-xl font-sans",children:fp.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:fp.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:fp.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:fp.brokerage_over_25.period})]}),e.jsx(Hn,{className:"text-base mt-2",children:fp.brokerage_over_25.description})]}),e.jsx(Ae,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:fp.brokerage_over_25.features.map((L,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Lr,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:L})]},M))})}),e.jsx(nz,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_over_25"),children:"Get Started"})})]})]})]})}),e.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium mb-4",children:[e.jsx(hh,{className:"w-4 h-4"}),"Our Commitment"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-sans font-bold",children:["LevelUp Brokerage ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Neutrality Policy"})]}),e.jsx("p",{className:"text-lg text-muted-foreground mt-4 max-w-2xl mx-auto",children:"We are committed to being a trusted, independent partner for every agent and brokerage."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ae,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Ga,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ae,{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(Rc,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not share member information with any brokerage."})]})}),e.jsx(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ae,{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(_b,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not recruit brokerage partners' agents."})]})}),e.jsx(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ae,{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(Nr,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not use LevelUp events, trainings, webinars, CRM data, or member lists for recruiting purposes."})]})})]})]})})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),e.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs(B,{size:"lg",onClick:()=>{var L;return(L=document.getElementById("pricing"))==null?void 0:L.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(za,{className:"ml-2 w-5 h-5"})]}),e.jsx(B,{size:"lg",onClick:()=>n("/auth"),className:"px-10 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#4a6b6d]",children:"Sign In"})]})]})})]}),e.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("img",{src:Efe,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(res,{open:_,onOpenChange:S}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Qn,{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(se,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ge,{id:"dialog-name",type:"text",placeholder:"John Smith",value:p,onChange:L=>f(L.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ge,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:L=>h(L.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(ge,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:g,onChange:L=>b(L.target.value),className:"mt-1"})]})]}),e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:D,disabled:v,children:v?"Loading...":"Continue to Checkout"})]})})]})},xUe=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"Privacy Policy | LevelUp"}),e.jsx("meta",{name:"description",content:"Privacy Policy for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Privacy Policy"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Introduction"}),e.jsx("p",{children:'Welcome to LevelUp ("we," "our," or "us"). We are committed to protecting your personal information and your right to privacy. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you use our platform.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Information We Collect"}),e.jsx("p",{children:"We collect information that you provide directly to us, including:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Name and contact information (email address, phone number)"}),e.jsx("li",{children:"Account credentials"}),e.jsx("li",{children:"Profile information"}),e.jsx("li",{children:"Transaction and billing information"}),e.jsx("li",{children:"Communications you send to us"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. How We Use Your Information"}),e.jsx("p",{children:"We use the information we collect to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide, maintain, and improve our services"}),e.jsx("li",{children:"Process transactions and send related information"}),e.jsx("li",{children:"Send you technical notices and support messages"}),e.jsx("li",{children:"Respond to your comments and questions"}),e.jsx("li",{children:"Communicate with you about products, services, and events"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Information Sharing"}),e.jsx("p",{children:"We do not sell, trade, or otherwise transfer your personal information to third parties without your consent, except as described in this policy or as required by law."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Data Security"}),e.jsx("p",{children:"We implement appropriate technical and organizational measures to protect the security of your personal information. However, no method of transmission over the Internet is 100% secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Your Rights"}),e.jsx("p",{children:"You have the right to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access your personal information"}),e.jsx("li",{children:"Correct inaccurate data"}),e.jsx("li",{children:"Request deletion of your data"}),e.jsx("li",{children:"Opt-out of marketing communications"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. SMS / Text Messaging Program & Mobile Information"}),e.jsx("p",{children:"Your privacy is important to us. This section outlines how we collect, use, and protect your information when you use our services, including our SMS/text messaging program."}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Information We Collect:"})," We collect personal information you provide, including your name, email address, phone number, and mobile number when you opt in to receive text messages from us."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How We Use Your Information:"})," If you opt in, we use your mobile number to send SMS account notifications, real-time lead alerts, service updates, and customer support communications related to your LevelUp account."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No Sharing of Mobile Information:"})," No mobile information will be shared with third parties/affiliates for marketing/promotional purposes. All the above categories exclude text messaging originator opt-in data and consent; this information will not be shared with any third parties."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Your Rights:"})," You have the right to access, modify, or delete your personal information at any time. You may opt out of text messages at any time by replying STOP to any message. Reply HELP for help. Message and data rates may apply. Message frequency varies."]}),e.jsxs("p",{className:"mt-3",children:["For questions about this policy, contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Third-Party Services"}),e.jsx("p",{children:"Our platform may integrate with third-party services such as Facebook and Instagram for social media posting features. When you connect these accounts, you are subject to their respective privacy policies."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. SMS Privacy Policy"}),e.jsx("p",{children:"We collect contact information you provide to us, including your name, email address, phone number, and business details, in order to provide our services, respond to inquiries, and deliver requested communications."}),e.jsx("p",{className:"mt-3",children:"If you choose to opt in to SMS communications from LevelUp, we may send you text messages including account notifications, real-time lead alerts, service updates, and customer support communications related to your LevelUp account."}),e.jsx("p",{className:"mt-3",children:"SMS consent is not shared with third parties or affiliates for marketing purposes. Mobile information will not be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties, except with vendors, aggregators, and providers that help us deliver these text messages."}),e.jsx("p",{className:"mt-3",children:"Message frequency may vary depending on your activity and use of our services. Message and data rates may apply."}),e.jsxs("p",{className:"mt-3",children:["You can opt out at any time by replying STOP. For help, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:hello@relevelup.com",className:"text-primary hover:underline",children:"hello@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. Contact Us"}),e.jsxs("p",{children:["If you have questions about this Privacy Policy, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),gUe=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"Terms of Service | LevelUp"}),e.jsx("meta",{name:"description",content:"Terms of Service for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Terms of Service"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Acceptance of Terms"}),e.jsx("p",{children:'By accessing or using the LevelUp platform ("Service"), you agree to be bound by these Terms of Service. If you do not agree to these terms, please do not use our Service.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Description of Service"}),e.jsx("p",{children:"LevelUp provides a platform for real estate professionals to access training, resources, marketing tools, and community features. We reserve the right to modify or discontinue the Service at any time."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. User Accounts"}),e.jsx("p",{children:"To use certain features, you must create an account. You agree to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide accurate and complete information"}),e.jsx("li",{children:"Maintain the security of your account credentials"}),e.jsx("li",{children:"Notify us immediately of any unauthorized access"}),e.jsx("li",{children:"Accept responsibility for all activities under your account"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Acceptable Use"}),e.jsx("p",{children:"You agree not to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Violate any applicable laws or regulations"}),e.jsx("li",{children:"Infringe on the rights of others"}),e.jsx("li",{children:"Upload malicious code or interfere with the Service"}),e.jsx("li",{children:"Attempt to gain unauthorized access to any part of the Service"}),e.jsx("li",{children:"Use the Service for any unlawful purpose"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Intellectual Property"}),e.jsx("p",{children:"The Service and its original content, features, and functionality are owned by LevelUp and are protected by international copyright, trademark, and other intellectual property laws."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Third-Party Integrations"}),e.jsx("p",{children:"Our Service may integrate with third-party platforms such as Facebook and Instagram. Your use of these integrations is subject to the terms and policies of those third parties. We are not responsible for the content or practices of any third-party services."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Payment Terms"}),e.jsx("p",{children:"Certain features may require payment. By subscribing to paid features, you agree to pay all applicable fees. All payments are non-refundable unless otherwise specified."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Limitation of Liability"}),e.jsx("p",{children:"To the maximum extent permitted by law, LevelUp shall not be liable for any indirect, incidental, special, consequential, or punitive damages resulting from your use of the Service."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Termination"}),e.jsx("p",{children:"We may terminate or suspend your account at any time, without prior notice, for conduct that we believe violates these Terms or is harmful to other users, us, or third parties."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. Changes to Terms"}),e.jsx("p",{children:"We reserve the right to modify these Terms at any time. We will notify you of significant changes by posting a notice on our platform. Continued use of the Service constitutes acceptance of the modified terms."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. SMS / Text Messaging Terms"}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 mb-4 text-sm",children:[e.jsx("strong",{children:"To opt in:"})," Submit our public SMS opt-in form at"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline font-medium",children:"/sms-opt-in"})," ","— consent is captured with timestamp and the exact disclosure text shown below."]}),e.jsx("p",{children:"By opting in to receive text messages from LevelUp, you agree to the following terms:"}),e.jsx("p",{className:"mt-2",children:"You consent to receive recurring SMS/MMS messages from LevelUp, including account notifications, real-time lead alerts, service updates, and customer support communications. Message frequency varies. Message and data rates may apply. Consent is not a condition of purchase."}),e.jsxs("p",{className:"mt-2",children:["You may opt out at any time by replying STOP to any message. After opting out, you will receive a confirmation message and no further messages will be sent. For assistance, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]}),e.jsxs("p",{className:"mt-2",children:["No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties. See our"," ",e.jsx("a",{href:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," ","for full details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. Contact Us"}),e.jsxs("p",{children:["If you have questions about these Terms, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),ces=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"Data Deletion | LevelUp"}),e.jsx("meta",{name:"description",content:"Data deletion instructions for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Data Deletion Instructions"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"How to Request Data Deletion"}),e.jsx("p",{children:"If you wish to have your data deleted from LevelUp, you can request deletion through one of the following methods:"})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Option 1: Email Request"}),e.jsxs("p",{children:["Send an email to"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})," ",'with the subject line "Data Deletion Request" and include:']}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Your full name"}),e.jsx("li",{children:"The email address associated with your account"}),e.jsx("li",{children:"A clear statement requesting deletion of your data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Option 2: Account Settings"}),e.jsx("p",{children:"If you have an active account, you can request data deletion through your account settings:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Log in to your LevelUp account"}),e.jsx("li",{children:"Navigate to your Profile settings"}),e.jsx("li",{children:"Contact support through the Support page to request account deletion"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What Data Will Be Deleted"}),e.jsx("p",{children:"Upon a valid deletion request, we will delete:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Your account information (name, email, profile data)"}),e.jsx("li",{children:"Any content you have created or uploaded"}),e.jsx("li",{children:"Your activity history and preferences"}),e.jsx("li",{children:"Connected social media account tokens and data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Data Retention"}),e.jsx("p",{children:"Some data may be retained for legal or legitimate business purposes, such as:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Transaction records required for financial reporting"}),e.jsx("li",{children:"Data necessary to comply with legal obligations"}),e.jsx("li",{children:"Anonymized or aggregated data that cannot identify you"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Facebook/Instagram Data"}),e.jsx("p",{children:"If you have connected your Facebook or Instagram account to LevelUp, you can also manage your data through Facebook's settings:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Go to your Facebook Settings & Privacy → Settings"}),e.jsx("li",{children:'Click on "Apps and Websites"'}),e.jsx("li",{children:'Find LevelUp and click "Remove"'}),e.jsx("li",{children:"This will revoke our access to your Facebook/Instagram data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Processing Time"}),e.jsx("p",{children:"We will process your data deletion request within 30 days of receiving it. You will receive a confirmation email once your data has been deleted."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Contact Us"}),e.jsxs("p",{children:["If you have questions about data deletion, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),yUe="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.",des=Zw({name:go().trim().min(1,"Name is required").max(200),phone:go().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:go().trim().email("Enter a valid email").max(320).optional().or(Np(""))});function ues(){const[s,t]=N.useState(""),[n,r]=N.useState(""),[a,i]=N.useState(""),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState(!1),p=async f=>{var v;if(f.preventDefault(),!l){ae.error("Please check the consent box to opt in.");return}const g=des.safeParse({name:s,phone:n,email:a});if(!g.success){ae.error(((v=g.error.issues[0])==null?void 0:v.message)??"Please check your inputs.");return}d(!0);const{error:b}=await q.from("sms_opt_in_consents").insert({name:g.data.name,phone:g.data.phone,email:g.data.email||null,consent_text:yUe,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),b){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(Yo,{children:[e.jsx("title",{children:"SMS Opt-In | LevelUp"}),e.jsx("meta",{name:"description",content:"Opt in to receive SMS account notifications and real-time lead alerts from LevelUp. Review consent terms, message frequency, and STOP/HELP instructions."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/sms-opt-in"})]}),e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("header",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary/10 text-primary mb-4",children:e.jsx(Ci,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Opt-In"}),e.jsx("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:"Sign up to receive SMS account notifications and real-time lead alerts from LevelUp. These messages help subscribed real estate agents review and respond to new consumer inquiries submitted through their websites."})]}),u?e.jsxs(fe,{className:"p-8 text-center",children:[e.jsx(xr,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're opted in!"}),e.jsxs("p",{className:"text-muted-foreground",children:["You'll now receive SMS account notifications and real-time lead alerts from LevelUp. Reply ",e.jsx("strong",{children:"STOP"})," at any time to opt out, or ",e.jsx("strong",{children:"HELP"})," for assistance."]})]}):e.jsx(fe,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:p,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Full Name *"}),e.jsx(ge,{id:"name",value:s,onChange:f=>t(f.target.value),required:!0,maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Mobile Number *"}),e.jsx(ge,{id:"phone",type:"tel",value:n,onChange:f=>r(f.target.value),required:!0,maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email (optional)"}),e.jsx(ge,{id:"email",type:"email",value:a,onChange:f=>i(f.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(hi,{id:"consent",checked:l,onCheckedChange:f=>o(f===!0),className:"mt-0.5"}),e.jsx(se,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:yUe})]})}),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(Ln,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(Ln,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," account notifications, real-time lead alerts, service updates, customer support."," ",e.jsx("strong",{children:"Frequency:"})," varies."," ",e.jsx("strong",{children:"Msg & data rates may apply."})," ","Reply ",e.jsx("strong",{children:"STOP"})," to opt out, ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsx("p",{children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties."})]}),e.jsx(B,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(ng,{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 Qht="/assets/levelup-logo-horizontal-DEFNc0ms.png",hes=Zw({email:go().email("Invalid email address"),password:go().min(6,"Password must be at least 6 characters")}),mes="https://dashboard.relevelup.com",fH="/oauth-connect",qme="levelupOAuthRouteHistory";function vUe(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function pes(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(qme)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(qme,JSON.stringify([{route:s,at:t}])),!1}}function fes(){sessionStorage.removeItem(qme)}const xes=()=>{const{signIn:s,user:t,loading:n}=gs(),r=(t==null?void 0:t.id)??null,a=In(),[i]=yl(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=N.useState(!1),[u,h]=N.useState({}),[p,f]=N.useState(""),[g,b]=N.useState(!1),[v,j]=N.useState(!1),[_,S]=N.useState(null),A=N.useRef(!1);N.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const L=new URL("/auth",mes);L.searchParams.set("next",`${fH}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(L.toString());return}if(l){const L=`${fH}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",L);return}o&&vUe(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),N.useEffect(()=>{if(n||!r||A.current)return;const L=l?`${fH}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!vUe(L)){sessionStorage.removeItem("redirectAfterLogin"),A.current=!0,a("/dashboard",{replace:!0});return}const M=L.startsWith(fH)||L.startsWith("/oauth/consent")||L.startsWith("/.lovable/oauth/consent");if(M&&pes("auth")){S("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}A.current=!0,M||(fes(),sessionStorage.removeItem("redirectAfterLogin")),a(L,{replace:!0})},[l,n,a,r]);const T=async L=>{L.preventDefault(),h({}),d(!0);const M=new FormData(L.currentTarget),F=M.get("email"),z=M.get("password");try{hes.parse({email:F,password:z}),await s(F,z)}catch(V){if(V instanceof zGt){const W={};V.issues.forEach(K=>{K.path[0]&&(W[K.path[0]]=K.message)}),h(W)}}finally{d(!1)}},D=async()=>{if(!p){ae.error("Please enter your email address");return}b(!0);try{const{error:L}=await q.functions.invoke("send-password-reset",{body:{email:p,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(L)throw L;ae.success("Password reset email sent! Check your inbox."),j(!1),f("")}catch(L){ae.error(L instanceof Error?L.message:"Failed to send reset email")}finally{b(!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(Ln,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(Wr,{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:Qht,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(fe,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Mt,{className:"space-y-1 text-center pb-4",children:[e.jsx(Pt,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(Hn,{className:"text-gray-600",children:_||"Sign in to access your dashboard"})]}),e.jsx(Ae,{children:e.jsxs("form",{onSubmit:T,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(ge,{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(se,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(ge,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.password&&e.jsx("p",{className:"text-sm text-red-600",children:u.password})]}),e.jsx(B,{type:"submit",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg transition-all duration-200 shadow-lg hover:shadow-xl",disabled:c,children:c?"Signing in...":"Sign In"}),e.jsxs(bs,{open:v,onOpenChange:j,children:[e.jsx(Di,{asChild:!0,children:e.jsx(B,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(vs,{className:"bg-white",children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Qn,{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(se,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(ge,{id:"reset-email",type:"email",placeholder:"your@email.com",value:p,onChange:L=>f(L.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(B,{onClick:D,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(Ln,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},bUe=()=>q.auth.oauth,ges="https://dashboard.relevelup.com",yes="/oauth-connect",Vme="levelupOAuthRouteHistory",ves="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",bes="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function _es(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function wes(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(Vme)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(Vme,JSON.stringify([{route:s,at:t}])),!1}}function jes(){sessionStorage.removeItem(Vme)}async function _Ue(s,t,n){const r=await fetch(`${ves}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:bes,"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 Oje(){var b;const{user:s,session:t,loading:n}=gs(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=yl(),l=i.get("authorization_id")??"",[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(!1);N.useEffect(()=>{let v=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const j=`${yes}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${ges}${j}`;return}if(n)return;if(!r){if(wes("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}_es(j)&&sessionStorage.setItem("redirectAfterLogin",j),window.location.replace(`/auth?next=${encodeURIComponent(j)}`);return}if(!a)return;jes(),sessionStorage.removeItem("redirectAfterLogin");const _=bUe(),{data:S,error:A}=_?await _.getAuthorizationDetails(l):await _Ue(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!v)return;if(A){u(A.message);return}const T=(S==null?void 0:S.redirect_url)??(S==null?void 0:S.redirect_to);if(T&&!(S!=null&&S.client)){window.location.href=T;return}c(S)})(),()=>{v=!1}},[a,l,n,r]);async function f(v){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}p(!0);const j=bUe(),{data:_,error:S}=j?v?await j.approveAuthorization(l,{skipBrowserRedirect:!0}):await j.denyAuthorization(l,{skipBrowserRedirect:!0}):await _Ue(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:v?"approve":"deny"})});if(S){p(!1),u(S.message);return}const A=(_==null?void 0:_.redirect_url)??(_==null?void 0:_.redirect_to);if(!A){p(!1),u("No redirect returned by the authorization server.");return}window.location.href=A}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(fe,{className:"w-full max-w-md",children:e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Authorization error"}),e.jsx(Hn,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-primary"})});const g=((b=o.client)==null?void 0:b.name)??"An app";return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{children:["Connect ",g," to LevelUp"]}),e.jsxs(Hn,{children:[g," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Ae,{className:"flex gap-3 justify-end",children:[e.jsx(B,{variant:"outline",disabled:h,onClick:()=>f(!1),children:"Deny"}),e.jsx(B,{disabled:h,onClick:()=>f(!0),children:h?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const Xht=s=>{const[t,n]=N.useState(null),[r,a]=N.useState(!0);return N.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await q.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=q.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);n(`${c.publicUrl}?t=${Date.now()}`)}else n(null)}catch(o){console.error("Error fetching avatar:",o),n(null)}finally{a(!1)}})()},[s]),{avatarUrl:t,loading:r,refreshAvatar:async()=>{if(s)try{const{data:l}=await q.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=q.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);n(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},Jht=async s=>{const t=new Map;return await Promise.all(s.map(async n=>{try{const{data:r}=await q.storage.from("avatars").list(`${n}`);if(r&&r.length>0){const{data:a}=q.storage.from("avatars").getPublicUrl(`${n}/${r[0].name}`);t.set(n,a.publicUrl)}}catch{}})),t},Nes=s=>{const[t,n]=N.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return N.useEffect(()=>{if(!s){n(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await q.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),n(h=>({...h,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const h=new Date().getTime(),p=new Date(d).getTime(),f=Math.ceil((p-h)/(1e3*60*60*24)),g=f<=0;n({isTrial:!0,isExpired:g,expiresAt:d,daysLeft:g?0:f,loading:!1})}else n({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),n(i=>({...i,loading:!1}))}})()},[s]),t},emt=()=>{const{data:s,isLoading:t}=lt({queryKey:["feature-flags"],queryFn:async()=>{const{data:r,error:a}=await q.from("feature_flags").select("*");if(a)throw a;return r}}),n=r=>{if(!s)return!1;const a=s.find(i=>i.key===r);return(a==null?void 0:a.enabled)??!1};return{flags:s,isLoading:t,isFeatureEnabled:n,isAgentOSEnabled:n("agent_os_enabled"),isInnerCircleEnabled:n("innercircle_enabled"),isMarketplaceEnabled:n("marketplace")}},wUe="community_last_seen_post_at";function kes(){const{user:s}=gs(),t=Jl(),[n,r]=N.useState(0),[a,i]=N.useState(null);N.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${wUe}_${s.id}`);i(o)},[s]),N.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const f=sessionStorage.getItem(o);if(f){const g=JSON.parse(f);if(g.ts&&Date.now()-g.ts{if(!s)return;const o=q.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const u=t.pathname==="/community";u||r(b=>b+1);const{data:h}=await q.from("profiles").select("name").eq("id",d.user_id).single(),p=(h==null?void 0:h.name)||"Someone",f=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),g=f.length>50?f.substring(0,50)+"...":f;u||ae("New Community Post",{description:`${p}: ${g}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{q.removeChannel(o)}},[s,t.pathname]);const l=N.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${wUe}_${s.id}`,o),i(o),r(0)},[s]);return N.useEffect(()=>{t.pathname==="/community"&&n>0&&l()},[t.pathname,n,l]),{unreadCount:n,markAsRead:l}}function Ses(){const{isAdmin:s}=gs(),{data:t=0}=lt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:n,error:r}=await q.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(r)throw r;return n||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}var Rye="Collapsible",[Ces,tmt]=gu(Rye),[Tes,r6e]=Ces(Rye),smt=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=mm({prop:r,defaultProp:a??!1,onChange:l,caller:Rye});return e.jsx(Tes,{scope:n,disabled:i,contentId:um(),open:c,onOpenToggle:N.useCallback(()=>d(u=>!u),[d]),children:e.jsx(sa.div,{"data-state":l6e(c),"data-disabled":i?"":void 0,...o,ref:t})})});smt.displayName=Rye;var nmt="CollapsibleTrigger",a6e=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,...r}=s,a=r6e(nmt,n);return e.jsx(sa.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":l6e(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:t,onClick:wr(s.onClick,a.onOpenToggle)})});a6e.displayName=nmt;var i6e="CollapsibleContent",o6e=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=r6e(i6e,s.__scopeCollapsible);return e.jsx(Bh,{present:n||a.open,children:({present:i})=>e.jsx(Ees,{...r,ref:t,present:i})})});o6e.displayName=i6e;var Ees=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=s,l=r6e(i6e,n),[o,c]=N.useState(r),d=N.useRef(null),u=Ti(t,d),h=N.useRef(0),p=h.current,f=N.useRef(0),g=f.current,b=l.open||o,v=N.useRef(b),j=N.useRef(void 0);return N.useEffect(()=>{const _=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(_)},[]),fh(()=>{const _=d.current;if(_){j.current=j.current||{transitionDuration:_.style.transitionDuration,animationName:_.style.animationName},_.style.transitionDuration="0s",_.style.animationName="none";const S=_.getBoundingClientRect();h.current=S.height,f.current=S.width,v.current||(_.style.transitionDuration=j.current.transitionDuration,_.style.animationName=j.current.animationName),c(r)}},[l.open,r]),e.jsx(sa.div,{"data-state":l6e(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!b,...i,ref:u,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...s.style},children:b&&a})});function l6e(s){return s?"open":"closed"}var rmt=smt,Aes=a6e,Mes=o6e;const uy=rmt,hy=a6e,my=o6e,Ies="/assets/levelup-logo-Eif24dqY.png",Pes="/assets/levelup-logo-icon-C-7iromj.png",Les="/assets/levelup-logo-mobile-B9skSjUG.png";var pU=s=>s.type==="checkbox",ZE=s=>s instanceof Date,Hx=s=>s==null;const amt=s=>typeof s=="object";var zh=s=>!Hx(s)&&!Array.isArray(s)&&amt(s)&&!ZE(s),imt=s=>zh(s)&&s.target?pU(s.target)?s.target.checked:s.target.value:s,Des=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,omt=(s,t)=>s.has(Des(t)),Res=s=>{const t=s.constructor&&s.constructor.prototype;return zh(t)&&t.hasOwnProperty("isPrototypeOf")},c6e=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Em(s){let t;const n=Array.isArray(s),r=typeof FileList<"u"?s instanceof FileList:!1;if(s instanceof Date)t=new Date(s);else if(!(c6e&&(s instanceof Blob||r))&&(n||zh(s)))if(t=n?[]:{},!n&&!Res(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=Em(s[a]));else return s;return t}var Oye=s=>/^\w*$/.test(s),Th=s=>s===void 0,d6e=s=>Array.isArray(s)?s.filter(Boolean):[],u6e=s=>d6e(s.replace(/["|']|\]/g,"").split(/\.|\[/)),La=(s,t,n)=>{if(!t||!zh(s))return n;const r=(Oye(t)?[t]:u6e(t)).reduce((a,i)=>Hx(a)?a:a[i],s);return Th(r)||r===s?Th(s[t])?n:s[t]:r},G0=s=>typeof s=="boolean",Cc=(s,t,n)=>{let r=-1;const a=Oye(t)?[t]:u6e(t),i=a.length,l=i-1;for(;++rNt.useContext(h6e),Oes=s=>{const{children:t,...n}=s;return Nt.createElement(h6e.Provider,{value:n},t)};var lmt=(s,t,n,r=!0)=>{const a={defaultValues:t._defaultValues};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==rb.all&&(t._proxyFormState[l]=!r||rb.all),n&&(n[l]=!0),s[l]}});return a};const m6e=typeof window<"u"?Nt.useLayoutEffect:Nt.useEffect;function Fes(s){const t=Fye(),{control:n=t.control,disabled:r,name:a,exact:i}=s||{},[l,o]=Nt.useState(n._formState),c=Nt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return m6e(()=>n._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!r&&o({...n._formState,...d})}}),[a,r,i]),Nt.useEffect(()=>{c.current.isValid&&n._setValid(!0)},[n]),Nt.useMemo(()=>lmt(l,n,c.current,!1),[l,n])}var aw=s=>typeof s=="string",cmt=(s,t,n,r,a)=>aw(s)?(r&&t.watch.add(s),La(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),La(n,i))):(r&&(t.watchAll=!0),n),yCe=s=>Hx(s)||!amt(s);function P2(s,t,n=new WeakSet){if(yCe(s)||yCe(t))return s===t;if(ZE(s)&&ZE(t))return s.getTime()===t.getTime();const r=Object.keys(s),a=Object.keys(t);if(r.length!==a.length)return!1;if(n.has(s)||n.has(t))return!0;n.add(s),n.add(t);for(const i of r){const l=s[i];if(!a.includes(i))return!1;if(i!=="ref"){const o=t[i];if(ZE(l)&&ZE(o)||zh(l)&&zh(o)||Array.isArray(l)&&Array.isArray(o)?!P2(l,o,n):l!==o)return!1}}return!0}function zes(s){const t=Fye(),{control:n=t.control,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Nt.useRef(a),d=Nt.useRef(o),u=Nt.useRef(void 0);d.current=o;const h=Nt.useMemo(()=>n._getWatch(r,c.current),[n,r]),[p,f]=Nt.useState(d.current?d.current(h):h);return m6e(()=>n._subscribe({name:r,formState:{values:!0},exact:l,callback:g=>{if(!i){const b=cmt(r,n._names,g.values||n._formValues,!1,c.current);if(d.current){const v=d.current(b);P2(v,u.current)||(f(v),u.current=v)}else f(b)}}}),[n,i,r,l]),Nt.useEffect(()=>n._removeUnmounted()),p}function Bes(s){const t=Fye(),{name:n,disabled:r,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=omt(a._names.array,n),c=Nt.useMemo(()=>La(a._formValues,n,La(a._defaultValues,n,l)),[a,n,l]),d=zes({control:a,name:n,defaultValue:c,exact:!0}),u=Fes({control:a,name:n,exact:!0}),h=Nt.useRef(s),p=Nt.useRef(a.register(n,{...s.rules,value:d,...G0(s.disabled)?{disabled:s.disabled}:{}}));h.current=s;const f=Nt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!La(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!La(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!La(u.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!La(u.validatingFields,n)},error:{enumerable:!0,get:()=>La(u.errors,n)}}),[u,n]),g=Nt.useCallback(_=>p.current.onChange({target:{value:imt(_),name:n},type:Afe.CHANGE}),[n]),b=Nt.useCallback(()=>p.current.onBlur({target:{value:La(a._formValues,n),name:n},type:Afe.BLUR}),[n,a._formValues]),v=Nt.useCallback(_=>{const S=La(a._fields,n);S&&_&&(S._f.ref={focus:()=>_.focus&&_.focus(),select:()=>_.select&&_.select(),setCustomValidity:A=>_.setCustomValidity(A),reportValidity:()=>_.reportValidity()})},[a._fields,n]),j=Nt.useMemo(()=>({name:n,value:d,...G0(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:g,onBlur:b,ref:v}),[n,r,u.disabled,g,b,v,d]);return Nt.useEffect(()=>{const _=a._options.shouldUnregister||i;a.register(n,{...h.current.rules,...G0(h.current.disabled)?{disabled:h.current.disabled}:{}});const S=(A,T)=>{const D=La(a._fields,A);D&&D._f&&(D._f.mount=T)};if(S(n,!0),_){const A=Em(La(a._options.defaultValues,n));Cc(a._defaultValues,n,A),Th(La(a._formValues,n))&&Cc(a._formValues,n,A)}return!o&&a.register(n),()=>{(o?_&&!a._state.action:_)?a.unregister(n):S(n,!1)}},[n,a,o,i]),Nt.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),Nt.useMemo(()=>({field:j,formState:u,fieldState:f}),[j,u,f])}const $es=s=>s.render(Bes(s));var dmt=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{},rz=s=>Array.isArray(s)?s:[s],jUe=()=>{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=[]}}},Mg=s=>zh(s)&&!Object.keys(s).length,p6e=s=>s.type==="file",ab=s=>typeof s=="function",Mfe=s=>{if(!c6e)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},umt=s=>s.type==="select-multiple",f6e=s=>s.type==="radio",Ues=s=>f6e(s)||pU(s),Fje=s=>Mfe(s)&&s.isConnected;function qes(s,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in s)if(ab(s[t]))return!0;return!1};function Ife(s,t={}){const n=Array.isArray(s);if(zh(s)||n)for(const r in s)Array.isArray(s[r])||zh(s[r])&&!hmt(s[r])?(t[r]=Array.isArray(s[r])?[]:{},Ife(s[r],t[r])):Hx(s[r])||(t[r]=!0);return t}function mmt(s,t,n){const r=Array.isArray(s);if(zh(s)||r)for(const a in s)Array.isArray(s[a])||zh(s[a])&&!hmt(s[a])?Th(t)||yCe(n[a])?n[a]=Array.isArray(s[a])?Ife(s[a],[]):{...Ife(s[a])}:mmt(s[a],Hx(t)?{}:t[a],n[a]):n[a]=!P2(s[a],t[a]);return n}var hF=(s,t)=>mmt(s,t,Ife(t));const NUe={value:!1,isValid:!1},kUe={value:!0,isValid:!0};var pmt=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&&!Th(s[0].attributes.value)?Th(s[0].value)||s[0].value===""?kUe:{value:s[0].value,isValid:!0}:kUe:NUe}return NUe},fmt=(s,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Th(s)?s:t?s===""?NaN:s&&+s:n&&aw(s)?new Date(s):r?r(s):s;const SUe={isValid:!1,value:null};var xmt=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,SUe):SUe;function CUe(s){const t=s.ref;return p6e(t)?t.files:f6e(t)?xmt(s.refs).value:umt(t)?[...t.selectedOptions].map(({value:n})=>n):pU(t)?pmt(s.refs).value:fmt(Th(t.value)?s.ref.value:t.value,s)}var Hes=(s,t,n,r)=>{const a={};for(const i of s){const l=La(t,i);l&&Cc(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},Pfe=s=>s instanceof RegExp,mF=s=>Th(s)?s:Pfe(s)?s.source:zh(s)?Pfe(s.value)?s.value.source:s.value:s,TUe=s=>({isOnSubmit:!s||s===rb.onSubmit,isOnBlur:s===rb.onBlur,isOnChange:s===rb.onChange,isOnAll:s===rb.all,isOnTouch:s===rb.onTouched});const EUe="AsyncFunction";var Ges=s=>!!s&&!!s.validate&&!!(ab(s.validate)&&s.validate.constructor.name===EUe||zh(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===EUe)),Wes=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),AUe=(s,t,n)=>!n&&(t.watchAll||t.watch.has(s)||[...t.watch].some(r=>s.startsWith(r)&&/^\.\w+/.test(s.slice(r.length))));const az=(s,t,n,r)=>{for(const a of n||Object.keys(s)){const i=La(s,a);if(i){const{_f:l,...o}=i;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],a)&&!r)return!0;if(l.ref&&t(l.ref,l.name)&&!r)return!0;if(az(o,t))break}else if(zh(o)&&az(o,t))break}}};function MUe(s,t,n){const r=La(s,n);if(r||Oye(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=La(t,i),o=La(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 Kes=(s,t,n,r)=>{n(s);const{name:a,...i}=s;return Mg(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||rb.all))},Yes=(s,t,n)=>!s||!t||s===t||rz(s).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),Zes=(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,Qes=(s,t)=>!d6e(La(s,t)).length&&Zh(s,t),Xes=(s,t,n)=>{const r=rz(La(s,n));return Cc(r,"root",t[n]),Cc(s,n,r),s},Hme=s=>aw(s);function IUe(s,t,n="validate"){if(Hme(s)||Array.isArray(s)&&s.every(Hme)||G0(s)&&!s)return{type:n,message:Hme(s)?s:"",ref:t}}var jI=s=>zh(s)&&!Pfe(s)?s:{value:s,message:""},PUe=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:p,pattern:f,validate:g,name:b,valueAsNumber:v,mount:j}=s._f,_=La(n,b);if(!j||t.has(b))return{};const S=o?o[0]:l,A=W=>{a&&S.reportValidity&&(S.setCustomValidity(G0(W)?"":W||""),S.reportValidity())},T={},D=f6e(l),L=pU(l),M=D||L,F=(v||p6e(l))&&Th(l.value)&&Th(_)||Mfe(l)&&l.value===""||_===""||Array.isArray(_)&&!_.length,z=dmt.bind(null,b,r,T),V=(W,K,Y,ee=r2.maxLength,ne=r2.minLength)=>{const oe=W?K:Y;T[b]={type:W?ee:ne,message:oe,ref:l,...z(W?ee:ne,oe)}};if(i?!Array.isArray(_)||!_.length:c&&(!M&&(F||Hx(_))||G0(_)&&!_||L&&!pmt(o).isValid||D&&!xmt(o).isValid)){const{value:W,message:K}=Hme(c)?{value:!!c,message:c}:jI(c);if(W&&(T[b]={type:r2.required,message:K,ref:S,...z(r2.required,K)},!r))return A(K),T}if(!F&&(!Hx(h)||!Hx(p))){let W,K;const Y=jI(p),ee=jI(h);if(!Hx(_)&&!isNaN(_)){const ne=l.valueAsNumber||_&&+_;Hx(Y.value)||(W=ne>Y.value),Hx(ee.value)||(K=nenew Date(new Date().toDateString()+" "+de),pe=l.type=="time",ce=l.type=="week";aw(Y.value)&&_&&(W=pe?oe(_)>oe(Y.value):ce?_>Y.value:ne>new Date(Y.value)),aw(ee.value)&&_&&(K=pe?oe(_)+W.value,ee=!Hx(K.value)&&_.length<+K.value;if((Y||ee)&&(V(Y,W.message,K.message),!r))return A(T[b].message),T}if(f&&!F&&aw(_)){const{value:W,message:K}=jI(f);if(Pfe(W)&&!_.match(W)&&(T[b]={type:r2.pattern,message:K,ref:l,...z(r2.pattern,K)},!r))return A(K),T}if(g){if(ab(g)){const W=await g(_,n),K=IUe(W,S);if(K&&(T[b]={...K,...z(r2.validate,K.message)},!r))return A(K.message),T}else if(zh(g)){let W={};for(const K in g){if(!Mg(W)&&!r)break;const Y=IUe(await g[K](_,n),S,K);Y&&(W={...Y,...z(K,Y.message)},A(Y.message),r&&(T[b]=W))}if(!Mg(W)&&(T[b]={ref:S,...W},!r))return T}}return A(!0),T};const Jes={mode:rb.onSubmit,reValidateMode:rb.onChange,shouldFocusError:!0};function ets(s={}){let t={...Jes,...s},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:ab(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=zh(t.defaultValues)||zh(t.values)?Em(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:Em(a),l={action:!1,mount:!1,watch:!1},o={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c,d=0;const u={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let h={...u};const p={array:jUe(),state:jUe()},f=t.criteriaMode===rb.all,g=Ke=>rt=>{clearTimeout(d),d=setTimeout(Ke,rt)},b=async Ke=>{if(!t.disabled&&(u.isValid||h.isValid||Ke)){const rt=t.resolver?Mg((await L()).errors):await F(r,!0);rt!==n.isValid&&p.state.next({isValid:rt})}},v=(Ke,rt)=>{!t.disabled&&(u.isValidating||u.validatingFields||h.isValidating||h.validatingFields)&&((Ke||Array.from(o.mount)).forEach(tt=>{tt&&(rt?Cc(n.validatingFields,tt,rt):Zh(n.validatingFields,tt))}),p.state.next({validatingFields:n.validatingFields,isValidating:!Mg(n.validatingFields)}))},j=(Ke,rt=[],tt,at,Ge=!0,dt=!0)=>{if(at&&tt&&!t.disabled){if(l.action=!0,dt&&Array.isArray(La(r,Ke))){const Bt=tt(La(r,Ke),at.argA,at.argB);Ge&&Cc(r,Ke,Bt)}if(dt&&Array.isArray(La(n.errors,Ke))){const Bt=tt(La(n.errors,Ke),at.argA,at.argB);Ge&&Cc(n.errors,Ke,Bt),Qes(n.errors,Ke)}if((u.touchedFields||h.touchedFields)&&dt&&Array.isArray(La(n.touchedFields,Ke))){const Bt=tt(La(n.touchedFields,Ke),at.argA,at.argB);Ge&&Cc(n.touchedFields,Ke,Bt)}(u.dirtyFields||h.dirtyFields)&&(n.dirtyFields=hF(a,i)),p.state.next({name:Ke,isDirty:V(Ke,rt),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Cc(i,Ke,rt)},_=(Ke,rt)=>{Cc(n.errors,Ke,rt),p.state.next({errors:n.errors})},S=Ke=>{n.errors=Ke,p.state.next({errors:n.errors,isValid:!1})},A=(Ke,rt,tt,at)=>{const Ge=La(r,Ke);if(Ge){const dt=La(i,Ke,Th(tt)?La(a,Ke):tt);Th(dt)||at&&at.defaultChecked||rt?Cc(i,Ke,rt?dt:CUe(Ge._f)):Y(Ke,dt),l.mount&&b()}},T=(Ke,rt,tt,at,Ge)=>{let dt=!1,Bt=!1;const kt={name:Ke};if(!t.disabled){if(!tt||at){(u.isDirty||h.isDirty)&&(Bt=n.isDirty,n.isDirty=kt.isDirty=V(),dt=Bt!==kt.isDirty);const Qt=P2(La(a,Ke),rt);Bt=!!La(n.dirtyFields,Ke),Qt?Zh(n.dirtyFields,Ke):Cc(n.dirtyFields,Ke,!0),kt.dirtyFields=n.dirtyFields,dt=dt||(u.dirtyFields||h.dirtyFields)&&Bt!==!Qt}if(tt){const Qt=La(n.touchedFields,Ke);Qt||(Cc(n.touchedFields,Ke,tt),kt.touchedFields=n.touchedFields,dt=dt||(u.touchedFields||h.touchedFields)&&Qt!==tt)}dt&&Ge&&p.state.next(kt)}return dt?kt:{}},D=(Ke,rt,tt,at)=>{const Ge=La(n.errors,Ke),dt=(u.isValid||h.isValid)&&G0(rt)&&n.isValid!==rt;if(t.delayError&&tt?(c=g(()=>_(Ke,tt)),c(t.delayError)):(clearTimeout(d),c=null,tt?Cc(n.errors,Ke,tt):Zh(n.errors,Ke)),(tt?!P2(Ge,tt):Ge)||!Mg(at)||dt){const Bt={...at,...dt&&G0(rt)?{isValid:rt}:{},errors:n.errors,name:Ke};n={...n,...Bt},p.state.next(Bt)}},L=async Ke=>{v(Ke,!0);const rt=await t.resolver(i,t.context,Hes(Ke||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return v(Ke),rt},M=async Ke=>{const{errors:rt}=await L(Ke);if(Ke)for(const tt of Ke){const at=La(rt,tt);at?Cc(n.errors,tt,at):Zh(n.errors,tt)}else n.errors=rt;return rt},F=async(Ke,rt,tt={valid:!0})=>{for(const at in Ke){const Ge=Ke[at];if(Ge){const{_f:dt,...Bt}=Ge;if(dt){const kt=o.array.has(dt.name),Qt=Ge._f&&Ges(Ge._f);Qt&&u.validatingFields&&v([at],!0);const ns=await PUe(Ge,o.disabled,i,f,t.shouldUseNativeValidation&&!rt,kt);if(Qt&&u.validatingFields&&v([at]),ns[dt.name]&&(tt.valid=!1,rt))break;!rt&&(La(ns,dt.name)?kt?Xes(n.errors,ns,dt.name):Cc(n.errors,dt.name,ns[dt.name]):Zh(n.errors,dt.name))}!Mg(Bt)&&await F(Bt,rt,tt)}}return tt.valid},z=()=>{for(const Ke of o.unMount){const rt=La(r,Ke);rt&&(rt._f.refs?rt._f.refs.every(tt=>!Fje(tt)):!Fje(rt._f.ref))&&Ee(Ke)}o.unMount=new Set},V=(Ke,rt)=>!t.disabled&&(Ke&&rt&&Cc(i,Ke,rt),!P2(de(),a)),W=(Ke,rt,tt)=>cmt(Ke,o,{...l.mount?i:Th(rt)?a:aw(Ke)?{[Ke]:rt}:rt},tt,rt),K=Ke=>d6e(La(l.mount?i:a,Ke,t.shouldUnregister?La(a,Ke,[]):[])),Y=(Ke,rt,tt={})=>{const at=La(r,Ke);let Ge=rt;if(at){const dt=at._f;dt&&(!dt.disabled&&Cc(i,Ke,fmt(rt,dt)),Ge=Mfe(dt.ref)&&Hx(rt)?"":rt,umt(dt.ref)?[...dt.ref.options].forEach(Bt=>Bt.selected=Ge.includes(Bt.value)):dt.refs?pU(dt.ref)?dt.refs.forEach(Bt=>{(!Bt.defaultChecked||!Bt.disabled)&&(Array.isArray(Ge)?Bt.checked=!!Ge.find(kt=>kt===Bt.value):Bt.checked=Ge===Bt.value||!!Ge)}):dt.refs.forEach(Bt=>Bt.checked=Bt.value===Ge):p6e(dt.ref)?dt.ref.value="":(dt.ref.value=Ge,dt.ref.type||p.state.next({name:Ke,values:Em(i)})))}(tt.shouldDirty||tt.shouldTouch)&&T(Ke,Ge,tt.shouldTouch,tt.shouldDirty,!0),tt.shouldValidate&&ce(Ke)},ee=(Ke,rt,tt)=>{for(const at in rt){if(!rt.hasOwnProperty(at))return;const Ge=rt[at],dt=Ke+"."+at,Bt=La(r,dt);(o.array.has(Ke)||zh(Ge)||Bt&&!Bt._f)&&!ZE(Ge)?ee(dt,Ge,tt):Y(dt,Ge,tt)}},ne=(Ke,rt,tt={})=>{const at=La(r,Ke),Ge=o.array.has(Ke),dt=Em(rt);Cc(i,Ke,dt),Ge?(p.array.next({name:Ke,values:Em(i)}),(u.isDirty||u.dirtyFields||h.isDirty||h.dirtyFields)&&tt.shouldDirty&&p.state.next({name:Ke,dirtyFields:hF(a,i),isDirty:V(Ke,dt)})):at&&!at._f&&!Hx(dt)?ee(Ke,dt,tt):Y(Ke,dt,tt),AUe(Ke,o)&&p.state.next({...n,name:Ke}),p.state.next({name:l.mount?Ke:void 0,values:Em(i)})},oe=async Ke=>{l.mount=!0;const rt=Ke.target;let tt=rt.name,at=!0;const Ge=La(r,tt),dt=Qt=>{at=Number.isNaN(Qt)||ZE(Qt)&&isNaN(Qt.getTime())||P2(Qt,La(i,tt,Qt))},Bt=TUe(t.mode),kt=TUe(t.reValidateMode);if(Ge){let Qt,ns;const $s=rt.type?CUe(Ge._f):imt(Ke),Ds=Ke.type===Afe.BLUR||Ke.type===Afe.FOCUS_OUT,Dt=!Wes(Ge._f)&&!t.resolver&&!La(n.errors,tt)&&!Ge._f.deps||Zes(Ds,La(n.touchedFields,tt),n.isSubmitted,kt,Bt),St=AUe(tt,o,Ds);Cc(i,tt,$s),Ds?(Ge._f.onBlur&&Ge._f.onBlur(Ke),c&&c(0)):Ge._f.onChange&&Ge._f.onChange(Ke);const $t=T(tt,$s,Ds),ht=!Mg($t)||St;if(!Ds&&p.state.next({name:tt,type:Ke.type,values:Em(i)}),Dt)return(u.isValid||h.isValid)&&(t.mode==="onBlur"?Ds&&b():Ds||b()),ht&&p.state.next({name:tt,...St?{}:$t});if(!Ds&&St&&p.state.next({...n}),t.resolver){const{errors:Ut}=await L([tt]);if(dt($s),at){const Es=MUe(n.errors,r,tt),Xt=MUe(Ut,r,Es.name||tt);Qt=Xt.error,tt=Xt.name,ns=Mg(Ut)}}else v([tt],!0),Qt=(await PUe(Ge,o.disabled,i,f,t.shouldUseNativeValidation))[tt],v([tt]),dt($s),at&&(Qt?ns=!1:(u.isValid||h.isValid)&&(ns=await F(r,!0)));at&&(Ge._f.deps&&ce(Ge._f.deps),D(tt,ns,Qt,$t))}},pe=(Ke,rt)=>{if(La(n.errors,rt)&&Ke.focus)return Ke.focus(),1},ce=async(Ke,rt={})=>{let tt,at;const Ge=rz(Ke);if(t.resolver){const dt=await M(Th(Ke)?Ke:Ge);tt=Mg(dt),at=Ke?!Ge.some(Bt=>La(dt,Bt)):tt}else Ke?(at=(await Promise.all(Ge.map(async dt=>{const Bt=La(r,dt);return await F(Bt&&Bt._f?{[dt]:Bt}:Bt)}))).every(Boolean),!(!at&&!n.isValid)&&b()):at=tt=await F(r);return p.state.next({...!aw(Ke)||(u.isValid||h.isValid)&&tt!==n.isValid?{}:{name:Ke},...t.resolver||!Ke?{isValid:tt}:{},errors:n.errors}),rt.shouldFocus&&!at&&az(r,pe,Ke?Ge:o.mount),at},de=Ke=>{const rt={...l.mount?i:a};return Th(Ke)?rt:aw(Ke)?La(rt,Ke):Ke.map(tt=>La(rt,tt))},ie=(Ke,rt)=>({invalid:!!La((rt||n).errors,Ke),isDirty:!!La((rt||n).dirtyFields,Ke),error:La((rt||n).errors,Ke),isValidating:!!La(n.validatingFields,Ke),isTouched:!!La((rt||n).touchedFields,Ke)}),ye=Ke=>{Ke&&rz(Ke).forEach(rt=>Zh(n.errors,rt)),p.state.next({errors:Ke?n.errors:{}})},_e=(Ke,rt,tt)=>{const at=(La(r,Ke,{_f:{}})._f||{}).ref,Ge=La(n.errors,Ke)||{},{ref:dt,message:Bt,type:kt,...Qt}=Ge;Cc(n.errors,Ke,{...Qt,...rt,ref:at}),p.state.next({name:Ke,errors:n.errors,isValid:!1}),tt&&tt.shouldFocus&&at&&at.focus&&at.focus()},Me=(Ke,rt)=>ab(Ke)?p.state.subscribe({next:tt=>"values"in tt&&Ke(W(void 0,rt),tt)}):W(Ke,rt,!0),Te=Ke=>p.state.subscribe({next:rt=>{Yes(Ke.name,rt.name,Ke.exact)&&Kes(rt,Ke.formState||u,He,Ke.reRenderRoot)&&Ke.callback({values:{...i},...n,...rt,defaultValues:a})}}).unsubscribe,Ce=Ke=>(l.mount=!0,h={...h,...Ke.formState},Te({...Ke,formState:h})),Ee=(Ke,rt={})=>{for(const tt of Ke?rz(Ke):o.mount)o.mount.delete(tt),o.array.delete(tt),rt.keepValue||(Zh(r,tt),Zh(i,tt)),!rt.keepError&&Zh(n.errors,tt),!rt.keepDirty&&Zh(n.dirtyFields,tt),!rt.keepTouched&&Zh(n.touchedFields,tt),!rt.keepIsValidating&&Zh(n.validatingFields,tt),!t.shouldUnregister&&!rt.keepDefaultValue&&Zh(a,tt);p.state.next({values:Em(i)}),p.state.next({...n,...rt.keepDirty?{isDirty:V()}:{}}),!rt.keepIsValid&&b()},De=({disabled:Ke,name:rt})=>{(G0(Ke)&&l.mount||Ke||o.disabled.has(rt))&&(Ke?o.disabled.add(rt):o.disabled.delete(rt))},Ie=(Ke,rt={})=>{let tt=La(r,Ke);const at=G0(rt.disabled)||G0(t.disabled);return Cc(r,Ke,{...tt||{},_f:{...tt&&tt._f?tt._f:{ref:{name:Ke}},name:Ke,mount:!0,...rt}}),o.mount.add(Ke),tt?De({disabled:G0(rt.disabled)?rt.disabled:t.disabled,name:Ke}):A(Ke,!0,rt.value),{...at?{disabled:rt.disabled||t.disabled}:{},...t.progressive?{required:!!rt.required,min:mF(rt.min),max:mF(rt.max),minLength:mF(rt.minLength),maxLength:mF(rt.maxLength),pattern:mF(rt.pattern)}:{},name:Ke,onChange:oe,onBlur:oe,ref:Ge=>{if(Ge){Ie(Ke,rt),tt=La(r,Ke);const dt=Th(Ge.value)&&Ge.querySelectorAll&&Ge.querySelectorAll("input,select,textarea")[0]||Ge,Bt=Ues(dt),kt=tt._f.refs||[];if(Bt?kt.find(Qt=>Qt===dt):dt===tt._f.ref)return;Cc(r,Ke,{_f:{...tt._f,...Bt?{refs:[...kt.filter(Fje),dt,...Array.isArray(La(a,Ke))?[{}]:[]],ref:{type:dt.type,name:Ke}}:{ref:dt}}}),A(Ke,!1,void 0,dt)}else tt=La(r,Ke,{}),tt._f&&(tt._f.mount=!1),(t.shouldUnregister||rt.shouldUnregister)&&!(omt(o.array,Ke)&&l.action)&&o.unMount.add(Ke)}}},Fe=()=>t.shouldFocusError&&az(r,pe,o.mount),qe=Ke=>{G0(Ke)&&(p.state.next({disabled:Ke}),az(r,(rt,tt)=>{const at=La(r,tt);at&&(rt.disabled=at._f.disabled||Ke,Array.isArray(at._f.refs)&&at._f.refs.forEach(Ge=>{Ge.disabled=at._f.disabled||Ke}))},0,!1))},ve=(Ke,rt)=>async tt=>{let at;tt&&(tt.preventDefault&&tt.preventDefault(),tt.persist&&tt.persist());let Ge=Em(i);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:dt,values:Bt}=await L();n.errors=dt,Ge=Em(Bt)}else await F(r);if(o.disabled.size)for(const dt of o.disabled)Zh(Ge,dt);if(Zh(n.errors,"root"),Mg(n.errors)){p.state.next({errors:{}});try{await Ke(Ge,tt)}catch(dt){at=dt}}else rt&&await rt({...n.errors},tt),Fe(),setTimeout(Fe);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Mg(n.errors)&&!at,submitCount:n.submitCount+1,errors:n.errors}),at)throw at},Je=(Ke,rt={})=>{La(r,Ke)&&(Th(rt.defaultValue)?ne(Ke,Em(La(a,Ke))):(ne(Ke,rt.defaultValue),Cc(a,Ke,Em(rt.defaultValue))),rt.keepTouched||Zh(n.touchedFields,Ke),rt.keepDirty||(Zh(n.dirtyFields,Ke),n.isDirty=rt.defaultValue?V(Ke,Em(La(a,Ke))):V()),rt.keepError||(Zh(n.errors,Ke),u.isValid&&b()),p.state.next({...n}))},we=(Ke,rt={})=>{const tt=Ke?Em(Ke):a,at=Em(tt),Ge=Mg(Ke),dt=Ge?a:at;if(rt.keepDefaultValues||(a=tt),!rt.keepValues){if(rt.keepDirtyValues){const Bt=new Set([...o.mount,...Object.keys(hF(a,i))]);for(const kt of Array.from(Bt))La(n.dirtyFields,kt)?Cc(dt,kt,La(i,kt)):ne(kt,La(dt,kt))}else{if(c6e&&Th(Ke))for(const Bt of o.mount){const kt=La(r,Bt);if(kt&&kt._f){const Qt=Array.isArray(kt._f.refs)?kt._f.refs[0]:kt._f.ref;if(Mfe(Qt)){const ns=Qt.closest("form");if(ns){ns.reset();break}}}}if(rt.keepFieldsRef)for(const Bt of o.mount)ne(Bt,La(dt,Bt));else r={}}i=t.shouldUnregister?rt.keepDefaultValues?Em(a):{}:Em(dt),p.array.next({values:{...dt}}),p.state.next({values:{...dt}})}o={mount:rt.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!u.isValid||!!rt.keepIsValid||!!rt.keepDirtyValues,l.watch=!!t.shouldUnregister,p.state.next({submitCount:rt.keepSubmitCount?n.submitCount:0,isDirty:Ge?!1:rt.keepDirty?n.isDirty:!!(rt.keepDefaultValues&&!P2(Ke,a)),isSubmitted:rt.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:Ge?{}:rt.keepDirtyValues?rt.keepDefaultValues&&i?hF(a,i):n.dirtyFields:rt.keepDefaultValues&&Ke?hF(a,Ke):rt.keepDirty?n.dirtyFields:{},touchedFields:rt.keepTouched?n.touchedFields:{},errors:rt.keepErrors?n.errors:{},isSubmitSuccessful:rt.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},it=(Ke,rt)=>we(ab(Ke)?Ke(i):Ke,rt),Ne=(Ke,rt={})=>{const tt=La(r,Ke),at=tt&&tt._f;if(at){const Ge=at.refs?at.refs[0]:at.ref;Ge.focus&&(Ge.focus(),rt.shouldSelect&&ab(Ge.select)&&Ge.select())}},He=Ke=>{n={...n,...Ke}},Ye={control:{register:Ie,unregister:Ee,getFieldState:ie,handleSubmit:ve,setError:_e,_subscribe:Te,_runSchema:L,_focusError:Fe,_getWatch:W,_getDirty:V,_setValid:b,_setFieldArray:j,_setDisabledField:De,_setErrors:S,_getFieldArray:K,_reset:we,_resetDefaultValues:()=>ab(t.defaultValues)&&t.defaultValues().then(Ke=>{it(Ke,t.resetOptions),p.state.next({isLoading:!1})}),_removeUnmounted:z,_disableForm:qe,_subjects:p,_proxyFormState:u,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(Ke){l=Ke},get _defaultValues(){return a},get _names(){return o},set _names(Ke){o=Ke},get _formState(){return n},get _options(){return t},set _options(Ke){t={...t,...Ke}}},subscribe:Ce,trigger:ce,register:Ie,handleSubmit:ve,watch:Me,setValue:ne,getValues:de,reset:it,resetField:Je,clearErrors:ye,unregister:Ee,setError:_e,setFocus:Ne,getFieldState:ie};return{...Ye,formControl:Ye}}function zye(s={}){const t=Nt.useRef(void 0),n=Nt.useRef(void 0),[r,a]=Nt.useState({isDirty:!1,isValidating:!1,isLoading:ab(s.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:s.errors||{},disabled:s.disabled||!1,isReady:!1,defaultValues:ab(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:r},s.defaultValues&&!ab(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=ets(s);t.current={...o,formState:r}}const i=t.current.control;return i._options=s,m6e(()=>{const l=i._subscribe({formState:i._proxyFormState,callback:()=>a({...i._formState}),reRenderRoot:!0});return a(o=>({...o,isReady:!0})),i._formState.isReady=!0,l},[i]),Nt.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),Nt.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),Nt.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),Nt.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),Nt.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),Nt.useEffect(()=>{s.values&&!P2(s.values,n.current)?(i._reset(s.values,{keepFieldsRef:!0,...i._options.resetOptions}),n.current=s.values,a(l=>({...l}))):i._resetDefaultValues()},[i,s.values]),Nt.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=lmt(r,i),t.current}const LUe=(s,t,n)=>{if(s&&"reportValidity"in s){const r=La(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},gmt=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?LUe(r.ref,n,s):r.refs&&r.refs.forEach(a=>LUe(a,n,s))}},tts=(s,t)=>{t.shouldUseNativeValidation&&gmt(s,t);const n={};for(const r in s){const a=La(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(sts(t.names||Object.keys(s),r)){const l=Object.assign({},La(n,r));Cc(l,"root",i),Cc(n,r,l)}else Cc(n,r,i)}return n},sts=(s,t)=>s.some(n=>n.startsWith(t+"."));var nts=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]=dmt(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},Bye=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&&gmt({},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:tts(nts(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};const $ye=Oes,ymt=N.createContext({}),Cu=({...s})=>e.jsx(ymt.Provider,{value:{name:s.name},children:e.jsx($es,{...s})}),Uye=()=>{const s=N.useContext(ymt),t=N.useContext(vmt),{getFieldState:n,formState:r}=Fye(),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}},vmt=N.createContext({}),iu=N.forwardRef(({className:s,...t},n)=>{const r=N.useId();return e.jsx(vmt.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Et("space-y-2",s),...t})})});iu.displayName="FormItem";const ou=N.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=Uye();return e.jsx(se,{ref:n,className:Et(r&&"text-destructive",s),htmlFor:a,...t})});ou.displayName="FormLabel";const lu=N.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=Uye();return e.jsx(uAe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});lu.displayName="FormControl";const Gme=N.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=Uye();return e.jsx("p",{ref:n,id:r,className:Et("text-sm text-muted-foreground",s),...t})});Gme.displayName="FormDescription";const Zx=N.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=Uye(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:r,id:i,className:Et("text-sm font-medium text-destructive",s),...n,children:l}):null});Zx.displayName="FormMessage";const rts=Zw({category:wMe(["general","technology","crm","marketing"]),subject:go().min(5,"Subject must be at least 5 characters").max(200),description:go().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),ats={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function vCe({trigger:s}){const[t,n]=N.useState(!1),[r,a]=N.useState(!1),{user:i}=gs(),l=zye({resolver:Bye(rts),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){ae.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await q.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await q.functions.invoke("support-ticket-notify",{body:{category:ats[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(bs,{open:t,onOpenChange:n,children:[e.jsx(Di,{asChild:!0,children:s||e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(f9,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(vs,{className:"sm:max-w-[500px]",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Need Help?"}),e.jsx(Qn,{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(Pr,{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($ye,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(Cu,{control:l.control,name:"category",render:({field:c})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Category"}),e.jsxs(us,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(lu,{children:e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select a category"})})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"general",children:"General Support"}),e.jsx(Ze,{value:"technology",children:"Technology Support"}),e.jsx(Ze,{value:"crm",children:"CRM Support"}),e.jsx(Ze,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(Zx,{})]})}),e.jsx(Cu,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Subject"}),e.jsx(lu,{children:e.jsx(ge,{placeholder:"Brief description of your issue",...c})}),e.jsx(Zx,{})]})}),e.jsx(Cu,{control:l.control,name:"description",render:({field:c})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Description"}),e.jsx(lu,{children:e.jsx(Ts,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(Zx,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:r,children:r?"Submitting...":"Submit Ticket"})]})]})})]})]})}const its=()=>{const{user:s}=gs(),t=In(),[n,r]=N.useState([]),[a,i]=N.useState(0),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null);N.useEffect(()=>{u.current=c},[c]),N.useEffect(()=>{if(!s)return;const b=`notification_last_read_${s.id}`,v=localStorage.getItem(b);v&&!u.current&&(u.current=v,d(v));const j=`nb_cache_${s.id}`,_=60*1e3,S=async()=>{try{const M=sessionStorage.getItem(j);if(M){const F=JSON.parse(M);if(F.ts&&Date.now()-F.ts<_&&Array.isArray(F.data)){A(F.data);return}}}catch{}const{data:D,error:L}=await q.from("push_notifications").select("*").order("created_at",{ascending:!1}).limit(20);!L&&D&&(sessionStorage.setItem(j,JSON.stringify({ts:Date.now(),data:D})),A(D))},A=D=>{r(D);const L=u.current?new Date(u.current):null,M=D.filter(F=>L?new Date(F.created_at)>L:!0);i(M.length)};S();const T=q.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},D=>{const L=D.new;r(F=>{const z=[L,...F].slice(0,20);try{sessionStorage.setItem(j,JSON.stringify({ts:Date.now(),data:z}))}catch{}return z});const M=u.current?new Date(u.current):null;(!M||new Date(L.created_at)>M)&&i(F=>F+1),Notification.permission==="granted"&&new Notification(L.title,{body:L.body,icon:"/favicon.ico"})}).subscribe();return()=>{q.removeChannel(T)}},[s]);const h=b=>{const v=b.toLowerCase();return v.includes("community")||v.includes("post")?Ci:v.includes("academy")||v.includes("video")?vr:v.includes("template")?xl:v.includes("event")?yr:v.includes("newsletter")?iy:v.includes("brokerage")?Vm:v.includes("swag")||v.includes("social")?Bi:v.includes("toolbox")||v.includes("tool")?wb:v.includes("brief")?un:Ci},p=b=>{o(!1),b.url&&b.url!=="/"&&t(b.url)},f=()=>{if(!s)return;const b=new Date().toISOString(),v=`notification_last_read_${s.id}`;localStorage.setItem(v,b),d(b),i(0)},g=b=>{o(b),b&&a>0&&f()};return e.jsxs(jc,{open:l,onOpenChange:g,children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(lm,{className:"h-5 w-5"}),a>0&&e.jsx(ze,{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(cc,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),n.length>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:f,children:"Mark all read"})]}),e.jsx(mi,{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(b=>{const v=h(b.title);return e.jsxs(Xr,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>p(b),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(v,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[e.jsx("span",{className:"font-medium text-sm",children:b.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:b.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:Go(new Date(b.created_at),{addSuffix:!0})})]})]},b.id)})})]})]})};var DUe=1,ots=.9,lts=.8,cts=.17,zje=.1,Bje=.999,dts=.9999,uts=.99,hts=/[\\\/_+.#"@\[\(\{&]/,mts=/[\\\/_+.#"@\[\(\{&]/g,pts=/[\s-]/,bmt=/[\s-]/g;function bCe(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?DUe:uts;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=n.indexOf(c,a),u=0,h,p,f,g;d>=0;)h=bCe(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=DUe:hts.test(s.charAt(d-1))?(h*=lts,f=s.slice(a,d-1).match(mts),f&&a>0&&(h*=Math.pow(Bje,f.length))):pts.test(s.charAt(d-1))?(h*=ots,g=s.slice(a,d-1).match(bmt),g&&a>0&&(h*=Math.pow(Bje,g.length))):(h*=cts,a>0&&(h*=Math.pow(Bje,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=dts)),(hh&&(h=p*zje)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function RUe(s){return s.toLowerCase().replace(bmt," ")}function fts(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,bCe(s,t,RUe(s),RUe(t),0,0,{})}var pF='[cmdk-group=""]',$je='[cmdk-group-items=""]',xts='[cmdk-group-heading=""]',_mt='[cmdk-item=""]',OUe=`${_mt}:not([aria-disabled="true"])`,_Ce="cmdk-item-select",oP="data-value",gts=(s,t,n)=>fts(s,t,n),wmt=N.createContext(void 0),fU=()=>N.useContext(wmt),jmt=N.createContext(void 0),x6e=()=>N.useContext(jmt),Nmt=N.createContext(void 0),kmt=N.forwardRef((s,t)=>{let n=lP(()=>{var ye,_e;return{search:"",value:(_e=(ye=s.value)!=null?ye:s.defaultValue)!=null?_e:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=lP(()=>new Set),a=lP(()=>new Map),i=lP(()=>new Map),l=lP(()=>new Set),o=Smt(s),{label:c,children:d,value:u,onValueChange:h,filter:p,shouldFilter:f,loop:g,disablePointerSelection:b=!1,vimBindings:v=!0,...j}=s,_=um(),S=um(),A=um(),T=N.useRef(null),D=Tts();_M(()=>{if(u!==void 0){let ye=u.trim();n.current.value=ye,L.emit()}},[u]),_M(()=>{D(6,K)},[]);let L=N.useMemo(()=>({subscribe:ye=>(l.current.add(ye),()=>l.current.delete(ye)),snapshot:()=>n.current,setState:(ye,_e,Me)=>{var Te,Ce,Ee,De;if(!Object.is(n.current[ye],_e)){if(n.current[ye]=_e,ye==="search")W(),z(),D(1,V);else if(ye==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Ie=document.getElementById(A);Ie?Ie.focus():(Te=document.getElementById(_))==null||Te.focus()}if(D(7,()=>{var Ie;n.current.selectedItemId=(Ie=Y())==null?void 0:Ie.id,L.emit()}),Me||D(5,K),((Ce=o.current)==null?void 0:Ce.value)!==void 0){let Ie=_e??"";(De=(Ee=o.current).onValueChange)==null||De.call(Ee,Ie);return}}L.emit()}},emit:()=>{l.current.forEach(ye=>ye())}}),[]),M=N.useMemo(()=>({value:(ye,_e,Me)=>{var Te;_e!==((Te=i.current.get(ye))==null?void 0:Te.value)&&(i.current.set(ye,{value:_e,keywords:Me}),n.current.filtered.items.set(ye,F(_e,Me)),D(2,()=>{z(),L.emit()}))},item:(ye,_e)=>(r.current.add(ye),_e&&(a.current.has(_e)?a.current.get(_e).add(ye):a.current.set(_e,new Set([ye]))),D(3,()=>{W(),z(),n.current.value||V(),L.emit()}),()=>{i.current.delete(ye),r.current.delete(ye),n.current.filtered.items.delete(ye);let Me=Y();D(4,()=>{W(),(Me==null?void 0:Me.getAttribute("id"))===ye&&V(),L.emit()})}),group:ye=>(a.current.has(ye)||a.current.set(ye,new Set),()=>{i.current.delete(ye),a.current.delete(ye)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:_,inputId:A,labelId:S,listInnerRef:T}),[]);function F(ye,_e){var Me,Te;let Ce=(Te=(Me=o.current)==null?void 0:Me.filter)!=null?Te:gts;return ye?Ce(ye,n.current.search,_e):0}function z(){if(!n.current.search||o.current.shouldFilter===!1)return;let ye=n.current.filtered.items,_e=[];n.current.filtered.groups.forEach(Te=>{let Ce=a.current.get(Te),Ee=0;Ce.forEach(De=>{let Ie=ye.get(De);Ee=Math.max(Ie,Ee)}),_e.push([Te,Ee])});let Me=T.current;ee().sort((Te,Ce)=>{var Ee,De;let Ie=Te.getAttribute("id"),Fe=Ce.getAttribute("id");return((Ee=ye.get(Fe))!=null?Ee:0)-((De=ye.get(Ie))!=null?De:0)}).forEach(Te=>{let Ce=Te.closest($je);Ce?Ce.appendChild(Te.parentElement===Ce?Te:Te.closest(`${$je} > *`)):Me.appendChild(Te.parentElement===Me?Te:Te.closest(`${$je} > *`))}),_e.sort((Te,Ce)=>Ce[1]-Te[1]).forEach(Te=>{var Ce;let Ee=(Ce=T.current)==null?void 0:Ce.querySelector(`${pF}[${oP}="${encodeURIComponent(Te[0])}"]`);Ee==null||Ee.parentElement.appendChild(Ee)})}function V(){let ye=ee().find(Me=>Me.getAttribute("aria-disabled")!=="true"),_e=ye==null?void 0:ye.getAttribute(oP);L.setState("value",_e||void 0)}function W(){var ye,_e,Me,Te;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let Ce=0;for(let Ee of r.current){let De=(_e=(ye=i.current.get(Ee))==null?void 0:ye.value)!=null?_e:"",Ie=(Te=(Me=i.current.get(Ee))==null?void 0:Me.keywords)!=null?Te:[],Fe=F(De,Ie);n.current.filtered.items.set(Ee,Fe),Fe>0&&Ce++}for(let[Ee,De]of a.current)for(let Ie of De)if(n.current.filtered.items.get(Ie)>0){n.current.filtered.groups.add(Ee);break}n.current.filtered.count=Ce}function K(){var ye,_e,Me;let Te=Y();Te&&(((ye=Te.parentElement)==null?void 0:ye.firstChild)===Te&&((Me=(_e=Te.closest(pF))==null?void 0:_e.querySelector(xts))==null||Me.scrollIntoView({block:"nearest"})),Te.scrollIntoView({block:"nearest"}))}function Y(){var ye;return(ye=T.current)==null?void 0:ye.querySelector(`${_mt}[aria-selected="true"]`)}function ee(){var ye;return Array.from(((ye=T.current)==null?void 0:ye.querySelectorAll(OUe))||[])}function ne(ye){let _e=ee()[ye];_e&&L.setState("value",_e.getAttribute(oP))}function oe(ye){var _e;let Me=Y(),Te=ee(),Ce=Te.findIndex(De=>De===Me),Ee=Te[Ce+ye];(_e=o.current)!=null&&_e.loop&&(Ee=Ce+ye<0?Te[Te.length-1]:Ce+ye===Te.length?Te[0]:Te[Ce+ye]),Ee&&L.setState("value",Ee.getAttribute(oP))}function pe(ye){let _e=Y(),Me=_e==null?void 0:_e.closest(pF),Te;for(;Me&&!Te;)Me=ye>0?Sts(Me,pF):Cts(Me,pF),Te=Me==null?void 0:Me.querySelector(OUe);Te?L.setState("value",Te.getAttribute(oP)):oe(ye)}let ce=()=>ne(ee().length-1),de=ye=>{ye.preventDefault(),ye.metaKey?ce():ye.altKey?pe(1):oe(1)},ie=ye=>{ye.preventDefault(),ye.metaKey?ne(0):ye.altKey?pe(-1):oe(-1)};return N.createElement(sa.div,{ref:t,tabIndex:-1,...j,"cmdk-root":"",onKeyDown:ye=>{var _e;(_e=j.onKeyDown)==null||_e.call(j,ye);let Me=ye.nativeEvent.isComposing||ye.keyCode===229;if(!(ye.defaultPrevented||Me))switch(ye.key){case"n":case"j":{v&&ye.ctrlKey&&de(ye);break}case"ArrowDown":{de(ye);break}case"p":case"k":{v&&ye.ctrlKey&&ie(ye);break}case"ArrowUp":{ie(ye);break}case"Home":{ye.preventDefault(),ne(0);break}case"End":{ye.preventDefault(),ce();break}case"Enter":{ye.preventDefault();let Te=Y();if(Te){let Ce=new Event(_Ce);Te.dispatchEvent(Ce)}}}}},N.createElement("label",{"cmdk-label":"",htmlFor:M.inputId,id:M.labelId,style:Ats},c),qye(s,ye=>N.createElement(jmt.Provider,{value:L},N.createElement(wmt.Provider,{value:M},ye))))}),yts=N.forwardRef((s,t)=>{var n,r;let a=um(),i=N.useRef(null),l=N.useContext(Nmt),o=fU(),c=Smt(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;_M(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=Cmt(a,i,[s.value,s.children,i],s.keywords),h=x6e(),p=R4(D=>D.value&&D.value===u.current),f=R4(D=>d||o.filter()===!1?!0:D.search?D.filtered.items.get(a)>0:!0);N.useEffect(()=>{let D=i.current;if(!(!D||s.disabled))return D.addEventListener(_Ce,g),()=>D.removeEventListener(_Ce,g)},[f,s.onSelect,s.disabled]);function g(){var D,L;b(),(L=(D=c.current).onSelect)==null||L.call(D,u.current)}function b(){h.setState("value",u.current,!0)}if(!f)return null;let{disabled:v,value:j,onSelect:_,forceMount:S,keywords:A,...T}=s;return N.createElement(sa.div,{ref:hN(i,t),...T,id:a,"cmdk-item":"",role:"option","aria-disabled":!!v,"aria-selected":!!p,"data-disabled":!!v,"data-selected":!!p,onPointerMove:v||o.getDisablePointerSelection()?void 0:b,onClick:v?void 0:g},s.children)}),vts=N.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=um(),o=N.useRef(null),c=N.useRef(null),d=um(),u=fU(),h=R4(f=>a||u.filter()===!1?!0:f.search?f.filtered.groups.has(l):!0);_M(()=>u.group(l),[]),Cmt(l,o,[s.value,s.heading,c]);let p=N.useMemo(()=>({id:l,forceMount:a}),[a]);return N.createElement(sa.div,{ref:hN(o,t),...i,"cmdk-group":"",role:"presentation",hidden:h?void 0:!0},n&&N.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),qye(s,f=>N.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},N.createElement(Nmt.Provider,{value:p},f))))}),bts=N.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=N.useRef(null),i=R4(l=>!l.search);return!n&&!i?null:N.createElement(sa.div,{ref:hN(a,t),...r,"cmdk-separator":"",role:"separator"})}),_ts=N.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=x6e(),l=R4(d=>d.search),o=R4(d=>d.selectedItemId),c=fU();return N.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),N.createElement(sa.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)}})}),wts=N.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=N.useRef(null),l=N.useRef(null),o=R4(d=>d.selectedItemId),c=fU();return N.useEffect(()=>{if(l.current&&i.current){let d=l.current,u=i.current,h,p=new ResizeObserver(()=>{h=requestAnimationFrame(()=>{let f=d.offsetHeight;u.style.setProperty("--cmdk-list-height",f.toFixed(1)+"px")})});return p.observe(d),()=>{cancelAnimationFrame(h),p.unobserve(d)}}},[]),N.createElement(sa.div,{ref:hN(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},qye(s,d=>N.createElement("div",{ref:hN(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),jts=N.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return N.createElement(aye,{open:n,onOpenChange:r},N.createElement(iye,{container:l},N.createElement(UD,{"cmdk-overlay":"",className:a}),N.createElement(qD,{"aria-label":s.label,"cmdk-dialog":"",className:i},N.createElement(kmt,{ref:t,...o}))))}),Nts=N.forwardRef((s,t)=>R4(n=>n.filtered.count===0)?N.createElement(sa.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),kts=N.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return N.createElement(sa.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},qye(s,l=>N.createElement("div",{"aria-hidden":!0},l)))}),i0=Object.assign(kmt,{List:wts,Item:yts,Input:_ts,Group:vts,Separator:bts,Dialog:jts,Empty:Nts,Loading:kts});function Sts(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function Cts(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function Smt(s){let t=N.useRef(s);return _M(()=>{t.current=s}),t}var _M=typeof window>"u"?N.useEffect:N.useLayoutEffect;function lP(s){let t=N.useRef();return t.current===void 0&&(t.current=s()),t}function R4(s){let t=x6e(),n=()=>s(t.snapshot());return N.useSyncExternalStore(t.subscribe,n,n)}function Cmt(s,t,n,r=[]){let a=N.useRef(),i=fU();return _M(()=>{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(oP,o),a.current=o}),a}var Tts=()=>{let[s,t]=N.useState(),n=lP(()=>new Map);return _M(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function Ets(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function qye({asChild:s,children:t},n){return s&&N.isValidElement(t)?N.cloneElement(Ets(t),{ref:t.ref},n(t.props.children)):n(t)}var Ats={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Xg=N.forwardRef(({className:s,...t},n)=>e.jsx(i0,{ref:n,className:Et("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));Xg.displayName=i0.displayName;const Mts=({children:s,...t})=>e.jsx(bs,{...t,children:e.jsx(vs,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(Xg,{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})})}),Jg=N.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(_r,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(i0.Input,{ref:n,className:Et("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})]}));Jg.displayName=i0.Input.displayName;const e0=N.forwardRef(({className:s,...t},n)=>e.jsx(i0.List,{ref:n,className:Et("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));e0.displayName=i0.List.displayName;const t0=N.forwardRef((s,t)=>e.jsx(i0.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));t0.displayName=i0.Empty.displayName;const s0=N.forwardRef(({className:s,...t},n)=>e.jsx(i0.Group,{ref:n,className:Et("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}));s0.displayName=i0.Group.displayName;const Its=N.forwardRef(({className:s,...t},n)=>e.jsx(i0.Separator,{ref:n,className:Et("-mx-1 h-px bg-border",s),...t}));Its.displayName=i0.Separator.displayName;const ex=N.forwardRef(({className:s,...t},n)=>e.jsx(i0.Item,{ref:n,className:Et("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}));ex.displayName=i0.Item.displayName;const Pts={event:{label:"Events",icon:Tl,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:xl,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:_d,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:wb,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:un,color:"bg-fuchsia-500/10 text-fuchsia-600"}},FUe=()=>{const[s,t]=N.useState(!1),[n,r]=N.useState(""),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=In();N.useEffect(()=>{const p=f=>{f.key==="k"&&(f.metaKey||f.ctrlKey)&&(f.preventDefault(),t(g=>!g))};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[]);const d=N.useCallback(async p=>{if(!p.trim()){i([]);return}o(!0);const f=`%${p}%`;try{const[g,b,v,j,_]=await Promise.all([q.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5),q.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${f},description.ilike.${f}`).limit(5),q.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5),q.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${f},description.ilike.${f}`).limit(5),q.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5)]),S=[];g.data&&g.data.forEach(A=>{S.push({id:A.id,title:A.title,description:A.description,type:"event",date:A.event_date,path:`/event/${A.id}`})}),b.data&&b.data.forEach(A=>{S.push({id:A.id,title:A.name,description:A.description,type:"template",date:A.publish_date,path:`/templates/${A.id}`})}),v.data&&v.data.forEach(A=>{S.push({id:A.id,title:A.title,description:A.description,type:"academy",date:A.publish_date,path:`/academy/${A.id}`})}),j.data&&j.data.forEach(A=>{S.push({id:A.id,title:A.name,description:A.description,type:"toolbox",date:A.publish_date,path:`/toolbox/${A.id}`})}),_.data&&_.data.forEach(A=>{S.push({id:A.id,title:A.title,description:A.description,type:"social-swag",date:A.publish_date,path:`/social-swag/${A.id}`})}),i(S)}catch(g){console.error("Search error:",g)}finally{o(!1)}},[]);N.useEffect(()=>{const p=setTimeout(()=>{d(n)},300);return()=>clearTimeout(p)},[n,d]);const u=p=>{t(!1),r(""),c(p)},h=a.reduce((p,f)=>(p[f.type]||(p[f.type]=[]),p[f.type].push(f),p),{});return e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"relative h-9 w-9 p-0 xl:h-9 xl:w-60 xl:justify-start xl:px-3 xl:py-2",onClick:()=>t(!0),children:[e.jsx(_r,{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(Mts,{open:s,onOpenChange:t,children:[e.jsx(Jg,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(e0,{children:[l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&e.jsxs(t0,{children:['No results found for "',n,'"']}),!l&&!n&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search across all content..."}),Object.entries(h).map(([p,f])=>{const g=Pts[p],b=g.icon;return e.jsx(s0,{heading:g.label,children:f.map(v=>e.jsxs(ex,{value:`${v.type}-${v.id}-${v.title}`,onSelect:()=>u(v.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${g.color}`,children:e.jsx(b,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:v.title}),v.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:v.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(ze,{variant:"secondary",className:"text-xs",children:g.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Go(new Date(v.date),{addSuffix:!0})})]})]},`${v.type}-${v.id}`))},p)})]})]})]})},Lts=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=N.useState(null),i=In();if(N.useEffect(()=>{const d=()=>{const h=new Date().getTime(),f=new Date(s).getTime()-h;if(f<=0){a({days:0,hours:0,minutes:0});return}const g=Math.floor(f/(1e3*60*60*24)),b=Math.floor(f%(1e3*60*60*24)/(1e3*60*60)),v=Math.floor(f%(1e3*60*60)/(1e3*60));a({days:g,hours:b,minutes:v})};d();const u=setInterval(d,6e4);return()=>clearInterval(u)},[s]),!r)return null;const l=r.days===0&&r.hours===0&&r.minutes===0,o=r.days<=1,c=r.days<=3&&!o;return l?e.jsxs("div",{className:Et("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(Dl,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),n&&e.jsxs(B,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Et("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(gr,{className:Et("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:Et("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:Et("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:Et("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:Et("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:Et("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),n&&e.jsxs(B,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:Et("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},Dts=()=>{const s=In();return e.jsx("div",{className:"fixed inset-0 bg-background/95 backdrop-blur-sm z-50 flex items-center justify-center p-4 overflow-y-auto",children:e.jsxs(fe,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(Mt,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-4 h-16 w-16 rounded-full bg-destructive/10 flex items-center justify-center",children:e.jsx(Dl,{className:"h-8 w-8 text-destructive"})}),e.jsx(Pt,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(Hn,{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(Ae,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(fe,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Ae,{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(_n,{className:"h-6 w-6 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),e.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),e.jsxs(B,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(fe,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Ae,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Ga,{className:"h-6 w-6 text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Brokerage"}),e.jsxs("p",{className:"text-2xl font-bold text-amber-600 mb-2",children:["$299",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"For teams and brokerages"}),e.jsxs(B,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Choose Brokerage"]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"With a full membership, you'll get:"}),e.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground grid sm:grid-cols-2 gap-x-4",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Unlimited access to all marketing templates"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Complete Academy training library"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," AI-powered tools and resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Community forums and support"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Exclusive member events and workshops"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Deal pipeline & scorecard tracking"]})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-center",children:"Questions? Contact us:"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(Pr,{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(Hs,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},Rts=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",onClick:t,className:Et("relative transition-colors",s&&"text-primary hover:text-primary",n),children:[e.jsx(qd,{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(yc,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var g6e="Radio",[Ots,Tmt]=gu(g6e),[Fts,zts]=Ots(g6e),Emt=N.forwardRef((s,t)=>{const{__scopeRadio:n,name:r,checked:a=!1,required:i,disabled:l,value:o="on",onCheck:c,form:d,...u}=s,[h,p]=N.useState(null),f=Ti(t,v=>p(v)),g=N.useRef(!1),b=h?d||!!h.closest("form"):!0;return e.jsxs(Fts,{scope:n,checked:a,disabled:l,children:[e.jsx(sa.button,{type:"button",role:"radio","aria-checked":a,"data-state":Pmt(a),"data-disabled":l?"":void 0,disabled:l,value:o,...u,ref:f,onClick:wr(s.onClick,v=>{a||c==null||c(),b&&(g.current=v.isPropagationStopped(),g.current||v.stopPropagation())})}),b&&e.jsx(Imt,{control:h,bubbles:!g.current,name:r,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});Emt.displayName=g6e;var Amt="RadioIndicator",Mmt=N.forwardRef((s,t)=>{const{__scopeRadio:n,forceMount:r,...a}=s,i=zts(Amt,n);return e.jsx(Bh,{present:r||i.checked,children:e.jsx(sa.span,{"data-state":Pmt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});Mmt.displayName=Amt;var Bts="RadioBubbleInput",Imt=N.forwardRef(({__scopeRadio:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=N.useRef(null),o=Ti(l,i),c=rU(n),d=q$(t);return N.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&f){const g=new Event("click",{bubbles:r});f.call(u,n),u.dispatchEvent(g)}},[c,n,r]),e.jsx(sa.input,{type:"radio","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Imt.displayName=Bts;function Pmt(s){return s?"checked":"unchecked"}var $ts=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Vye="RadioGroup",[Uts,Jxn]=gu(Vye,[K4,Tmt]),Lmt=K4(),Dmt=Tmt(),[qts,Vts]=Uts(Vye),Rmt=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:a,value:i,required:l=!1,disabled:o=!1,orientation:c,dir:d,loop:u=!0,onValueChange:h,...p}=s,f=Lmt(n),g=kN(d),[b,v]=mm({prop:i,defaultProp:a??null,onChange:h,caller:Vye});return e.jsx(qts,{scope:n,name:r,required:l,disabled:o,value:b,onValueChange:v,children:e.jsx(Q0e,{asChild:!0,...f,orientation:c,dir:g,loop:u,children:e.jsx(sa.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:g,...p,ref:t})})})});Rmt.displayName=Vye;var Omt="RadioGroupItem",Fmt=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,disabled:r,...a}=s,i=Vts(Omt,n),l=i.disabled||r,o=Lmt(n),c=Dmt(n),d=N.useRef(null),u=Ti(t,d),h=i.value===a.value,p=N.useRef(!1);return N.useEffect(()=>{const f=b=>{$ts.includes(b.key)&&(p.current=!0)},g=()=>p.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",g),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",g)}},[]),e.jsx(X0e,{asChild:!0,...o,focusable:!l,active:h,children:e.jsx(Emt,{disabled:l,required:i.required,checked:h,...c,...a,name:i.name,ref:u,onCheck:()=>i.onValueChange(a.value),onKeyDown:wr(f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:wr(a.onFocus,()=>{var f;p.current&&((f=d.current)==null||f.click())})})})});Fmt.displayName=Omt;var Hts="RadioGroupIndicator",zmt=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,...r}=s,a=Dmt(n);return e.jsx(Mmt,{...a,...r,ref:t})});zmt.displayName=Hts;var Bmt=Rmt,$mt=Fmt,Gts=zmt;const db=N.forwardRef(({className:s,...t},n)=>e.jsx(Bmt,{className:Et("grid gap-2",s),...t,ref:n}));db.displayName=Bmt.displayName;const Fd=N.forwardRef(({className:s,...t},n)=>e.jsx($mt,{ref:n,className:Et("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(Gts,{className:"flex items-center justify-center",children:e.jsx(dm,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Fd.displayName=$mt.displayName;const Wts=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=gs(),[i,l]=N.useState({}),[o,c]=N.useState({}),[d,u]=N.useState([]);N.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const v=s.polls.map(_=>_.id),{data:j}=await q.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",v);if(j){const _={};j.forEach(S=>{_[S.poll_id]||(_[S.poll_id]=[]),_[S.poll_id].push(S.option_id)}),c(_)}},p=(v,j)=>{l(_=>({..._,[v]:j}))},f=(v,j,_)=>{l(S=>{const A=S[v]||[];return _?{...S,[v]:[...A,j]}:{...S,[v]:A.filter(T=>T!==j)}})},g=async v=>{if(!a)return;const j=i[v];if(!j||Array.isArray(j)&&j.length===0){ae.error("Please select an option");return}u(_=>[..._,v]);try{await q.from("levelup_brief_poll_responses").delete().eq("poll_id",v).eq("user_id",a.id);const _=Array.isArray(j)?j:[j],S=_.map(T=>({poll_id:v,option_id:T,user_id:a.id})),{error:A}=await q.from("levelup_brief_poll_responses").insert(S);if(A)throw A;c(T=>({...T,[v]:_})),ae.success("Response submitted!")}catch(_){console.error("Error submitting poll response:",_),ae.error("Failed to submit response")}finally{u(_=>_.filter(S=>S!==v))}},b=v=>(v.includes("mediadelivery.net")||v.includes("bunny"),v);return e.jsx(bs,{open:t,onOpenChange:v=>!v&&n(),children:e.jsxs(vs,{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(Fn,{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(qd,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(ze,{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(mi,{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:b(s.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),s.brief.graphic_url&&!s.brief.video_url&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:s.brief.graphic_link_url?e.jsx("a",{href:s.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),s.links.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.links.map(v=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(v.url,"_blank"),className:"gap-2",children:[e.jsx(tr,{className:"h-4 w-4"}),v.title]},v.id))})]}),s.polls.map(v=>{var S,A;const j=((S=o[v.id])==null?void 0:S.length)>0,_=d.includes(v.id);return e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:v.question}),j&&e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(xr,{className:"h-3 w-3"}),"Responded"]})]}),v.poll_type==="single"?e.jsx(db,{value:i[v.id]||((A=o[v.id])==null?void 0:A[0])||"",onValueChange:T=>p(v.id,T),className:"space-y-2",children:v.options.map(T=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:T.id,id:T.id}),e.jsx(se,{htmlFor:T.id,className:"cursor-pointer",children:T.option_text})]},T.id))}):e.jsx("div",{className:"space-y-2",children:v.options.map(T=>{const L=(i[v.id]||o[v.id]||[]).includes(T.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(hi,{id:T.id,checked:L,onCheckedChange:M=>f(v.id,T.id,M)}),e.jsx(se,{htmlFor:T.id,className:"cursor-pointer",children:T.option_text})]},T.id)})}),e.jsx(B,{size:"sm",onClick:()=>g(v.id),disabled:_,children:_?"Submitting...":j?"Update Response":"Submit"})]},v.id)})]})}),e.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[e.jsx(B,{onClick:n,className:"w-full max-w-xs",children:"Got it!"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:r,children:"Don't show again"})]})]})})},Kts=()=>{const{user:s}=gs(),[t,n]=N.useState(null),[r,a]=N.useState(!1),[i,l]=N.useState(!0),[o,c]=N.useState(!1),d=N.useCallback(async()=>{if(!s){l(!1);return}try{const{data:g,error:b}=await q.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(b||!g){l(!1);return}const{data:v}=await q.from("levelup_brief_views").select("*").eq("brief_id",g.id).eq("user_id",s.id).maybeSingle(),[j,_]=await Promise.all([q.from("levelup_brief_links").select("*").eq("brief_id",g.id).order("sort_order"),q.from("levelup_brief_polls").select("*").eq("brief_id",g.id).order("sort_order")]),S=[];if(_.data)for(const M of _.data){const{data:F}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",M.id).order("sort_order");S.push({...M,options:F||[]})}const A={brief:g,links:j.data||[],polls:S};n(A);const T=!!v,D=(v==null?void 0:v.dismissed_at)!=null,L=localStorage.getItem(`brief-dismissed-${g.id}`)==="true";if(D||L)c(!1),a(!1);else if(!T)a(!0),c(!0);else if(g.show_frequency==="every_login")a(!0),c(!0);else if(g.show_frequency==="daily"){const M=new Date(v.viewed_at);(new Date().getTime()-M.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(g){console.error("Error fetching brief:",g)}finally{l(!1)}},[s]);N.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:g}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();g?await q.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",g.id):await q.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:b}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(b&&console.error("Error checking existing brief view:",b),g){const{error:v}=await q.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",g.id).eq("user_id",s.id);v&&console.error("Error updating brief dismiss:",v)}else{const{error:v}=await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});v&&console.error("Error inserting brief dismiss:",v)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(g){console.error("Error dismissing brief:",g),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function Yts(){const[s,t]=N.useState(!1),[n,r]=N.useState(!1),[a,i]=N.useState(null);N.useEffect(()=>{if(localStorage.getItem("install-banner-dismissed")||window.matchMedia("(display-mode: standalone)").matches||!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const h=/iPhone|iPad|iPod/i.test(navigator.userAgent);r(h),t(!0);const p=f=>{f.preventDefault(),i(f)};return window.addEventListener("beforeinstallprompt",p),()=>{window.removeEventListener("beforeinstallprompt",p)}},[]);const l=()=>{localStorage.setItem("install-banner-dismissed","true"),t(!1)},o=async()=>{if(a){await a.prompt();const{outcome:c}=await a.userChoice;c==="accepted"&&l(),i(null)}};return s?e.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-50 p-4 bg-primary text-primary-foreground shadow-lg animate-in slide-in-from-bottom duration-300",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:e.jsx(Da,{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(A9,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):e.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!n&&a&&e.jsx(B,{size:"sm",variant:"secondary",onClick:o,className:"text-xs",children:"Install"}),e.jsx("button",{onClick:l,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:e.jsx(Fn,{className:"h-4 w-4"})})]})]})}):null}const Zts=({children:s,onRefresh:t})=>{const[n,r]=N.useState(!1),[a,i]=N.useState(0),[l,o]=N.useState(!1),c=N.useRef(null),d=N.useRef(0),u=Gt(),h=80,p=120,f=N.useCallback(_=>{const S=c.current;S&&S.scrollTop<=0&&(d.current=_.touches[0].clientY,r(!0))},[]),g=N.useCallback(_=>{if(!n||l)return;const S=c.current;if(!S||S.scrollTop>0){r(!1),i(0);return}const T=_.touches[0].clientY-d.current;if(T>0){const L=Math.min(T*.5,p);i(L),L>10&&_.preventDefault()}},[n,l]),b=N.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]),v=Math.min(a/h,1),j=v*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:f,onTouchMove:g,onTouchEnd:b,children:[e.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:a>0?a:0,opacity:v},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${j}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(Ai,{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})]})},Umt=()=>{const{user:s}=gs(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(!0);N.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:f}=await q.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(f){a(!0),n(!1),c(!1);return}const{data:g}=await q.from("profiles").select("login_count").eq("id",s.id).single(),b=(g==null?void 0:g.login_count)||0;l(b);const v=sessionStorage.getItem("review-prompt-dismissed");n(b>=4&&!v)}catch(f){console.error("Error checking review eligibility:",f)}finally{c(!1)}})()},[s]);const d=N.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=N.useCallback(async(p,f)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:g}=await q.from("membership_reviews").insert({user_id:s.id,rating:p,review_text:f});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=N.useCallback(async()=>{if(s)try{await q.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(p){console.error("Error updating Google review status:",p)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:r,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:u,markPostedToGoogle:h}},Qts="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",Xts=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=Umt(),[i,l]=N.useState(!1),[o,c]=N.useState("review"),[d,u]=N.useState(0),[h,p]=N.useState(0),[f,g]=N.useState(""),[b,v]=N.useState(!1),[j,_]=N.useState(!1);if(t||!s&&!j)return null;const S=async()=>{if(d===0){Dr({title:"Please select a rating",variant:"destructive"});return}v(!0);const D=await r(d,f);v(!1),D.success?(_(!0),Dr({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):Dr({title:"Error submitting review",description:D.error,variant:"destructive"})},A=async D=>{D&&(await navigator.clipboard.writeText(f||`${d} star rating for LevelUp!`),Dr({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(Qts,"_blank")),l(!1),n()},T=()=>{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(ua,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(bs,{open:i,onOpenChange:T,children:e.jsx(vs,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Qn,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(D=>e.jsx("button",{type:"button",onClick:()=>u(D),onMouseEnter:()=>p(D),onMouseLeave:()=>p(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(ua,{className:Et("h-8 w-8 transition-colors",(h||d)>=D?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},D))}),e.jsx(Ts,{placeholder:"Tell us about your experience (optional)",value:f,onChange:D=>g(D.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:T,className:"flex-1",children:"Maybe Later"}),e.jsx(B,{onClick:S,disabled:b||d===0,className:"flex-1",children:b?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Qn,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>A(!1),className:"flex-1",children:"No Thanks"}),e.jsx(B,{onClick:()=>A(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function Jts(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 b="vapid_public_key";let v=localStorage.getItem(b);if(!v){const{data:S,error:A}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(A)throw A;if(v=(S==null?void 0:S.vapidPublicKey)??null,!v)throw new Error("Missing VAPID public key");localStorage.setItem(b,v)}u(v);const j=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(j),n(Notification.permission);const _=await j.pushManager.getSubscription();a(!!_)}catch(b){console.error("Error initializing push notifications:",b)}finally{l(!1)}})()},[h]);const p=N.useCallback(async()=>{if(!h||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return ae.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const g=await o.pushManager.getSubscription();if(g){try{await g.unsubscribe()}catch(A){console.warn("Failed to unsubscribe existing push subscription:",A)}const{error:S}=await q.from("push_subscriptions").delete().eq("user_id",s.id);S&&console.warn("Failed to cleanup push_subscriptions rows:",S)}if(Notification.permission!=="granted"){const S=await Notification.requestPermission();if(n(S),S!=="granted")return S==="denied"?ae.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):ae.error("Notification permission was dismissed. Please try again."),!1}const b=Jts(d);let v;try{v=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:b})}catch(S){console.error("PushManager.subscribe() failed:",S);const A=(S==null?void 0:S.message)||String(S);return A.includes("permission")?ae.error("Push permission denied. Check your browser notification settings."):A.includes("key")||A.includes("VAPID")?ae.error("Push configuration error. Please contact support."):A.includes("AbortError")?ae.error("Push subscription was cancelled. Please try again."):ae.error(`Failed to subscribe: ${A}`),!1}const j=v.toJSON(),{error:_}=await q.from("push_subscriptions").upsert({user_id:s.id,endpoint:j.endpoint,p256dh_key:j.keys.p256dh,auth_key:j.keys.auth},{onConflict:"user_id,endpoint"});if(_)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 b=g instanceof Error?g.message:"Unknown error";ae.error("Failed to enable push notifications: "+b)}return!1}finally{l(!1)}},[h,o,s,d]),f=N.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const g=await o.pushManager.getSubscription();return g&&await g.unsubscribe(),await q.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 b=g instanceof Error?g.message:"Unknown error";return ae.error("Failed to disable push notifications: "+b),!1}finally{l(!1)}},[o,s]);return{isSupported:h,permission:t,isSubscribed:r,isLoading:i,vapidPublicKey:d,subscribe:p,unsubscribe:f}}const Uje="push_notification_prompt_dismissed",ess=["/dashboard","/admin"],tss=()=>{const{user:s}=gs(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=qmt(),i=Jl(),[l,o]=N.useState(!1),[c,d]=N.useState(!1),u=ess.some(f=>i.pathname===f||i.pathname.startsWith(`${f}/`));N.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${Uje}_${s.id}`))return;const g=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(g)},[s,t,n,r,u]);const h=async()=>{d(!0);const f=await a();d(!1),f&&(s&&localStorage.setItem(`${Uje}_${s.id}`,"true"),o(!1))},p=()=>{s&&localStorage.setItem(`${Uje}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(bs,{open:l,onOpenChange:f=>!f&&p(),children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{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(lm,{className:"h-6 w-6 text-primary"})}),e.jsx(_s,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Qn,{className:"text-center",children:"Enable push notifications to get alerted when:"})]}),e.jsxs("ul",{className:"my-4 space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New events go live"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Fresh templates are added"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New toolbox resources drop"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Social swag updates"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New newsletters arrive"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Posts in your community groups"]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(B,{onClick:h,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx(B,{variant:"ghost",onClick:p,className:"w-full",children:"Not Now"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"You can always change this in your Profile settings."})]})})},zUe=s=>{let t;const n=new Set,r=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(f=>f(t,p))}},a=()=>t,o={setState:r,getState:a,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=s(r,a,o);return o},sss=s=>s?zUe(s):zUe,nss=s=>s;function rss(s,t=nss){const n=Nt.useSyncExternalStore(s.subscribe,Nt.useCallback(()=>t(s.getState()),[s,t]),Nt.useCallback(()=>t(s.getInitialState()),[s,t]));return Nt.useDebugValue(n),n}const BUe=s=>{const t=sss(s),n=r=>rss(t,r);return Object.assign(n,t),n},ass=s=>s?BUe(s):BUe;function iss(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 wCe=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return wCe(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return wCe(r)(n)}}}},oss=(s,t)=>(n,r,a)=>{let i={storage:iss(()=>window.localStorage),partialize:v=>v,version:0,merge:(v,j)=>({...j,...v}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...v)},r,a);const h=()=>{const v=i.partialize({...r()});return u.setItem(i.name,{state:v,version:i.version})},p=a.setState;a.setState=(v,j)=>(p(v,j),h());const f=s((...v)=>(n(...v),h()),r,a);a.getInitialState=()=>f;let g;const b=()=>{var v,j;if(!u)return;const _=++o;l=!1,c.forEach(A=>{var T;return A((T=r())!=null?T:f)});const S=((j=i.onRehydrateStorage)==null?void 0:j.call(i,(v=r())!=null?v:f))||void 0;return wCe(u.getItem.bind(u))(i.name).then(A=>{if(A)if(typeof A.version=="number"&&A.version!==i.version){if(i.migrate){const T=i.migrate(A.state,A.version);return T instanceof Promise?T.then(D=>[!0,D]):[!0,T]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,A.state];return[!1,void 0]}).then(A=>{var T;if(_!==o)return;const[D,L]=A;if(g=i.merge(L,(T=r())!=null?T:f),n(g,!0),D)return h()}).then(()=>{_===o&&(S==null||S(r(),void 0),g=r(),l=!0,d.forEach(A=>A(g)))}).catch(A=>{_===o&&(S==null||S(void 0,A))})};return a.persist={setOptions:v=>{i={...i,...v},v.storage&&(u=v.storage)},clearStorage:()=>{u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>b(),hasHydrated:()=>l,onHydrate:v=>(c.add(v),()=>{c.delete(v)}),onFinishHydration:v=>(d.add(v),()=>{d.delete(v)})},i.skipHydration||b(),g||f},lss=oss,Hye=ass()(lss((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 css(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function Pp(){const{user:s}=gs(),{data:t,isLoading:n}=lt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:r,error:a}=await q.from("lead_sites").select("id, subdomain_slug, site_title, is_active, mls_provider_id, no_mls_mode, mls_agent_id, mls_agent_key, mls_office_id").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(a)throw a;return css(r)},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isLoading:n,siteUrl:t?`https://${t.subdomain_slug}.thelocalmove.com`:null}}const $Ue="dashboard-sidebar-collapsed",Cs=({children:s,title:t})=>{var it;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=gs(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=Y0e(),{isImpersonating:h}=K0e(),f=(c&&!!d?40:0)+(h?40:0),{avatarUrl:g}=Xht(n==null?void 0:n.id),{isTrial:b,isExpired:v,expiresAt:j}=Nes(n==null?void 0:n.id),{isInnerCircleEnabled:_,isMarketplaceEnabled:S}=emt(),{currentBrief:A,shouldShowPopup:T,hasUnseenBrief:D,openBrief:L,closeBrief:M,dismissBrief:F}=Kts(),{unreadCount:z}=kes(),{openCount:V}=Ses(),{data:W}=Xv(),K=!!W,ee=Hye(Ne=>Ne.cartItems).reduce((Ne,He)=>Ne+He.quantity,0),{leadSite:ne,hasLeadSite:oe,siteUrl:pe}=Pp(),ce=In(),de=Jl(),[ie,ye]=N.useState(null);N.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("name").eq("id",n.id).single().then(({data:Ne})=>{Ne!=null&&Ne.name&&ye(Ne.name)})},[n==null?void 0:n.id]);const _e=ie||((it=n==null?void 0:n.user_metadata)==null?void 0:it.name)||(n==null?void 0:n.email)||"User",[Me,Te]=N.useState(()=>typeof window<"u"?localStorage.getItem($Ue)==="true":!1);N.useEffect(()=>{localStorage.setItem($Ue,String(Me))},[Me]);const[Ce,Ee]=N.useState({agentos:!0,tools:!0,marketing:!0,learning:!0,community:!0,contacts:!0,website:!0,help:!1}),De=Ne=>{Ee(He=>({...He,[Ne]:!He[Ne]}))},Ie=Ne=>Ne.split(" ").map(He=>He[0]).join("").toUpperCase().slice(0,2),Fe=Ne=>de.pathname===Ne,qe=Ne=>Ne.some(He=>de.pathname===He),ve=({path:Ne,icon:He,label:$e,badgeCount:Ye})=>{const Ke=e.jsxs(B,{variant:"ghost",size:"sm",className:Et("text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Fe(Ne)&&"bg-sidebar-accent text-sidebar-accent-foreground",Me?"w-10 h-10 p-0 justify-center":"w-full justify-start gap-2"),onClick:()=>ce(Ne),children:[e.jsxs("div",{className:"relative",children:[e.jsx(He,{className:"h-4 w-4 shrink-0"}),Me&&Ye!=null&&Ye>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]}),!Me&&$e,!Me&&Ye!=null&&Ye>0&&e.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Ye>9?"9+":Ye})]});return Me?e.jsxs(Ac,{delayDuration:0,children:[e.jsx(Mc,{asChild:!0,children:Ke}),e.jsxs(yc,{side:"right",className:"flex items-center gap-2",children:[$e,Ye!=null&&Ye>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Ye>9?"9+":Ye})]})]}):Ke},Je=({id:Ne,label:He,icon:$e,children:Ye,activePaths:Ke,showBetaBadge:rt,defaultPath:tt,badgeCount:at})=>{if(Me){const Ge=tt||Ke[0];return e.jsxs(Ac,{delayDuration:0,children:[e.jsx(Mc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:Et("w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",qe(Ke)&&"text-primary"),onClick:()=>ce(Ge),children:e.jsxs("div",{className:"relative",children:[e.jsx($e,{className:"h-4 w-4"}),at!=null&&at>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]})})}),e.jsxs(yc,{side:"right",className:"flex items-center gap-2",children:[He,rt&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600",children:"Beta"}),at!=null&&at>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:at>9?"9+":at})]})]})}return e.jsxs(uy,{open:Ce[Ne],onOpenChange:()=>De(Ne),children:[e.jsx(hy,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",qe(Ke)&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold text-[15px]",children:[e.jsx($e,{className:"h-4 w-4"}),He,rt&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[at!=null&&at>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:at>9?"9+":at}),e.jsx(io,{className:Et("h-4 w-4 transition-transform duration-200",Ce[Ne]&&"rotate-180")})]})]})}),e.jsx(my,{className:"pl-4 space-y-1 mt-1",children:Ye})]})},we=({isMobile:Ne=!1})=>{const He=Ne?!1:Me;return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:Et("p-3 border-b border-sidebar-border",He?"flex flex-col items-center gap-2":"flex items-center justify-between"),children:[He?e.jsx("img",{src:Pes,alt:"LevelUp",className:"h-8 w-auto"}):e.jsx("img",{src:Ies,alt:"LevelUp",className:"h-8 w-auto"}),!Ne&&e.jsxs(Ac,{delayDuration:0,children:[e.jsx(Mc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>Te(!He),children:e.jsx(fl,{className:Et("h-4 w-4 transition-transform duration-300",He&&"rotate-180")})})}),e.jsx(yc,{side:"right",children:He?"Expand sidebar":"Collapse sidebar"})]})]}),e.jsx(mi,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:e.jsxs("nav",{className:Et("p-3 space-y-1",He&&"flex flex-col items-center"),children:[Ne&&b&&!v&&e.jsx("button",{type:"button",onClick:()=>ce("/subscription"),className:Et("relative w-full overflow-hidden rounded-md p-[1.5px] mb-2","bg-[linear-gradient(120deg,#f59e0b,#ef4444,#a855f7,#f59e0b)] bg-[length:200%_200%]","animate-gradient-x shadow-lg shadow-amber-500/20"),children:e.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[e.jsx(un,{className:"h-4 w-4 text-amber-500 animate-pulse"}),e.jsx("span",{className:"flex-1 text-left bg-[linear-gradient(90deg,#f59e0b,#ef4444,#a855f7)] bg-clip-text text-transparent",children:"Ready to Upgrade?"}),j&&e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-600 dark:text-amber-400 border border-amber-500/30",children:[Math.max(0,Math.ceil((new Date(j).getTime()-Date.now())/864e5)),"d left"]})]})}),e.jsx(ve,{path:"/dashboard",icon:t4,label:"Dashboard"}),e.jsx(ve,{path:"/apps",icon:xv,label:"Apps & Tools"}),Me?e.jsxs(Ac,{delayDuration:0,children:[e.jsx(Mc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:Et("w-10 h-10 p-0 justify-center relative bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30",Fe("/programs")&&"bg-primary/25"),onClick:()=>ce("/programs"),children:e.jsx(nx,{className:"h-4 w-4 shrink-0"})})}),e.jsx(yc,{side:"right",children:"Programs"})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 bg-primary/10 text-primary border border-primary/30 hover:bg-primary/20 hover:text-primary font-semibold",Fe("/programs")&&"bg-primary/25"),onClick:()=>ce("/programs"),children:[e.jsx(nx,{className:"h-4 w-4 shrink-0"}),"Programs"]}),Me?e.jsxs(Ac,{delayDuration:0,children:[e.jsx(Mc,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/levelup-u"),children:[e.jsx(_d,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),e.jsxs(yc,{side:"right",className:"flex items-center gap-2",children:["LevelUp U",e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1 py-0.5",children:"New"})]})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/levelup-u"),children:[e.jsx(_d,{className:"h-4 w-4 shrink-0"}),"LevelUp U",e.jsx("span",{className:"ml-auto text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1.5 py-0.5",children:"New"})]}),e.jsx(ve,{path:"/events",icon:Tl,label:"Events"}),e.jsxs(Je,{id:"agentos",label:"Agent OS",icon:ZS,activePaths:["/mission-control","/mission-control/contacts","/mission-control/plans","/mission-control/popbys","/mission-control/video-library","/mission-control/scorecard","/mission-control/listings","/mission-control/pipeline","/mission-control/tasks","/mission-control/smart-drips","/mission-control/relationship-scorecard","/mission-control/sphere-gaps","/mission-control/signals","/mission-control/connect-page","/mission-control/client-portals","/mission-control/vendors","/mission-control/portal-referrals","/email-campaigns/templates"],showBetaBadge:!0,defaultPath:"/mission-control",children:[u("contacts")&&e.jsx(ve,{path:"/mission-control",icon:yi,label:"Mission Control"}),u("contacts")&&!He&&e.jsxs(uy,{open:Ce.contacts,onOpenChange:()=>De("contacts"),children:[e.jsx(hy,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",qe(["/mission-control/contacts","/mission-control/relationship-scorecard","/mission-control/sphere-gaps","/mission-control/connect-page"])&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-4 w-4"}),"Contacts"]}),e.jsx(io,{className:Et("h-3.5 w-3.5 transition-transform duration-200",Ce.contacts&&"rotate-180")})]})}),e.jsxs(my,{className:"pl-4 pr-1 space-y-0.5 mt-0.5",children:[e.jsx(ve,{path:"/mission-control/contacts",icon:_n,label:"All Contacts"}),e.jsx(ve,{path:"/mission-control/relationship-scorecard",icon:am,label:"Relationship Report"}),e.jsx(ve,{path:"/mission-control/sphere-gaps",icon:T9,label:"Sphere Gaps"}),e.jsx(ve,{path:"/mission-control/sent-emails",icon:cr,label:"Sent Emails"}),e.jsx(ve,{path:"/mission-control/connect-page",icon:El,label:"Connect Page"})]})]}),u("contacts")&&He&&e.jsx(ve,{path:"/mission-control/contacts",icon:_n,label:"Contacts"}),u("contacts")&&e.jsx(ve,{path:"/mission-control/plans",icon:Tl,label:"TouchPlans"}),u("pipeline")&&e.jsx(ve,{path:"/mission-control/pipeline",icon:Q2,label:"Deal Pipeline"}),u("pipeline")&&e.jsx(ve,{path:"/mission-control/transactions",icon:W2,label:"Transactions"}),u("pipeline")&&e.jsx(ve,{path:"/mission-control/tasks",icon:A2,label:"Tasks"}),u("popbys")&&e.jsx(ve,{path:"/mission-control/popbys",icon:Bi,label:"Popbys"}),u("videos")&&e.jsx(ve,{path:"/mission-control/video-library",icon:vr,label:"Video Library"}),u("scorecard")&&e.jsx(ve,{path:"/mission-control/scorecard",icon:yo,label:"Scorecard"}),u("listings")&&e.jsx(ve,{path:"/mission-control/listings",icon:Ga,label:"Listing Exchange"}),e.jsx(ve,{path:"/mission-control/client-portals",icon:un,label:"Client Portals"}),e.jsx(ve,{path:"/mission-control/signals",icon:zA,label:"Signals"}),!He&&e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/mission-control/smart-drips")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/mission-control/smart-drips"),children:[e.jsx(ph,{className:"h-4 w-4"}),"Smart Drips",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),He&&e.jsx(ve,{path:"/mission-control/smart-drips",icon:ph,label:"Smart Drips"}),e.jsx(ve,{path:"/email-campaigns/templates",icon:Hs,label:"Email Templates"})]}),oe&&ne&&e.jsxs(Je,{id:"website",label:"My Website",icon:lc,activePaths:[`/admin/lead-sites/${ne.id}/edit`],defaultPath:`/admin/lead-sites/${ne.id}/edit`,children:[He?e.jsxs(Ac,{delayDuration:0,children:[e.jsx(Mc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open(pe||"#","_blank"),children:e.jsx(Ir,{className:"h-4 w-4"})})}),e.jsx(yc,{side:"right",children:"View Site"})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open(pe||"#","_blank"),children:[e.jsx(Ir,{className:"h-4 w-4"}),"View Site",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsx(ve,{path:`/my-website/${ne.id}/edit`,icon:ja,label:"Edit Website"}),e.jsx(ve,{path:"/my-website/mls-listings",icon:zr,label:"MLS Listings"}),e.jsx(ve,{path:"/my-website/market-report",icon:yo,label:"Market Reports"}),(ne==null?void 0:ne.mls_provider_id)&&e.jsx(ve,{path:"/mission-control/cma",icon:xw,label:"CMA Reports"}),e.jsx(ve,{path:"/mission-control/website-activity",icon:am,label:"Website Activity"}),e.jsx(ve,{path:"/m",icon:rg,label:"Mobile Command"})]}),e.jsxs(Je,{id:"marketing",label:"Marketing",icon:qd,activePaths:["/templates","/social-swag-2","/newsletters","/website-apps","/marketing-studio"],defaultPath:"/templates",children:[e.jsx(ve,{path:"/templates",icon:xl,label:"Templates"}),e.jsx(ve,{path:"/marketing-studio",icon:nl,label:"Marketing Studio"}),e.jsx(ve,{path:"/social-swag-2",icon:rg,label:"Social Swag"}),Me?e.jsxs(Ac,{delayDuration:0,children:[e.jsx(Mc,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/newsletters"),children:[e.jsx(iy,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),e.jsxs(yc,{side:"right",className:"flex items-center gap-2",children:["Newsletter Pro",e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1 py-0.5",children:"New"})]})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/newsletters"),children:[e.jsx(iy,{className:"h-4 w-4 shrink-0"}),"Newsletter Pro",e.jsx("span",{className:"ml-auto text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1.5 py-0.5",children:"New"})]}),e.jsx(ve,{path:"/website-apps",icon:un,label:"Website Apps"})]}),e.jsxs(Je,{id:"learning",label:"Learning",icon:$u,activePaths:["/academy","/toolbox","/programs"],defaultPath:"/academy",children:[e.jsx(ve,{path:"/academy",icon:_d,label:"Academy"}),e.jsx(ve,{path:"/toolbox",icon:wb,label:"Toolbox"})]}),e.jsxs(Je,{id:"community",label:"Community",icon:Ci,activePaths:["/community","/wishlist"],defaultPath:"/community",badgeCount:z,children:[e.jsx(ve,{path:"/community",icon:_n,label:"Community",badgeCount:z}),e.jsx(ve,{path:"/wishlist",icon:bw,label:"Wishlist",badgeCount:V}),!He&&e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open("https://www.facebook.com/share/g/1CC6thti2V/","_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"Facebook Group"]})]}),e.jsxs(Je,{id:"goods",label:"The Goods",icon:zg,activePaths:["/marketplace","/reward-store"],defaultPath:"/reward-store",children:[S&&!He&&e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",de.pathname.startsWith("/marketplace")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/marketplace"),children:[e.jsx(zg,{className:"h-4 w-4"}),"Marketplace",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded-full bg-primary text-primary-foreground",children:"New"})]}),S&&He&&e.jsx(ve,{path:"/marketplace",icon:zg,label:"Marketplace"}),e.jsx(ve,{path:"/reward-store",icon:vo,label:"Reward Store"}),e.jsx(ve,{path:"/refer-friends",icon:Bi,label:"Refer & Earn"})]}),e.jsxs(Je,{id:"help",label:"Help & Services",icon:Y_,activePaths:["/support","/additional-services"],defaultPath:"/support",children:[e.jsx(ve,{path:"/support",icon:oL,label:"Support"}),e.jsx(ve,{path:"/additional-services",icon:un,label:"Additional Services"})]}),l&&e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(ve,{path:"/coaching",icon:_d,label:"Coaching"})}),e.jsx(dss,{}),(n==null?void 0:n.email)==="jeremy@relevelup.com"&&e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",de.pathname.startsWith("/attract")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/attract"),children:[e.jsx(un,{className:"h-4 w-4 text-violet-600"}),!He&&e.jsx("span",{children:"LevelUp Attract"}),!He&&e.jsx("span",{className:"ml-auto text-[9px] font-semibold text-violet-600 uppercase tracking-wider",children:"Beta"})]}),a&&e.jsxs(e.Fragment,{children:[!He&&e.jsx("div",{className:"pt-3 pb-1",children:e.jsx("p",{className:"px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Admin"})}),He?e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(ve,{path:"/admin",icon:Rc,label:"Admin Dashboard"})}):e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",de.pathname==="/admin"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/admin"),children:[e.jsx(Rc,{className:"h-4 w-4"}),"Admin Dashboard"]})]}),(o||i)&&!a&&e.jsxs(e.Fragment,{children:[!He&&e.jsx("div",{className:"pt-3 pb-1",children:e.jsx("p",{className:"px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"My Brokerage"})}),He?e.jsxs("div",{className:"border-t border-sidebar-border mt-3 pt-3 space-y-1",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(ve,{path:"/my-brokerage",icon:Ga,label:"My Brokerage"}),e.jsx(ve,{path:"/brokerage/help-board",icon:sb,label:"Help Board"}),e.jsx(ve,{path:"/brokerage-content",icon:$u,label:"Brokerage Content"})]}),K&&!i&&e.jsx(ve,{path:"/my-team",icon:_n,label:"My Team"}),i&&e.jsxs(e.Fragment,{children:[e.jsx(ve,{path:"/brokerage/dashboard",icon:Vo,label:"Manage Brokerages"}),e.jsx(ve,{path:"/brokerage/teams",icon:_n,label:"Teams"}),e.jsx(ve,{path:"/brokerage/recruiting",icon:qd,label:"Recruiting"}),e.jsx(ve,{path:"/brokerage/vendors",icon:fb,label:"Vendors"}),e.jsx(ve,{path:"/brokerage-resources",icon:Vm,label:"Brokerage Resources"})]})]}):e.jsxs(e.Fragment,{children:[o&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/my-brokerage")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/my-brokerage"),children:[e.jsx(Ga,{className:"h-4 w-4"}),"My Brokerage"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/brokerage/help-board")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/help-board"),children:[e.jsx(sb,{className:"h-4 w-4"}),"Help Board"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/brokerage-content")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage-content"),children:[e.jsx($u,{className:"h-4 w-4"}),"Brokerage Content"]})]}),K&&!i&&e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/my-team")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/my-team"),children:[e.jsx(_n,{className:"h-4 w-4"}),"My Team"]}),i&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/brokerage/dashboard")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/dashboard"),children:[e.jsx(Vo,{className:"h-4 w-4"}),"Manage Brokerages"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/brokerage/teams")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/teams"),children:[e.jsx(_n,{className:"h-4 w-4"}),"Teams",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"New"})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/brokerage/recruiting")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/recruiting"),children:[e.jsx(qd,{className:"h-4 w-4"}),"Recruiting"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/brokerage/vendors")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/vendors"),children:[e.jsx(fb,{className:"h-4 w-4"}),"Vendors"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/brokerage-resources")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage-resources"),children:[e.jsx(Vm,{className:"h-4 w-4"}),"Brokerage Resources"]})]})]})]})]})}),e.jsxs("div",{className:"p-3 border-t border-sidebar-border md:hidden",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Fe("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/profile"),children:[e.jsx(Xi,{className:"h-4 w-4"}),"Profile"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:r,children:[e.jsx(DA,{className:"h-4 w-4"}),"Sign Out"]})]})]})};return e.jsx(Kw,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[b&&v&&de.pathname!=="/subscription"&&e.jsx(Dts,{}),typeof document<"u"&&Gx.createPortal(e.jsx("aside",{className:Et("hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto transition-[width] duration-300",Me?"w-16":"w-56"),style:{top:`${f}px`,height:`calc(100vh - ${f}px)`},children:e.jsx(we,{})}),document.body),e.jsxs("div",{className:Et("flex-1 flex flex-col overflow-hidden transition-all duration-300",Me?"md:ml-16":"md:ml-56"),style:{height:`calc(100vh - ${f}px)`,marginTop:`${f}px`},children:[e.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[e.jsxs(ug,{children:[e.jsx(oU,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(n4,{className:"h-5 w-5"})})}),e.jsx(ox,{side:"left",className:"w-56 p-0 bg-card",children:e.jsx(we,{isMobile:!0})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:Les,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(FUe,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[b&&!v&&j&&e.jsx(Lts,{expiresAt:j,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(FUe,{})}),A&&e.jsx(Rts,{hasUnseenBrief:D,onClick:L}),S&&e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",onClick:()=>ce("/marketplace/cart"),children:[e.jsx(zg,{className:"h-5 w-5"}),ee>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-primary text-primary-foreground text-xs font-medium flex items-center justify-center",children:ee>99?"99+":ee})]}),e.jsx(its,{}),e.jsx(vCe,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",_e.split(" ")[0],"!"]}),e.jsxs(jc,{children:[e.jsx(Nc,{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(aa,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(ri,{src:g||void 0}),e.jsx(ia,{className:"bg-primary text-primary-foreground font-medium text-sm",children:Ie(_e)})]})})}),e.jsxs(cc,{align:"end",className:"w-48",children:[e.jsxs(Xr,{onClick:()=>ce("/profile"),className:"cursor-pointer",children:[e.jsx(Xi,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(Xr,{onClick:()=>ce("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(J2,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(Xr,{onClick:()=>ce("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(J2,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(Qg,{}),e.jsxs(Xr,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(DA,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(Zts,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),A&&e.jsx(Wts,{brief:A,open:T,onClose:M,onDismiss:F}),e.jsx(Yts,{}),e.jsx(Xts,{}),e.jsx(tss,{})]})]})})};function dss(){const{user:s}=gs(),t=Jl(),n=In(),{data:r}=lt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i}=await q.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(i||[]).length>0}});if(!r)return null;const a=t.pathname==="/my-coach";return e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsxs(B,{variant:"ghost",size:"sm",className:`w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground ${a?"bg-sidebar-accent text-sidebar-accent-foreground":""}`,onClick:()=>n("/my-coach"),children:[e.jsx(_d,{className:"h-4 w-4"}),"My Coach"]})})}const UUe="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",uss="https://tile-portal.lovable.app/mcp-oauth-bridge.html",hss=[{label:"Open ChatGPT",description:"You need ChatGPT Plus, Pro, or Team to add custom MCP connectors."},{label:"Add a new connector",description:"Settings → Connectors → Add. Choose 'Custom / MCP Server'."},{label:"Fill in the basics",description:"Name it LevelUp and add a short description like 'Tools for the LevelUp real estate platform.'"},{label:"Paste the server URL",description:"Paste the MCP server URL below into the Server URL field. Do not paste the tile-portal bridge URL."},{label:"Confirm OAuth",description:"Authentication should be OAuth. Check the 'I understand' box, then tap Create."},{label:"Sign in to LevelUp",description:"ChatGPT will open a LevelUp consent page. Sign in with your LevelUp account and tap Approve."},{label:"Start chatting",description:"Ask ChatGPT to 'list my upcoming LevelUp trainings' or 'summarize my Inner Circle contacts'."}];function mss(){const[s,t]=N.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(UUe),t(!0),ae.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{ae.error("Could not copy URL")}};return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(ZS,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Connect ChatGPT to LevelUp"}),e.jsx("p",{className:"text-muted-foreground",children:"Let ChatGPT use LevelUp tools while you are signed in."})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Use this exact MCP server URL"}),e.jsx(Hn,{children:"Paste only this URL into ChatGPT's Server URL field."})]}),e.jsx(Ae,{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:UUe}),e.jsx(B,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(zi,{className:"h-4 w-4 text-green-600"}):e.jsx(ta,{className:"h-4 w-4"})})]})})]}),e.jsx(fe,{className:"border-destructive/30 bg-destructive/5",children:e.jsx(Ae,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Dl,{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:uss}),e.jsx("p",{className:"text-muted-foreground",children:"Delete that plugin attempt and create a new one with the MCP server URL above."})]})]})})}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Quick steps"}),e.jsx(Hn,{children:"ChatGPT adds MCP servers as a new plugin / custom tool. Share these steps with any agent who wants to connect."})]}),e.jsx(Ae,{children:e.jsx("ol",{className:"space-y-4",children:hss.map((r,a)=>e.jsxs("li",{className:"flex gap-3",children:[e.jsx("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-medium text-primary",children:a+1}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r.description})]})]},a))})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(tr,{className:"h-4 w-4"}),e.jsx("span",{children:"Only basic tools are exposed today. More LevelUp actions will be added over time."})]})]})})}const pss=()=>{const[s]=yl(),t=s.get("tier"),n=t==null?void 0:t.includes("brokerage");return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(fe,{className:"max-w-lg w-full",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-green-500/10 flex items-center justify-center mb-4",children:e.jsx(zi,{className:"w-10 h-10 text-green-500"})}),e.jsx(Pt,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(Hn,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Ae,{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(Hs,{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."})})]})]})})},fss=()=>{const{user:s}=gs(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(""),o=async h=>{var p;if(!(s!=null&&s.email)){ae.error("Please sign in to upgrade");return}n(!0),a(h);try{const{data:f,error:g}=await q.functions.invoke("create-checkout",{body:{tier:h,email:s.email,name:((p=s.user_metadata)==null?void 0:p.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(g)throw g;if(f!=null&&f.url)window.open(f.url,"_blank","noopener,noreferrer"),ae.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(f){console.error("Checkout error:",f),ae.error(f.message||"Failed to start checkout. Please try again.")}finally{n(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan","Up to 25 agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"],u=["Everything in Brokerage plan","Unlimited agent seats","Dedicated account manager","Advanced analytics & reporting","White-label options","API access","Custom integrations","Enterprise-level support"];return e.jsx(Cs,{children:e.jsxs("div",{className:"container max-w-6xl py-8 px-4",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Upgrade Your Membership"}),e.jsx("p",{className:"text-muted-foreground text-lg",children:"Choose the plan that's right for you and unlock the full power of LevelUp"})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(se,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(ge,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:h=>l(h.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mb-8",children:[e.jsxs(fe,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 right-0 bg-primary text-primary-foreground text-xs px-3 py-1 rounded-bl-lg font-medium",children:"Popular"}),e.jsxs(Mt,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(_n,{className:"h-7 w-7 text-primary"})}),e.jsx(Pt,{className:"text-xl",children:"Individual Agent"}),e.jsx(Hn,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Ae,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-primary",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:c.map((h,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},p))}),e.jsxs(B,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&r==="individual_agent"?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(fe,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors",children:[e.jsxs(Mt,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Ga,{className:"h-7 w-7 text-amber-600"})}),e.jsx(Pt,{className:"text-xl",children:"Brokerage"}),e.jsx(Hn,{children:"For teams and brokerages up to 25 agents"})]}),e.jsxs(Ae,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-amber-600",children:"$299"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:d.map((h,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Lr,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},p))}),e.jsxs(B,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",size:"lg",onClick:()=>o("brokerage_under_25"),disabled:t,children:[t&&r==="brokerage_under_25"?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(fe,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(Mt,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-purple-500/10 flex items-center justify-center",children:e.jsx(Ga,{className:"h-7 w-7 text-purple-600"})}),e.jsx(Pt,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(Hn,{children:"For larger brokerages with 25+ agents"})]}),e.jsxs(Ae,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-purple-600",children:"$499"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:u.map((h,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Lr,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},p))}),e.jsxs(B,{variant:"outline",className:"w-full border-purple-500 text-purple-600 hover:bg-purple-50",size:"lg",onClick:()=>o("brokerage_over_25"),disabled:t,children:[t&&r==="brokerage_over_25"?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(fe,{className:"bg-muted/50",children:e.jsxs(Ae,{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(Pr,{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(Hs,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},xss=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=gs(),a=In(),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(!1);N.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),N.useEffect(()=>{!t&&s&&r&&a("/profile?setup=true")},[s,t,r,a]);const h=async()=>{if(!i.trim()){ae.error("Please enter a brokerage name");return}const{data:p}=await q.auth.getSession(),f=p.session;if(!s||!f){ae.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!f,userId:s==null?void 0:s.id});const{data:g,error:b}=await q.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:g,error:b}),b)throw b;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(fe,{className:"max-w-lg w-full",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(ss,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(Pt,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(Hn,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(zi,{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(ss,{className:"w-5 h-5 animate-spin text-primary"}),e.jsx("span",{children:"Assigning you as manager..."})]}),e.jsx("p",{className:"text-center text-sm text-muted-foreground mt-4",children:"You'll be redirected to complete your profile setup in a moment."})]})]})}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(fe,{className:"max-w-lg w-full",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(Ga,{className:"w-10 h-10 text-primary"})}),e.jsx(Pt,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Hn,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Ae,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(ge,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:p=>l(p.target.value),onKeyDown:p=>p.key==="Enter"&&h()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(_n,{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(zi,{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(zi,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(zi,{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(zi,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs(B,{onClick:h,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(za,{className:"w-4 h-4 ml-2"})]})]})]})})},qUe=()=>{const s=In(),[t,n]=N.useState("verifying"),[r,a]=N.useState("");N.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await q.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await q.from("profiles").select("login_count").eq("id",o.user.id).single();if(((d==null?void 0:d.login_count)||0)>1){console.log("Account already claimed, redirecting to dashboard"),n("already_claimed");return}console.log("User logged in successfully:",o.user.email),n("success");try{await q.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(u){console.log("Trial claim hook (non-critical):",u)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{n("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),n("already_claimed")}})()},[s]);const i=()=>{window.location.href="https://dashboard.relevelup.com/auth"};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"space-y-1 text-center",children:[e.jsxs("div",{className:"mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10",children:[t==="verifying"&&e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"}),t==="success"&&e.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),t==="already_claimed"&&e.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),t==="error"&&e.jsx("svg",{className:"h-8 w-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})]}),e.jsxs(Pt,{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(Hn,{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(Ae,{children:e.jsx(B,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},gss=()=>{const[s,t]=N.useState(!1),n=N.useMemo(()=>new URLSearchParams(window.location.search).get("link"),[]),r=N.useMemo(()=>{if(!n)return!1;try{const i=new URL(n);return i.hostname.endsWith(".supabase.co")&&i.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[n]);N.useEffect(()=>{document.title="Reset Your Password"},[]);const a=()=>{!r||!n||(t(!0),window.location.href=n)};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:Qht,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(fe,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsx(Pt,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(Hn,{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(Ae,{className:"space-y-4",children:[r?e.jsx(B,{onClick:a,disabled:s,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:s?"Continuing…":"Continue to Reset Password"}):e.jsx(B,{onClick:()=>window.location.href="/auth",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg",children:"Go to Sign In"}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"For your security, password reset links expire and can only be used once."})]})]})]})})]})},yss=()=>{const s=In(),[t]=yl(),[n,r]=N.useState(t.get("code")||""),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,b]=N.useState(!1),[v,j]=N.useState(!1),[_,S]=N.useState(null),[A,T]=N.useState(null),[D,L]=N.useState(null),[M,F]=N.useState(null);N.useEffect(()=>{const K=t.get("code");K&&(r(K),z(K))},[t]);const z=async K=>{b(!0);const{data:Y,error:ee}=await q.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",K.toUpperCase().trim()).single();if(ee||!Y){ae.error("Invalid invite code"),b(!1);return}if(!Y.is_active){ae.error("This invite code is no longer active"),b(!1);return}if(Y.max_uses&&Y.uses_count>=Y.max_uses){ae.error("This invite code has reached its maximum uses"),b(!1);return}if(Y.expires_at&&new Date(Y.expires_at){K.preventDefault(),z(n)},W=async K=>{var Y;if(K.preventDefault(),!c.trim()){ae.error("Please enter your name");return}if(l.length<6){ae.error("Password must be at least 6 characters");return}f(!0);try{const ee=`${window.location.origin}/`,{data:ne,error:oe}=await q.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:ee,data:{name:c.trim()}}});if(oe){oe.message.includes("already registered")?ae.error("This email is already registered. Please sign in instead."):ae.error(oe.message);return}if(ne.user){await q.rpc("add_default_signup_tag",{user_id:ne.user.id});const pe=n.toUpperCase().trim();A?await q.functions.invoke("assign-brokerage",{body:{userId:ne.user.id,brokerageId:A,inviteCode:pe}}):M?await q.functions.invoke("assign-brokerage",{body:{userId:ne.user.id,trialDays:M,inviteCode:pe}}):await q.functions.invoke("assign-brokerage",{body:{userId:ne.user.id,grandfathered:!0,inviteCode:pe}}),_&&await q.from("invite_codes").update({uses_count:((Y=(await q.from("invite_codes").select("uses_count").eq("id",_).single()).data)==null?void 0:Y.uses_count)+1}).eq("id",_),ae.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(ee){console.error("Signup error:",ee),ae.error("An unexpected error occurred")}finally{f(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsx(Pt,{className:"text-2xl font-bold text-primary",children:D?`Join ${D}`:"Join LevelUp"}),e.jsx(Hn,{children:v?D?`Create your account to join ${D}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Ae,{children:v?e.jsxs("form",{onSubmit:W,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Full Name"}),e.jsx(ge,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:K=>d(K.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ge,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:K=>i(K.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:K=>o(K.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(gf,{className:"h-4 w-4"}):e.jsx(Ir,{className:"h-4 w-4"})})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:p,children:p?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:V,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(ge,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:n,onChange:K=>r(K.target.value),required:!0,autoFocus:!0})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},xU=()=>{const{user:s,isCoach:t}=gs();return lt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:n,error:r}=await q.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return n}})},vss=()=>{const{data:s}=xU();return lt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("coach_id",s.id).order("started_at",{ascending:!1});if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(o=>o.agent_id),{data:i}=await q.from("profiles").select("id, name, email, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>({...o,agent:l.get(o.agent_id)||null}))}})},bss=()=>{const{user:s}=gs();return lt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("agent_id",s.id).eq("status","active").order("started_at",{ascending:!1}).limit(1);if(n)throw n;const r=(t||[])[0];if(!r)return null;const{data:a}=await q.from("coaches").select("*").eq("id",r.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await q.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...r,coach:a,coachProfile:i}}})},_ss=s=>lt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return null;const{data:r}=await q.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:r}}}),Vmt=s=>lt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(n)throw n;return t||[]}}),Hmt=s=>lt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(n)throw n;return t||[]}}),wss=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function jss(){const s=In(),{data:t,isLoading:n}=xU(),{data:r=[],isLoading:a}=vss();if(n)return e.jsx(Cs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Cs,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(_d,{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."})]})});wss.map(l=>({...l,items:r.filter(o=>(o.pipeline_stage||"active")===l.key)}));const i=r.filter(l=>l.status==="active").length;return e.jsx(Cs,{title:"Coaching",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-white/80",children:[e.jsx(un,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider font-medium",children:"Coaching Command Center"})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-2",children:"Welcome back, Coach"}),e.jsx("p",{className:"text-white/80 mb-6",children:"Lead your agents. Track momentum. Build champions."}),e.jsxs("div",{className:"flex flex-wrap gap-6",children:[e.jsx(qje,{icon:_d,label:"Active agents",value:i}),e.jsx(qje,{icon:Tl,label:"This month",value:"—"}),e.jsx(qje,{icon:_c,label:"Momentum",value:"🔥"})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Your Roster"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>s("/coaching/waitlist"),children:"Waitlist"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>s("/coaching/billing"),children:"Billing & Packages"})]})]}),a?e.jsx("div",{className:"text-muted-foreground",children:"Loading roster…"}):r.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No agents assigned yet. An admin or you can invite agents to get started."})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:r.map(l=>{var o,c,d,u;return e.jsx(fe,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Ae,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(aa,{className:"h-14 w-14",children:[e.jsx(ri,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(ia,{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(za,{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(ze,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",Go(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function qje({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 Gmt({assignmentId:s}){const{user:t}=gs(),n=Gt(),[r,a]=N.useState(""),[i,l]=N.useState(!1),o=N.useRef(null),{data:c=[]}=lt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await q.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(h)throw h;return u||[]}});N.useEffect(()=>{if(!s)return;const u=q.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>n.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{q.removeChannel(u)}},[s,n]),N.useEffect(()=>{var u;(u=o.current)==null||u.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const u=r.trim();if(!u||!t)return;l(!0);const{error:h}=await q.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),h||a("")};return e.jsxs(fe,{className:"flex flex-col h-[60vh] min-h-[400px]",children:[e.jsx("div",{ref:o,className:"flex-1 overflow-y-auto p-4 space-y-3",children:c.length===0?e.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"No messages yet. Say hi 👋"}):c.map(u=>{const h=u.sender_id===(t==null?void 0:t.id);return e.jsxs("div",{className:Et("flex gap-2",h?"justify-end":"justify-start"),children:[!h&&e.jsx(aa,{className:"h-8 w-8 mt-1",children:e.jsx(ia,{className:"text-xs",children:(u.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:Et("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:Et("text-[10px] mt-1",h?"text-white/70":"text-muted-foreground"),children:Go(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(Ae,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Ts,{value:r,onChange:u=>a(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),d())},placeholder:"Type a message…",rows:1,className:"resize-none min-h-[40px]"}),e.jsx(B,{onClick:d,disabled:i||!r.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(cr,{className:"h-4 w-4"})})]})})]})}var y6e="Progress",v6e=100,[Nss,egn]=gu(y6e),[kss,Sss]=Nss(y6e),Wmt=N.forwardRef((s,t)=>{const{__scopeProgress:n,value:r=null,max:a,getValueLabel:i=Css,...l}=s;(a||a===0)&&!VUe(a)&&console.error(Tss(`${a}`,"Progress"));const o=VUe(a)?a:v6e;r!==null&&!HUe(r,o)&&console.error(Ess(`${r}`,"Progress"));const c=HUe(r,o)?r:null,d=Lfe(c)?i(c,o):void 0;return e.jsx(kss,{scope:n,value:c,max:o,children:e.jsx(sa.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":Lfe(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":Zmt(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});Wmt.displayName=y6e;var Kmt="ProgressIndicator",Ymt=N.forwardRef((s,t)=>{const{__scopeProgress:n,...r}=s,a=Sss(Kmt,n);return e.jsx(sa.div,{"data-state":Zmt(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...r,ref:t})});Ymt.displayName=Kmt;function Css(s,t){return`${Math.round(s/t*100)}%`}function Zmt(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function Lfe(s){return typeof s=="number"}function VUe(s){return Lfe(s)&&!isNaN(s)&&s>0}function HUe(s,t){return Lfe(s)&&!isNaN(s)&&s<=t&&s>=0}function Tss(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${v6e}\`.`}function Ess(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 ${v6e} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var Qmt=Wmt,Ass=Ymt;const xi=N.forwardRef(({className:s,value:t,...n},r)=>e.jsx(Qmt,{ref:r,className:Et("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(Ass,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));xi.displayName=Qmt.displayName;function Xmt({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=lt({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:b,error:v}=await q.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",n).lte("close_date",r);if(v)throw v;return b||[]}}),{data:i}=lt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:b}=await q.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return b}}),l=a.filter(b=>b.is_win),o=l.length,c=l.reduce((b,v)=>b+(Number(v.sale_price)||0),0),d=l.reduce((b,v)=>b+(Number(v.commission_amount)||0),0),u=i,h=(u==null?void 0:u.transactions_goal)||0,p=(u==null?void 0:u.volume_goal)||0,f=(u==null?void 0:u.gci_goal)||0,g=b=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(b);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(mo,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(Vje,{icon:vc,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(Vje,{icon:mo,label:"Volume",value:g(c),goal:p,current:c,suffix:p?`of ${g(p)}`:""}),e.jsx(Vje,{icon:Zl,label:"GCI",value:g(d),goal:f,current:d,suffix:f?`of ${g(f)}`:""})]}),o===0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function Vje({icon:s,label:t,value:n,goal:r,current:a,suffix:i}){const l=r>0?Math.min(100,a/r*100):0;return e.jsx(fe,{children:e.jsxs(Ae,{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(xi,{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 Jmt({assignmentId:s,canEdit:t}){const n=Gt(),[r,a]=N.useState(!1),[i,l]=N.useState(null),{data:o=[]}=lt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(u)throw u;return d||[]}}),c=()=>n.invalidateQueries({queryKey:["coaching-goals",s]});return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(wc,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const u=Number(d.target_value||0),h=Number(d.current_value||0),p=u>0?Math.min(100,h/u*100):0;return e.jsx(fe,{children:e.jsxs(Ae,{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(ze,{variant:"outline",className:"capitalize",children:d.status||"active"})]}),d.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:d.description})]}),t&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(ja,{className:"h-4 w-4"})})]}),u>0&&e.jsxs("div",{className:"mt-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[h.toLocaleString()," / ",u.toLocaleString()," ",d.target_metric||""]}),e.jsxs("span",{children:[p.toFixed(0),"%"]})]}),e.jsx(xi,{value:p})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",ks(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(Mss,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function Mss({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var A,T;const[i,l]=N.useState((r==null?void 0:r.title)||""),[o,c]=N.useState((r==null?void 0:r.description)||""),[d,u]=N.useState((r==null?void 0:r.target_metric)||""),[h,p]=N.useState(((A=r==null?void 0:r.target_value)==null?void 0:A.toString())||""),[f,g]=N.useState(((T=r==null?void 0:r.current_value)==null?void 0:T.toString())||"0"),[b,v]=N.useState((r==null?void 0:r.due_date)||""),[j,_]=N.useState(!1);N.useState(()=>{var D,L;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),p(((D=r==null?void 0:r.target_value)==null?void 0:D.toString())||""),g(((L=r==null?void 0:r.current_value)==null?void 0:L.toString())||"0"),v((r==null?void 0:r.due_date)||"")});const S=async()=>{if(!i.trim())return;_(!0);const D={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:f?Number(f):0,due_date:b||null},{error:L}=r!=null&&r.id?await q.from("coaching_goals").update(D).eq("id",r.id):await q.from("coaching_goals").insert(D);if(_(!1),L)return ae.error(L.message);ae.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ge,{placeholder:"Title",value:i,onChange:D=>l(D.target.value)}),e.jsx(Ts,{placeholder:"Description (optional)",rows:2,value:o,onChange:D=>c(D.target.value)}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Metric"}),e.jsx(ge,{placeholder:"transactions",value:d,onChange:D=>u(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(ge,{type:"number",value:h,onChange:D=>p(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(ge,{type:"number",value:f,onChange:D=>g(D.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(ge,{type:"date",value:b,onChange:D=>v(D.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:S,disabled:j,children:r!=null&&r.id?"Save":"Create"})]})]})})}function ept({assignmentId:s}){const t=Gt(),{user:n}=gs(),r=N.useRef(null),[a,i]=N.useState(!1),{data:l=[]}=lt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:h,error:p}=await q.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(p)throw p;return h||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async h=>{var f;const p=(f=h.target.files)==null?void 0:f[0];if(!(!p||!n)){i(!0);try{const g=`${s}/${Date.now()}-${p.name}`,{error:b}=await q.storage.from("coaching-files").upload(g,p);if(b)throw b;const{error:v}=await q.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:g,file_name:p.name,file_size_bytes:p.size,mime_type:p.type});if(v)throw v;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:p,error:f}=await q.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(f||!p)return ae.error("Could not get download link");window.open(p.signedUrl,"_blank")},u=async h=>{confirm("Delete this file?")&&(await q.storage.from("coaching-files").remove([h.file_url]),await q.from("coaching_shared_files").delete().eq("id",h.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs(B,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(Sa,{className:"h-4 w-4 mr-1"})," ",a?"Uploading…":"Upload"]}),e.jsx("input",{ref:r,type:"file",hidden:!0,onChange:c})]}),l.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"p-6 text-center text-muted-foreground",children:"No files yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(h=>e.jsx(fe,{children:e.jsxs(Ae,{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(Nr,{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 · `:"",ks(new Date(h.created_at),"PP")]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(Da,{className:"h-4 w-4"})}),h.uploaded_by===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u(h),children:e.jsx(bn,{className:"h-4 w-4"})})]})},h.id))})]})}function Iss(){var p,f,g,b;const{id:s}=_i(),t=In(),n=Gt(),{data:r,isLoading:a}=_ss(s),{data:i=[]}=Vmt(s),{data:l=[]}=Hmt(s),[o,c]=N.useState(!1),[d,u]=N.useState(!1);if(a)return e.jsx(Cs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx(Cs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs(Cs,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Ae,{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(aa,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(ri,{src:((p=h.agent)==null?void 0:p.avatar_url)||void 0}),e.jsx(ia,{className:"text-2xl",children:(((f=h.agent)==null?void 0:f.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((g=h.agent)==null?void 0:g.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(b=h.agent)==null?void 0:b.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(ze,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx(ze,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Pss,{value:h.pipeline_stage||"active",onChange:async v=>{await q.from("coaching_assignments").update({pipeline_stage:v}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsxs($r,{defaultValue:"sessions",children:[e.jsxs(Ur,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Zt,{value:"sessions",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Zt,{value:"actions",children:[e.jsx(pu,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Zt,{value:"goals",children:[e.jsx(wc,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Zt,{value:"kpis",children:[e.jsx(mo,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Zt,{value:"messages",children:[e.jsx(Ci,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Zt,{value:"files",children:[e.jsx(yf,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Zt,{value:"notes",children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(ls,{value:"sessions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sessions"}),e.jsxs(B,{size:"sm",onClick:()=>c(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(v=>e.jsx(fe,{children:e.jsx(Ae,{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:ks(new Date(v.scheduled_at),"PPp")}),e.jsx(ze,{variant:"outline",className:"capitalize",children:v.status}),v.template&&e.jsx(ze,{variant:"secondary",children:v.template})]}),v.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:v.summary}),v.private_notes&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-muted/50 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-1",children:[e.jsx(Rc,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:v.private_notes})]})]})})})},v.id))})]}),e.jsxs(ls,{value:"actions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Action Items"}),e.jsxs(B,{size:"sm",onClick:()=>u(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(v=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-3 flex items-center gap-3",children:[e.jsx(hi,{checked:v.status==="done",onCheckedChange:async j=>{await q.from("coaching_action_items").update({status:j?"done":"open",completed_at:j?new Date().toISOString():null}).eq("id",v.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:v.status==="done"?"line-through text-muted-foreground":"font-medium",children:v.title}),v.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v.description})]}),v.due_date&&e.jsx(ze,{variant:"outline",children:ks(new Date(v.due_date),"MMM d")}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:v.priority})]})},v.id))})]}),e.jsx(ls,{value:"goals",children:e.jsx(Jmt,{assignmentId:h.id,canEdit:!0})}),e.jsx(ls,{value:"kpis",children:h.agent_id&&e.jsx(Xmt,{agentUserId:h.agent_id})}),e.jsx(ls,{value:"messages",children:e.jsx(Gmt,{assignmentId:h.id})}),e.jsx(ls,{value:"files",children:e.jsx(ept,{assignmentId:h.id})}),e.jsx(ls,{value:"notes",className:"space-y-4",children:e.jsx(fe,{children:e.jsx(Ae,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(Lss,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(Dss,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function Pss({value:s,onChange:t}){return e.jsxs(us,{value:s,onValueChange:t,children:[e.jsx(cs,{className:"w-40",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"onboarding",children:"Onboarding"}),e.jsx(Ze,{value:"active",children:"Active"}),e.jsx(Ze,{value:"thriving",children:"Thriving"}),e.jsx(Ze,{value:"at_risk",children:"At Risk"}),e.jsx(Ze,{value:"graduated",children:"Graduated"})]})]})}function Lss({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=N.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=N.useState(60),[c,d]=N.useState("weekly_1on1"),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,b]=N.useState(!1),[v,j]=N.useState(!0),[_,S]=N.useState(null),[A,T]=N.useState(!1),D=async()=>{T(!0);const{data:M,error:F}=await q.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(T(!1),F||M!=null&&M.error)return ae.error((M==null?void 0:M.error)||(F==null?void 0:F.message)||"Failed to generate brief");S(M.brief||"No brief returned.")},L=async()=>{b(!0);const{data:M,error:F}=await q.from("coaching_sessions").insert({assignment_id:n,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:u,private_notes:p,status:"completed"}).select("id").maybeSingle();if(F)return b(!1),ae.error(F.message);if(ae.success("Session saved"),v&&u.trim()&&(M!=null&&M.id)){const{error:z}=await q.functions.invoke("coaching-send-recap",{body:{sessionId:M.id}});z?ae.error("Saved, but recap email failed: "+z.message):ae.success("Recap emailed to agent")}b(!1),r==null||r(),t(!1),h(""),f(""),S(null)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(_s,{children:"New Session"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:D,disabled:A,children:[A?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[_&&e.jsxs("div",{className:"rounded-lg border bg-gradient-to-br from-[#406E71]/5 to-[#2a4c64]/5 p-3 text-sm whitespace-pre-wrap max-h-60 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[#406E71] mb-2",children:[e.jsx(un,{className:"h-3 w-3"})," AI Brief"]}),_]}),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(ge,{type:"datetime-local",value:a,onChange:M=>i(M.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(ge,{type:"number",value:l,onChange:M=>o(Number(M.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(us,{value:c,onValueChange:d,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(Ze,{value:"grow",children:"GROW Model"}),e.jsx(Ze,{value:"goal_review",children:"Goal Review"}),e.jsx(Ze,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Ts,{rows:4,value:u,onChange:M=>h(M.target.value),placeholder:"Key takeaways, wins, focus areas…"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium flex items-center gap-1",children:[e.jsx(Rc,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Ts,{rows:3,value:p,onChange:M=>f(M.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(hi,{checked:v,onCheckedChange:M=>j(!!M)}),e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:L,disabled:g,children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function Dss({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState("medium"),[p,f]=N.useState(!1),g=async()=>{if(!a.trim())return;f(!0);const{error:b}=await q.from("coaching_action_items").insert({assignment_id:n,title:a,description:l||null,due_date:c||null,priority:u});if(f(!1),b)return ae.error(b.message);ae.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ge,{placeholder:"Title",value:a,onChange:b=>i(b.target.value)}),e.jsx(Ts,{rows:3,placeholder:"Description (optional)",value:l,onChange:b=>o(b.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(ge,{type:"date",value:c,onChange:b=>d(b.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(us,{value:u,onValueChange:h,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"low",children:"Low"}),e.jsx(Ze,{value:"medium",children:"Medium"}),e.jsx(Ze,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:g,disabled:p,children:"Add"})]})]})})}function jCe({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(ua,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function Rss({coachId:s}){const[t,n]=N.useState([]),[r,a]=N.useState(!0);N.useEffect(()=>{(async()=>{const{data:l}=await q.from("coaching_reviews").select("*").eq("coach_id",s).eq("is_published",!0).order("created_at",{ascending:!1}),o=l||[];if(o.length){const c=o.map(h=>h.agent_id),{data:d}=await q.from("profiles").select("id, name, avatar_url").in("id",c),u=new Map((d||[]).map(h=>[h.id,h]));o.forEach(h=>h.profile=u.get(h.agent_id))}n(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return r||!t.length?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(jCe,{value:Math.round(i)}),e.jsxs("span",{children:[i.toFixed(1)," · ",t.length," review",t.length===1?"":"s"]})]})]}),e.jsx("div",{className:"space-y-3",children:t.map(l=>{var o,c,d;return e.jsx(fe,{children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(aa,{className:"h-9 w-9",children:[e.jsx(ri,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(ia,{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(jCe,{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 Oss({coachId:s,assignmentId:t}){const{user:n}=gs(),[r,a]=N.useState(null),[i,l]=N.useState(0),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(!1);N.useEffect(()=>{n&&(async()=>{const{data:g}=await q.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 f=async()=>{if(!n)return;if(!i)return ae.error("Pick a rating");p(!0);const g={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:b}=r?await q.from("coaching_reviews").update(g).eq("id",r.id):await q.from("coaching_reviews").insert(g);if(p(!1),b)return ae.error(b.message);ae.success("Thanks for your review!"),a({...g,id:r==null?void 0:r.id})};return e.jsx(fe,{children:e.jsxs(Ae,{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(jCe,{value:i,size:28,onChange:l}),e.jsx(ge,{placeholder:"Title (optional)",value:o,onChange:g=>c(g.target.value)}),e.jsx(Ts,{rows:4,placeholder:"What was your experience like?",value:d,onChange:g=>u(g.target.value)}),e.jsx(B,{onClick:f,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}function Fss(){var h,p,f,g,b,v;const{user:s}=gs(),{data:t,isLoading:n,refetch:r}=bss(),a=Gt(),i=t==null?void 0:t.id,{data:l=[]}=Vmt(i),{data:o=[]}=Hmt(i);if(N.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&q.functions.invoke("coaching-verify-checkout").then(()=>{r(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[r,a]),n)return e.jsx(Cs,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Cs,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(_d,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're not in a coaching program yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Browse LevelUp Certified Coaches to find a fit (coming soon)."})]})});const c=t,d=o.filter(j=>j.status!=="done"),u=o.length-d.length;return e.jsx(Cs,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(fe,{className:"overflow-hidden",children:e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs(aa,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(ri,{src:((h=c.coachProfile)==null?void 0:h.avatar_url)||void 0}),e.jsx(ia,{className:"text-2xl bg-white/20 text-white",children:(((p=c.coachProfile)==null?void 0:p.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80 mb-1",children:[e.jsx(un,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((f=c.coachProfile)==null?void 0:f.name)||"Your Coach"}),((g=c.coach)==null?void 0:g.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((b=c.coach)==null?void 0:b.is_certified)&&e.jsx(ze,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(ze,{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(Hje,{icon:pu,label:"Open action items",value:d.length}),e.jsx(Hje,{icon:wc,label:"Completed",value:u}),e.jsx(Hje,{icon:yr,label:"Sessions",value:l.length})]}),((v=c.coach)==null?void 0:v.id)&&e.jsx(Oss,{coachId:c.coach.id,assignmentId:i}),e.jsxs($r,{defaultValue:"actions",children:[e.jsxs(Ur,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Zt,{value:"actions",children:[e.jsx(pu,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Zt,{value:"sessions",children:[e.jsx(yr,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Zt,{value:"goals",children:[e.jsx(wc,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Zt,{value:"kpis",children:[e.jsx(mo,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Zt,{value:"messages",children:[e.jsx(Ci,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Zt,{value:"files",children:[e.jsx(yf,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(ls,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(j=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-3 flex items-center gap-3",children:[e.jsx(hi,{checked:j.status==="done",onCheckedChange:async _=>{await q.from("coaching_action_items").update({status:_?"done":"open",completed_at:_?new Date().toISOString():null}).eq("id",j.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:j.status==="done"?"line-through text-muted-foreground":"font-medium",children:j.title}),j.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:j.description})]}),j.due_date&&e.jsx(ze,{variant:"outline",children:ks(new Date(j.due_date),"MMM d")}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:j.priority})]})},j.id))}),e.jsx(ls,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(j=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:ks(new Date(j.scheduled_at),"PPp")}),e.jsx(ze,{variant:"outline",className:"capitalize",children:j.status})]}),j.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},j.id))}),e.jsx(ls,{value:"goals",children:e.jsx(Jmt,{assignmentId:i,canEdit:!1})}),e.jsx(ls,{value:"kpis",children:s&&e.jsx(Xmt,{agentUserId:s.id})}),e.jsx(ls,{value:"messages",children:e.jsx(Gmt,{assignmentId:i})}),e.jsx(ls,{value:"files",children:e.jsx(ept,{assignmentId:i})})]})]})})}function Hje({icon:s,label:t,value:n}){return e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}function zss(){const s=Gt(),[t,n]=N.useState(""),[r,a]=N.useState([]),[i,l]=N.useState(null),{data:o=[],isLoading:c}=lt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:h,error:p}=await q.from("coaches").select("*").order("created_at",{ascending:!1});if(p)throw p;if(!(h!=null&&h.length))return[];const f=h.map(v=>v.user_id),{data:g}=await q.from("profiles").select("id, name, email, avatar_url").in("id",f),b=new Map((g||[]).map(v=>[v.id,v]));return h.map(v=>({...v,profile:b.get(v.user_id)}))}});N.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const p=setTimeout(async()=>{const{data:f}=await q.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(f||[])},250);return()=>clearTimeout(p)},[t]);const d=async h=>{const{error:p}=await q.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(p)return ae.error(p.message);const{error:f}=await q.from("coaches").insert({user_id:h.id});if(f&&!String(f.message).includes("duplicate"))return ae.error(f.message);ae.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,p)=>{const{error:f}=await q.from("coaches").update({is_certified:p}).eq("id",h);if(f)return ae.error(f.message);ae.success(p?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(Cs,{title:"Coaching Admin",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_d,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsx(Bss,{}),e.jsx(Uss,{}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 space-y-3",children:[e.jsx(ge,{placeholder:"Search by user email or name…",value:t,onChange:h=>n(h.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):r.map(h=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted/40",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.name||h.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:h.email})]}),e.jsxs(B,{size:"sm",onClick:()=>d(h),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Make Coach"]})]},h.id))})]})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Coaches"}),c?e.jsx("div",{children:"Loading…"}):o.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(h=>{var p,f,g;return e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((p=h.profile)==null?void 0:p.name)||((f=h.profile)==null?void 0:f.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(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(ze,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx(ze,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(Fo,{className:"h-4 w-4 mr-1"})," Assign"]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm pt-2 border-t",children:[e.jsx("span",{className:"text-muted-foreground",children:"LevelUp Certified"}),e.jsx(vn,{checked:h.is_certified,onCheckedChange:b=>u(h.id,b)})]})]})},h.id)})})]})]}),e.jsx($ss,{coachId:i,onClose:()=>l(null)})]})}function Bss(){const[s,t]=N.useState("1500"),[n,r]=N.useState(!1),[a,i]=N.useState(!1);N.useEffect(()=>{(async()=>{const{data:c}=await q.from("settings").select("value").eq("key","coaching_platform_fee_bps").maybeSingle();c!=null&&c.value&&t(String(c.value)),i(!0)})()},[]);const l=async()=>{const c=parseInt(s,10);if(isNaN(c)||c<0||c>5e3)return ae.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await q.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return ae.error(d.message);ae.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(i4,{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(se,{children:"Fee (bps)"}),e.jsx(ge,{type:"number",value:s,onChange:c=>t(c.target.value),min:0,max:5e3}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["= ",o,"%"]})]}),e.jsx(B,{onClick:l,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:n?"Saving…":"Save"})]})]})})}function $ss({coachId:s,onClose:t}){const[n,r]=N.useState(""),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=Gt();N.useEffect(()=>{if(!s){r(""),i([]);return}},[s]),N.useEffect(()=>{const u=n.trim();if(u.length<2){i([]);return}o(!0);const h=setTimeout(async()=>{const{data:p}=await q.from("profiles").select("id, name, email").or(`email.ilike.%${u}%,name.ilike.%${u}%`).limit(15);i(p||[]),o(!1)},250);return()=>clearTimeout(h)},[n]);const d=async u=>{const{error:h}=await q.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return ae.error(h.message);ae.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(bs,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Assign Agent"})}),e.jsx(ge,{placeholder:"Search agents by name or email…",value:n,onChange:u=>r(u.target.value),autoFocus:!0}),e.jsx("div",{className:"space-y-1 max-h-72 overflow-auto border rounded-md",children:n.trim().length<2?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Type at least 2 characters to search…"}):l?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Searching…"}):a.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No agents found"}):a.map(u=>e.jsxs("button",{onClick:()=>d(u.id),className:"w-full text-left p-2 hover:bg-muted",children:[e.jsx("div",{className:"font-medium",children:u.name||u.email}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.email})]},u.id))}),e.jsx(Xn,{children:e.jsx(B,{variant:"outline",onClick:t,children:"Close"})})]})})}function Uss(){const s=Gt(),[t,n]=N.useState("pending"),[r,a]=N.useState(null),{data:i=[],isLoading:l}=lt({queryKey:["coach-applications",t],queryFn:async()=>{let u=q.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(u=u.eq("status",t));const{data:h,error:p}=await u;if(p)throw p;return h||[]}}),{data:o=0}=lt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await q.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:p}=await q.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(p)return ae.error(p.message);ae.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs(ze,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs(ze,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(Fn,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(ze,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(fe,{children:[e.jsxs(Ae,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Z2,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(ze,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[o," pending"]}),e.jsx("div",{className:"ml-auto flex gap-1 flex-wrap",children:["pending","approved","rejected","all"].map(u=>e.jsx(B,{size:"sm",variant:t===u?"default":"outline",onClick:()=>n(u),className:t===u?"bg-[#406E71] hover:bg-[#2a4c64]":"",children:u.charAt(0).toUpperCase()+u.slice(1)},u))})]}),l?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center border rounded-md",children:["No applications ",t!=="all"?`with status "${t}"`:"yet","."]}):e.jsx("div",{className:"divide-y border rounded-md",children:i.map(u=>e.jsx("button",{onClick:()=>a(u),className:"w-full text-left p-3 hover:bg-muted/40 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:u.full_name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-3 mt-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Hs,{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(bs,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(ws,{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(NI,{icon:Hs,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(NI,{icon:Pr,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(NI,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(NI,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(NI,{icon:tr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(NI,{icon:tr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(Gje,{label:"Specialties",children:r.specialties}),e.jsx(Gje,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(Gje,{label:"Results story",children:r.results_story}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(Ts,{defaultValue:r.admin_notes||"",rows:3,onBlur:async u=>{const h=u.target.value;h!==(r.admin_notes||"")&&(await q.from("coach_applications").update({admin_notes:h}).eq("id",r.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(Xn,{className:"gap-2 flex-wrap",children:[r.status!=="rejected"&&e.jsxs(B,{variant:"outline",onClick:()=>c(r.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx(Fn,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs(B,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(gr,{className:"h-4 w-4 mr-1"})," Move to pending"]}),r.status!=="approved"&&e.jsxs(B,{onClick:()=>c(r.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(Lr,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function NI({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 Gje({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 qss(){const s=In(),{data:t}=xU(),n=Gt(),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),{data:d,refetch:u}=lt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await q.functions.invoke("coach-stripe-status");return v}}),{data:h=[]}=lt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await q.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return v||[]}});N.useEffect(()=>{const v=new URLSearchParams(window.location.search);(v.get("onboarded")||v.get("refresh"))&&u()},[u]);const p=async()=>{var S,A;a(!0);const{data:v,error:j}=await q.functions.invoke("coach-stripe-connect");a(!1);let _=v==null?void 0:v.error;if(!_&&j)try{const T=await((A=(S=j==null?void 0:j.context)==null?void 0:S.json)==null?void 0:A.call(S));_=(T==null?void 0:T.error)||j.message}catch{_=j.message}if(_)return ae.error(_,{duration:1e4});v!=null&&v.url&&(window.location.href=v.url)},f=d||{},g=!!(t!=null&&t.use_platform_stripe),b=g||f.connected&&f.charges_enabled;return e.jsx(Cs,{title:"Coaching · Billing",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(Wr,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(fe,{children:e.jsxs(Ae,{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(ff,{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."})]}),b?e.jsxs(ze,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(xr,{className:"h-3 w-3"})," ",g?"Using LevelUp billing":"Connected"]}):f.connected?e.jsxs(ze,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(Gi,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(ze,{variant:"outline",children:"Not connected"})]}),!g&&e.jsxs(B,{onClick:p,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[b?"Update Stripe details":f.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(tr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages"}),e.jsxs(B,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!b,children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!b&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No packages yet."}):e.jsx("div",{className:"space-y-2",children:h.map(v=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[v.name,v.is_active&&v.accepting_clients===!1&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-800 font-semibold",children:"Booked full"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["$",(v.price_cents/100).toFixed(0)," / ",v.billing_interval,!v.is_active&&" · Inactive"]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{c(v),l(!0)},children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{confirm("Delete this package?")&&(await q.from("coaching_packages").delete().eq("id",v.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(bn,{className:"h-4 w-4"})})]},v.id))})]})}),e.jsx(Vss,{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 Vss({open:s,onOpenChange:t,coachId:n,pkg:r,onSaved:a}){const[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState("month"),[f,g]=N.useState(!0),[b,v]=N.useState(!0),[j,_]=N.useState(!1);N.useEffect(()=>{s&&(l((r==null?void 0:r.name)||""),c((r==null?void 0:r.description)||""),u(r?(r.price_cents/100).toString():""),p((r==null?void 0:r.billing_interval)||"month"),g((r==null?void 0:r.is_active)??!0),v((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const S=async()=>{if(!i.trim()||!d)return ae.error("Name and price required");_(!0);const A={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:f,accepting_clients:b},{error:T}=r!=null&&r.id?await q.from("coaching_packages").update(A).eq("id",r.id):await q.from("coaching_packages").insert(A);if(_(!1),T)return ae.error(T.message);ae.success("Saved"),a==null||a(),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ge,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:A=>l(A.target.value)}),e.jsx(Ts,{rows:3,placeholder:"What's included",value:o,onChange:A=>c(A.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(ge,{type:"number",value:d,onChange:A=>u(A.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"month",children:"Monthly"}),e.jsx(Ze,{value:"year",children:"Yearly"}),e.jsx(Ze,{value:"one_time",children:"One-time"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:A=>g(A.target.checked)}),"Active (visible to agents)"]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:b,onChange:A=>v(A.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Accepting new clients"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Uncheck if you're booked full — visitors will still see the package but can't sign up."})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:S,disabled:j,children:r!=null&&r.id?"Save":"Create"})]})]})})}function GUe({kind:s,value:t,onChange:n}){const r=N.useRef(null),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null),h=N.useRef(null),p=N.useRef(null),f=N.useRef([]),[g,b]=N.useState(!1),v=s==="photo"?"image/*":"video/*",j=s==="photo"?10*1024*1024:200*1024*1024,_=async(M,F)=>{var ee;const{data:z}=await q.auth.getUser(),V=(ee=z.user)==null?void 0:ee.id;if(!V)return ae.error("Not signed in");if(M.size>j)return ae.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const W=`${V}/${s}-${Date.now()}.${F}`,{error:K}=await q.storage.from("coach-media").upload(W,M,{upsert:!0,contentType:M.type||(s==="photo"?"image/jpeg":"video/webm")});if(K)return i(!1),ae.error(K.message);const{data:Y}=await q.storage.from("coach-media").createSignedUrl(W,60*60*24*365*10);i(!1),Y!=null&&Y.signedUrl&&(n(Y.signedUrl),ae.success("Uploaded"),d(null))},S=async M=>{const F=M.name.split(".").pop()||(s==="photo"?"jpg":"webm");await _(M,F)},A=async()=>{try{const M=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=M,b(!0),setTimeout(()=>{u.current&&(u.current.srcObject=M,u.current.play())},50);const F=new MediaRecorder(M,{mimeType:"video/webm"});f.current=[],F.ondataavailable=z=>z.data.size>0&&f.current.push(z.data),F.onstop=()=>{const z=new Blob(f.current,{type:"video/webm"});d(z),M.getTracks().forEach(V=>V.stop())},p.current=F,F.start(),o(!0)}catch(M){ae.error(M.message||"Could not access camera")}},T=()=>{var M;(M=p.current)==null||M.stop(),o(!1)},D=()=>{var M;(M=h.current)==null||M.getTracks().forEach(F=>F.stop()),b(!1),o(!1),d(null)},L=async()=>{c&&(await _(c,"webm"),D())};return N.useEffect(()=>()=>{var M;return(M=h.current)==null?void 0:M.getTracks().forEach(F=>F.stop())},[]),e.jsxs("div",{className:"space-y-2",children:[t&&e.jsx("div",{className:"rounded-lg overflow-hidden border bg-muted/30",children:s==="photo"?e.jsx("img",{src:t,alt:"Profile",className:"w-32 h-32 object-cover"}):e.jsx("video",{src:t,controls:!0,className:"w-full max-h-64"})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{ref:r,type:"file",accept:v,className:"hidden",onChange:M=>{var z;const F=(z=M.target.files)==null?void 0:z[0];F&&S(F),M.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var M;return(M=r.current)==null?void 0:M.click()},children:[a?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:A,disabled:a||g,children:[e.jsx(pf,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(bn,{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(B,{type:"button",size:"sm",onClick:T,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(cy,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(B,{type:"button",size:"sm",onClick:()=>{var M;return(M=p.current)==null?void 0:M.start()},children:[e.jsx(vr,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{type:"button",size:"sm",onClick:L,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(B,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),A()},children:"Re-record"})]}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:D,children:"Cancel"})]})]})]})}function Hss(){const s=In(),{data:t,isLoading:n}=xU(),r=Gt(),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,b]=N.useState(!1),[v,j]=N.useState([]),[_,S]=N.useState(""),[A,T]=N.useState(!1);N.useEffect(()=>{if(!t)return;const z=t;i(z.slug||""),o(z.headline||""),d(z.bio||""),h(z.photo_url||""),f(z.intro_video_url||""),b(!!z.accepting_clients),j(z.specialties||[])},[t]);const D=async()=>{if(!t)return;T(!0);const{error:z}=await q.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:p||null,accepting_clients:g,specialties:v}).eq("id",t.id);if(T(!1),z)return ae.error(z.message);ae.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},L=()=>{const z=_.trim();if(z){if(v.includes(z))return S("");j([...v,z]),S("")}};if(n)return e.jsx(Cs,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Cs,{title:"Coach Settings",children:e.jsx("div",{className:"max-w-2xl mx-auto p-8 text-center text-muted-foreground",children:"You don't have a coach profile yet."})});const M=t,F=M.slug?`${window.location.origin}/coaches/${M.slug}`:null;return e.jsx(Cs,{title:"Coach Settings",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(Wr,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[F&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(F,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(B,{onClick:D,disabled:A,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," ",A?"Saving…":"Save"]})]})]}),M.is_certified&&e.jsxs("div",{className:"rounded-lg border border-yellow-300/50 bg-yellow-50 dark:bg-yellow-950/20 px-4 py-3 text-sm",children:["✨ ",e.jsx("strong",{children:"LevelUp Certified"})," — Your profile displays a verified badge."]}),e.jsx(fe,{children:e.jsxs(Ae,{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(vn,{checked:g,onCheckedChange:b})]}),e.jsxs("div",{children:[e.jsx(se,{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(ge,{value:a,onChange:z=>i(z.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(ge,{value:l,onChange:z=>o(z.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Bio"}),e.jsx(Ts,{rows:6,value:c,onChange:z=>d(z.target.value),placeholder:"Tell agents who you are, what you've done, how you coach…"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Profile photo"}),e.jsx(GUe,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Intro video"}),e.jsx(GUe,{kind:"video",value:p,onChange:f})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:v.map(z=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[z,e.jsx("button",{onClick:()=>j(v.filter(V=>V!==z)),children:e.jsx(Fn,{className:"h-3 w-3"})})]},z))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:_,onChange:z=>S(z.target.value),placeholder:"Add a specialty…",onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),L())}}),e.jsx(B,{type:"button",variant:"outline",onClick:L,children:e.jsx(As,{className:"h-4 w-4"})})]})]})]})}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages & Stripe"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your monetized packages on the Billing page."})]}),e.jsx(B,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(Gss,{coachId:M.id})]})})}function Gss({coachId:s}){const[t,n]=N.useState("");Gt();const{data:r=[],refetch:a}=lt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await q.from("coaching_invites").select("*").eq("coach_id",s).order("created_at",{ascending:!1});return c||[]}}),i=async()=>{const c=t.trim().toLowerCase();if(!c)return ae.error("Email required");const{error:d}=await q.from("coaching_invites").insert({coach_id:s,email:c});if(d)return ae.error(d.message);n(""),ae.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),ae.success("Link copied")},o=async c=>{confirm("Revoke this invite?")&&(await q.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(tl,{className:"h-5 w-5"})," Invite agents"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a magic link to onboard agents directly."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{placeholder:"agent@email.com",value:t,onChange:c=>n(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs(B,{onClick:i,children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Create"]})]}),e.jsxs("div",{className:"space-y-2",children:[r.map(c=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:c.email}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.status," · expires ",new Date(c.expires_at).toLocaleDateString()]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(ta,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(bn,{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 xH=[{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 Wss(){const s=In(),t=Gt(),{data:n,isLoading:r}=xU(),[a,i]=N.useState("pending"),[l,o]=N.useState(""),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(""),[g,b]=N.useState(!1),[v,j]=N.useState(""),{data:_=[],isLoading:S}=lt({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:z,error:V}=await q.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if(V)throw V;return z||[]}}),A=N.useMemo(()=>_.filter(z=>{if(a!=="all"&&z.status!==a)return!1;if(l){const V=l.toLowerCase();return(z.name||"").toLowerCase().includes(V)||(z.email||"").toLowerCase().includes(V)||(z.brokerage||"").toLowerCase().includes(V)}return!0}),[_,a,l]),T=N.useMemo(()=>{const z={all:_.length};for(const V of xH)z[V.value]=0;for(const V of _)z[V.status]=(z[V.status]||0)+1;return z},[_]),D=async(z,V)=>{const{error:W}=await q.from("coaching_waitlist").update(V).eq("id",z);if(W)return ae.error(W.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===z&&d(K=>({...K,...V}))},L=async z=>{if(!confirm("Remove this person from the waitlist?"))return;const{error:V}=await q.from("coaching_waitlist").delete().eq("id",z);if(V)return ae.error(V.message);ae.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},M=async()=>{if(!c)return;const{data:z,error:V}=await q.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:p}});if(V||z!=null&&z.error)return ae.error((z==null?void 0:z.error)||(V==null?void 0:V.message)||"Could not send invite");ae.success(`Invite sent to ${c.name}`),h(!1),f(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})},F=async()=>{if(!n)return;const{data:z,error:V}=await q.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:v}});if(V||z!=null&&z.error)return ae.error((z==null?void 0:z.error)||(V==null?void 0:V.message)||"Could not notify");ae.success(`Notified ${(z==null?void 0:z.count)||0} agents`),b(!1),j(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(Cs,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(Cs,{title:"Coaching Waitlist",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"mb-2 -ml-2",onClick:()=>s("/coaching"),children:[e.jsx(Wr,{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(Ov,{className:"h-6 w-6 text-[#406E71]"}),"Waitlist"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Agents waiting for a spot to open up with you."})]}),e.jsxs(B,{variant:"outline",onClick:()=>b(!0),disabled:!T.pending,title:T.pending?"":"No pending applicants",children:[e.jsx(cL,{className:"h-4 w-4 mr-2"}),"Notify all pending (",T.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 (",T.all,")"]}),xH.map(z=>e.jsxs("button",{onClick:()=>i(z.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===z.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[z.label," (",T[z.value]||0,")"]},z.value))]}),e.jsx(ge,{placeholder:"Search by name, email, brokerage…",value:l,onChange:z=>o(z.target.value),className:"max-w-md"}),S?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):A.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"p-10 text-center text-muted-foreground",children:"No entries here yet."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:A.map(z=>{const V=xH.find(W=>W.value===z.status);return e.jsx(fe,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(z),children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold truncate",children:z.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:z.email}),z.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:z.brokerage})]}),e.jsx(ze,{className:(V==null?void 0:V.tone)||"",children:(V==null?void 0:V.label)||z.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",Go(new Date(z.created_at),{addSuffix:!0})]}),z.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",z.preferred_package]})]})]})},z.id)})})]}),e.jsx(bs,{open:!!c,onOpenChange:z=>!z&&d(null),children:e.jsx(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:c.name}),e.jsxs(Qn,{children:["Joined ",Go(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(fF,{label:"Email",value:c.email}),e.jsx(fF,{label:"Phone",value:c.phone}),e.jsx(fF,{label:"Brokerage",value:c.brokerage}),e.jsx(fF,{label:"Years",value:c.years_in_business}),e.jsx(fF,{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 ",Go(new Date(c.invited_at),{addSuffix:!0})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Status"}),e.jsxs(us,{value:c.status,onValueChange:z=>D(c.id,{status:z}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:xH.map(z=>e.jsx(Ze,{value:z.value,children:z.label},z.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(Ts,{rows:3,defaultValue:c.coach_notes||"",onBlur:z=>{z.target.value!==(c.coach_notes||"")&&D(c.id,{coach_notes:z.target.value})}})]})]}),e.jsxs(Xn,{className:"flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"text-destructive",onClick:()=>L(c.id),children:[e.jsx(bn,{className:"h-4 w-4 mr-1"})," Remove"]}),e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${c.email}`,children:[e.jsx(Hs,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{f(""),h(!0)},children:[e.jsx(cr,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(bs,{open:u,onOpenChange:h,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Invite to subscribe"}),e.jsxs(Qn,{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(Ts,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:p,onChange:z=>f(z.target.value)})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:M,children:[e.jsx(cr,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(bs,{open:g,onOpenChange:b,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Notify all pending applicants"}),e.jsx(Qn,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Ts,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:v,onChange:z=>j(z.target.value)}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:F,children:[e.jsx(cL,{className:"h-4 w-4 mr-1"})," Send to ",T.pending||0," agents"]})]})]})})]}):e.jsx(Cs,{title:"Waitlist",children:e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"You need a coach profile to view this page."})})}function fF({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 Kss(){const{data:s=[],isLoading:t}=lt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:n,error:r}=await q.from("coaches").select("id, slug, headline, bio, specialties, photo_url, is_certified, accepting_clients, user_id").not("slug","is",null);if(r)throw r;const a=(n||[]).map(o=>o.user_id);if(a.length===0)return[];const{data:i}=await q.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(n||[]).map(o=>({...o,profile:l.get(o.user_id)}))}});return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 py-20 md:py-28 text-center",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-yellow-300"}),"LevelUp Certified Coaches"]}),e.jsxs("h1",{className:"text-5xl md:text-7xl font-bold tracking-tight leading-[1.05]",children:["Coaching that ",e.jsx("span",{className:"bg-gradient-to-r from-yellow-300 to-yellow-100 bg-clip-text text-transparent",children:"moves the needle."})]}),e.jsx("p",{className:"text-white/75 mt-6 max-w-2xl mx-auto text-lg leading-relaxed",children:"Hand-picked real-estate coaches ready to help you hit your next breakthrough — from lead gen to listings to luxury."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-6 mt-10 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{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(Ln,{to:`/coaches/${n.slug||n.id}`,className:"group",children:e.jsx("article",{className:"relative h-full rounded-2xl bg-[#1c3447] overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_24px_60px_-20px_rgba(42,76,100,0.5)]",children:e.jsxs("div",{className:"relative aspect-[3/4] w-full overflow-hidden",children:[a?e.jsx("img",{src:a,alt:r,className:"absolute inset-0 h-full w-full object-cover object-top group-hover:scale-105 transition-transform duration-700"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white text-6xl font-bold",children:r.charAt(0)}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0d1f2d] via-[#0d1f2d]/70 to-transparent"}),e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-start justify-between gap-2",children:[n.is_certified?e.jsxs("div",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-300 text-[#2a4c64] text-[11px] font-semibold shadow-md",children:[e.jsx(un,{className:"h-3 w-3"})," Certified"]}):e.jsx("span",{}),e.jsxs("div",{className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium backdrop-blur-md ${n.accepting_clients?"bg-emerald-500/90 text-white":"bg-white/85 text-[#2a4c64]"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${n.accepting_clients?"bg-white":"bg-amber-500"}`}),n.accepting_clients?"Accepting":"Waitlist"]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-5 text-white",children:[e.jsx("h3",{className:"text-xl font-bold leading-tight drop-shadow-sm",children:r}),n.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:n.headline}),n.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:n.bio}),n.specialties&&n.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:n.specialties.slice(0,2).map(o=>e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-white/15 backdrop-blur-sm text-white border border-white/20",children:o},o))}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-3 border-t border-white/15",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:"View profile"}),e.jsx("span",{className:"inline-flex items-center justify-center h-8 w-8 rounded-full bg-white/15 backdrop-blur-sm text-white group-hover:bg-yellow-300 group-hover:text-[#1c3447] transition-colors",children:e.jsx(za,{className:"h-4 w-4"})})]})]})]})})},n.id)})}),e.jsxs("div",{className:"mt-20 rounded-3xl bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white p-10 md:p-14 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"18px 18px"}}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-yellow-300/15 blur-3xl"}),e.jsxs("div",{className:"relative md:flex items-center gap-10",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 border border-white/15 text-[11px] uppercase tracking-[0.18em] font-semibold mb-5",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-yellow-300"})," Coach Applications Open"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold leading-tight",children:["Are you the kind of agent ",e.jsx("span",{className:"text-yellow-300",children:"other agents need?"})]}),e.jsx("p",{className:"text-white/80 mt-4 max-w-xl leading-relaxed",children:"LevelUp Coaches are the top 1% — top producers, proven mentors, and category leaders making a measurable difference in agents' businesses. If that's you, we want to meet you."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3 text-sm text-white/70",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(xr,{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(xr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(xr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(Ln,{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(za,{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 Yss=Zw({name:go().trim().min(1,"Name required").max(120),email:go().trim().email("Invalid email").max(255),phone:go().trim().max(40).optional().or(Np("")),brokerage:go().trim().max(160).optional().or(Np("")),years_in_business:go().max(40).optional().or(Np("")),biggest_challenge:go().trim().max(1e3).optional().or(Np("")),preferred_package:go().max(120).optional().or(Np("")),message:go().trim().max(1500).optional().or(Np(""))});function Zss({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=gs(),[l,o]=N.useState(!1),[c,d]=N.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(p,f)=>d(g=>({...g,[p]:f})),h=async()=>{var g;const p=Yss.safeParse(c);if(!p.success){ae.error(((g=p.error.issues[0])==null?void 0:g.message)||"Please check your entries");return}o(!0);const{error:f}=await q.from("coaching_waitlist").insert({coach_id:n,agent_user_id:(i==null?void 0:i.id)||null,name:c.name.trim(),email:c.email.trim().toLowerCase(),phone:c.phone||null,brokerage:c.brokerage||null,years_in_business:c.years_in_business||null,biggest_challenge:c.biggest_challenge||null,preferred_package:c.preferred_package||null,message:c.message||null,status:"pending"});if(o(!1),f){ae.error(f.message||"Could not join waitlist");return}ae.success(`You're on the waitlist${r?` for ${r}`:""}. We'll be in touch when a spot opens.`),t(!1),d({...c,biggest_challenge:"",message:""})};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(Qn,{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(se,{children:"Name *"}),e.jsx(ge,{value:c.name,onChange:p=>u("name",p.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email *"}),e.jsx(ge,{type:"email",value:c.email,onChange:p=>u("email",p.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ge,{value:c.phone,onChange:p=>u("phone",p.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Brokerage"}),e.jsx(ge,{value:c.brokerage,onChange:p=>u("brokerage",p.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Years in business"}),e.jsxs(us,{value:c.years_in_business,onValueChange:p=>u("years_in_business",p),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select…"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(Ze,{value:"1-3 years",children:"1-3 years"}),e.jsx(Ze,{value:"4-7 years",children:"4-7 years"}),e.jsx(Ze,{value:"8-15 years",children:"8-15 years"}),e.jsx(Ze,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(se,{children:"Preferred package"}),e.jsxs(us,{value:c.preferred_package,onValueChange:p=>u("preferred_package",p),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Any"})}),e.jsx(ds,{children:a.map(p=>e.jsx(Ze,{value:p.name,children:p.name},p.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Biggest challenge right now"}),e.jsx(Ts,{rows:2,value:c.biggest_challenge,onChange:p=>u("biggest_challenge",p.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Anything else?"}),e.jsx(Ts,{rows:2,value:c.message,onChange:p=>u("message",p.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:l,children:"Cancel"}),e.jsx(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:h,disabled:l,children:l?"Submitting…":"Join Waitlist"})]})]})})}function Qss(){var b;const{slug:s}=_i(),t=In(),{user:n}=gs(),[r,a]=N.useState(null),[i,l]=N.useState(!1),{data:o,isLoading:c}=lt({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const v=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),j=q.from("coaches").select("*"),{data:_}=v?await j.eq("id",s).maybeSingle():await j.eq("slug",s).maybeSingle();if(!_)return null;const[{data:S},{data:A}]=await Promise.all([q.from("profiles").select("id, name, avatar_url").eq("id",_.user_id).maybeSingle(),q.from("coaching_packages").select("*").eq("coach_id",_.id).eq("is_active",!0).order("sort_order")]);return{coach:_,profile:S,packages:A||[]}}}),d=async v=>{if(!n){ae.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(v);const{data:j,error:_}=await q.functions.invoke("create-coaching-checkout",{body:{packageId:v}});if(a(null),_||j!=null&&j.error){ae.error((j==null?void 0:j.error)||(_==null?void 0:_.message)||"Checkout failed");return}j!=null&&j.url&&(window.location.href=j.url)};if(c)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(o!=null&&o.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:u,profile:h,packages:p}=o,f=u,g=(v,j)=>{const _=(v/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return j==="one_time"?_:`${_} / ${j}`};return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 md:py-20",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(Wr,{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(aa,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(ri,{src:f.photo_url||(h==null?void 0:h.avatar_url)}),e.jsx(ia,{className:"text-3xl bg-white/20",children:((h==null?void 0:h.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[f.is_certified&&e.jsxs("div",{className:"inline-flex items-center gap-1 bg-yellow-400/20 border border-yellow-300/30 text-yellow-100 px-2 py-1 rounded-full text-xs mb-2",children:[e.jsx(un,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(h==null?void 0:h.name)||"Coach"}),f.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:f.headline}),((b=f.specialties)==null?void 0:b.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:f.specialties.map(v=>e.jsx(ze,{className:"bg-white/15 text-white border-white/20",children:v},v))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[f.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:f.intro_video_url,controls:!0,className:"w-full h-full"})}),f.bio&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-3",children:"About"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap leading-relaxed",children:f.bio})]}),e.jsx(Rss,{coachId:f.id})]}),e.jsxs("div",{className:"space-y-4 md:sticky md:top-6 md:self-start",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Choose a plan"}),p.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):p.map(v=>{const j=v.accepting_clients===!1;return e.jsx(fe,{className:`border-2 transition-colors ${j?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Ae,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:v.name}),j&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-bold px-2 py-1 rounded-full bg-amber-500 text-white shrink-0",children:"Booked Full"})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:v.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:g(v.price_cents,v.billing_interval)}),j?e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx("div",{className:"rounded-md bg-amber-100 border border-amber-200 text-amber-900 px-3 py-2.5 text-sm text-center",children:"Currently not accepting new clients."}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(Ov,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs(B,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(v.id),disabled:r===v.id,children:[r===v.id?"Loading…":"Get Started",e.jsx(Lr,{className:"h-4 w-4 ml-1"})]})]})},v.id)}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Secure checkout powered by Stripe."}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(Ov,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(Zss,{open:i,onOpenChange:l,coachId:f.id,coachName:h==null?void 0:h.name,packages:p.map(v=>({id:v.id,name:v.name}))})]})}const Xss=Zw({full_name:go().trim().min(2,"Please enter your full name").max(100),email:go().trim().email("Enter a valid email").max(255),phone:go().trim().max(40).optional().or(Np("")),brokerage:go().trim().max(150).optional().or(Np("")),years_experience:go().trim().max(40).optional().or(Np("")),specialties:go().trim().max(500).optional().or(Np("")),why_coach:go().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:go().trim().max(2e3).optional().or(Np("")),website_url:go().trim().max(300).optional().or(Np("")),linkedin_url:go().trim().max(300).optional().or(Np(""))});function Jss(){const s=In(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,u)=>l(h=>({...h,[d]:u})),c=async d=>{var p;d.preventDefault();const u=Xss.safeParse(i);if(!u.success){const f=(p=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:p[0];return ae.error(f||"Please check the form and try again")}n(!0);const{error:h}=await q.from("coach_applications").insert(u.data);if(n(!1),h)return ae.error(h.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return r?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-xl text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-20 w-20 rounded-full bg-gradient-to-br from-yellow-400 to-yellow-300 text-[#1c3447] mb-6 shadow-2xl",children:e.jsx(xr,{className:"h-10 w-10"})}),e.jsx("h1",{className:"text-4xl md:text-5xl font-bold mb-4",children:"Application received."}),e.jsx("p",{className:"text-white/80 text-lg leading-relaxed mb-8",children:"Thank you for applying to the LevelUp Coaching program. Our team personally reviews every application — we'll be in touch within 5 business days."}),e.jsx(B,{onClick:()=>s("/coaches"),className:"bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-semibold",children:"Browse our coaches"})]})}):e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-5xl mx-auto px-4 py-16 md:py-20",children:[e.jsxs(Ln,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(Wr,{className:"h-4 w-4"})," Back to coaches"]}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-yellow-300"}),"Coach Application — By Invitation & Application Only"]}),e.jsx("h1",{className:"text-4xl md:text-6xl font-bold tracking-tight leading-[1.05] max-w-3xl",children:"Join the most respected coaching program in real estate."}),e.jsx("p",{className:"text-white/80 mt-6 max-w-2xl text-lg leading-relaxed",children:"LevelUp Coaches don't just teach — they transform careers. We hand-pick top-producing agents and proven mentors who are ready to multiply their impact, build a recurring revenue stream, and help thousands of agents finally break through."}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-4 mt-12",children:[e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(_n,{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(mo,{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(vc,{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(xr,{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(vo,{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(ua,{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(T_,{label:"Full name *",children:e.jsx(ge,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(T_,{label:"Email *",children:e.jsx(ge,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(T_,{label:"Phone",children:e.jsx(ge,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(T_,{label:"Current brokerage",children:e.jsx(ge,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(T_,{label:"Years in real estate",children:e.jsx(ge,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(T_,{label:"Coaching specialties",children:e.jsx(ge,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(T_,{label:"Website",children:e.jsx(ge,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(T_,{label:"LinkedIn",children:e.jsx(ge,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(T_,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Ts,{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(T_,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Ts,{value:i.results_story,onChange:d=>o("results_story",d.target.value),rows:5,maxLength:2e3,placeholder:"Production numbers, agent breakthroughs, testimonials — anything that shows the impact you've had."})}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-3 pt-2",children:[e.jsx(B,{type:"submit",disabled:t,className:"bg-gradient-to-r from-[#406E71] to-[#2a4c64] hover:opacity-95 text-white font-semibold px-8 py-6 text-base flex-1 sm:flex-none",children:t?"Submitting…":"Submit application"}),e.jsx("p",{className:"text-xs text-slate-500",children:"We review every application within 5 business days."})]})]})]})]})}function T_({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const ens="/assets/testimonial-avatar-1-BsCQFauB.jpg",tns="/assets/testimonial-avatar-2-B6VPVc2t.jpg",sns="/assets/testimonial-avatar-3-GuEFwYUE.jpg",nns="/assets/testimonial-avatar-4-98iKMtkB.jpg",rns="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",ans=[ens,tns,sns,nns,rns],ins=Zw({name:go().trim().min(2,"Name must be at least 2 characters").max(100),email:go().trim().email("Please enter a valid email address").max(255),phone:go().trim().min(10,"Please enter a valid phone number").max(20).optional().or(Np("")),brokerage:go().trim().max(200).optional().or(Np(""))}),ons=[{icon:Pu,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:xl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:yr,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ql,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Nr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Bi,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],lns=[{icon:_n,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:un,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Pr,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:hu,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Ca,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:yo,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:yi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:ph,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],cns=[{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."}],dns=()=>{const s=In(),[t,n]=N.useState(!1),[r,a]=N.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=N.useState({}),o=async c=>{var u,h;c.preventDefault(),l({});const d=ins.safeParse(r);if(!d.success){const p={};d.error.issues.forEach(f=>{f.path[0]&&(p[f.path[0]]=f.message)}),l(p);return}n(!0);try{const p=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:f,error:g}=await q.functions.invoke("create-trial-signup",{body:{name:r.name.trim(),email:r.email.trim().toLowerCase(),phone:((u=r.phone)==null?void 0:u.trim())||void 0,brokerage:((h=r.brokerage)==null?void 0:h.trim())||void 0,referral_code:p}});if(g){console.error("Trial signup error:",g),ae.error(g.message||"Something went wrong. Please try again.");return}if(f!=null&&f.error){ae.error(f.error);return}ae.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),typeof window<"u"&&window.fbq&&window.fbq("track","Lead",{content_name:"Trial Signup",value:0,currency:"USD"}),s("/trial/success")}catch(p){console.error("Trial signup error:",p),ae.error("Something went wrong. Please try again.")}finally{n(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"Start Your Free 7-Day Trial | LevelUp Dashboard"}),e.jsx("meta",{name:"description",content:"Take LevelUp for a free 7-day test drive. No credit card required. The all-in-one platform for real estate agents and brokerages."}),e.jsx("meta",{property:"og:title",content:"Start Your Free 7-Day Trial | LevelUp"}),e.jsx("meta",{property:"og:description",content:"Take LevelUp for a free 7-day test drive. No credit card required."}),e.jsx("meta",{property:"og:type",content:"website"}),e.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:Efe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var c;return(c=document.getElementById("features"))==null?void 0:c.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(B,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-8 text-center lg:text-left",children:[e.jsx("div",{className:"flex justify-center lg:justify-start",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-24 md:h-32 drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium",children:[e.jsx(un,{className:"h-4 w-4 text-yellow-400"}),e.jsx("span",{children:"7-Day Free Trial • No Credit Card Required"})]}),e.jsxs("h1",{className:"text-3xl md:text-4xl lg:text-5xl font-bold text-white leading-tight font-sans",children:["Take LevelUp for a"," ",e.jsx("span",{className:"italic",children:"Free Test Drive"})]}),e.jsxs("p",{className:"text-lg md:text-xl text-white/80 max-w-xl mx-auto lg:mx-0 font-sans",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center lg:justify-start",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(xr,{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(xr,{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:ans.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(ua,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},c))}),e.jsx("p",{className:"text-sm text-white/60",children:"Trusted by 3,000+ agents"})]})]})]}),e.jsx("div",{className:"lg:pl-8",children:e.jsx(fe,{className:"bg-white shadow-2xl border-0",children:e.jsxs(Ae,{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(nx,{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(se,{htmlFor:"name",children:"Full Name *"}),e.jsx(ge,{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(se,{htmlFor:"email",children:"Email Address *"}),e.jsx(ge,{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(se,{htmlFor:"phone",children:"Phone Number"}),e.jsx(ge,{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(se,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(ge,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:r.brokerage,onChange:c=>a({...r,brokerage:c.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx(B,{type:"submit",className:"w-full h-12 text-lg font-semibold bg-[#4a6b6d] hover:bg-[#3d5a5c]",disabled:t,children:t?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(za,{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:ons.map((c,d)=>e.jsxs(fe,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Mt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(c.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Pt,{className:"text-xl font-sans",children:c.title})]}),e.jsx(Ae,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:c.description})})]},d))})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(un,{className:"w-4 h-4"}),"Included with Your Trial"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:lns.map((c,d)=>e.jsxs(fe,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(c.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Pt,{className:"text-lg font-semibold text-white",children:c.title})]}),e.jsx(Ae,{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:cns.map((c,d)=>e.jsx(fe,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Ae,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(u=>e.jsx(ua,{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(hh,{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(ph,{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(_n,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Expert Support"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Real estate pros"})]})]})]})})}),e.jsx("section",{id:"free-trial",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs(fe,{className:"bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] border-0 shadow-2xl overflow-hidden relative",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs(Ae,{className:"p-12 text-center relative",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-4 font-sans",children:"Ready to Level Up Your Business?"}),e.jsx("p",{className:"text-xl text-white/80 mb-8 max-w-2xl mx-auto",children:"Join thousands of successful agents. Start your free 7-day trial today."}),e.jsxs(B,{onClick:()=>window.scrollTo({top:0,behavior:"smooth"}),size:"lg",className:"h-14 px-8 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Start Your Free Trial Now",e.jsx(za,{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:dfe,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."})]})})})]})]})},uns=()=>{const s=In();return e.jsxs(e.Fragment,{children:[e.jsx(Yo,{children:e.jsx("title",{children:"Welcome to LevelUp! | Check Your Email"})}),e.jsxs("div",{className:"min-h-screen bg-background flex flex-col",children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:Efe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx(B,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})}),e.jsxs("section",{className:"relative pt-24 pb-12 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden flex-1 flex items-center",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsx("div",{className:"flex justify-center",children:e.jsx(fe,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Ae,{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(xr,{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(uh,{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(Hs,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Check Your Inbox"})]}),e.jsx("p",{className:"text-muted-foreground",children:"We just sent you a magic link to claim your account and set up your password. Click the link in your email to get started!"})]}),e.jsxs("div",{className:"text-left space-y-3 mb-8",children:[e.jsx("p",{className:"text-sm text-muted-foreground font-medium uppercase tracking-wide",children:"What happens next:"}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"1"})}),e.jsx("p",{className:"text-foreground",children:"Check your email for the welcome message"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"2"})}),e.jsx("p",{className:"text-foreground",children:'Click "Claim Your Account" to set your password'})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"3"})}),e.jsx("p",{className:"text-foreground",children:"Start exploring all the features!"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:["Didn't receive the email? Check your spam folder or"," ",e.jsx("button",{onClick:()=>s("/trial"),className:"text-[#4a6b6d] hover:underline font-medium",children:"try again"})]}),e.jsxs(B,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(za,{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:dfe,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},hns=Zw({viewerName:go().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:go().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:go().max(20,"Phone must be less than 20 characters").optional(),message:go().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function mns({shareToken:s,agentName:t,hasContact:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),d=zye({resolver:Bye(hns),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:p,error:f}=await q.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:h.viewerName,viewerEmail:h.viewerEmail,viewerPhone:h.viewerPhone||void 0,message:h.message}});if(f)throw new Error(f.message);if(!(p!=null&&p.success))throw new Error((p==null?void 0:p.error)||"Failed to send reply");l(!0)}catch(p){console.error("Failed to submit reply:",p),c(p.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(fe,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Ae,{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(xr,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Message Sent!"}),e.jsxs("p",{className:"text-muted-foreground",children:[t?`${t} will`:"They'll"," get back to you soon."]})]})}):e.jsxs(fe,{children:[e.jsxs(Mt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ql,{className:"h-5 w-5 text-primary"}),e.jsx(Pt,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(Hn,{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(Ae,{children:e.jsx($ye,{...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(Cu,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Your Name *"}),e.jsx(lu,{children:e.jsx(ge,{placeholder:"John Smith",...h})}),e.jsx(Zx,{})]})}),e.jsx(Cu,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Email *"}),e.jsx(lu,{children:e.jsx(ge,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(Zx,{})]})})]}),!n&&e.jsx(Cu,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Phone (optional)"}),e.jsx(lu,{children:e.jsx(ge,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(Zx,{})]})}),e.jsx(Cu,{control:d.control,name:"message",render:({field:h})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Message *"}),e.jsx(lu,{children:e.jsx(Ts,{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(Zx,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx(B,{type:"submit",className:"w-full gap-2",disabled:r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const pns=()=>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(ua,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(ua,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(ua,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(ua,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(ua,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(Y2,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),fns=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-red-500/5 via-transparent to-blue-500/5"}),e.jsxs("div",{className:"absolute top-[10%] left-[15%] w-32 h-32",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-red-400/20 animate-ping",style:{animationDuration:"3s"}}),e.jsx(un,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 text-red-400/40"})]}),e.jsxs("div",{className:"absolute top-[5%] right-[20%] w-24 h-24",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-blue-400/20 animate-ping",style:{animationDuration:"4s",animationDelay:"1s"}}),e.jsx(ua,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-6 h-6 text-blue-400/40 fill-blue-400/20"})]}),e.jsxs("div",{className:"absolute top-[20%] left-[50%] w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border border-white/10 animate-ping",style:{animationDuration:"3.5s",animationDelay:"0.5s"}}),e.jsx(un,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-5 h-5 text-amber-400/40"})]}),e.jsx(ua,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(ua,{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(Y2,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),xns=()=>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(lb,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(lb,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(lb,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(lb,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(yi,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(yi,{className:"absolute top-[25%] right-[25%] w-4 h-4 text-pink-300/40 fill-pink-300/20 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(yi,{className:"absolute top-[10%] left-[60%] w-4 h-4 text-rose-400/30 fill-rose-400/15 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx("div",{className:"absolute top-[8%] left-[45%] w-8 h-8 rounded-full bg-pink-300/10 blur-sm"}),e.jsx("div",{className:"absolute bottom-[25%] right-[30%] w-6 h-6 rounded-full bg-rose-300/10 blur-sm"})]}),gns=()=>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(vc,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(ua,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(vc,{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(ua,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(ua,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),yns=()=>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(lb,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(lb,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(nL,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),vns=()=>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(EA,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(EA,{className:"absolute top-[10%] right-[12%] w-12 h-12 text-purple-400/20 animate-pulse"}),e.jsxs("div",{className:"absolute bottom-[18%] left-[8%]",children:[e.jsx("div",{className:"w-14 h-12 rounded-full bg-orange-500/20"}),e.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 w-2 h-4 bg-green-600/25 rounded-t-full"})]}),e.jsxs("div",{className:"absolute bottom-[22%] right-[12%]",children:[e.jsx("div",{className:"w-12 h-10 rounded-full bg-orange-400/15"}),e.jsx("div",{className:"absolute -top-1.5 left-1/2 -translate-x-1/2 w-1.5 h-3 bg-green-600/20 rounded-t-full"})]}),e.jsx("div",{className:"absolute top-[15%] left-[40%] opacity-20",children:e.jsx("svg",{viewBox:"0 0 24 12",className:"w-10 h-5 text-slate-800 fill-current",children:e.jsx("path",{d:"M12 6c-2-4-6-6-12-6 4 2 6 4 6 6s-2 4-6 6c6 0 10-2 12-6zm0 0c2-4 6-6 12-6-4 2-6 4-6 6s2 4 6 6c-6 0-10-2-12-6z"})})}),e.jsx(un,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(un,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),bns=()=>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(d4,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(d4,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(d4,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(Mv,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(Mv,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(Mv,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(Mv,{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(ua,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),_ns=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-orange-900/10 via-amber-800/6 to-red-900/10"}),e.jsx("div",{className:"absolute top-[5%] left-[10%] w-10 h-8 rounded-full bg-orange-500/25 rotate-45"}),e.jsx("div",{className:"absolute top-[10%] right-[15%] w-8 h-6 rounded-full bg-red-500/20 -rotate-12"}),e.jsx("div",{className:"absolute top-[15%] left-[35%] w-7 h-5 rounded-full bg-amber-500/22 rotate-30"}),e.jsx("div",{className:"absolute bottom-[18%] left-[12%] w-10 h-7 rounded-full bg-yellow-600/18 -rotate-45"}),e.jsx("div",{className:"absolute bottom-[22%] right-[10%] w-9 h-6 rounded-full bg-orange-600/15 rotate-12"}),e.jsxs("div",{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2",children:[e.jsx("div",{className:"w-16 h-14 rounded-full bg-orange-400/15"}),e.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 w-2 h-5 bg-green-600/18 rounded-t-full"})]}),e.jsx(yi,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(yi,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),wns=()=>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(ua,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(ua,{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(ua,{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(ua,{className:"absolute top-[12%] right-[35%] w-8 h-8 text-amber-300/28 fill-amber-300/18 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[20%] left-[25%] w-4 h-4 rounded-full bg-pink-400/30"}),e.jsx("div",{className:"absolute top-[18%] right-[30%] w-3 h-3 rounded-full bg-sky-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[60%] w-2.5 h-2.5 rounded-full bg-emerald-400/30"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-3 h-3 rounded-full bg-purple-400/30"}),e.jsx(un,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(uh,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(uh,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),jns=()=>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(ua,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(un,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(un,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),Nns=()=>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(O2,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(O2,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(O2,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(O2,{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"})]})]})]}),kns=()=>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(ua,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(ua,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(vc,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(vc,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(Y2,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),Sns=()=>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(hu,{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(uh,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Bi,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),Cns=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-rose-900/12 via-pink-900/8 to-red-900/12"}),e.jsx(yi,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(yi,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(yi,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(yi,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(yi,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(yi,{className:"absolute top-[20%] right-[35%] w-5 h-5 text-rose-300/35 fill-rose-300/20 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(yi,{className:"absolute top-[12%] left-[55%] w-5 h-5 text-red-300/30 fill-red-300/15 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(yi,{className:"absolute top-[25%] right-[25%] w-4 h-4 text-pink-400/30 fill-pink-400/15 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[18%] left-[45%] w-8 h-8 rounded-full bg-rose-300/18 blur-sm"}),e.jsx("div",{className:"absolute bottom-[25%] right-[40%] w-6 h-6 rounded-full bg-pink-300/15 blur-sm"})]}),Tns=()=>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(vb,{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(vb,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(un,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(vb,{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"})]}),Ens=()=>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(zr,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(zr,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(Gg,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(Gg,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(yi,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(yi,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(un,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(uh,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),Ans=()=>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(uh,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(uh,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(Gg,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(zr,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(un,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(un,{className:"absolute top-[20%] right-[32%] w-7 h-7 text-cyan-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[55%] w-3 h-3 bg-amber-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-2.5 h-2.5 bg-teal-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[28%] left-[35%] w-2 h-2 bg-emerald-400/30 rounded-full"})]}),Mns=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-amber-900/10 via-yellow-900/6 to-orange-900/10"}),e.jsx(Gg,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(Gg,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(Gg,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(zr,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(uh,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(un,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(ua,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),Ins=()=>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(zr,{className:"absolute bottom-[10%] left-[50%] -translate-x-1/2 w-20 h-20 text-teal-500/22"}),e.jsx("div",{className:"absolute bottom-[18%] left-[12%] w-12 h-10 bg-amber-400/18 rounded-sm"}),e.jsx("div",{className:"absolute bottom-[20%] left-[20%] w-10 h-8 bg-orange-400/15 rounded-sm"}),e.jsx("div",{className:"absolute bottom-[16%] right-[15%] w-11 h-9 bg-amber-300/18 rounded-sm"}),e.jsx(Gg,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(yi,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(un,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(gw,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),WUe=()=>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"})]}),Pns=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(yi,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(yi,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(yi,{className:"absolute top-4 left-[40%] w-2.5 h-2.5 text-rose-400/40 fill-rose-400/20 animate-pulse delay-300"}),e.jsx(yi,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),Lns=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(gw,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(un,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(zr,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),Dns=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(ry,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(hL,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(ry,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),xF=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(un,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(uh,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(un,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),KUe=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(zr,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(un,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(zr,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),NCe=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(un,{className:"h-5 w-5"}),category:"general",headerText:()=>"Video Message",subText:"A personal video just for you",gradientClasses:"from-background to-muted/30",accentColor:"primary"},{id:"thank_you",name:"Thank You",description:"Express your gratitude",icon:e.jsx(yi,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Thank You, ${s}!`:"Thank You!",subText:"Your support means the world to me",gradientClasses:"from-rose-50/70 via-pink-50/50 to-red-50/40 dark:from-rose-950/30 dark:via-pink-950/20 dark:to-red-950/20",accentColor:"rose",decorativeElement:e.jsx(Pns,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(Z7,{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(xF,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(ry,{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(Dns,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(yo,{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(_n,{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(xF,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(vc,{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(WUe,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(Ca,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Welcome to the Neighborhood, ${s}!`:"Welcome to the Neighborhood!",subText:"So excited to have you as our new neighbor",gradientClasses:"from-teal-50/70 via-cyan-50/50 to-sky-50/40 dark:from-teal-950/30 dark:via-cyan-950/20 dark:to-sky-950/20",accentColor:"teal",decorativeElement:e.jsx(KUe,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(hL,{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(xF,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(hu,{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(Sns,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(yi,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Valentine's Day, ${s}!`:"Happy Valentine's Day!",subText:"A heartfelt message from your real estate professional",gradientClasses:"from-rose-50/80 via-pink-50/60 to-red-50/40 dark:from-rose-950/30 dark:via-pink-950/20 dark:to-red-950/20",accentColor:"rose",decorativeElement:e.jsx(Cns,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(vb,{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(Tns,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(ua,{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(wns,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(nL,{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(yns,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(lb,{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(xns,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(vc,{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(gns,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(Y2,{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(pns,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(_c,{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(fns,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(vc,{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(kns,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(EA,{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(vns,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(yi,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Thanksgiving, ${s}!`:"Happy Thanksgiving!",subText:"Grateful for you and your friendship",gradientClasses:"from-orange-50/70 via-amber-50/50 to-red-50/40 dark:from-orange-950/30 dark:via-amber-950/20 dark:to-red-950/20",accentColor:"orange",decorativeElement:e.jsx(_ns,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(d4,{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(bns,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(un,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Hanukkah, ${s}!`:"Happy Hanukkah!",subText:"Wishing you eight nights of light and joy",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue",decorativeElement:e.jsx(jns,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(O2,{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(Nns,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(zr,{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(Ens,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(uh,{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(Ans,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(yr,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Exciting News, ${s}!`:"Just Listed!",subText:"A new property is now on the market",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-violet-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-violet-950/20",accentColor:"blue",decorativeElement:e.jsx(KUe,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(Zl,{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(xF,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(bb,{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(gw,{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(Lns,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(Gg,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Congratulations, ${s}!`:"Congratulations!",subText:"It's official – the keys are yours!",gradientClasses:"from-amber-50/70 via-yellow-50/50 to-orange-50/40 dark:from-amber-950/30 dark:via-yellow-950/20 dark:to-orange-950/20",accentColor:"amber",decorativeElement:e.jsx(Mns,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(zr,{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(Ins,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(Hm,{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(xF,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(vc,{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(WUe,{})}],Rns=[{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 Ons(s){return NCe.filter(t=>t.category===s)}function DL(s){return NCe.find(t=>t.id===s)||NCe[0]}function YUe(){const{shareToken:s,recipientToken:t}=_i(),[n,r]=N.useState(null),[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!0),[u,h]=N.useState(null),[p,f]=N.useState(!0),g=N.useRef(null),b=N.useRef(0),v=N.useRef(0),j=(()=>{const W=new URLSearchParams(window.location.search);return t||W.get("rt")||null})(),_=N.useCallback((W,K=!1)=>{if(!j||W<=0)return;const Y=Math.max(1,Math.round(W));if(Y<=v.current)return;const ne=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(j)}&e=watch&ws=${Y}`;K&&navigator.sendBeacon?navigator.sendBeacon(ne):fetch(ne,{method:"GET",keepalive:K}).catch(()=>{}),v.current=Math.max(v.current,Y)},[j]);N.useEffect(()=>{var pe;if(!p||!(n!=null&&n.playback_url)||!j)return;let W=!1;const K=()=>{b.current>0&&_(b.current,!0)},Y=()=>{document.visibilityState==="hidden"&&K()},ee=()=>{K()},ne=()=>{var de;if(W||!g.current||!((de=window.playerjs)!=null&&de.Player))return;const ce=new window.playerjs.Player(g.current);ce.on("timeupdate",ie=>{const ye=Math.floor(Number((ie==null?void 0:ie.seconds)??0));!Number.isFinite(ye)||ye<=0||(b.current=Math.max(b.current,ye))}),ce.on("pause",()=>{b.current>0&&_(b.current)}),ce.on("ended",()=>{b.current>0&&_(b.current,!0)})},oe=document.querySelector('script[data-bunny-playerjs="true"]');if((pe=window.playerjs)!=null&&pe.Player)ne();else if(oe)oe.addEventListener("load",ne,{once:!0});else{const ce=document.createElement("script");ce.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",ce.async=!0,ce.defer=!0,ce.dataset.bunnyPlayerjs="true",ce.onload=ne,document.body.appendChild(ce)}return document.addEventListener("visibilitychange",Y),window.addEventListener("beforeunload",ee),()=>{W=!0,document.removeEventListener("visibilitychange",Y),window.removeEventListener("beforeunload",ee),K()}},[p,n==null?void 0:n.playback_url,j,_]),N.useEffect(()=>{b.current=0,v.current=0},[j,s]),N.useEffect(()=>{const W=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="msgsndr"]',"[data-chat-widget]"].forEach(ne=>{document.querySelectorAll(ne).forEach(oe=>{oe.style.display="none"})})};W();const K=[setTimeout(W,500),setTimeout(W,1500),setTimeout(W,3e3)],Y=new MutationObserver(W);return Y.observe(document.body,{childList:!0,subtree:!0}),()=>{K.forEach(clearTimeout),Y.disconnect()}},[]),N.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:K,error:Y}=await q.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if(Y||!K){h("Video not found or has been removed"),d(!1);return}r(K);try{await q.rpc("log_video_view",{p_video_id:K.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(ee){console.warn("Failed to log video view:",ee)}if(K.owner_user_id){const{data:ee}=await q.from("profiles").select("id, name, email, phone").eq("id",K.owner_user_id).single();if(ee){i(ee);try{const{data:ne}=await q.storage.from("avatars").list(`${K.owner_user_id}`);if(ne&&ne.length>0){const{data:oe}=q.storage.from("avatars").getPublicUrl(`${K.owner_user_id}/${ne[0].name}`);o(oe.publicUrl)}}catch{}}}d(!1)})()},[s]);const S=W=>{if(!W)return"0:00";const K=Math.floor(W/60),Y=W%60;return`${K}:${Y.toString().padStart(2,"0")}`},A=W=>W.includes("iframe.mediadelivery.net/play/")?W.replace("/play/","/embed/")+"?autoplay=true&responsive=true":W,T=W=>{if(!W)return"?";const K=W.split(" ");return K.length>=2?`${K[0][0]}${K[1][0]}`.toUpperCase():W.substring(0,2).toUpperCase()},D=DL((n==null?void 0:n.page_template)||"default"),L=(n==null?void 0:n.recipient_name)||null,M=D.headerText(L),z=`https://dashboard.relevelup.com/share/video/${s}`;if(c)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-primary"})});if(u||!n)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsx(fe,{className:"max-w-md w-full",children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx(vr,{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 V=D.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsx("title",{children:M}),e.jsx("meta",{name:"description",content:D.subText}),e.jsx("meta",{property:"og:title",content:M}),e.jsx("meta",{property:"og:description",content:D.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:z}),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:M}),e.jsx("meta",{name:"twitter:description",content:D.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:Et("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",D.gradientClasses),children:[V&&D.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[V&&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:Et("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",D.accentColor==="primary"&&"bg-primary/10 text-primary",D.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",D.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",D.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",D.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",D.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",D.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",D.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",D.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",D.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",D.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",D.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",D.accentColor==="sky"&&"bg-sky-100 text-sky-600 dark:bg-sky-900/50 dark:text-sky-400"),children:e.jsx("div",{className:"scale-150",children:D.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:M}),e.jsx("p",{className:"text-muted-foreground",children:D.subText})]}),a&&e.jsxs("div",{className:"flex items-center gap-4 p-4 bg-card/90 backdrop-blur-sm rounded-lg border shadow-sm",children:[e.jsxs(aa,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(ri,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(ia,{className:"bg-primary/10 text-primary font-semibold",children:T(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:V?"A special video from":"A personal video from"}),e.jsx("h2",{className:"text-lg font-semibold truncate",children:a.name||"Your Agent"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Real Estate Professional"})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[a.phone&&e.jsx(B,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`tel:${a.phone}`,"aria-label":"Call agent",children:e.jsx(Pr,{className:"h-4 w-4"})})}),a.email&&e.jsx(B,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`mailto:${a.email}`,"aria-label":"Email agent",children:e.jsx(Hs,{className:"h-4 w-4"})})})]})]}),e.jsx(fe,{className:"overflow-hidden shadow-lg",children:p&&n.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:g,src:A(n.playback_url),title:n.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>f(!0),children:[n.preview_url||n.thumbnail_url?e.jsx("img",{src:n.preview_url||n.thumbnail_url||"",alt:n.title?`${n.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:W=>{var Y;W.currentTarget.style.display="none";const K=(Y=W.currentTarget.parentElement)==null?void 0:Y.querySelector(".video-fallback");K&&(K.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(vr,{className:"h-16 w-16 text-primary/50"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/40 transition-colors",children:e.jsx("div",{className:"w-20 h-20 rounded-full bg-white/90 flex items-center justify-center shadow-lg transform group-hover:scale-105 transition-transform",children:e.jsx(Al,{className:"h-10 w-10 text-primary ml-1"})})}),n.duration_seconds&&e.jsx("div",{className:"absolute bottom-3 right-3 bg-black/70 text-white text-sm px-2 py-1 rounded",children:S(n.duration_seconds)})]})}),!V&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:p?"Enjoy the video!":"Click to play the video"})]}),!p&&e.jsx("div",{className:"flex justify-center",children:e.jsxs(B,{size:"lg",onClick:()=>f(!0),className:"gap-2",children:[e.jsx(Al,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(mns,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function Fns(){return N.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(Bat,{})}function zns(){const{token:s}=_i();return N.useEffect(()=>{if(!s)return;const t=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/video-og-image?token=${s}`;window.location.replace(t)},[s]),e.jsx("main",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(ss,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const Bns={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},$ns=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function Uns(){var ye;const[s]=yl(),t=s.get("r"),n=s.get("m"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!0),[d,u]=N.useState(0),[h,p]=N.useState(!1),[f,g]=N.useState(""),[b,v]=N.useState(""),[j,_]=N.useState(""),[S,A]=N.useState(""),[T,D]=N.useState("tour"),[L,M]=N.useState(!1),[F,z]=N.useState(!1),V=async()=>{if(!f.trim()||!b.trim()){ae.error("Please enter your name and email");return}M(!0);try{const Me=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:n,name:f.trim(),email:b.trim(),phone:j.trim()||null,message:S.trim()||null,intent:T})}),Te=await Me.json();if(!Me.ok||!(Te!=null&&Te.success))throw new Error((Te==null?void 0:Te.error)||"Could not send");z(!0),ae.success("Sent! The agent will be in touch shortly.")}catch(_e){ae.error((_e==null?void 0:_e.message)||"Could not send")}finally{M(!1)}};if(N.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const _e=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(_e).then(Me=>Me.json()).then(Me=>{Me.error?l("This private listing link is no longer valid."):a({listing:Me.listing,agent:Me.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(Yo,{children:e.jsx("meta",{name:"robots",content:"noindex,nofollow,noarchive"})}),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50 px-6 text-center",children:e.jsxs("div",{children:[e.jsx(Rc,{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:W,agent:K}=r,Y=(ye=W.photos)!=null&&ye.length?W.photos:[],ee=Y[0],ne=Bns[W.status]||W.status,oe=(K==null?void 0:K.sender_name)||(K==null?void 0:K.name)||"Your Agent",pe=(K==null?void 0:K.sender_email)||null,ce=encodeURIComponent(`Interested in ${W.address}`),de=encodeURIComponent(`Hi ${oe}, I'd love to learn more about ${W.address}, ${W.city}. Thanks!`),ie=K!=null&&K.booking_slug?`https://dashboard.relevelup.com/book/${K.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsxs("title",{children:["Private Listing · ",W.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(Rc,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",oe]})]}),e.jsxs("div",{className:"relative",children:[ee?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),p(!0)},children:e.jsx("img",{src:ee,alt:W.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(ze,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:ne})}),Y.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:[Y.length," photos"]})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-10 relative z-10",children:[e.jsx(fe,{className:"shadow-xl border-slate-200",children:e.jsxs(Ae,{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:W.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(Ca,{className:"h-4 w-4"}),W.city,", ",W.state," ",W.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:$ns(W.price)})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[W.bedrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(ny,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:W.bedrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Beds"})]}):null,W.bathrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(Tp,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:W.bathrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Baths"})]}):null,W.sqft?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(cy,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:W.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),W.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:W.description})]}),Y.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:Y.slice(0,9).map((_e,Me)=>e.jsx("button",{type:"button",onClick:()=>{u(Me),p(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:_e,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},Me))})]})]})}),e.jsxs(fe,{className:"mt-6 shadow-lg border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-indigo-600 to-indigo-500 px-6 py-4 text-white",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Request more info or a private tour"}),e.jsxs("p",{className:"text-indigo-100 text-sm",children:[oe," will get back to you personally."]})]}),e.jsx(Ae,{className:"p-6 sm:p-8",children:F?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(xr,{className:"h-12 w-12 text-emerald-500 mb-3"}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Message sent"}),e.jsxs("p",{className:"text-slate-600 mt-1",children:[oe," just got your request and will reach out shortly."]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{id:"tour",label:"Private tour"},{id:"info",label:"More info"},{id:"offer",label:"Make an offer"}].map(_e=>e.jsx("button",{type:"button",onClick:()=>D(_e.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${T===_e.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:_e.label},_e.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(ge,{id:"pl-name",value:f,onChange:_e=>g(_e.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-email",children:"Email *"}),e.jsx(ge,{id:"pl-email",type:"email",value:b,onChange:_e=>v(_e.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(ge,{id:"pl-phone",value:j,onChange:_e=>_(_e.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Ts,{id:"pl-msg",value:S,onChange:_e=>A(_e.target.value),placeholder:`I'd love to see ${W.address}…`,rows:4,maxLength:2e3})]}),e.jsx(B,{onClick:V,disabled:L,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:L?"Sending…":"Send to "+oe.split(" ")[0]}),e.jsx("p",{className:"text-xs text-slate-500 text-center",children:"By submitting, you agree to be contacted about this property."})]})})]}),e.jsx(fe,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(Ae,{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:[K!=null&&K.avatar_url?e.jsx("img",{src:K.avatar_url,alt:oe,className:"h-20 w-20 rounded-full object-cover ring-2 ring-indigo-100"}):e.jsx("div",{className:"h-20 w-20 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 text-2xl font-bold",children:oe.charAt(0)}),e.jsxs("div",{className:"flex-1 text-center sm:text-left",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-500",children:"Shared by"}),e.jsx("h3",{className:"text-xl font-bold text-slate-900",children:oe}),(K==null?void 0:K.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:K.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:[pe&&e.jsx(B,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${pe}?subject=${ce}&body=${de}`,children:[e.jsx(Hs,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(K==null?void 0:K.phone)&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${K.phone}`,children:[e.jsx(Pr,{className:"h-4 w-4 mr-1.5"}),K.phone]})}),ie&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:ie,target:"_blank",rel:"noreferrer",children:[e.jsx(cm,{className:"h-4 w-4 mr-1.5"}),"Book a tour"]})})]})]})})]}),h&&Y.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",children:[e.jsx("button",{className:"absolute top-4 right-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>p(!1),"aria-label":"Close",children:e.jsx(Fn,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(_e=>(_e-1+Y.length)%Y.length),"aria-label":"Previous",children:e.jsx(fl,{className:"h-8 w-8"})}),e.jsx("img",{src:Y[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(_e=>(_e+1)%Y.length),"aria-label":"Next",children:e.jsx(ga,{className:"h-8 w-8"})}),e.jsxs("p",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white/80 text-sm",children:[d+1," / ",Y.length]})]})]})]})}function qns(){var i;const{slug:s}=_i(),{data:t,isLoading:n,error:r}=jct(s);if(N.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),N.useEffect(()=>{t!=null&&t.id&&pl(t.id,"card_view")},[t==null?void 0:t.id]),n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Ws,{className:"h-28 w-28 rounded-full"}),e.jsx(Ws,{className:"h-6 w-48"}),e.jsx(Ws,{className:"h-4 w-36"})]}),e.jsx(Ws,{className:"h-12 w-full"}),e.jsx(Ws,{className:"h-12 w-full"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsxs("title",{children:[a," | Real Estate Agent"]}),e.jsx("meta",{name:"description",content:t.positioning_statement||`Connect with ${a}, your trusted real estate professional.`}),e.jsx("meta",{property:"og:title",content:`${a} | Real Estate Agent`}),e.jsx("meta",{property:"og:description",content:t.positioning_statement||`Connect with ${a}`}),t.avatar_url&&e.jsx("meta",{property:"og:image",content:t.avatar_url})]}),e.jsx(aMe,{card:t})]})}const Vns="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",Hns="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",Gns="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",Wns="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",Kns="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",Yns="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",Wme={"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:Yns},"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:Vns},"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:Hns},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:Gns},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:Wns},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:Kns}},Zns=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function tpt(s){return s&&s in Wme?Wme[s]:Wme["minimal-mono"]}function Qns(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 spt({slugOverride:s}={}){var Ys;const{slug:t}=_i(),n=s||t,[r]=yl(),a=r.get("t"),[i,l]=N.useState(!0),[o,c]=N.useState(null),[d,u]=N.useState(null),h=N.useRef(null),p=N.useRef(null),[f,g]=N.useState(null),[b,v]=N.useState(null),[j,_]=N.useState(!1),[S,A]=N.useState(!1),[T,D]=N.useState(0),[L,M]=N.useState(!1),[F,z]=N.useState(""),[V,W]=N.useState(""),[K,Y]=N.useState(""),[ee,ne]=N.useState(""),[oe,pe]=N.useState(""),[ce,de]=N.useState(""),[ie,ye]=N.useState(""),[_e,Me]=N.useState(""),[Te,Ce]=N.useState(""),[Ee,De]=N.useState(""),[Ie,Fe]=N.useState(""),[qe,ve]=N.useState(""),[Je,we]=N.useState(""),[it,Ne]=N.useState([]),[He,$e]=N.useState([]),[Ye,Ke]=N.useState(""),[rt,tt]=N.useState(""),[at,Ge]=N.useState(""),[dt,Bt]=N.useState([]);N.useEffect(()=>{kt()},[n,a]);const kt=async()=>{if(!n)return;l(!0);const{data:Ss,error:Bs}=await q.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(Bs||!Ss){M(!0),l(!1);return}u(Ss),p.current=Ss;const{data:Us}=await q.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Ss.user_id).single();if(Us){let sn;if(Us.brokerage_id){const{data:Sn}=await q.from("brokerages").select("name").eq("id",Us.brokerage_id).single();sn=(Sn==null?void 0:Sn.name)||void 0}let Jn=Us.avatar_url||null;if(!Jn){const{data:Sn}=q.storage.from("avatars").getPublicUrl(`${Ss.user_id}/avatar.jpg`);Sn!=null&&Sn.publicUrl&&(Jn=`${Sn.publicUrl}?t=${Date.now()}`)}const fn={...Us,avatar_url:Jn,brokerage_name:sn};c(fn),h.current=fn}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Ss.id);const{data:sn,error:Jn}=await q.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Ss.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:sn,resolveErr:Jn}),!Jn&&(sn!=null&&sn.contact_id)){v(sn.contact_id);const fn=sn.contact;fn&&(g(fn),z(fn.first_name||""),W(fn.last_name||""),Y(fn.email||""),ne(fn.phone||""),pe(fn.address||""),de(fn.city||""),ye(fn.state||""),Me(fn.zip||""),Ce(fn.birthday||""),De(fn.home_anniversary||""))}}catch(sn){console.error("Failed to resolve token:",sn)}l(!1)},Qt=async()=>{var Ss,Bs;if(!F.trim()){ae.error("Please enter your first name");return}if(!n){ae.error("Invalid page. Please refresh.");return}A(!0);try{let Us=(Ss=p.current)==null?void 0:Ss.id,sn=(Bs=p.current)==null?void 0:Bs.user_id;if(!Us||!sn){const{data:Sn}=await q.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!Sn){ae.error("This page is no longer active. Please contact the agent directly."),A(!1);return}Us=Sn.id,sn=Sn.user_id}const Jn={intake_page_id:Us,agent_user_id:sn,existing_contact_id:b,first_name:F.trim(),last_name:V.trim()||null,email:K.trim()||null,phone:ee.trim()||null,address:oe.trim()||null,city:ce.trim()||null,state:ie.trim()||null,zip:_e.trim()||null,birthday:Te||null,home_anniversary:Ee||null,real_estate_interest:Ie||null,message:qe.trim()||null,life_events:{spouse_name:Je.trim()||null,kids:it.filter(Sn=>Sn.name.trim()),pets:He.filter(Sn=>Sn.name.trim()),favorite_spots:Ye.trim()||null,dream_neighborhood:rt.trim()||null,wedding_anniversary:at||null},referrals:dt.filter(Sn=>Sn.name.trim()&&Sn.contact.trim())},{error:fn}=await q.from("contact_intake_submissions").insert(Jn);if(console.log("[ConnectPage] Insert result:",{error:fn}),fn)throw fn;a&&await q.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Sn=[F.trim(),V.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:sn,contactName:Sn,contactEmail:K.trim()||null,contactPhone:ee.trim()||null,slug:n})})}catch(Sn){console.warn("Connect page notification failed (non-blocking):",Sn)}_(!0)}catch(Us){console.error(Us),ae.error("Something went wrong. Please try again.")}finally{A(!1)}};if(i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-slate-400"})});if(L)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(j)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50 p-4",children:[e.jsx(Yo,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Zn.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"max-w-md w-full text-center space-y-6 p-8",children:[e.jsx(Zn.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",delay:.2},className:"mx-auto w-20 h-20 rounded-full bg-emerald-100 flex items-center justify-center",children:e.jsx(xr,{className:"h-10 w-10 text-emerald-600"})}),e.jsx("h1",{className:"text-3xl font-bold text-slate-800",children:"Thank You!"}),e.jsxs("p",{className:"text-lg text-slate-600",children:[o==null?void 0:o.name," has received your info and will be in touch soon."]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 text-sm text-slate-400 pt-4",children:[e.jsx(yi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const ns=!!a&&!!f,$s=(d==null?void 0:d.show_little_things)??!0,Ds=[{title:ns?"Confirm Your Info":"Let's Get Connected",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"First Name *"}),e.jsx("input",{type:"text",value:F,onChange:Ss=>z(Ss.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:V,onChange:Ss=>W(Ss.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:K,onChange:Ss=>Y(Ss.target.value),placeholder:"jane@email.com",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Phone"}),e.jsx("input",{type:"tel",value:ee,onChange:Ss=>ne(Ss.target.value),placeholder:"(555) 123-4567",className:"connect-input"})]})]})},{title:"A Little More About You",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Street Address"}),e.jsx("input",{type:"text",value:oe,onChange:Ss=>pe(Ss.target.value),placeholder:"123 Main St",className:"connect-input"})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),e.jsx("input",{type:"text",value:ce,onChange:Ss=>de(Ss.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:ie,onChange:Ss=>ye(Ss.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:_e,onChange:Ss=>Me(Ss.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:Te,onChange:Ss=>Ce(Ss.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:Ee,onChange:Ss=>De(Ss.target.value),className:"connect-input"})]})]})]})},...$s?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),e.jsx("input",{type:"text",value:Je,onChange:Ss=>we(Ss.target.value),placeholder:"Alex",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),e.jsx("input",{type:"date",value:at,onChange:Ss=>Ge(Ss.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:()=>Ne(Ss=>[...Ss,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(As,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[it.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),it.map((Ss,Bs)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ss.name,onChange:Us=>Ne(sn=>sn.map((Jn,fn)=>fn===Bs?{...Jn,name:Us.target.value}:Jn)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ss.age,onChange:Us=>Ne(sn=>sn.map((Jn,fn)=>fn===Bs?{...Jn,age:Us.target.value}:Jn)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Ne(Us=>Us.filter((sn,Jn)=>Jn!==Bs)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(Fn,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Bs))]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Pets"}),e.jsxs("button",{type:"button",onClick:()=>$e(Ss=>[...Ss,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(As,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[He.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),He.map((Ss,Bs)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ss.name,onChange:Us=>$e(sn=>sn.map((Jn,fn)=>fn===Bs?{...Jn,name:Us.target.value}:Jn)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ss.kind,onChange:Us=>$e(sn=>sn.map((Jn,fn)=>fn===Bs?{...Jn,kind:Us.target.value}:Jn)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>$e(Us=>Us.filter((sn,Jn)=>Jn!==Bs)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(Fn,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Bs))]})]}),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:Ye,onChange:Ss=>Ke(Ss.target.value),placeholder:"That coffee shop on Main, Town Lake…",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Dream neighborhood"}),e.jsx("input",{type:"text",value:rt,onChange:Ss=>tt(Ss.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."})]}),dt.length<3&&e.jsxs("button",{type:"button",onClick:()=>Bt(Ss=>[...Ss,{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(As,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:dt.map((Ss,Bs)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ss.name,onChange:Us=>Bt(sn=>sn.map((Jn,fn)=>fn===Bs?{...Jn,name:Us.target.value}:Jn)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ss.contact,onChange:Us=>Bt(sn=>sn.map((Jn,fn)=>fn===Bs?{...Jn,contact:Us.target.value}:Jn)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>Bt(Us=>Us.filter((sn,Jn)=>Jn!==Bs)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(Fn,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Bs))})]})]})}]:[],{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(Ss=>e.jsxs("button",{type:"button",onClick:()=>Fe(Ie===Ss.value?"":Ss.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Ie===Ss.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:Ss.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Ss.desc})]},Ss.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:qe,onChange:Ss=>ve(Ss.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],Dt=Ds.length,St=tpt(d==null?void 0:d.theme),$t=Qns(St,(d==null?void 0:d.accent_color)||null),ht=(d==null?void 0:d.cover_image_url)||St.defaultCover,Ut=(d==null?void 0:d.headline)||"Let's stay connected",Es=(d==null?void 0:d.subheadline)||(o!=null&&o.brokerage_name?`${o==null?void 0:o.name} · ${o.brokerage_name}`:(o==null?void 0:o.name)||""),Xt=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:$t,children:[e.jsxs(Yo,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${Ut} — ${(o==null?void 0:o.name)||"your agent"}`}),ht&&e.jsx("meta",{property:"og:image",content:ht}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:Ut}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsx("style",{children:` .connect-shell { font-family: var(--c-body-font); color: var(--c-text); } .connect-shell h1, .connect-shell h2 { font-family: var(--c-heading-font); } .connect-input { width: 100%; padding: 0.75rem 1rem; border-radius: 0.75rem; border: 1px solid var(--c-border); background: var(--c-surface); color: var(--c-text); font-family: var(--c-body-font); font-size: 0.95rem; transition: border-color 150ms, box-shadow 150ms; } .connect-input::placeholder { color: var(--c-text-muted); opacity: 0.7; } .connect-input:focus { outline: none; border-color: var(--c-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c-accent) 25%, transparent); } `}),e.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[e.jsx(Zn.img,{src:ht,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[e.jsx(Zn.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:St.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Ut}),Es&&e.jsx(Zn.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:Es})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(Zn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.25},className:"text-center mb-6",children:[o!=null&&o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-24 h-24 rounded-full object-cover mx-auto shadow-xl",style:{border:"4px solid var(--c-surface)"}}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center shadow-xl",style:{background:St.accent,color:St.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((Ys=o==null?void 0:o.name)==null?void 0:Ys.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(Pr,{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(Hs,{className:"h-4 w-4"})})]})]}),e.jsx(Zn.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.35},className:"text-center mb-6 px-2 leading-relaxed text-sm",style:{color:"var(--c-text-muted)"},children:(d==null?void 0:d.welcome_message)||"I'd love to stay in touch — just a few quick details."}),e.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:Dt}).map((Ss,Bs)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:Bs<=T?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},Bs))}),e.jsxs(Zn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.4},className:"rounded-2xl p-6 sm:p-8",style:{background:"var(--c-surface)",border:"1px solid var(--c-border)",boxShadow:Xt?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(Pye,{mode:"wait",children:e.jsxs(Zn.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:Ds[T].title})]}),Ds[T].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:Ds[T].subtitle})]}),Ds[T].fields]},T)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[T>0?e.jsx("button",{type:"button",onClick:()=>D(Ss=>Ss-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",{}),T{if(T===0&&!F.trim()){ae.error("Please enter your first name");return}D(Ss=>Ss+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:()=>Qt(),disabled:S,className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm disabled:opacity-50 flex items-center gap-2",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:S?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),T>0&&TD(Ss=>Ss+1),className:"text-xs transition-opacity hover:opacity-80",style:{color:"var(--c-text-muted)"},children:"Skip this step"})})]}),e.jsx("div",{className:"text-center mt-8",children:e.jsxs("div",{className:"flex items-center justify-center gap-1 text-xs",style:{color:"var(--c-text-muted)"},children:[e.jsx(yi,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const QD=()=>({trackEngagement:N.useCallback(async(t,n,r,a="view")=>{try{const{data:{user:i}}=await q.auth.getUser();if(!i)return;await q.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:n,resource_title:r,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function gF({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=N.useState(0),[i,l]=N.useState(!1),{trackEngagement:o}=QD(),c=N.useCallback(f=>{o("newsletter",f.id,f.title,"click_link")},[o]),d=N.useCallback(()=>{a(f=>(f+1)%s.length)},[s.length]),u=N.useCallback(()=>{a(f=>(f-1+s.length)%s.length)},[s.length]),h=N.useCallback(f=>{a(f)},[]);if(N.useEffect(()=>{if(s.length<=1||i)return;const f=setInterval(d,t);return()=>clearInterval(f)},[s.length,i,t,d]),!s||s.length===0)return null;const p=s[r];return e.jsxs("div",{className:Et("relative w-full overflow-hidden rounded-xl",n),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[e.jsxs("div",{className:"relative aspect-[21/9] md:aspect-[3/1] w-full",children:[e.jsx("img",{src:p.image_url,alt:p.title,className:"w-full h-full object-cover rounded-t-xl"}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",className:Et("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(fl,{className:"h-6 w-6"})}),e.jsx(B,{variant:"ghost",size:"icon",className:Et("absolute right-2 top-1/2 -translate-y-1/2 bg-black/30 hover:bg-black/50 text-white rounded-full","opacity-0 transition-opacity",i&&"opacity-100"),onClick:d,children:e.jsx(ga,{className:"h-6 w-6"})})]}),s.length>1&&e.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-2",children:s.map((f,g)=>e.jsx("button",{onClick:()=>h(g),className:Et("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:p.title}),p.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:p.description})]}),p.link_url&&e.jsx("a",{href:p.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(p),children:e.jsx(B,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:p.link_text||"Learn More"})})]})]})}function Xns(s){return"EST"}function vB(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=Xns();return`${n} ${r}`}function RL(s){const t=new Date,n=new Date(s),r=CP(n,-15),a=CP(n,30);return t>a?"ended":Q1(t,{start:n,end:a})?"live":Q1(t,{start:r,end:n})?"starting_soon":"upcoming"}function b6e(s){const t=RL(s);return t==="starting_soon"||t==="live"}const ZUe=b6e,Jns=({events:s,registrations:t,onNavigateToEvents:n})=>{const[r,a]=N.useState(new Date);N.useEffect(()=>{const f=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(f)},[]);const i=s.filter(f=>b6e(f.event_date));if(i.length===0)return null;const l=i[0],o=RL(l.event_date),c=t.find(f=>f.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,u=!!c,h=o==="live",p=h?{container:"from-red-500/10 via-red-500/5 to-primary/10 border-red-500/30",pulse:"from-red-500/5",indicator:"bg-red-500",text:"text-red-500",button:"bg-red-500 hover:bg-red-600",outlineButton:"border-red-500/50 text-red-500 hover:bg-red-500/10"}:{container:"from-amber-500/10 via-amber-500/5 to-primary/10 border-amber-500/30",pulse:"from-amber-500/5",indicator:"bg-amber-500",text:"text-amber-500",button:"bg-amber-500 hover:bg-amber-600",outlineButton:"border-amber-500/50 text-amber-500 hover:bg-amber-500/10"};return e.jsxs("div",{className:`relative mb-8 overflow-hidden rounded-xl bg-gradient-to-r ${p.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${p.pulse} to-transparent animate-pulse`}),e.jsx("div",{className:"relative p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex items-center justify-center",children:[e.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${p.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${p.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${p.text} font-bold text-sm uppercase tracking-wider`,children:h?e.jsxs(e.Fragment,{children:[e.jsx(wf,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(gr,{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 ${vB(new Date(l.event_date))}`:`Starts at ${vB(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:u?e.jsxs(B,{onClick:()=>window.open(d,"_blank"),className:`${p.button} text-white gap-2`,children:[e.jsx(tr,{className:"h-4 w-4"}),h?"Join Now":"Join When Live"]}):e.jsxs(B,{variant:"outline",onClick:n,className:`${p.outlineButton} gap-2`,children:[e.jsx(_n,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function bh(){const{user:s}=gs(),{data:t,isLoading:n}=lt({queryKey:["gmail-integration",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:h,error:p}=await q.from("gmail_integrations").select("*").eq("user_id",s.id).maybeSingle();if(p)throw p;return h}}),{data:r,isLoading:a}=lt({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:h}=await q.from("user_verified_senders").select("email, status").eq("user_id",s.id).eq("status","verified").order("verified_at",{ascending:!1}).limit(1).maybeSingle();return h}}),i=!!(t!=null&&t.is_active),l=(t==null?void 0:t.gmail_email)||null,o=!!(r!=null&&r.email),c=(r==null?void 0:r.email)||null;return{isGmailConnected:i,gmailEmail:l,hasVerifiedSes:o,sesEmail:c,canSendEmail:i||o,sendMethod:i?"gmail":o?"mass_email":"none",isLoading:n||a}}function ers(){const{user:s}=gs(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=bh(),[a,i]=N.useState(!1),[l,o]=N.useState(!1);N.useEffect(()=>{s!=null&&s.id&&q.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle().then(({data:j})=>{i(!!j),o(!0)})},[s==null?void 0:s.id]);const{data:c,isLoading:d}=lt({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[j,_,S,A,T]=await Promise.all([q.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),q.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),q.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),q.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),q.from("events").select("id, title, event_date, image_url").eq("is_published",!0).gte("event_date",new Date().toISOString()).or("title.ilike.%onboarding%,title.ilike.%new member%,title.ilike.%welcome%,description.ilike.%new member onboarding%").order("event_date",{ascending:!0}).limit(1).maybeSingle()]),D=j.data,L=!!(D!=null&&D.avatar_url&&(D!=null&&D.phone)&&(D!=null&&D.bio)),M=_.count||0,F=(S.count||0)>0,z=A.count||0;return{profile:D,profileComplete:L,contactsCount:M,contactsComplete:M>=5,eventsRegistered:F,communityComplete:z>0,nextOnboardingEvent:T.data||null}}}),u=t||n,h=[{id:"profile",complete:!!(c!=null&&c.profileComplete)},{id:"email",complete:u},{id:"contacts",complete:!!(c!=null&&c.contactsComplete)},{id:"event",complete:!!(c!=null&&c.eventsRegistered)},{id:"community",complete:!!(c!=null&&c.communityComplete)}],p=h.filter(j=>j.complete).length,f=h.length;return{steps:h,completedCount:p,totalCount:f,allComplete:p===f,dismissed:a,dismiss:async()=>{s!=null&&s.id&&(i(!0),await q.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(i(!1),await q.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:c,isGmailConnected:t,hasVerifiedSes:n,loading:d||r||!l}}const trs={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:Xi,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:Hs,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:_n,accent:"from-[#c9a84c] to-[#e8c76f]",cta:"Add Contacts"},event:{title:"Register for New Member Onboarding",description:"Join our live LevelUp onboarding session to hit the ground running.",icon:yr,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:Ci,accent:"from-[#ec4899] to-[#f472b6]",cta:"Visit Community"}};function srs(){var b,v;const s=In(),{user:t}=gs(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=ers(),[u,h]=N.useState(!0);if(d||l||i)return null;const p=(((b=c==null?void 0:c.profile)==null?void 0:b.name)||((v=t==null?void 0:t.user_metadata)==null?void 0:v.name)||"there").split(" ")[0],f=r/a*100,g=async j=>{switch(j){case"profile":s("/profile");break;case"email":s("/mission-control/integrations");break;case"contacts":s("/mission-control/contacts");break;case"event":{const _=c==null?void 0:c.nextOnboardingEvent;if(!_){s("/events");return}if(!(t!=null&&t.id))return;const{error:S}=await q.from("event_registrations").insert({user_id:t.id,event_id:_.id});S&&!String(S.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}};return e.jsxs(fe,{className:"mb-6 overflow-hidden border-0 shadow-lg",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345a75] to-[#406E71] p-6 md:p-8 text-white",children:[e.jsx("button",{onClick:o,className:"absolute top-4 right-4 p-1.5 rounded-full hover:bg-white/10 transition","aria-label":"Dismiss",children:e.jsx(Fn,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"hidden sm:flex h-12 w-12 rounded-xl bg-white/15 backdrop-blur items-center justify-center shrink-0",children:e.jsx(un,{className:"h-6 w-6 text-[#f5f0e0]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h2",{className:"text-xl md:text-2xl font-bold",children:["Welcome to LevelUp, ",p,"! 👋"]}),e.jsx("p",{className:"text-white/80 mt-1 text-sm md:text-base",children:"Let's get you set up in under 10 minutes."}),e.jsxs("div",{className:"mt-4 max-w-md",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1.5 text-white/90",children:[e.jsxs("span",{className:"font-medium",children:[r," of ",a," complete"]}),e.jsxs("span",{children:[a-r," steps left"]})]}),e.jsx(xi,{value:f,className:"h-2 bg-white/20 [&>div]:bg-[#f5f0e0]"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3",children:[e.jsxs(B,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(za,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(j=>!j),className:"text-sm text-white/80 hover:text-white flex items-center gap-1",children:u?e.jsxs(e.Fragment,{children:["Hide steps ",e.jsx(sx,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(io,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Ae,{className:"p-4 md:p-6 bg-gradient-to-b from-background to-muted/30",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:n.map(j=>{const _=trs[j.id],S=_.icon;return e.jsx("div",{className:Et("relative rounded-xl border p-4 transition-all group",j.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!j.complete&&g(j.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Et("h-10 w-10 rounded-lg flex items-center justify-center shrink-0 bg-gradient-to-br text-white",j.complete?"from-emerald-500 to-emerald-600":_.accent),children:j.complete?e.jsx(xr,{className:"h-5 w-5"}):e.jsx(S,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h3",{className:Et("font-semibold text-sm",j.complete&&"text-muted-foreground line-through"),children:_.title})}),e.jsx("p",{className:Et("text-xs text-muted-foreground mt-1 leading-relaxed",j.complete&&"line-through"),children:_.description}),j.id==="event"&&!j.complete&&(c==null?void 0:c.nextOnboardingEvent)&&e.jsxs("div",{className:"mt-2 text-xs font-medium text-primary",children:[new Date(c.nextOnboardingEvent.event_date).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"America/New_York"})," ","ET"]}),!j.complete&&e.jsxs(B,{size:"sm",variant:"ghost",className:"mt-2 h-7 px-2 -ml-2 text-primary hover:text-primary hover:bg-primary/10",onClick:A=>{A.stopPropagation(),g(j.id)},children:[_.cta," ",e.jsx(za,{className:"h-3 w-3 ml-1"})]})]}),j.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},j.id)})})})]})}const Cy=()=>lt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await q.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),lx=s=>{const t=fa(),n=1e3,r=async a=>{const i=[];let l=0;for(;;){const{data:o,error:c}=await a.range(l,l+n-1);if(c)throw c;const d=o??[];if(i.push(...d),d.length{let a=q.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");return await r(a)},enabled:!!t})},nrs=s=>lt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:n}=await q.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),npt=()=>{const s=fa();return lt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:n}=await q.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(n)throw n;const r={};return t==null||t.forEach(a=>{var i;(i=a.tags)==null||i.forEach(l=>{r[l.relationship_type_id]=(r[l.relationship_type_id]||0)+1})}),r},enabled:!!s})},Gye=()=>{const s=Gt(),t=fa();return gt({mutationFn:async n=>{const{tagIds:r,...a}=n,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,spouse_birthday:a.spouse_birthday||null,owner_user_id:t},{data:l,error:o}=await q.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(r&&r.length>0){const{error:c}=await q.from("innercircle_contact_tags").insert(r.map(d=>({contact_id:l.id,relationship_type_id:d})));if(c)throw c}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Dr({title:"Contact created successfully"})},onError:n=>{Dr({title:"Error creating contact",description:n.message,variant:"destructive"})}})},_6e=()=>{const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{tagIds:r,tags:a,...i}=n,l=["birthday","home_anniversary","spouse_birthday","wedding_anniversary","last_contacted_at","next_touch_date"],o={...i};for(const u of Object.keys(o)){const h=o[u];(h===""||typeof h=="string"&&l.includes(u)&&h.trim()==="")&&(o[u]=null)}const{data:c,error:d}=await q.from("innercircle_contacts").update(o).eq("id",t).select().single();if(d)throw d;if(r!==void 0&&(await q.from("innercircle_contact_tags").delete().eq("contact_id",t),r.length>0)){const{error:u}=await q.from("innercircle_contact_tags").insert(r.map(h=>({contact_id:t,relationship_type_id:h})));if(u)throw u}return c},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Dr({title:"Contact updated successfully"})},onError:t=>{Dr({title:"Error updating contact",description:t.message,variant:"destructive"})}})},rpt=()=>{const s=Gt();return gt({mutationFn:async({contactId:t,spouseContactId:n})=>{if(n){const{error:r}=await q.from("innercircle_contacts").update({spouse_contact_id:n}).eq("id",t);if(r)throw r;const{error:a}=await q.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",n);if(a)throw a}else{const{data:r}=await q.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=r==null?void 0:r.spouse_contact_id,{error:i}=await q.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await q.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",a);if(l)throw l}}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),Dr({title:"Spouse link updated"})},onError:t=>{Dr({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},w6e=()=>{const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("innercircle_contacts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Dr({title:"Contact deleted successfully"})},onError:t=>{Dr({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},XD=()=>lt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await q.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),rrs=s=>lt({queryKey:["action-scripts",s],queryFn:async()=>{let t=q.from("action_scripts").select("*, action_type:action_types(*)");const{data:n,error:r}=await t;if(r)throw r;return n}}),ars=()=>lt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await q.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),irs=()=>{const s=Gt(),t=fa();return gt({mutationFn:async({name:n,description:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").insert({name:n,description:r,owner_user_id:t,active:!0,is_template:!1}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Dr({title:"Plan created successfully"})},onError:n=>{Dr({title:"Error creating plan",description:n.message,variant:"destructive"})}})},ors=()=>{const s=Gt(),t=fa();return gt({mutationFn:async({sourcePlanId:n,newName:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",n).single();if(i)throw i;if(!a)throw new Error("Source plan not found");const{data:l,error:o}=await q.from("touchpoint_plans").insert({name:r,description:a.description,owner_user_id:t,active:!0,is_template:!1}).select().single();if(o)throw o;if(a.items&&a.items.length>0){const c=a.items.map(u=>({plan_id:l.id,month_number:u.month_number,action_type_id:u.action_type_id,default_script_id:u.default_script_id,notes:u.notes})),{error:d}=await q.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Dr({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{Dr({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},lrs=()=>{const s=Gt();return gt({mutationFn:async({id:t,name:n,description:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").update({name:n,description:r}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Dr({title:"Plan updated successfully"})}})},crs=()=>{const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("touchpoint_plans").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Dr({title:"Plan deleted successfully"})}})},drs=()=>{const s=Gt();return gt({mutationFn:async({planId:t,items:n})=>{if(await q.from("touchpoint_plan_items").delete().eq("plan_id",t),n.length>0){const{error:r}=await q.from("touchpoint_plan_items").insert(n.map(a=>({plan_id:t,month_number:a.month_number,action_type_id:a.action_type_id,default_script_id:a.default_script_id||null,notes:a.notes})));if(r)throw r}},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Dr({title:"Plan schedule updated"})}})},urs=()=>{const s=Gt();return gt({mutationFn:async({actionTypeId:t,title:n,scriptBody:r,emailSubject:a,tone:i})=>{const{data:{user:l}}=await q.auth.getUser(),{data:o,error:c}=await q.from("action_scripts").insert({action_type_id:t,title:n,script_body:r,email_subject:a||null,tone:i||null,active:!0,user_id:l==null?void 0:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["action-scripts"]}),Dr({title:"Script created successfully"})},onError:t=>{Dr({title:"Error creating script",description:t.message,variant:"destructive"})}})},hrs=()=>{const s=fa();return lt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:n}=await q.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(n)throw n;return t},enabled:!!s})},mrs=()=>{const s=Gt(),t=fa();return gt({mutationFn:async({planId:n,relationshipTypeId:r,active:a})=>{const{data:i}=await q.from("user_plan_enrollments").select("id").eq("plan_id",n).eq("relationship_type_id",r).maybeSingle();if(i){const{error:l}=await q.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await q.from("user_plan_enrollments").insert({owner_user_id:t,plan_id:n,relationship_type_id:r,active:!0,start_date:new Date().toISOString().split("T")[0]});if(l)throw l}},onSuccess:()=>{s.invalidateQueries({queryKey:["user-plan-enrollments"]}),Dr({title:"Plan enrollment updated"})}})},JD=(s=7)=>{const t=fa();return lt({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const n=new Date;n.setDate(n.getDate()-s);const{data:r,error:a}=await q.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",t).gte("completed_at",n.toISOString()).order("completed_at",{ascending:!1});if(a)throw a;return r},enabled:!!t})},apt=()=>{const s=fa();return lt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",s).order("completed_at",{ascending:!1});if(n)throw n;const r={};return t==null||t.forEach(a=>{r[a.contact_id]||(r[a.contact_id]=a.completed_at)}),r},enabled:!!s})},prs=(s=90)=>{const{data:t}=lx(),{data:n}=apt();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=Gt(),t=fa();return gt({mutationFn:async({contactId:n,actionTypeId:r,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await q.from("contact_touch_logs").insert({owner_user_id:t,contact_id:n,action_type_id:r,script_used_id:a,notes:i,completed_at:l||new Date().toISOString()}).select().single();if(c)throw c;return o},onSuccess:async(n,r)=>{var a,i;s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),Dr({title:"Action completed!"});try{const[l,o]=await Promise.all([q.from("innercircle_contacts").select("email").eq("id",r.contactId).single(),q.from("action_types").select("name").eq("id",r.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";/pop[\s-]?by/i.test(d)&&q.from("popby_logs").insert({owner_user_id:t,contact_id:r.contactId,notes:r.notes??null,completed_at:r.completedAt||n.completed_at}).then(()=>{s.invalidateQueries({queryKey:["popby-logs"]})}),c&&q.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:c,touch_type:d,touch_notes:r.notes||null,touch_date:r.completedAt||n.completed_at}}).catch(()=>{})}catch{}}})},ipt="agentos_weekly_touch_goal",QUe=20,Dfe=()=>{if(typeof window>"u")return QUe;const s=localStorage.getItem(ipt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return QUe},opt=s=>{localStorage.setItem(ipt,s.toString())},j6e=()=>{const{data:s}=JD(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=Dfe();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},frs=()=>{const s=fa();return lt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(n)throw n;return t},enabled:!!s})},xrs=()=>{const s=Gt();return fa(),gt({mutationFn:async()=>{var c;const{data:t}=await q.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:n}=await q.auth.getUser(),r=(c=n==null?void 0:n.user)==null?void 0:c.id;if(!r)return;const{data:a}=await q.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",r);if(!a)return;const{data:i}=await q.from("contact_plan_cycles").select("contact_id, plan_id"),l=new Set((i==null?void 0:i.map(d=>`${d.contact_id}-${d.plan_id}`))||[]),o=[];for(const d of a)for(const u of d.tags||[]){const h=t.find(p=>p.relationship_type_id===u.relationship_type_id);h&&!l.has(`${d.id}-${h.plan_id}`)&&o.push({contact_id:d.id,plan_id:h.plan_id,relationship_type_id:u.relationship_type_id})}if(o.length>0){const{error:d}=await q.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&Dr({title:`${t} contact(s) enrolled in plans`})}})},lpt=()=>{const s=fa(),{data:t}=frs(),{data:n}=JD(30);return lt({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 q.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((r==null?void 0:r.map(b=>b.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((n==null?void 0:n.filter(b=>new Date(b.completed_at)>=o).map(b=>`${b.contact_id}-${b.action_type_id}`))||[]);for(const b of t){if(!((g=b.plan)!=null&&g.items)||b.plan.items.length===0||!b.contact||a.has(b.contact_id))continue;const v=new Date(b.cycle_start_date),_=Math.floor((i.getTime()-v.getTime())/(30.44*24*60*60*1e3))%12+1,S=b.plan.items.find(A=>A.month_number===_);if(S&&S.action_type){const A=`${b.contact_id}-${S.action_type_id}`;if(!c.has(A)){const{data:T}=await q.from("relationship_types").select("name").eq("id",b.relationship_type_id).single();l.push({contact:b.contact,actionType:S.action_type,script:S.default_script||void 0,planName:b.plan.name,relationshipTypeName:(T==null?void 0:T.name)||"",monthNumber:_})}}}const d=5,u=i.getDate(),h=l.sort((b,v)=>b.contact.first_name.localeCompare(v.contact.first_name)),p=(u-1)%Math.max(1,h.length);return[...h.slice(p),...h.slice(0,p)].slice(0,d)},enabled:!!s&&!!t})};function grs(){const s=In(),{data:t,isLoading:n}=lpt(),{data:r}=lx(),a=j6e(),[i,l]=N.useState(Dfe()),[o,c]=N.useState(""),[d,u]=N.useState(!1);N.useEffect(()=>{l(Dfe())},[]);const h=()=>{const D=parseInt(o,10);if(isNaN(D)||D<1){Dr({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}l(D),opt(D),u(!1),Dr({title:"Goal updated",description:`Weekly touch goal set to ${D}`})},p=()=>{c(i.toString()),u(!0)},f=Sf(new Date),g=Ul(f,7),b=D=>{if(!D)return null;const L=D.split(/[-/T]/);if(L.length<3)return null;const M=parseInt(L[1],10)-1,F=parseInt(L[2],10);return isNaN(M)||isNaN(F)?null:new Date(f.getFullYear(),M,F)},v=(r==null?void 0:r.map(D=>{const L=b(D.birthday),M=b(D.home_anniversary),F=[];return L&&L>=f&&L<=g&&F.push({contact:D,type:"birthday",date:L,isToday:Rl(L,f)}),M&&M>=f&&M<=g&&F.push({contact:D,type:"anniversary",date:M,isToday:Rl(M,f)}),F}).flat().sort((D,L)=>D.date.getTime()-L.date.getTime()).slice(0,3))||[],j=(r==null?void 0:r.filter(D=>{const L=b(D.birthday),M=b(D.home_anniversary);return L&&Rl(L,f)||M&&Rl(M,f)}).length)||0,_=(t==null?void 0:t.length)||0,S=j+_,A=(a==null?void 0:a.actionsThisWeek)||0,T=(a==null?void 0:a.streak)||0;return n?e.jsx(fe,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 bg-primary/20 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-4 bg-primary/20 rounded w-1/3"}),e.jsx("div",{className:"h-3 bg-primary/10 rounded w-1/2"})]})]})})}):e.jsxs(fe,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:[e.jsxs(Mt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5 text-primary"}),"Agent OS"]}),e.jsx("div",{className:"flex items-center gap-2",children:T>0&&e.jsxs(ze,{variant:"secondary",className:"gap-1 bg-orange-500/10 text-orange-600 border-orange-200",children:[e.jsx(_c,{className:"h-3 w-3"}),T," day streak"]})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[S>0?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary font-medium",children:[S," tasks"]})," for today"]}):"No tasks for today",A>0&&e.jsxs("span",{className:"ml-2",children:["• ",e.jsx("span",{className:"text-emerald-600 font-medium",children:A})," touches this week"]})]})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control/contacts?new=true")},children:[e.jsx(Fo,{className:"h-3.5 w-3.5"}),"Add Contact"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control")},children:[e.jsx(Pr,{className:"h-3.5 w-3.5"}),"Log Touch"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 border-emerald-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800",onClick:D=>{D.stopPropagation(),s("/mission-control/video/record")},children:[e.jsx(vr,{className:"h-3.5 w-3.5"}),"Quick Video"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control/popbys")},children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),"Pop-by Map"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 border-purple-200 text-purple-700 hover:bg-purple-50 hover:text-purple-800",onClick:D=>{D.stopPropagation(),s("/mission-control/pipeline")},children:[e.jsx(Q2,{className:"h-3.5 w-3.5"}),"Pipeline"]})]}),e.jsxs("div",{className:"pt-3 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wc,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Weekly Goal"}),e.jsxs(bs,{open:d,onOpenChange:u,children:[e.jsx(Di,{asChild:!0,children:e.jsx("button",{onClick:p,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(Vo,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-primary"})})}),e.jsxs(vs,{className:"sm:max-w-[360px]",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Set Weekly Goal"}),e.jsx(Qn,{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(se,{htmlFor:"weekly-goal",children:"Weekly touch goal"}),e.jsx(ge,{id:"weekly-goal",type:"number",min:"1",value:o,onChange:D=>c(D.target.value),placeholder:"20",onKeyDown:D=>{D.key==="Enter"&&h()}})]}),e.jsx(B,{onClick:h,className:"w-full",children:"Save Goal"})]})]})]})]}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-primary",children:A}),e.jsxs("span",{className:"text-muted-foreground",children:[" / ",i," touches"]})]})]}),e.jsx(xi,{value:Math.min(A/i*100,100),className:"h-2 bg-muted [&>div]:bg-primary"}),A>=i&&e.jsxs("p",{className:"text-xs text-emerald-600 mt-1.5 flex items-center gap-1",children:[e.jsx("span",{children:"🎉"})," Goal achieved! Keep the momentum going."]}),A0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1.5",children:[i-A," more to hit your weekly goal"]})]}),v.length>0&&e.jsxs("div",{className:"pt-3 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(hu,{className:"h-4 w-4 text-pink-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Upcoming Milestones"})]}),e.jsx("div",{className:"space-y-2",children:v.map((D,L)=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${D.isToday?"bg-pink-500/10 hover:bg-pink-500/15":"bg-muted/50 hover:bg-muted"}`,onClick:M=>{M.stopPropagation(),s(`/mission-control/contacts/${D.contact.id}`)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[D.type==="birthday"?e.jsx(hu,{className:"h-3.5 w-3.5 text-pink-500"}):e.jsx(zr,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsxs("span",{className:"text-sm",children:[D.contact.first_name," ",D.contact.last_name]}),D.isToday&&e.jsx(ze,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-pink-500/20 text-pink-600",children:"Today!"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:D.isToday?D.type==="birthday"?"🎂":"🏠":ks(D.date,"EEE, MMM d")}),e.jsx(ga,{className:"h-3 w-3"})]})]},`${D.contact.id}-${D.type}-${L}`))})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full gap-1 text-muted-foreground hover:text-primary",onClick:()=>s("/mission-control"),children:["Open Agent OS",e.jsx(za,{className:"h-4 w-4"})]})]})]})}function yrs(s){return lt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(n)throw n;return t},enabled:!!s})}function vrs(s,t){return lt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let n=q.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t&&(n=n.eq("category_id",t));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!s})}function brs(s,t=4){return lt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:n,error:r}=await q.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(t);if(r)throw r;return n},enabled:!!s})}function _rs(s){const t=Gt();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("brokerage_content").insert(n).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content"]}),t.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function wrs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_content").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function jrs(s){const t=Gt();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("brokerage_content_categories").insert({...n,brokerage_id:s}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function Nrs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_content_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function krs(s){const t=Gt();return gt({mutationFn:async()=>{const n=[{name:"Events",icon:"📅",sort_order:0,is_default:!0,brokerage_id:s},{name:"Videos",icon:"🎥",sort_order:1,is_default:!0,brokerage_id:s},{name:"Documents",icon:"📄",sort_order:2,is_default:!0,brokerage_id:s},{name:"Resources",icon:"🔗",sort_order:3,is_default:!0,brokerage_id:s},{name:"Graphics",icon:"🎨",sort_order:4,is_default:!0,brokerage_id:s}],{error:r}=await q.from("brokerage_content_categories").upsert(n,{onConflict:"brokerage_id,name"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const Srs={video:Al,pdf:Nr,link:El,event:yr,graphic:xl},Crs={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 Trs(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 Ers(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 Ars({item:s}){const t=In(),n=Srs[s.content_type]||El,r=Crs[s.content_type]||"",[a,i]=N.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?Trs(s.url):null);N.useEffect(()=>{l||!s.url||s.content_type!=="video"||!Ers(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(c=>c.ok?c.json():null).then(c=>{c!=null&&c.thumbnail_url&&i(c.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,l]);const o=l||a;return e.jsxs(fe,{className:"group cursor-pointer overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",onClick:()=>t(`/brokerage-content/${s.id}`),children:[o?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:o,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/20 flex items-center justify-center",children:e.jsx(n,{className:"h-8 w-8 text-muted-foreground/30"})}),e.jsxs(Ae,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(ze,{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:ks(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function Mrs(){const{brokerageId:s}=gs(),t=In(),{data:n=[],isLoading:r}=brs(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(Ga,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(za,{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(Ars,{item:a},a.id))})]})}const cpt=()=>lt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),dpt=s=>{const{user:t,brokerageId:n}=gs();return lt({queryKey:["listings",s,n],queryFn:async()=>{let r=q.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0);s!=null&&s.status&&(r=r.eq("status",s.status)),s!=null&&s.propertyType&&(r=r.eq("property_type",s.propertyType)),s!=null&&s.city&&(r=r.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(r=r.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(r=r.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(r=r.eq("open_to_referrals",!0));const{data:a,error:i}=await r;if(i)throw i;let l=a||[];if(n){const{data:o}=await q.from("profiles").select("id").eq("brokerage_id",n);if(o&&o.length>0){const c=o.map(h=>h.id);let d=q.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).in("agent_id",c);s!=null&&s.status&&(d=d.eq("status",s.status)),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:u}=await d;if(u){const h=new Set(l.map(f=>f.id)),p=u.filter(f=>!h.has(f.id));l=[...l,...p]}}}switch(s==null?void 0:s.sortBy){case"updated":l.sort((o,c)=>new Date(c.updated_at).getTime()-new Date(o.updated_at).getTime());break;case"price_asc":l.sort((o,c)=>o.price-c.price);break;case"price_desc":l.sort((o,c)=>c.price-o.price);break;default:l.sort((o,c)=>new Date(c.created_at).getTime()-new Date(o.created_at).getTime())}return l}})},upt=()=>{const{user:s}=gs();return lt({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})},N6e=s=>{const{user:t}=gs();return lt({queryKey:["listing",s],queryFn:async()=>{const{data:n,error:r}=await q.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds) `).eq("id",s).single();if(r)throw r;return t&&await q.from("listing_views").insert({listing_id:s,viewer_id:t.id}),n},enabled:!!s})},Irs=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("listings").insert({...n,agent_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Prs=()=>{const s=Gt();return gt({mutationFn:async({agentId:t,...n})=>{const{data:r,error:a}=await q.from("listings").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["brokerage-listings"]})}})},Lrs=()=>{const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("listings").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},hpt=()=>{const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("listings").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Drs=()=>{const s=Gt();return gt({mutationFn:async({listingId:t,photoUrl:n,isPrimary:r=!1})=>{const{data:a,error:i}=await q.from("listing_photos").insert({listing_id:t,photo_url:n,is_primary:r}).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t.listing_id]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Rrs=()=>{const s=Gt();return gt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await q.from("listing_photos").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Ors=()=>{const s=Gt();return gt({mutationFn:async({photos:t})=>{var i;const n=t.map(l=>q.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(n)).find(l=>l.error))==null?void 0:i.error;if(a)throw a;return t},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Frs=()=>{const s=Gt();return gt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await q.from("listing_photos").update({is_primary:!1}).eq("listing_id",n);if(r)throw r;const{error:a}=await q.from("listing_photos").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},zrs=()=>{const{user:s}=gs();return lt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("listing_saves").select(` *, listing:listings( *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id) ) `).eq("agent_id",s.id);if(n)throw n;return t},enabled:!!s})},mpt=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await q.from("listing_saves").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await q.from("listing_saves").delete().eq("id",r.id),{saved:!1}):(await q.from("listing_saves").insert({listing_id:n,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},ppt=s=>{const{user:t}=gs();return lt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await q.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},Brs=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await q.from("listing_follows").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await q.from("listing_follows").delete().eq("id",r.id),{following:!1}):(await q.from("listing_follows").insert({listing_id:n,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},$rs=s=>{const{user:t}=gs();return lt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await q.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},Urs=()=>{const{user:s}=gs();return gt({mutationFn:async({listingId:t,shareType:n})=>{if(!s)throw new Error("Not authenticated");const{error:r}=await q.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:n});if(r)throw r}})},qrs=()=>{const{user:s}=gs();return lt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,n]=await Promise.all([q.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),q.from("listing_referrals").select(` *, sender:profiles!listing_referrals_sender_agent_id_fkey(id, name, email), listing:listings(*,photos:listing_photos(*)) `).eq("listing_agent_id",s.id).order("created_at",{ascending:!1})]);return{sent:t.data||[],received:n.data||[]}},enabled:!!s})},Vrs=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async({listingId:n,listingAgentId:r,buyerName:a,buyerType:i,notes:l})=>{if(!t)throw new Error("Not authenticated");const{data:o,error:c}=await q.from("listing_referrals").insert({listing_id:n,sender_agent_id:t.id,listing_agent_id:r,buyer_name:a,buyer_type:i,notes:l}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["my-referrals"]})}})},Hrs=()=>lt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await q.from("listing_shares").select("sharing_agent_id, profiles!listing_shares_agent_id_fkey(name)").order("created_at",{ascending:!1}),t=new Map;s==null||s.forEach(l=>{var d;const o=l.sharing_agent_id;if(!o)return;const c=t.get(o);c?c.count++:t.set(o,{name:((d=l.profiles)==null?void 0:d.name)||"Unknown",count:1})});const n=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:r}=await q.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),a=new Map;r==null||r.forEach(l=>{var c;const o=a.get(l.agent_id);o?o.count++:a.set(l.agent_id,{name:((c=l.agent)==null?void 0:c.name)||"Unknown",count:1})});const i=Array.from(a.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10);return{topSharers:n,topListers:i}}}),Grs=()=>{const{user:s,brokerageId:t}=gs();return lt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:n}=await q.from("profiles").select("id").eq("brokerage_id",t);if(!n||n.length===0)return[];const r=n.map(l=>l.id),{data:a,error:i}=await q.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).in("agent_id",r).eq("is_approved",!0).order("created_at",{ascending:!1});if(i)throw i;return a},enabled:!!s&&!!t})},fpt=({className:s,variant:t="default"})=>e.jsx(ze,{variant:"outline",className:Et("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"}),Wrs={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"},Krs={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function Yrs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function Zrs(){const s=In(),{data:t,isLoading:n}=cpt(),{data:r,isLoading:a}=dpt({status:void 0,propertyType:void 0,sortBy:"newest"}),i=(r==null?void 0:r.filter(u=>u.is_approved&&u.is_public))||[],l=i.filter(u=>u.is_featured),o=i.filter(u=>!u.is_featured),c=[...l,...o].slice(0,6),d=n||a;return!d&&!t?null:d?e.jsx(fe,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Ae,{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(fpt,{})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(za,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(zr,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No listings available yet"}),e.jsx(B,{variant:"link",size:"sm",onClick:()=>s("/mission-control/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:c.map(u=>{var p,f;const h=((p=u.photos)==null?void 0:p.find(g=>g.is_primary))||((f=u.photos)==null?void 0:f[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${u.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[h!=null&&h.photo_url?e.jsx("img",{src:h.photo_url,alt:`${u.city}, ${u.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(zr,{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(ze,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(ua,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(ze,{className:`text-[10px] px-1.5 py-0.5 ${Wrs[u.status]}`,children:Krs[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:Yrs(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 xpt(s=10,t){return lt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:n}=await q.from("user_roles").select("user_id").eq("role","admin"),r=new Set((n==null?void 0:n.map(p=>p.user_id))||[]);let a=null;if(t){const{data:p}=await q.from("profiles").select("id").eq("brokerage_id",t);a=new Set((p==null?void 0:p.map(f=>f.id))||[])}const{data:i,error:l}=await q.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+r.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(p=>!r.has(p.user_id));a&&(o=o.filter(p=>a.has(p.user_id)));const c=o.slice(0,s),d=c.map(p=>p.user_id),{data:u}=await q.from("profiles").select("id, name").in("id",d),h=new Map((u==null?void 0:u.map(p=>[p.id,{name:p.name}]))||[]);return c.map(p=>({user_id:p.user_id,total_points:p.total_points,total_events_attended:p.total_events_attended,current_streak:p.current_streak,profile:h.get(p.user_id)||null}))}})}function gpt(s){return lt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return t},enabled:!!s})}function ypt(s){return lt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function vpt(s,t){return lt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:n}=await q.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!n)return null;const{data:r}=await q.from("user_roles").select("user_id").eq("role","admin"),a=new Set((r==null?void 0:r.map(c=>c.user_id))||[]),{data:i,error:l}=await q.from("agent_attendance_stats").select("user_id, total_points").gt("total_points",n.total_points);if(l)throw l;let o=(i==null?void 0:i.filter(c=>!a.has(c.user_id)))||[];if(t){const{data:c}=await q.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(u=>u.id))||[]);o=o.filter(u=>d.has(u.user_id))}return o.length+1},enabled:!!s})}function Qrs(){const{user:s,brokerageId:t,isAdmin:n}=gs();In();const r=!!t,[a,i]=N.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=xpt(5,l()),{data:d}=gpt(s==null?void 0:s.id),{data:u}=vpt(s==null?void 0:s.id,l()),{data:h}=ypt(s==null?void 0:s.id),p=n||r,f=()=>n?"Agent Leaderboard":r?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(vo,{className:"h-4 w-4 text-yellow-500"}),f()]})}),e.jsx(Ae,{children:e.jsx("div",{className:"space-y-2",children:[...Array(p?5:3)].map((b,v)=>e.jsx(Ws,{className:"h-10 w-full"},v))})})]});const g=b=>b===0?e.jsx(vo,{className:"h-4 w-4 text-yellow-500 mx-auto"}):b===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):b===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:b+1});if(p){const b=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"pb-2",children:[e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(vo,{className:"h-4 w-4 text-yellow-500"}),f()]}),!n&&r&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(B,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(B,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Ae,{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:[b.map((v,j)=>{var _,S,A;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${v.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":j===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:g(j)}),e.jsx(aa,{className:"h-6 w-6",children:e.jsx(ia,{className:"text-xs",children:((S=(_=v.profile)==null?void 0:_.name)==null?void 0:S.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((A=v.profile)==null?void 0:A.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:v.total_points})]},v.user_id)}),b.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(Ln,{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(Bi,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(ga,{className:"h-4 w-4"})]})]})]})}return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(vo,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Ae,{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(_c,{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(vc,{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(b=>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:b.badge_name},b.id)),h.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",h.length-4," more"]})]})]}),e.jsxs(Ln,{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(Bi,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(ga,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(ua,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(Ln,{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(Bi,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(ga,{className:"h-4 w-4"})]})]})})]})}const KM=()=>lt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await q.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),k6e=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{const{data:r}=await q.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",n.trim()),a=(r||[]).find(o=>o.name.toLowerCase()===n.trim().toLowerCase()&&!0);if(a)throw new Error(`Lead source "${a.name}" already exists`);const{data:i,error:l}=await q.from("lead_sources").insert({name:n,owner_user_id:t==null?void 0:t.id,sort_order:100}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source added")},onError:n=>{ae.error("Failed to add lead source"),console.error(n)}})},Xrs=()=>{const s=Gt();return gt({mutationFn:async({id:t,name:n})=>{const{error:r}=await q.from("lead_sources").update({name:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source updated")},onError:t=>{ae.error(t.message||"Failed to update lead source")}})},Jrs=()=>{const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("lead_sources").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source removed")},onError:t=>{ae.error(t.message||"Failed to remove lead source")}})},S6e=(s,t)=>{const{user:n,isAdmin:r}=gs(),a=r&&t?t:n==null?void 0:n.id;return lt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",a).order("close_date",{ascending:!1});s&&(i=i.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:l,error:o}=await i;if(o)throw o;return l},enabled:!!a})},C6e=s=>{const{user:t,isAdmin:n}=gs(),r=n&&s?s:t==null?void 0:t.id;return lt({queryKey:["scorecard-transactions-all",r],queryFn:async()=>{const{data:a,error:i}=await q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",r).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r})},Wye=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_transactions").insert({...n,owner_user_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction added")},onError:n=>{ae.error("Failed to add transaction"),console.error(n)}})},eas=()=>{const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("scorecard_transactions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction updated")},onError:t=>{ae.error("Failed to update transaction"),console.error(t)}})},tas=()=>{const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("scorecard_transactions").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction deleted")},onError:t=>{ae.error("Failed to delete transaction"),console.error(t)}})},bpt=(s,t)=>{const{user:n,isAdmin:r}=gs(),a=r&&t?t:n==null?void 0:n.id;return lt({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await q.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},sas=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_goals").upsert({...n,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["scorecard-goals",r.year]}),ae.success("Goals saved")},onError:n=>{ae.error("Failed to save goals"),console.error(n)}})},Kye=()=>{const{user:s}=gs();return lt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t},enabled:!!(s!=null&&s.id)})},nas=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_settings").upsert({...n,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),ae.success("Settings saved")},onError:n=>{ae.error("Failed to save settings"),console.error(n)}})},_pt=(s,t)=>{const{data:n,isLoading:r}=S6e(s,t),{data:a,isLoading:i}=C6e(t),{data:l}=Kye(),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(T=>T.transaction_type==="buyer").length,h=d.filter(T=>T.transaction_type==="seller").length,p=d.reduce((T,D)=>T+Number(D.sale_price),0),f=d.reduce((T,D)=>T+(Number(D.commission_amount)||0),0),g=d.reduce((T,D)=>{const L=Number(D.commission_amount)||0;if(!L)return T;let M=L;return D.brokerage_split_pct&&(M-=L*(D.brokerage_split_pct/100)),D.team_split_pct&&(M-=L*(D.team_split_pct/100)),D.franchise_fee_pct&&(M-=L*(D.franchise_fee_pct/100)),D.referral_fee_pct&&(M-=L*(D.referral_fee_pct/100)),D.transaction_fee&&(M-=D.transaction_fee),T+Math.max(0,M)},0),b={};d.forEach(T=>{var L;const D=((L=T.lead_source)==null?void 0:L.name)||"Unknown";b[D]=(b[D]||0)+1});const v=Object.entries(b).map(([T,D])=>({name:T,count:D})).sort((T,D)=>D.count-T.count),j=v[0]||null,_={};d.forEach(T=>{const D=ll(T.close_date).toLocaleString("default",{month:"short"});_[D]=(_[D]||0)+1});const A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(T=>({month:T,count:_[T]||0}));return{totalTransactions:d.length,buyerCount:u,sellerCount:h,totalVolume:p,averagePrice:d.length>0?p/d.length:0,totalCommission:o?f:0,totalNetToAgent:o?g:0,topLeadSource:j,transactionsByMonth:A,leadSourceBreakdown:v}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},ras=()=>{const{isAdmin:s}=gs();return lt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:n}=await q.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(n)throw n;const r=[...new Set(t.map(l=>l.owner_user_id))],{data:a,error:i}=await q.from("profiles").select("id, name, email").in("id",r);if(i)throw i;return a},enabled:s})},Xk={recency:40,touchpoints:30,transactions:20,referrals:10},XUe={warm:70,cooling:40};function aas(s){return s===null?0:s<=14?Xk.recency:s<=30?Xk.recency*.85:s<=60?Xk.recency*.65:s<=90?Xk.recency*.4:s<=180?Xk.recency*.2:Xk.recency*.05}function ias(s){const t=Math.min(s/12,1);return Math.round(Xk.touchpoints*t)}function oas(s){return s?Xk.transactions:0}function las(){return 0}function cas(s){return s>=XUe.warm?"warm":s>=XUe.cooling?"cooling":"at-risk"}function Yye(){const{data:s,isLoading:t}=lx(),{data:n}=apt(),{data:r}=JD(365),{data:a}=C6e(),i=N.useMemo(()=>{if(!s)return[];const o=new Date,c=WE(o,12),d={};r==null||r.forEach(h=>{new Date(h.completed_at)>=c&&(d[h.contact_id]=(d[h.contact_id]||0)+1)});const u=new Set((a==null?void 0:a.filter(h=>h.contact_id).map(h=>h.contact_id))||[]);return s.map(h=>{const p=(n==null?void 0:n[h.id])||null,f=p?Yv(o,new Date(p)):null,g=d[h.id]||0,b=u.has(h.id),v=aas(f),j=ias(g),_=oas(b),S=las(),A=Math.round(v+j+_+S),T={score:A,status:cas(A),breakdown:{recency:Math.round(v),touchpoints:Math.round(j),transactions:Math.round(_),referrals:Math.round(S)},lastTouchDate:p,daysSinceTouch:f,touchCountLast12Months:g,hasTransaction:b};return{...h,relationshipScore:T}})},[s,n,r,a]),l=N.useMemo(()=>{const o=i.filter(p=>p.relationshipScore.status==="warm").length,c=i.filter(p=>p.relationshipScore.status==="cooling").length,d=i.filter(p=>p.relationshipScore.status==="at-risk").length,u=i.length,h=u>0?Math.round(i.reduce((p,f)=>p+f.relationshipScore.score,0)/u):0;return{warm:o,cooling:c,atRisk:d,total:u,averageScore:h}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function wpt(){const s=In(),{stats:t,contactsWithScores:n,isLoading:r}=Yye();if(r)return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Ws,{className:"h-5 w-40"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsx(Ws,{className:"h-20 w-full"}),e.jsx(Ws,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Ae,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx(B,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>s("/mission-control/contacts?new=true"),children:"Add Your First Contact"})]})]});const a=Math.round(t.warm/t.total*100),i=Math.round(t.cooling/t.total*100),l=Math.round(t.atRisk/t.total*100),o=n.filter(c=>c.relationshipScore.status==="at-risk").sort((c,d)=>c.relationshipScore.score-d.relationshipScore.score).slice(0,3);return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:[e.jsx(mo,{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(Ae,{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(xi,{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(xi,{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(xi,{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(bb,{className:"h-4 w-4 text-red-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Needs Attention"})]}),e.jsx("div",{className:"space-y-2",children:o.map(c=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-red-500/5 hover:bg-red-500/10 cursor-pointer transition-colors",onClick:()=>s(`/mission-control/contacts/${c.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-red-500"}),e.jsxs("span",{className:"text-sm",children:[c.first_name," ",c.last_name]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:c.relationshipScore.daysSinceTouch===null?"Never":`${c.relationshipScore.daysSinceTouch}d`}),e.jsx(ga,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(ga,{className:"h-4 w-4 ml-1"})]})]})]})}const das=()=>{var ne;const{user:s,isAdmin:t}=gs(),n=In(),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState([]),[d,u]=N.useState([]),[h,p]=N.useState([]),[f,g]=N.useState([]),[b,v]=N.useState(new Set),[j,_]=N.useState([]),[S,A]=N.useState([]),[T,D]=N.useState([]),[L,M]=N.useState(null),[F,z]=N.useState(!0);N.useEffect(()=>{V()},[s]);const V=async()=>{var oe,pe,ce,de,ie;try{const[ye,_e,Me,Te,Ce,Ee,De,Ie,Fe,qe,ve]=await Promise.all([q.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),q.from("app_tiles").select("*").order("name"),q.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),q.from("events").select("*").order("event_date",{ascending:!0}),q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),q.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),q.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("additional_services").select("id, name, description, preview_image_url, signup_link_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),q.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(oe=ve.data)!=null&&oe.name&&M(ve.data.name);const Je=((pe=ye.data)==null?void 0:pe.map(Ye=>Ye.tag))||[],we=new Set(((ce=Me.data)==null?void 0:ce.map(Ye=>Ye.app_id))||[]);v(we);const Ne=(((de=_e.data)==null?void 0:de.filter(Ye=>!Ye.required_tags||Ye.required_tags.length===0?!0:Ye.required_tags.some(Ke=>Je.includes(Ke))))||[]).sort((Ye,Ke)=>Ye.name==="LevelUp Members Portal"?-1:Ke.name==="LevelUp Members Portal"?1:0);a(Ne.slice(0,6));const He=((ie=Te.data)==null?void 0:ie.filter(Ye=>RL(Ye.event_date)!=="ended"))||[];l(He.slice(0,4)),_(Ce.data||[]),c(Ee.data||[]),u(De.data||[]),p(Ie.data||[]),g(Fe.data||[]);const $e=qe.data||[];A($e.filter(Ye=>Ye.placement==="top")),D($e.filter(Ye=>Ye.placement==="between"))}catch(ye){console.error("Error loading dashboard:",ye),ae.error("Failed to load dashboard data")}finally{z(!1)}},W=async oe=>{var ce;const pe=window.open("about:blank","_blank");try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:oe.app_id,app_name:oe.name,user_agent:navigator.userAgent});const{data:de,error:ie}=await q.functions.invoke("sso-launch",{body:{app_id:oe.app_id}});if(ie)throw ie;de!=null&&de.redirect_url?pe&&!pe.closed?(pe.location.href=de.redirect_url,(ce=pe.focus)==null||ce.call(pe)):window.location.assign(de.redirect_url):(pe==null||pe.close(),ae.error("Launch link unavailable"))}catch(de){pe==null||pe.close(),console.error("Error launching app:",de),ae.error("Failed to launch app")}},K=oe=>j==null?void 0:j.some(pe=>pe.event_id===oe),Y=oe=>{const pe=j==null?void 0:j.find(ce=>ce.event_id===oe);return pe==null?void 0:pe.zoom_join_url};if(F)return e.jsx(Cs,{title:"Dashboard",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading your dashboard..."})]})})});const ee=oe=>T.filter(pe=>pe.section_after===oe);return e.jsxs(Cs,{title:"Dashboard",children:[e.jsx(Jns,{events:i,registrations:j,onNavigateToEvents:()=>n("/events")}),S.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(gF,{banners:S})}),e.jsx(srs,{}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h2",{className:"text-2xl font-bold text-foreground",children:["Welcome back, ",(L||((ne=s==null?void 0:s.user_metadata)==null?void 0:ne.name)||"there").split(" ")[0],"!"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Are you ready to LevelUp today?"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 mb-8",children:[e.jsx(grs,{}),e.jsx(wpt,{}),e.jsx(Qrs,{})]}),e.jsx(Mrs,{}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Upcoming Events"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/events"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(za,{className:"h-4 w-4"})]})]}),i.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(yr,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No upcoming events"})]})})}):e.jsx("div",{className:"bg-card rounded-xl border border-border overflow-hidden divide-y divide-border max-w-full",children:i.map(oe=>{const pe=K(oe.id),ce=Y(oe.id)||oe.zoom_link;return e.jsxs("div",{className:`flex items-start gap-3 sm:gap-4 p-3 sm:p-4 hover:bg-muted/50 transition-colors cursor-pointer group ${ZUe(oe.event_date)?"bg-red-500/5 border-l-2 border-l-red-500":""}`,onClick:()=>n("/events"),children:[ZUe(oe.event_date)?e.jsxs("div",{className:"flex-shrink-0 w-12 h-12 sm:w-14 sm:h-14 rounded-lg bg-red-500/10 flex flex-col items-center justify-center relative",children:[e.jsx("span",{className:"absolute inline-flex h-3 w-3 top-1 right-1 animate-ping rounded-full bg-red-500 opacity-75"}),e.jsx(wf,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"text-[10px] font-bold text-red-500 uppercase mt-0.5",children:"Live"})]}):e.jsxs("div",{className:"flex-shrink-0 w-12 h-12 sm:w-14 sm:h-14 rounded-lg bg-primary/10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-[10px] sm:text-xs font-medium text-primary uppercase",children:new Intl.DateTimeFormat("en-US",{month:"short",timeZone:"America/New_York"}).format(new Date(oe.event_date))}),e.jsx("span",{className:"text-lg sm:text-xl font-bold text-primary",children:new Intl.DateTimeFormat("en-US",{day:"numeric",timeZone:"America/New_York"}).format(new Date(oe.event_date))})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm sm:text-base text-foreground group-hover:text-primary transition-colors line-clamp-2 sm:truncate",children:oe.title}),e.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground mt-0.5",children:[new Intl.DateTimeFormat("en-US",{weekday:"long",timeZone:"America/New_York"}).format(new Date(oe.event_date))," at ",vB(new Date(oe.event_date))]})]}),e.jsx("div",{className:"hidden sm:flex flex-shrink-0",children:pe?e.jsxs(B,{size:"sm",variant:"default",className:"gap-1",onClick:de=>{de.stopPropagation(),window.open(ce,"_blank")},children:[e.jsx(tr,{className:"h-3.5 w-3.5"}),"Join"]}):e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground group-hover:text-primary transition-colors",children:[e.jsx("span",{className:"text-sm",children:"Register"}),e.jsx(ga,{className:"h-4 w-4"})]})})]},oe.id)})})]}),ee("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(gF,{banners:ee("events")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Academy Videos"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/academy"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(za,{className:"h-4 w-4"})]})]}),h.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Pu,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No academy videos available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:h.map(oe=>e.jsxs("div",{onClick:()=>n(`/academy/${oe.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted/50 overflow-hidden relative",children:[oe.thumbnail_url?e.jsx("img",{src:oe.thumbnail_url,alt:oe.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Pu,{className:"h-8 w-8 text-muted-foreground/50"})}),oe.duration&&e.jsx("span",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:oe.duration})]}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"font-medium text-sm text-foreground line-clamp-2 group-hover:text-primary transition-colors",children:oe.title})})]},oe.id))})]}),ee("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(gF,{banners:ee("academy")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Resource Kits"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/toolbox"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(za,{className:"h-4 w-4"})]})]}),d.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(yf,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No resource kits available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:d.map(oe=>e.jsxs("div",{onClick:()=>n(`/toolbox/${oe.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsx("div",{className:"aspect-[3/2] bg-muted/50 overflow-hidden",children:oe.featured_image_url?e.jsx("img",{src:oe.featured_image_url,alt:oe.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(yf,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:oe.name})})]},oe.id))})]}),ee("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(gF,{banners:ee("toolbox")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"New Templates"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/templates"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(za,{className:"h-4 w-4"})]})]}),o.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(K2,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No templates available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:o.map(oe=>e.jsxs("div",{onClick:()=>n("/templates"),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsx("div",{className:"aspect-[3/2] bg-muted/50 overflow-hidden",children:oe.preview_image_url?e.jsx("img",{src:oe.preview_image_url,alt:oe.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(K2,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:oe.name})})]},oe.id))})]}),ee("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(gF,{banners:ee("templates")})}),e.jsx("div",{className:"mb-10",children:e.jsx(Zrs,{})}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Your Apps"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(za,{className:"h-4 w-4"})]})]}),r.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ae,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Rv,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No apps available"})]})})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:r.map(oe=>{const pe=b.has(oe.id);return e.jsxs("div",{onClick:()=>W(oe),className:"group flex items-start gap-4 p-5 bg-card rounded-xl border border-border cursor-pointer transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:oe.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate",children:oe.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:oe.description})]}),pe&&e.jsx(Rv,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},oe.id)})})]}),e.jsxs("section",{className:"mt-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Additional Services"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/additional-services"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(za,{className:"h-4 w-4"})]})]}),f.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No additional services available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:f.map(oe=>e.jsxs("div",{onClick:()=>window.open(oe.signup_link_url,"_blank"),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsx("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden",children:oe.preview_image_url?e.jsx("img",{src:oe.preview_image_url,alt:oe.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(un,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsxs("div",{className:"p-3",children:[e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:oe.name}),oe.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:oe.description})]})]},oe.id))})]})]})};var jpt="AlertDialog",[uas,tgn]=gu(jpt,[qot]),SN=qot(),Npt=s=>{const{__scopeAlertDialog:t,...n}=s,r=SN(t);return e.jsx(aye,{...r,...n,modal:!0})};Npt.displayName=jpt;var has="AlertDialogTrigger",kpt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=SN(n);return e.jsx(ZAe,{...a,...r,ref:t})});kpt.displayName=has;var mas="AlertDialogPortal",Spt=s=>{const{__scopeAlertDialog:t,...n}=s,r=SN(t);return e.jsx(iye,{...r,...n})};Spt.displayName=mas;var pas="AlertDialogOverlay",Cpt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=SN(n);return e.jsx(UD,{...a,...r,ref:t})});Cpt.displayName=pas;var OL="AlertDialogContent",[fas,xas]=uas(OL),gas=irt("AlertDialogContent"),Tpt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,children:r,...a}=s,i=SN(n),l=N.useRef(null),o=Ti(t,l),c=N.useRef(null);return e.jsx(a9t,{contentName:OL,titleName:Ept,docsSlug:"alert-dialog",children:e.jsx(fas,{scope:n,cancelRef:c,children:e.jsxs(qD,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:wr(a.onOpenAutoFocus,d=>{var u;d.preventDefault(),(u=c.current)==null||u.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault(),children:[e.jsx(gas,{children:r}),e.jsx(vas,{contentRef:l})]})})})});Tpt.displayName=OL;var Ept="AlertDialogTitle",Apt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=SN(n);return e.jsx(eU,{...a,...r,ref:t})});Apt.displayName=Ept;var Mpt="AlertDialogDescription",Ipt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=SN(n);return e.jsx(tU,{...a,...r,ref:t})});Ipt.displayName=Mpt;var yas="AlertDialogAction",Ppt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=SN(n);return e.jsx(sU,{...a,...r,ref:t})});Ppt.displayName=yas;var Lpt="AlertDialogCancel",Dpt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,{cancelRef:a}=xas(Lpt,n),i=SN(n),l=Ti(t,a);return e.jsx(sU,{...i,...r,ref:l})});Dpt.displayName=Lpt;var vas=({contentRef:s})=>{const t=`\`${OL}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${OL}\` by passing a \`${Mpt}\` component as a child, which also benefits sighted users by adding visible context to the dialog. Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${OL}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component. For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return N.useEffect(()=>{var r;document.getElementById((r=s.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},bas=Npt,_as=kpt,was=Spt,Rpt=Cpt,Opt=Tpt,Fpt=Ppt,zpt=Dpt,Bpt=Apt,$pt=Ipt;const Oo=bas,Rh=_as,jas=was,Upt=N.forwardRef(({className:s,...t},n)=>e.jsx(Rpt,{className:Et("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}));Upt.displayName=Rpt.displayName;const Co=N.forwardRef(({className:s,...t},n)=>e.jsxs(jas,{children:[e.jsx(Upt,{}),e.jsx(Opt,{ref:n,className:Et("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...t})]}));Co.displayName=Opt.displayName;const To=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col space-y-2 text-center sm:text-left",s),...t});To.displayName="AlertDialogHeader";const Eo=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Eo.displayName="AlertDialogFooter";const Ao=N.forwardRef(({className:s,...t},n)=>e.jsx(Bpt,{ref:n,className:Et("text-lg font-semibold",s),...t}));Ao.displayName=Bpt.displayName;const Mo=N.forwardRef(({className:s,...t},n)=>e.jsx($pt,{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));Mo.displayName=$pt.displayName;const jo=N.forwardRef(({className:s,...t},n)=>e.jsx(Fpt,{ref:n,className:Et(w8(),s),...t}));jo.displayName=Fpt.displayName;const Io=N.forwardRef(({className:s,...t},n)=>e.jsx(zpt,{ref:n,className:Et(w8({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));Io.displayName=zpt.displayName;const Nas=[{key:"contacts",label:"Contacts",icon:Pr,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:t4,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:yf,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:vr,description:"View and upload videos"},{key:"listings",label:"Listings",icon:zr,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:Ov,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:Ca,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:ff,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:$u,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:oy,description:"Create and manage smart presentations"}];function kas(){var L;const{user:s}=gs(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState({email:"",name:"",password:""}),[f,g]=N.useState("create"),[b,v]=N.useState(!1),[j,_]=N.useState(null);N.useEffect(()=>{s&&S()},[s]);const S=async()=>{if(s){a(!0);try{const{data:M,error:F}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(F)throw F;if(M&&M.length>0){const z=M.map(K=>K.assistant_id),{data:V}=await q.from("profiles").select("id, name, email").in("id",z),W=M.map(K=>{const Y=V==null?void 0:V.find(ee=>ee.id===K.assistant_id);return{...K,permissions:K.permissions,assistant_profile:Y?{name:Y.name||"",email:Y.email||""}:void 0}});n(W)}else n([])}catch(M){console.error("Error loading assistants:",M)}finally{a(!1)}}},A=async()=>{if(s){if(f==="link"){if(!h.email.trim()){ae.error("Please enter the assistant's email");return}v(!0);try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const{data:F,error:z}=await q.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(z||!F){ae.error("No account found with that email. Try creating a new assistant instead.");return}const{data:V}=await q.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",F.id);if(V&&V.length>0){ae.error("This assistant is already assigned to you");return}const W=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:F.id,role:"assistant",action:"add",agentId:s.id})}),K=await W.json();if(!W.ok)throw new Error(K.error||"Failed to assign assistant role");const{error:Y}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:F.id,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if(Y)throw Y;ae.success(`${F.name||F.email} linked as your assistant`),l(!1),p({email:"",name:"",password:""}),S()}catch(M){console.error("Error linking assistant:",M),ae.error(M.message||"Failed to link assistant")}finally{v(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){ae.error("Please fill in all fields");return}if(h.password.length<6){ae.error("Password must be at least 6 characters");return}v(!0);try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const F=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({email:h.email.trim(),password:h.password,name:h.name.trim(),purpose:"assistant"})}),z=await F.json();if(!F.ok)throw new Error(z.error||"Failed to create assistant account");const V=z.userId||z.id;if(!V)throw new Error("No user ID returned");const W=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:V,role:"assistant",action:"add",agentId:s.id})}),K=await W.json();if(!W.ok)throw new Error(K.error||"Failed to assign assistant role");const{error:Y}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:V,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if(Y)throw Y;ae.success(`Assistant account created for ${h.name.trim()}`),l(!1),p({email:"",name:"",password:""}),S()}catch(M){console.error("Error adding assistant:",M),ae.error(M.message||"Failed to add assistant")}finally{v(!1)}}},T=async()=>{if(!(!d||!s))try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const{error:F}=await q.from("agent_assistant_assignments").delete().eq("id",d.id);if(F)throw F;const{data:z}=await q.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!z||z.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),ae.success("Assistant removed"),c(!1),u(null),S()}catch(M){console.error("Error removing assistant:",M),ae.error(M.message||"Failed to remove assistant")}},D=async(M,F,z)=>{_(M);try{const V=t.find(Y=>Y.id===M);if(!V)return;const W={...V.permissions,[F]:z},{error:K}=await q.from("agent_assistant_assignments").update({permissions:W}).eq("id",M);if(K)throw K;n(Y=>Y.map(ee=>ee.id===M?{...ee,permissions:W}:ee))}catch(V){console.error("Error updating permissions:",V),ae.error("Failed to update permissions")}finally{_(null)}};return r?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(Hn,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(B,{size:"sm",onClick:()=>{g("create"),l(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Ae,{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(M=>{var F,z,V,W;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(aa,{className:"h-10 w-10",children:e.jsx(ia,{children:((z=(F=M.assistant_profile)==null?void 0:F.name)==null?void 0:z.split(" ").map(K=>K[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((V=M.assistant_profile)==null?void 0:V.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((W=M.assistant_profile)==null?void 0:W.email)||""})]}),e.jsxs(ze,{variant:"secondary",className:"ml-2",children:[e.jsx(hh,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(M),c(!0)},children:e.jsx(bn,{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:Nas.map(K=>{const Y=K.icon;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:K.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:K.description})]})]}),e.jsx(vn,{checked:M.permissions[K.key]||!1,onCheckedChange:ee=>D(M.id,K.key,ee),disabled:j===M.id})]},K.key)})})]})]},M.id)})})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add Assistant"}),e.jsx(Qn,{children:f==="create"?"Create a new account for your assistant.":"Link an existing assistant account by their email."})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs(B,{variant:f==="create"?"default":"outline",size:"sm",onClick:()=>g("create"),children:[e.jsx(As,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(B,{variant:f==="link"?"default":"outline",size:"sm",onClick:()=>g("link"),children:[e.jsx(tl,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[f==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"assistant-name",children:"Name"}),e.jsx(ge,{id:"assistant-name",value:h.name,onChange:M=>p({...h,name:M.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"assistant-email",children:"Email"}),e.jsx(ge,{id:"assistant-email",type:"email",value:h.email,onChange:M=>p({...h,email:M.target.value}),placeholder:"assistant@email.com"})]}),f==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(ge,{id:"assistant-password",type:"password",value:h.password,onChange:M=>p({...h,password:M.target.value}),placeholder:"Min 6 characters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your assistant can change this after their first login."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:A,disabled:b,children:[b&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),f==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Oo,{open:o,onOpenChange:c,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove Assistant?"}),e.jsxs(Mo,{children:["This will remove ",(L=d==null?void 0:d.assistant_profile)==null?void 0:L.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:T,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function tf(s){this.content=s}tf.prototype={constructor:tf,find:function(s){for(var t=0;t>1}};tf.from=function(s){if(s instanceof tf)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new tf(t)};function qpt(s,t,n){for(let r=0;;r++){if(r==s.childCount||r==t.childCount)return s.childCount==t.childCount?null:n;let a=s.child(r),i=t.child(r);if(a==i){n+=a.nodeSize;continue}if(!a.sameMarkup(i))return n;if(a.isText&&a.text!=i.text){for(let l=0;a.text[l]==i.text[l];l++)n++;return n}if(a.content.size||i.content.size){let l=qpt(a.content,i.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function Vpt(s,t,n,r){for(let a=s.childCount,i=t.childCount;;){if(a==0||i==0)return a==i?null:{a:n,b:r};let l=s.child(--a),o=t.child(--i),c=l.nodeSize;if(l==o){n-=c,r-=c;continue}if(!l.sameMarkup(o))return{a:n,b:r};if(l.isText&&l.text!=o.text){let d=0,u=Math.min(l.text.length,o.text.length);for(;dt&&r(c,a+o,i||null,l)!==!1&&c.content.size){let u=o+1;c.nodesBetween(Math.max(0,t-u),Math.min(c.content.size,n-u),r,a+u)}o=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,r,a){let i="",l=!0;return this.nodesBetween(t,n,(o,c)=>{let d=o.isText?o.text.slice(Math.max(t,c)-c,n-c):o.isLeaf?a?typeof a=="function"?a(o):a:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&d||o.isTextblock)&&r&&(l?l=!1:i+=r),i+=d},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,a=this.content.slice(),i=0;for(n.isText&&n.sameMarkup(r)&&(a[a.length-1]=n.withText(n.text+r.text),i=1);it)for(let i=0,l=0;lt&&((ln)&&(o.isText?o=o.cut(Math.max(0,t-l),Math.min(o.text.length,n-l)):o=o.cut(Math.max(0,t-l-1),Math.min(o.content.size,n-l-1))),r.push(o),a+=o.nodeSize),l=c}return new Fx(r,a)}cutByIndex(t,n){return t==n?Fx.empty:t==0&&n==this.content.length?this:new Fx(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 Fx(a,i)}addToStart(t){return new Fx([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new Fx(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?gH(n+1,i):gH(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 Fx.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Fx(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return Fx.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}};nd.none=[];class Ofe extends Error{}class ka{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=Gpt(this.content,t+this.openStart,n);return r&&new ka(r,this.openStart,this.openEnd)}removeBetween(t,n){return new ka(Hpt(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 ka.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 ka(Vr.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 ka(t,r,a)}}ka.empty=new ka(Vr.empty,0,0);function Hpt(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(Hpt(i.content,t-a-1,n-a-1)))}function Gpt(s,t,n,r){let{index:a,offset:i}=s.findIndex(t),l=s.maybeChild(a);if(i==t||l.isText)return r&&!r.canReplace(a,a,n)?null:s.cut(0,t).append(n).append(s.cut(t));let o=Gpt(l.content,t-i-1,n,l);return o&&s.replaceChild(a,l.copy(o))}function Sas(s,t,n){if(n.openStart>s.depth)throw new Ofe("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new Ofe("Inconsistent open depths");return Wpt(s,t,n,0)}function Wpt(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 iz(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&&(WA(s.nodeAfter,r),i++));for(let o=i;oa&&SCe(s,t,a+1),l=r.depth>a&&SCe(n,r,a+1),o=[];return iz(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(Kpt(i,l),WA(KA(i,Ypt(s,t,n,r,a+1)),o)):(i&&WA(KA(i,Ffe(s,t,a+1)),o),iz(t,n,a,o),l&&WA(KA(l,Ffe(n,r,a+1)),o)),iz(r,null,a,o),new Vr(o)}function Ffe(s,t,n){let r=[];if(iz(null,s,n,r),s.depth>n){let a=SCe(s,t,n+1);WA(KA(a,Ffe(s,t,n+1)),r)}return iz(t,null,n,r),new Vr(r)}function Cas(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(Vr.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class bB{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 zfe(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 bB(n,r,i)}static resolveCached(t,n){let r=JUe.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()+")"),Zpt(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=Vr.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=Vr.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,a,r);return i.type.checkAttrs(i.attrs),i}};g4.prototype.text=void 0;class Bfe extends g4{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):Zpt(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 Bfe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new Bfe(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 Zpt(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}class wM{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new Mas(t,n);if(r.next==null)return wM.empty;let a=Qpt(r);r.next&&r.err("Unexpected trailing text");let i=Fas(Oas(a));return zas(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(` `)}}wM.empty=new wM(!0);class Mas{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 Qpt(s){let t=[];do t.push(Ias(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function Ias(s){let t=[];do t.push(Pas(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function Pas(s){let t=Ras(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=Las(s,t);else break;return t}function eqe(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function Las(s,t){let n=eqe(s),r=n;return s.eat(",")&&(s.next!="}"?r=eqe(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function Das(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 Ras(s){if(s.eat("(")){let t=Qpt(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=Das(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 Oas(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 wM(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:eft(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new g4(this,this.computeAttrs(t),Vr.from(n),nd.setFrom(r))}createChecked(t=null,n,r){return n=Vr.from(n),this.checkContent(n),new g4(this,this.computeAttrs(t),n,nd.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=Vr.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(Vr.empty,!0);return i?new g4(this,t,n.append(i),nd.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 nft(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 Bas(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 $as{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Bas(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Zye{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=sft(t,a.attrs),this.excluded=null;let i=Jpt(this.attrs);this.instance=i?new nd(this,i):null}create(t=null){return!t&&this.instance?this.instance:new nd(this,eft(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new Zye(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}class rft{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=tf.from(t.nodes),n.marks=tf.from(t.marks||{}),this.nodes=sqe.compile(this.spec.nodes,this),this.marks=Zye.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]=wM.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?nqe(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==""?[]:nqe(this,l.split(" "))}this.nodeFromJSON=a=>g4.fromJSON(this,a),this.markFromJSON=a=>nd.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 sqe){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 Bfe(r,r.defaultAttrs,t,nd.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 nqe(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 Uas(s){return s.tag!=null}function qas(s){return s.style!=null}let oz=class TCe{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(Uas(a))this.tags.push(a);else if(qas(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 aqe(this,n,!1);return r.addAll(t,nd.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new aqe(this,n,!0);return r.addAll(t,nd.none,n.from,n.to),ka.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=iqe(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=iqe(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new TCe(t,TCe.schemaRules(t)))}};const aft={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Vas={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},ift={ol:!0,ul:!0},_B=1,ECe=2,lz=4;function rqe(s,t,n){return t!=null?(t?_B:0)|(t==="full"?ECe:0):s&&s.whitespace=="pre"?_B|ECe:n&~lz}class yH{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=nd.none,this.match=i||(l&lz?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Vr.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&_B)){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=Vr.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(Vr.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&&!aft.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class aqe{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=rqe(null,n.preserveWhitespace,0)|(r?lz:0);a?i=new yH(a.type,a.attrs,nd.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new yH(null,null,nd.none,!0,null,l):i=new yH(t.schema.topNodeType,null,nd.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&ECe?"full":this.localPreserveWS||(a.options&_B)>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):oqe(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new yH(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|=_B)}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 Has(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&ift.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function Gas(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function iqe(s){let t={};for(let n in s)t[n]=s[n];return t}function oqe(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&&Kme(Kje(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return Kme(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new YM(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=lqe(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return lqe(t.marks)}}function lqe(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function Kje(s){return s.document||window.document}const cqe=new WeakMap;function Was(s){let t=cqe.get(s);return t===void 0&&cqe.set(s,t=Kas(s)),t}function Kas(s){let t=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")t||(t=[]),t.push(r);else for(let a=0;a-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let l=a.indexOf(" ");l>0&&(n=a.slice(0,l),a=a.slice(l+1));let o,c=n?s.createElementNS(n,a):s.createElement(a),d=t[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let h in d)if(d[h]!=null){let p=h.indexOf(" ");p>0?c.setAttributeNS(h.slice(0,p),h.slice(p+1),d[h]):h=="style"&&c.style?c.style.cssText=d[h]:c.setAttribute(h,d[h])}}for(let h=u;hu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:f,contentDOM:g}=Kme(s,p,n,r);if(c.appendChild(f),g){if(o)throw new RangeError("Multiple content holes");o=g}}}return{dom:c,contentDOM:o}}const oft=65535,lft=Math.pow(2,16);function Yas(s,t){return s+t*lft}function dqe(s){return s&oft}function Zas(s){return(s-(s&oft))/lft}const cft=1,dft=2,Yme=4,uft=8;class ACe{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&uft)>0}get deletedBefore(){return(this.delInfo&(cft|Yme))>0}get deletedAfter(){return(this.delInfo&(dft|Yme))>0}get deletedAcross(){return(this.delInfo&Yme)>0}}class Q0{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Q0.empty)return Q0.empty}recover(t){let n=0,r=dqe(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],u=this.ranges[o+l],h=c+d;if(t<=h){let p=d?t==c?-1:t==h?1:n:n,f=c+a+(p<0?0:u);if(r)return f;let g=t==(n<0?c:h)?null:Yas(o/3,t-c),b=t==c?dft:t==h?cft:Yme;return(n<0?t!=c:t!=h)&&(b|=uft),new ACe(f,b,g)}a+=u-d}return r?t+a:new ACe(t+a,0,null)}touches(t,n){let r=0,a=dqe(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 wB;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 nm.fromReplace(t,this.from,this.to,i)}invert(){return new iw(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 PS(n.pos,r.pos,this.mark)}merge(t){return t instanceof PS&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new PS(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 PS(n.from,n.to,t.markFromJSON(n.mark))}}cx.jsonID("addMark",PS);class iw extends cx{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 ka(T6e(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return nm.fromReplace(t,this.from,this.to,r)}invert(){return new PS(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 iw(n.pos,r.pos,this.mark)}merge(t){return t instanceof iw&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new iw(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 iw(n.from,n.to,t.markFromJSON(n.mark))}}cx.jsonID("removeMark",iw);class LS extends cx{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return nm.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return nm.fromReplace(t,this.pos,this.pos+1,new ka(Vr.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 Ap(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 Ap(n.from,n.to,n.gapFrom,n.gapTo,ka.fromJSON(t,n.slice),n.insert,!!n.structure)}}cx.jsonID("replaceAround",Ap);function MCe(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 Qas(s,t,n,r){let a=[],i=[],l,o;s.doc.nodesBetween(t,n,(c,d,u)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&u.type.allowsMarkType(r.type)){let p=Math.max(d,t),f=Math.min(d+c.nodeSize,n),g=r.addToSet(h);for(let b=0;bs.step(c)),i.forEach(c=>s.step(c))}function Xas(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 Zye){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 iw(l.from,l.to,l.style)))}function E6e(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 Jas(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function eR(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--)b||r.index(g)>0?(b=!0,u=Vr.from(r.node(g).copy(u)),h++):c--;let p=Vr.empty,f=0;for(let g=i,b=!1;g>n;g--)b||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=Vr.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new Ap(a,i,a,i,new ka(r,0,0),n.length,!0))}function ris(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)&&ais(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",g=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!g?d=!1:!f&&g&&(d=!0)}d===!1&&mft(s,l,o,i),E6e(s,s.mapping.slice(i).map(o,1),r,void 0,d===null);let u=s.mapping.slice(i),h=u.map(o,1),p=u.map(o+l.nodeSize,1);return s.step(new Ap(h,p,h+1,p-1,new ka(Vr.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&hft(s,l,o,i),!1}})}function hft(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 mft(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 ais(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function iis(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 Ap(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new ka(Vr.from(l),0,0),1,!0))}function FL(s,t,n=1,r){let a=s.resolve(t),i=a.depth-n,l=r&&r[r.length-1]||a.parent;if(i<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,u=n-2;d>i;d--,u--){let h=a.node(d),p=a.index(d);if(h.type.spec.isolating)return!1;let f=h.content.cutByIndex(p,h.childCount),g=r&&r[u+1];g&&(f=f.replaceChild(0,g.type.create(g.attrs)));let b=r&&r[u]||h;if(!h.canReplace(p+1,h.childCount)||!b.type.validContent(f))return!1}let o=a.indexAfter(i),c=r&&r[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function ois(s,t,n=1,r){let a=s.doc.resolve(t),i=Vr.empty,l=Vr.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=Vr.from(a.node(o).copy(i));let u=r&&r[d];l=Vr.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Jh(t,t,new ka(i.append(l),n,n),!0))}function tC(s,t){let n=s.resolve(t),r=n.index();return pft(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function lis(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&&pft(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 cis(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);mft(s,u.node(),u.before(),o)}l.inlineContent&&E6e(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 Jh(d,c.map(t+n,-1),ka.empty,!0)),r===!0){let u=s.doc.resolve(d);hft(s,u.node(),u.before(),s.steps.length)}return s}function dis(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 Xye(s,t,n=t,r=ka.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return xft(a,i,r)?new Jh(t,n,r):new uis(a,i,r).fit()}function xft(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class uis{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Vr.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=Vr.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 ka(i,l,o);return t>-1?new Ap(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Jh(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=Zje(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(Vr.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=Zje(t,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new ka(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=Zje(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new ka(g7(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new ka(g7(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 b=0;b1||c==0||b.content.size)&&(h=v,u.push(gft(b.mark(p.allowedMarks(b.marks)),d==1?c:0,d==o.childCount?f:-1)))}let g=d==o.childCount;g||(f=-1),this.placed=y7(this.placed,n,Vr.from(u)),this.frontier[n].match=h,g&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let b=0,v=o;b1&&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=Qje(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=y7(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=y7(this.placed,this.depth,Vr.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Vr.empty,!0);n.childCount&&(this.placed=y7(this.placed,this.frontier.length,n))}}function g7(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(g7(s.firstChild.content,t-1,n)))}function y7(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(y7(s.lastChild.content,t-1,n)))}function Zje(s,t){for(let n=0;n1&&(r=r.replaceChild(0,gft(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(Vr.empty,!0)))),s.copy(r)}function Qje(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&&!his(n,i.content,l)?o:null}function his(s,t,n){for(let r=n;r0;p--,f--){let g=a.node(p).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;l.indexOf(p)>-1?o=p:a.before(p)==f&&l.splice(1,0,-p)}let c=l.indexOf(o),d=[],u=r.openStart;for(let p=r.content,f=0;;f++){let g=p.firstChild;if(d.push(g),f==r.openStart)break;p=g.content}for(let p=u-1;p>=0;p--){let f=d[p],g=mis(f.type);if(g&&!f.sameMarkup(a.node(Math.abs(o)-1)))u=p;else if(g||!f.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let f=(p+u+1)%(r.openStart+1),g=d[f];if(g)for(let b=0;b=0&&(s.replace(t,n,r),!(s.steps.length>h));p--){let f=l[p];f<0||(t=a.before(f),n=i.after(f))}}function yft(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(Vr.empty,!0))}return s}function fis(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=dis(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new ka(Vr.from(r),0,0))}function xis(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=vft(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 vft(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 zL extends cx{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 nm.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 nm.fromReplace(t,this.pos,this.pos+1,new ka(Vr.from(a),0,n.isLeaf?0:1))}getMap(){return Q0.empty}invert(t){return new zL(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 zL(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 zL(n.pos,n.attr,n.value)}}cx.jsonID("attr",zL);class jB extends cx{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 nm.ok(r)}getMap(){return Q0.empty}invert(t){return new jB(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 jB(n.attr,n.value)}}cx.jsonID("docAttr",jB);let M8=class extends Error{};M8=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};M8.prototype=Object.create(Error.prototype);M8.prototype.constructor=M8;M8.prototype.name="TransformError";let M6e=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new wB}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new M8(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=ka.empty){let a=Xye(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new ka(Vr.from(r),0,0))}delete(t,n){return this.replace(t,n,ka.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return pis(this,t,n,r),this}replaceRangeWith(t,n,r){return fis(this,t,n,r),this}deleteRange(t,n){return xis(this,t,n),this}lift(t,n){return eis(this,t,n),this}join(t,n=1){return cis(this,t,n),this}wrap(t,n){return nis(this,t,n),this}setBlockType(t,n=t,r,a=null){return ris(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return iis(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new zL(t,n,r)),this}setDocAttribute(t,n){return this.step(new jB(t,n)),this}addNodeMark(t,n){return this.step(new LS(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 nd)n.isInSet(r.marks)&&this.step(new jM(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new jM(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 ois(this,t,n,r),this}addMark(t,n,r){return Qas(this,t,n,r),this}removeMark(t,n,r){return Xas(this,t,n,r),this}clearIncompatible(t,n,r){return E6e(this,t,n,r),this}};const Xje=Object.create(null);class no{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new bft(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?cP(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):cP(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 Vv(t.node(0))}static atStart(t){return cP(t,t,0,0,1)||new Vv(t)}static atEnd(t){return cP(t,t,t.content.size,t.childCount,-1)||new Vv(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Xje[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 Xje)throw new RangeError("Duplicate use of selection JSON ID "+t);return Xje[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Ki.between(this.$anchor,this.$head).getBookmark()}}no.prototype.visible=!0;class bft{constructor(t,n){this.$from=t,this.$to=n}}let hqe=!1;function mqe(s){!hqe&&!s.parent.inlineContent&&(hqe=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Ki extends no{constructor(t,n=t){mqe(t),mqe(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 no.near(r);let a=t.resolve(n.map(this.anchor));return new Ki(a.parent.inlineContent?a:r,r)}replace(t,n=ka.empty){if(super.replace(t,n),n==ka.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof Ki&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Jye(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 Ki(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=no.findFrom(n,r,!0)||no.findFrom(n,-r,!0);if(i)n=i.$head;else return no.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(no.findFrom(t,-r,!0)||no.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&&$i.isSelectable(o))return $i.create(s,n-(a<0?o.nodeSize:0))}else{let c=cP(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function pqe(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(no.near(s.doc.resolve(l),n))}const fqe=1,vH=2,xqe=4;class yis extends M6e{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|=vH,this}ensureMarks(t){return nd.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&vH)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~vH,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)||nd.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(no.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|=xqe,this}get scrolledIntoView(){return(this.updated&xqe)>0}}function gqe(s,t){return!t||!s?s:s.bind(t)}class v7{constructor(t,n,r){this.name=t,this.init=gqe(n.init,r),this.apply=gqe(n.apply,r)}}const vis=[new v7("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new v7("selection",{init(s,t){return s.selection||no.atStart(t.doc)},apply(s){return s.selection}}),new v7("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new v7("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class Jje{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=vis.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 v7(r.key,r.spec.state,r))})}}class IP{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 Jje(t.schema,t.plugins),i=new IP(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=g4.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=no.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 _ft(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=_ft(a,t,{})),n[r]=a}return n}class Zm{constructor(t){this.spec=t,this.props={},t.props&&_ft(t.props,this,this.props),this.key=t.key?t.key.key:wft("plugin")}getState(t){return t[this.key]}}const e2e=Object.create(null);function wft(s){return s in e2e?s+"$"+ ++e2e[s]:(e2e[s]=0,s+"$")}class dx{constructor(t="key"){this.key=wft(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const af=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},I8=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let ICe=null;const j2=function(s,t,n){let r=ICe||(ICe=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},bis=function(){ICe=null},NM=function(s,t,n,r){return n&&(yqe(s,t,n,r,-1)||yqe(s,t,n,r,1))},_is=/^(img|br|input|textarea|hr)$/i;function yqe(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:kv(s))){let l=s.parentNode;if(!l||l.nodeType!=1||yU(s)||_is.test(s.nodeName)||s.contentEditable=="false")return!1;t=af(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?kv(s):0}else return!1}}function kv(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function wis(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=kv(s)}else if(s.parentNode&&!yU(s))t=af(s),s=s.parentNode;else return null}}function jis(s,t){for(;;){if(s.nodeType==3&&t2),bv=P8||(Lw?/Mac/.test(Lw.platform):!1),kft=Lw?/Win/.test(Lw.platform):!1,z2=/Android \d/.test(sC),vU=!!vqe&&"webkitFontSmoothing"in vqe.documentElement.style,Cis=vU?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Tis(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 a2(s,t){return typeof s=="number"?s:s[t]}function Eis(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 bqe(s,t,n){let r=s.someProp("scrollThreshold")||0,a=s.someProp("scrollMargin")||5,i=s.dom.ownerDocument;for(let l=n||s.dom;l;){if(l.nodeType!=1){l=I8(l);continue}let o=l,c=o==i.body,d=c?Tis(i):Eis(o),u=0,h=0;if(t.topd.bottom-a2(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+a2(a,"top")-d.top:t.bottom-d.bottom+a2(a,"bottom")),t.leftd.right-a2(r,"right")&&(u=t.right-d.right+a2(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let f=o.scrollLeft,g=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let b=o.scrollLeft-f,v=o.scrollTop-g;t={left:t.left-b,top:t.top-v,right:t.right-b,bottom:t.bottom-v}}let p=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(p))break;l=p=="absolute"?l.offsetParent:I8(l)}}function Ais(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:Sft(s.dom)}}function Sft(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=I8(r));return t}function Mis({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;Cft(n,r==0?0:r-t)}function Cft(s,t){for(let n=0;n=o){l=Math.max(g.bottom,l),o=Math.min(g.top,o);let b=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?Pis(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:Tft(n,a)}function Pis(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 P6e(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function Lis(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 Ris(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 Eft(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;vU&&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=Ris(s,r,a,t))}o==null&&(o=Dis(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function _qe(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,yF(qk(j2(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==kv(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return t2e(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==kv(r))){let c=r.childNodes[a-1],d=c.nodeType==3?j2(c,kv(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return yF(qk(d,1),!1)}if(i==null&&a=0)}function yF(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 t2e(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 Mft(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 zis(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return Mft(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=Aft(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=j2(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 Bis=/[\u0590-\u08ac]/;function $is(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?!Bis.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:Mft(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),p=o.caretBidiLevel;o.modify("move",n,"character");let f=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:g,focusOffset:b}=s.domSelectionRange(),v=g&&!f.contains(g.nodeType==1?g:g.parentNode)||c==g&&d==b;try{o.collapse(u,h),c&&(c!=u||d!=h)&&o.extend&&o.extend(c,d)}catch{}return p!=null&&(o.caretBidiLevel=p),v}):r.pos==r.start()||r.pos==r.end()}let wqe=null,jqe=null,Nqe=!1;function Uis(s,t,n){return wqe==t&&jqe==n?Nqe:(wqe=t,jqe=n,Nqe=n=="up"||n=="down"?zis(s,t,n):$is(s,t,n))}const Gv=0,kqe=1,QE=2,Dw=3;class bU{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=Gv,r.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,n,r){return!1}matchesHack(t){return!1}parseRule(){return null}stopEvent(t){return!1}get size(){let t=0;for(let n=0;naf(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 Pft){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 Ift&&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?af(i.dom)+1:0}}else{let i,l=!0;for(;i=r=u&&n<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(t,n,u);t=l;for(let h=o;h>0;h--){let p=this.children[h-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){a=af(p.dom)+1;break}t-=p.size}a==-1&&(a=0)}if(a>-1&&(d>n||o==this.children.length-1)){n=d;for(let u=o+1;ug&&ln){let g=o;o=c,c=g}let f=document.createRange();f.setEnd(c.node,c.offset),f.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(f)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,n){for(let r=0,a=0;a=r:tr){let o=r+i.border,c=l-i.border;if(t>=o&&n<=c){this.dirty=t==r||n==l?QE:kqe,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=Dw:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?QE:Dw}r=l}this.dirty=QE}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?QE:kqe;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==Gv&&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 qis extends bU{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 kM extends bU{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=YM.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new kM(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&Dw||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=Dw&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=Gv){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=OCe(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}=YM.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!h&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let p=u;return u=Rft(u,r,n),d?c=new Vis(t,n,r,a,u,h||null,p,d,i,l+1):n.isText?new tve(t,n,r,a,u,p,i):new v4(t,n,r,a,u,h||null,p,i,l+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){t.contentElement=r.dom.parentNode;break}}t.contentElement||(t.getContent=()=>Vr.empty)}return t}matchesNode(t,n,r){return this.dirty==Gv&&t.eq(this.node)&&$fe(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 Gis(this,l&&l.node,t);Yis(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?nd.none:this.node.child(u).marks,r,t,u),c.placeWidget(d,t,a)},(d,u,h,p)=>{c.syncToMarks(d.marks,r,t,p);let f;c.findNodeMatch(d,u,h,p)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,u,h,f,t)||c.updateNextNode(d,u,h,t,p,a)||c.addNode(d,u,h,t,a),a+=d.nodeSize}),c.syncToMarks([],r,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==QE)&&(l&&this.protectLocalComposition(t,l),Lft(this.contentDOM,this.children,t),P8&&Zis(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof Ki)||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=Qis(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 qis(this,i,n,a);t.input.compositionNodes.push(l),this.children=OCe(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==Dw||!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=Gv}updateOuterDeco(t){if($fe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Dft(this.dom,this.nodeDOM,RCe(this.outerDeco,this.node,n),RCe(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 Sqe(s,t,n,r,a){Rft(r,t,s);let i=new v4(void 0,s,t,n,r,r,r,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class tve extends v4{constructor(t,n,r,a,i,l,o){super(t,n,r,a,i,null,l,o,0)}parseRule(){let t=this.nodeDOM.parentNode;for(;t&&t!=this.dom&&!t.pmIsDeco;)t=t.parentNode;return{skip:t||!0}}update(t,n,r,a){return this.dirty==Dw||this.dirty!=Gv&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=Gv||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=Gv,!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 tve(this.parent,a,this.outerDeco,this.innerDeco,i,i,r)}markDirty(t,n){super.markDirty(t,n),this.dom!=this.nodeDOM&&(t==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=Dw)}get domAtom(){return!1}isText(t){return this.node.text==t}}class Pft extends bU{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==Gv&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Vis extends v4{constructor(t,n,r,a,i,l,o,c,d,u){super(t,n,r,a,i,l,o,d,u),this.spec=c}update(t,n,r,a){if(this.dirty==Dw)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 Lft(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=kM.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 kM)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 Kis(s,t){return s.type.side-t.type.side}function Yis(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+p.nodeSize;if(p.isText){let v=g;l!v.inline):o.slice();r(p,b,t.forChild(i,p),f),i=g}}function Zis(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 Qis(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 OCe(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 L6e(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(eve(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&$i.isSelectable(h)&&a.parent&&!(h.isInline&&Nis(n.focusNode,n.focusOffset,a.dom))){let p=a.posBefore;d=new $i(l==p?o:r.resolve(p))}}else{if(n instanceof s.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=l,p=l;for(let f=0;f{(n.anchorNode!=r||n.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!Oft(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function Jis(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,af(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&Yg&&y4<=11&&(n.disabled=!0,n.disabled=!1)}function Fft(s,t){if(t instanceof $i){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(Mqe(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else Mqe(s)}function Mqe(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function D6e(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||Ki.between(t,n,r)}function Iqe(s){return s.editable&&!s.hasFocus()?!1:zft(s)}function zft(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 eos(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return NM(t.node,t.offset,n.anchorNode,n.anchorOffset)}function FCe(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&&no.findFrom(i,t)}function Jk(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function Pqe(s,t,n){let r=s.state.selection;if(r instanceof Ki)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 Jk(s,new Ki(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=FCe(s.state,t);return a&&a instanceof $i?Jk(s,a):!1}else if(!(bv&&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?$i.isSelectable(i)?Jk(s,new $i(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):vU?Jk(s,new Ki(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof $i&&r.node.isInline)return Jk(s,new Ki(t>0?r.$to:r.$from));{let a=FCe(s.state,t);return a?Jk(s,a):!1}}}function Ufe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function dz(s,t){let n=s.pmViewDesc;return n&&n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function SI(s,t){return t<0?tos(s):sos(s)}function tos(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(Hv&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(dz(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(Bft(n))break;{let o=n.previousSibling;for(;o&&dz(o,-1);)a=n.parentNode,i=af(o),o=o.previousSibling;if(o)n=o,r=Ufe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?zCe(s,n,r):a&&zCe(s,a,i)}function sos(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=Ufe(n),i,l;for(;;)if(r{s.state==a&&sN(s)},50)}function Lqe(s,t){let n=s.state.doc.resolve(t);if(!(hf||kft)&&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 Dqe(s,t,n){let r=s.state.selection;if(r instanceof Ki&&!r.empty||n.indexOf("s")>-1||bv&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=FCe(s.state,t);if(l&&l instanceof $i)return Jk(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof Vv?no.near(l,t):no.findFrom(l,t);return o?Jk(s,o):!1}return!1}function Rqe(s,t){if(!(s.state.selection instanceof Ki))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 Oqe(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function aos(s){if(!ax||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;Oqe(s,r,"true"),setTimeout(()=>Oqe(s,r,"false"),20)}return!1}function ios(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function oos(s,t){let n=t.keyCode,r=ios(t);if(n==8||bv&&n==72&&r=="c")return Rqe(s,-1)||SI(s,-1);if(n==46&&!t.shiftKey||bv&&n==68&&r=="c")return Rqe(s,1)||SI(s,1);if(n==13||n==27)return!0;if(n==37||bv&&n==66&&r=="c"){let a=n==37?Lqe(s,s.state.selection.from)=="ltr"?-1:1:-1;return Pqe(s,a,r)||SI(s,a)}else if(n==39||bv&&n==70&&r=="c"){let a=n==39?Lqe(s,s.state.selection.from)=="ltr"?1:-1:1;return Pqe(s,a,r)||SI(s,a)}else{if(n==38||bv&&n==80&&r=="c")return Dqe(s,-1,r)||SI(s,-1);if(n==40||bv&&n==78&&r=="c")return aos(s)||Dqe(s,1,r)||SI(s,1);if(r==(bv?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function R6e(s,t){s.someProp("transformCopied",f=>{t=f(t,s)});let n=[],{content:r,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,i--;let f=r.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let l=s.someProp("clipboardSerializer")||YM.fromSchema(s.state.schema),o=Gft(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=Hft[d.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let g=o.createElement(u[f]);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 p=s.someProp("clipboardTextSerializer",f=>f(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:p,slice:t}}function $ft(s,t,n,r,a){let i=a.parent.type.spec.code,l,o;if(!n&&!t)return null;let c=!!t&&(r||i||!n);if(c){if(s.someProp("transformPastedText",p=>{t=p(t,i||r,s)}),i)return o=new ka(Vr.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",p=>{o=p(o,s,!0)}),o;let h=s.someProp("clipboardTextParser",p=>p(t,a,r,s));if(h)o=h;else{let p=a.marks(),{schema:f}=s.state,g=YM.fromSchema(f);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(b=>{let v=l.appendChild(document.createElement("p"));b&&v.appendChild(g.serializeNode(f.text(b,p)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=uos(n),vU&&hos(l);let d=l&&l.querySelector("[data-pm-slice]"),u=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let h=+u[3];h>0;h--){let p=l.firstChild;for(;p&&p.nodeType!=1;)p=p.nextSibling;if(!p)break;l=p}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||oz.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!los.test(p.parentNode.nodeName)?{ignore:!0}:null}})),u)o=mos(Fqe(o,+u[1],+u[2]),u[4]);else if(o=ka.maxOpen(cos(o.content,a),!0),o.openStart||o.openEnd){let h=0,p=0;for(let f=o.content.firstChild;h{o=h(o,s,c)}),o}const los=/^(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 cos(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&&qft(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=Vft(l[l.length-1],i.length));let u=Uft(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return Vr.from(l)}return s}function Uft(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,Vr.from(s));return s}function qft(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(Vr.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function Fqe(s,t,n){return tn})),n2e.createHTML(s)):s}function uos(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=Gft().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(s),a;if((a=r&&Hft[r[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),n.innerHTML=dos(s),a)for(let i=0;i=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;a=Vr.from(c.create(r[o+1],a)),i++,l++}return new ka(a,i,l)}const ig={},og={},pos={touchstart:!0,touchmove:!0};class fos{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 xos(s){for(let t in ig){let n=ig[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{yos(s,r)&&!O6e(s,r)&&(s.editable||!(r.type in og))&&n(s,r)},pos[t]?{passive:!0}:void 0)}ax&&s.dom.addEventListener("input",()=>null),$Ce(s)}function DS(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function gos(s){s.domObserver.stop();for(let t in s.input.eventHandlers)s.dom.removeEventListener(t,s.input.eventHandlers[t]);clearTimeout(s.input.composingTimeout),clearTimeout(s.input.lastIOSEnterFallbackTimeout)}function $Ce(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>O6e(s,r))})}function O6e(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function yos(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 vos(s,t){!O6e(s,t)&&ig[t.type]&&(s.editable||!(t.type in og))&&ig[t.type](s,t)}og.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!Kft(s,n)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(z2&&hf&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),P8&&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,$E(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||oos(s,n)?n.preventDefault():DS(s,"key")};og.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};og.keypress=(s,t)=>{let n=t;if(Kft(s,n)||!n.charCode||n.ctrlKey&&!n.altKey||bv&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof Ki)||!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 sve(s){return{left:s.clientX,top:s.clientY}}function bos(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function F6e(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 BL(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 _os(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&$i.isSelectable(r)?(BL(s,new $i(n)),!0):!1}function wos(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof $i&&(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($i.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?(BL(s,$i.create(s.state.doc,a)),!0):!1}function jos(s,t,n,r,a){return F6e(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?wos(s,n):_os(s,n))}function Nos(s,t,n,r){return F6e(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function kos(s,t,n,r){return F6e(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||Sos(s,n,r)}function Sos(s,t,n){if(n.button!=0)return!1;let r=s.state.doc;if(t==-1)return r.inlineContent?(BL(s,Ki.create(r,0,r.content.size)),!0):!1;let a=r.resolve(t);for(let i=a.depth+1;i>0;i--){let l=i>a.depth?a.nodeAfter:a.node(i),o=a.before(i);if(l.inlineContent)BL(s,Ki.create(r,o+1,o+1+l.content.size));else if($i.isSelectable(l))BL(s,$i.create(r,o));else continue;return!0}}function z6e(s){return qfe(s)}const Wft=bv?"metaKey":"ctrlKey";ig.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=z6e(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&bos(n,s.input.lastClick)&&!n[Wft]&&s.input.lastClick.button==n.button&&(s.input.lastClick.type=="singleClick"?i="doubleClick":s.input.lastClick.type=="doubleClick"&&(i="tripleClick")),s.input.lastClick={time:a,x:n.clientX,y:n.clientY,type:i,button:n.button};let l=s.posAtCoords(sve(n));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new Cos(s,l,n,!!r)):(i=="doubleClick"?Nos:kos)(s,l.pos,l.inside,n)?n.preventDefault():DS(s,"pointer"))};class Cos{constructor(t,n,r,a){this.view=t,this.pos=n,this.event=r,this.flushed=a,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=t.state.doc,this.selectNode=!!r[Wft],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 $i&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Hv&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this)),DS(t,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>sN(this.view)),this.view.input.mouseDown=null}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(sve(t))),this.updateAllowDefault(t),this.allowDefault||!n?DS(this.view,"pointer"):jos(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||ax&&this.mightDrag&&!this.mightDrag.node.isAtom||hf&&!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)?(BL(this.view,no.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):DS(this.view,"pointer")}move(t){this.updateAllowDefault(t),DS(this.view,"pointer"),t.buttons==0&&this.done()}updateAllowDefault(t){!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4)&&(this.allowDefault=!0)}}ig.touchstart=s=>{s.input.lastTouch=Date.now(),z6e(s),DS(s,"pointer")};ig.touchmove=s=>{s.input.lastTouch=Date.now(),DS(s,"pointer")};ig.contextmenu=s=>z6e(s);function Kft(s,t){return s.composing?!0:ax&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const Tos=z2?5e3:-1;og.compositionstart=og.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof Ki&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||hf&&kft&&Eos(s)))s.markCursor=s.state.storedMarks||n.marks(),qfe(s,!0),s.markCursor=null;else if(qfe(s,!t.selection.empty),Hv&&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}Yft(s,Tos)};function Eos(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"}og.compositionend=(s,t)=>{s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=t.timeStamp,s.input.compositionPendingChanges=s.domObserver.pendingRecords().length?s.input.compositionID:0,s.input.compositionNode=null,s.input.badSafariComposition?s.domObserver.forceFlush():s.input.compositionPendingChanges&&Promise.resolve().then(()=>s.domObserver.flush()),s.input.compositionID++,Yft(s,20))};function Yft(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>qfe(s),t))}function Zft(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Mos());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function Aos(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=wis(t.focusNode,t.focusOffset),r=jis(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 Mos(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function qfe(s,t=!1){if(!(z2&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),Zft(s),t||s.docView&&s.docView.dirty){let n=L6e(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 Ios(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 NB=Yg&&y4<15||P8&&Cis<604;ig.copy=og.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=NB?null:n.clipboardData,l=r.content(),{dom:o,text:c}=R6e(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):Ios(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Pos(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function Los(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?kB(s,r.value,null,a,t):kB(s,r.textContent,r.innerHTML,a,t)},50)}function kB(s,t,n,r,a){let i=$ft(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||ka.empty)))return!0;if(!i)return!1;let l=Pos(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 Qft(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," "):""}og.paste=(s,t)=>{let n=t;if(s.composing&&!z2)return;let r=NB?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&kB(s,Qft(r),r.getData("text/html"),a,n)?n.preventDefault():Los(s,n)};class Xft{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const Dos=bv?"altKey":"ctrlKey";function Jft(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[Dos]}ig.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(sve(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof $i?a.to-1:a.to))){if(r&&r.mightDrag)l=$i.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=$i.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=R6e(s,o);(!n.dataTransfer.files.length||!hf||Nft>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(NB?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",NB||n.dataTransfer.setData("text/plain",d),s.dragging=new Xft(u,Jft(s,n),l)};ig.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};og.dragover=og.dragenter=(s,t)=>t.preventDefault();og.drop=(s,t)=>{try{Ros(s,t,s.dragging)}finally{s.dragging=null}};function Ros(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(sve(t));if(!r)return;let a=s.state.doc.resolve(r.pos),i=n&&n.slice;i?s.someProp("transformPasted",f=>{i=f(i,s,!1)}):i=$ft(s,Qft(t.dataTransfer),NB?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&Jft(s,t));if(s.someProp("handleDrop",f=>f(s,t,i||ka.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?fft(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:f}=n;f?f.replace(c):c.deleteSelection()}let d=c.mapping.map(o),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,h=c.doc;if(u?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(h))return;let p=c.doc.resolve(d);if(u&&$i.isSelectable(i.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new $i(p));else{let f=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((g,b,v,j)=>f=j),c.setSelection(D6e(s,p,c.doc.resolve(f)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}ig.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())&&sN(s)},20))};ig.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)};ig.beforeinput=(s,t)=>{if(hf&&z2&&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,$E(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 og)ig[s]=og[s];function SB(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 Vfe{constructor(t,n){this.toDOM=t,this.spec=n||YA,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 Qx(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof Vfe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&SB(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class b4{constructor(t,n){this.attrs=t,this.spec=n||YA}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 Qx(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==Kf||t.maps.length==0?this:this.mapInner(t,n,0,0,r||YA)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=txt(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 b4){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,YA));return mS.from(r)}forChild(t,n){if(n.isLeaf)return oh.empty;let r=[];for(let a=0;an instanceof oh)?t:t.reduce((n,r)=>n.concat(r instanceof oh?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let v=b-g-(f-p);for(let j=0;j_+u-h)continue;let S=o[j]+u-h;f>=S?o[j+1]=p<=S?-2:-1:p>=u&&v&&(o[j]+=v,o[j+1]+=v)}h+=v}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let p=n.map(s[d+1]+i,-1),f=p-a,{index:g,offset:b}=r.content.findIndex(h),v=r.maybeChild(g);if(v&&b==h&&b+v.nodeSize==f){let j=o[d+2].mapInner(n,v,u+1,s[d]+i+1,l);j!=Kf?(o[d]=h,o[d+1]=f,o[d+2]=j):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=Fos(o,s,t,n,a,i,l),u=Hfe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=txt(s,o,c+n);if(d){i=!0;let u=Hfe(d,o,n+c+1,r);u!=Kf&&a.push(c,c+o.nodeSize,u)}});let l=ext(i?sxt(s):s,-n).sort(ZA);for(let o=0;o0;)t++;s.splice(t,0,n)}function r2e(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=Kf&&t.push(r)}),s.cursorWrapper&&t.push(oh.create(s.state.doc,[s.cursorWrapper.deco])),mS.from(t)}const zos={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Bos=Yg&&y4<=11;class $os{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 Uos{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new $os,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():ax&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Bos&&(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,zos)),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(Iqe(this.view)){if(this.suppressingSelectionUpdates)return sN(this.view);if(Yg&&y4<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&NM(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=I8(i))n.add(i);for(let i=t.anchorNode;i;i=I8(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)&&Iqe(t)&&!this.ignoreSelectionChange(r),i=-1,l=-1,o=!1,c=[];if(t.editable)for(let u=0;uu.nodeName=="BR")&&(t.input.lastKeyCode==8||t.input.lastKeyCode==46)){for(let u of c)if(u.nodeName=="BR"&&u.parentNode){let h=u.nextSibling;for(;h&&h.nodeType==1;){if(h.contentEditable=="false"){u.parentNode.removeChild(u);break}h=h.firstChild}}}else if(Hv&&c.length){let u=c.filter(h=>h.nodeName=="BR");if(u.length==2){let[h,p]=u;h.parentNode&&h.parentNode.parentNode==p.parentNode?p.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let p of u){let f=p.parentNode;f&&f.nodeName=="LI"&&(!h||Hos(t,h)!=f)&&p.remove()}}}let d=null;i<0&&a&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)-1||a)&&(i>-1&&(t.docView.markDirty(i,l),qos(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,Gos(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||sN(t),this.currentSelection.set(r))}registerMutation(t,n){if(n.indexOf(t.target)>-1)return null;let r=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(r==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!r||r.ignoreMutation(t))return null;if(t.type=="childList"){for(let u=0;ua;v--){let j=r.childNodes[v-1],_=j.pmViewDesc;if(j.nodeName=="BR"&&!_){i=v;break}if(!_||_.size)break}let h=s.state.doc,p=s.someProp("domParser")||oz.fromSchema(s.state.schema),f=h.resolve(l),g=null,b=p.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:a,to:i,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:Kos,context:f});if(d&&d[0].pos!=null){let v=d[0].pos,j=d[1]&&d[1].pos;j==null&&(j=v),g={anchor:v+l,head:j+l}}return{doc:b,sel:g,from:l,to:o}}function Kos(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(ax&&/^(ul|ol)$/i.test(s.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(s.parentNode.lastChild==s||ax&&/^(tr|table)$/i.test(s.parentNode.nodeName))return{ignore:!0}}else if(s.nodeName=="IMG"&&s.getAttribute("mark-placeholder"))return{ignore:!0};return null}const Yos=/^(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 Zos(s,t,n,r,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let L=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,M=L6e(s,L);if(M&&!s.state.selection.eq(M)){if(hf&&z2&&s.input.lastKeyCode===13&&Date.now()-100z(s,$E(13,"Enter"))))return;let F=s.state.tr.setSelection(M);L=="pointer"?F.setMeta("pointer",!0):L=="key"&&F.scrollIntoView(),i&&F.setMeta("composition",i),s.dispatch(F)}return}let l=s.state.doc.resolve(t),o=l.sharedDepth(n);t=l.before(o+1),n=s.state.doc.resolve(n).after(o+1);let c=s.state.selection,d=Wos(s,t,n),u=s.state.doc,h=u.slice(d.from,d.to),p,f;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||z2)&&a.some(L=>L.nodeType==1&&!Yos.test(L.nodeName))&&(!g||g.endA>=g.endB)&&s.someProp("handleKeyDown",L=>L(s,$E(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!g)if(r&&c instanceof Ki&&!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 L=Vqe(s,s.state.doc,d.sel);if(L&&!L.eq(s.state.selection)){let M=s.state.tr.setSelection(L);i&&M.setMeta("composition",i),s.dispatch(M)}}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)),Yg&&y4<=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 b=d.doc.resolveNoCache(g.start-d.from),v=d.doc.resolveNoCache(g.endB-d.from),j=u.resolve(g.start),_=b.sameParent(v)&&b.parent.inlineContent&&j.end()>=g.endA;if((P8&&s.input.lastIOSEnter>Date.now()-225&&(!_||a.some(L=>L.nodeName=="DIV"||L.nodeName=="P"))||!_&&b.posL(s,$E(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>g.start&&Xos(u,g.start,g.endA,b,v)&&s.someProp("handleKeyDown",L=>L(s,$E(8,"Backspace")))){z2&&hf&&s.domObserver.suppressSelectionUpdates();return}hf&&g.endB==g.start&&(s.input.lastChromeDelete=Date.now()),z2&&!_&&b.start()!=v.start()&&v.parentOffset==0&&b.depth==v.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==g.endA&&(g.endB-=2,v=d.doc.resolveNoCache(g.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(L){return L(s,$E(13,"Enter"))})},20));let S=g.start,A=g.endA,T=L=>{let M=L||s.state.tr.replace(S,A,d.doc.slice(g.start-d.from,g.endB-d.from));if(d.sel){let F=Vqe(s,M.doc,d.sel);F&&!(hf&&s.composing&&F.empty&&(g.start!=g.endB||s.input.lastChromeDeletesN(s),20));let L=T(s.state.tr.delete(S,A)),M=u.resolve(g.start).marksAcross(u.resolve(g.endA));M&&L.ensureMarks(M),s.dispatch(L)}else if(g.endA==g.endB&&(D=Qos(b.parent.content.cut(b.parentOffset,v.parentOffset),j.parent.content.cut(j.parentOffset,g.endA-j.start())))){let L=T(s.state.tr);D.type=="add"?L.addMark(S,A,D.mark):L.removeMark(S,A,D.mark),s.dispatch(L)}else if(b.parent.child(b.index()).isText&&b.index()==v.index()-(v.textOffset?0:1)){let L=b.parent.textBetween(b.parentOffset,v.parentOffset),M=()=>T(s.state.tr.insertText(L,S,A));s.someProp("handleTextInput",F=>F(s,S,A,L,M))||s.dispatch(M())}else s.dispatch(T());else s.dispatch(T())}function Vqe(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:D6e(s,t.resolve(n.anchor),t.resolve(n.head))}function Qos(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||a2e(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 Jos(s,t,n,r,a){let i=s.findDiffStart(t,n);if(i==null)return null;let{a:l,b:o}=s.findDiffEnd(t,n+s.size,n+t.size);if(a=="end"){let c=Math.max(0,i-Math.min(l,o));r-=l+c-i}if(l=l?i-r:0;i-=c,i&&i=o?i-r:0;i-=c,i&&i=56320&&t<=57343&&n>=55296&&n<=56319}class nxt{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 fos,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(Zqe),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=Kqe(this),Wqe(this),this.nodeViews=Yqe(this),this.docView=Sqe(this.state.doc,Gqe(this),r2e(this),this.dom,this),this.domObserver=new Uos(this,(r,a,i,l)=>Zos(this,r,a,i,l)),this.domObserver.start(),xos(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&&$Ce(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(Zqe),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&&(Zft(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=n.plugins;if(o||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let f=Yqe(this);tls(f,this.nodeViews)&&(this.nodeViews=f,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&$Ce(this),this.editable=Kqe(this),Wqe(this);let c=r2e(this),d=Gqe(this),u=a.plugins!=t.plugins&&!a.doc.eq(t.doc)?"reset":t.scrollToSelection>a.scrollToSelection?"to selection":"preserve",h=i||!this.docView.matchesNode(t.doc,d,c);(h||!t.selection.eq(a.selection))&&(l=!0);let p=u=="preserve"&&l&&this.dom.style.overflowAnchor==null&&Ais(this);if(l){this.domObserver.stop();let f=h&&(Yg||hf)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&els(a.selection,t.selection);if(h){let g=hf?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Aos(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=Sqe(t.doc,d,c,this.dom,this)),g&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&eos(this))?sN(this,f):(Fft(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((r=this.dragging)===null||r===void 0)&&r.node&&!a.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,a),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():p&&Mis(p)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!this.dom.contains(t.nodeType==1?t:t.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof $i){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&bqe(this,n.getBoundingClientRect(),t)}else bqe(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 Ois(this,t)}coordsAtPos(t,n=1){return Aft(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 Uis(this,n||this.state,t)}pasteHTML(t,n){return kB(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return kB(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return R6e(this,t)}destroy(){this.docView&&(gos(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],r2e(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,bis())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return vos(this,t)}domSelectionRange(){let t=this.domSelection();return t?ax&&this.root.nodeType===11&&kis(this.dom.ownerDocument)==this.dom&&Vos(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}nxt.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function Gqe(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"),[Qx.node(0,s.state.doc.content.size,t)]}function Wqe(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:Qx.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function Kqe(s){return!s.someProp("editable",t=>t(s.state)===!1)}function els(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 Yqe(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 tls(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 Zqe(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 O4={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:"'"},Gfe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},sls=typeof navigator<"u"&&/Mac/.test(navigator.platform),nls=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var of=0;of<10;of++)O4[48+of]=O4[96+of]=String(of);for(var of=1;of<=24;of++)O4[of+111]="F"+of;for(var of=65;of<=90;of++)O4[of]=String.fromCharCode(of+32),Gfe[of]=String.fromCharCode(of);for(var i2e in O4)Gfe.hasOwnProperty(i2e)||(Gfe[i2e]=O4[i2e]);function rls(s){var t=sls&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||nls&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?Gfe:O4)[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 als=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),ils=typeof navigator<"u"&&/Win/.test(navigator.platform);function ols(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 rxt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const uls=(s,t,n)=>{let r=rxt(s,n);if(!r)return!1;let a=q6e(r);if(!a){let l=r.blockRange(),o=l&&eR(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(lxt(s,a,t,-1))return!0;if(r.parent.content.size==0&&(L8(i,"end")||$i.isSelectable(i)))for(let l=r.depth;;l--){let o=Xye(s.doc,r.before(l),r.after(l),ka.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},hls=(s,t,n)=>{let r=rxt(s,n);if(!r)return!1;let a=q6e(r);return a?axt(s,a,t):!1},mls=(s,t,n)=>{let r=ixt(s,n);if(!r)return!1;let a=V6e(r);return a?axt(s,a,t):!1};function axt(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=Xye(s.doc,i,c,ka.empty);if(!d||d.from!=i||d instanceof Jh&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(Ki.create(u.doc,i)),n(u.scrollIntoView())}return!0}function L8(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 pls=(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=q6e(r)}let l=i&&i.nodeBefore;return!l||!$i.isSelectable(l)?!1:(t&&t(s.tr.setSelection($i.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function q6e(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 ixt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=ixt(s,n);if(!r)return!1;let a=V6e(r);if(!a)return!1;let i=a.nodeAfter;if(lxt(s,a,t,1))return!0;if(r.parent.content.size==0&&(L8(i,"start")||$i.isSelectable(i))){let l=Xye(s.doc,r.before(),r.after(),ka.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 $i,a;if(r){if(n.node.isTextblock||!tC(s.doc,n.from))return!1;a=n.from}else if(a=Qye(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection($i.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},yls=(s,t)=>{let n=s.selection,r;if(n instanceof $i){if(n.node.isTextblock||!tC(s.doc,n.to))return!1;r=n.to}else if(r=Qye(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},vls=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&eR(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},bls=(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 oxt(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=oxt(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(no.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},wls=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof Vv||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=oxt(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(FL(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&eR(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)},Nls=(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($i.create(s.doc,a))),!0)};function kls(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||tC(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function lxt(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&kls(s,t,n))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(l=(o=a.contentMatchAt(a.childCount)).findWrapping(i.type))&&o.matchType(l[0]||i.type).validEnd){if(n){let f=t.pos+i.nodeSize,g=Vr.empty;for(let j=l.length-1;j>=0;j--)g=Vr.from(l[j].create(null,g));g=Vr.from(a.copy(g));let b=s.tr.step(new Ap(t.pos-1,f,t.pos,f,new ka(g,1,0),l.length,!0)),v=b.doc.resolve(f+2*l.length);v.nodeAfter&&v.nodeAfter.type==a.type&&tC(b.doc,v.pos)&&b.join(v.pos),n(b.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:no.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),p=h&&eR(h);if(p!=null&&p>=t.depth)return n&&n(s.tr.lift(h,p).scrollIntoView()),!0;if(d&&L8(i,"start",!0)&&L8(a,"end")){let f=a,g=[];for(;g.push(f),!f.isTextblock;)f=f.lastChild;let b=i,v=1;for(;!b.isTextblock;b=b.firstChild)v++;if(f.canReplace(f.childCount,f.childCount,b.content)){if(n){let j=Vr.empty;for(let S=g.length-1;S>=0;S--)j=Vr.from(g[S].copy(j));let _=s.tr.step(new Ap(t.pos-g.length,t.pos+i.nodeSize,t.pos+v,t.pos+i.nodeSize-v,new ka(j,g.length,0),0,!0));n(_.scrollIntoView())}return!0}}return!1}function cxt(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(Ki.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const Sls=cxt(-1),Cls=cxt(1);function Tls(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&A6e(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function Qqe(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 zfe(c,c,t.depth),t.endIndex=0;u--)i=Vr.from(n[u].type.create(n[u].attrs,i));s.step(new Ap(t.start-(r?2:0),t.end,t.start,t.end,new ka(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?Pls(t,n,s,i):Lls(t,n,i):!0:!1}}function Pls(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);ib;g--)f-=a.child(g).nodeSize,r.delete(f-1,f+1);let i=r.doc.resolve(n.start),l=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let o=n.startIndex==0,c=n.endIndex==a.childCount,d=i.node(-1),u=i.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?Vr.empty:Vr.from(a))))return!1;let h=i.pos,p=h+l.nodeSize;return r.step(new Ap(h-(o?1:0),p+(c?1:0),h+1,p-1,new ka((o?Vr.empty:Vr.from(a.copy(Vr.empty))).append(c?Vr.empty:Vr.from(a.copy(Vr.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function Dls(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=Vr.from(d?s.create():null),h=new ka(Vr.from(s.create(null,Vr.from(o.type.create(null,u)))),d?3:1,0),p=i.start,f=i.end;n(t.tr.step(new Ap(p-(d?3:1),f,p,f,h,1,!0)).scrollIntoView())}return!0}}function nve(s){const{state:t,transaction:n}=s;let{selection:r}=n,{doc:a}=n,{storedMarks:i}=n;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return i},get selection(){return r},get doc(){return a},get tr(){return r=n.selection,a=n.doc,i=n.storedMarks,n}}}class rve{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:r}=this,{view:a}=n,{tr:i}=r,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...u)=>{const h=c(...u)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,u=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(p=>p===!0)),h={...Object.fromEntries(Object.entries(r).map(([p,f])=>[p,(...b)=>{const v=this.buildProps(d,n),j=f(...b)(v);return o.push(j),h}])),run:u};return h}createCan(t){const{rawCommands:n,state:r}=this,a=!1,i=t||r.tr,l=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...u)=>d(...u)({...l,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o={tr:t,editor:a,view:l,state:nve({state:i,transaction:t}),dispatch:n?()=>{}:void 0,chain:()=>this.createChain(t,n),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...u)=>d(...u)(o)]))}};return o}}let Rls=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 di(s,t,n){return s.config[t]===void 0&&s.parent?di(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?di(s.parent,t,n):null}):s.config[t]}function ave(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 dxt(s){const t=[],{nodeExtensions:n,markExtensions:r}=ave(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=di(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(h=>{Object.entries(u.attributes).forEach(([p,f])=>{t.push({type:h,name:p,attribute:{...i,...f}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=di(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([u,h])=>{const p={...i,...h};typeof(p==null?void 0:p.default)=="function"&&(p.default=p.default()),p!=null&&p.isRequired&&(p==null?void 0:p.default)===void 0&&delete p.default,t.push({type:l.name,name:u,attribute:p})})}),t}function Ip(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 xu(...s){return s.filter(t=>!!t).reduce((t,n)=>{const r={...t};return Object.entries(n).forEach(([a,i])=>{if(!r[a]){r[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=r[a]?r[a].split(" "):[],d=o.filter(u=>!c.includes(u));r[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(u=>u.trim()).filter(Boolean):[],c=r[a]?r[a].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[h,p]=u.split(":").map(f=>f.trim());d.set(h,p)}),o.forEach(u=>{const[h,p]=u.split(":").map(f=>f.trim());d.set(h,p)}),r[a]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else r[a]=i}),r},{})}function UCe(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)=>xu(n,r),{})}function uxt(s){return typeof s=="function"}function el(s,t=void 0,...n){return uxt(s)?t?s.bind(t)(...n):s(...n):s}function Ols(s={}){return Object.keys(s).length===0&&s.constructor===Object}function Fls(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function Xqe(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):Fls(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function Jqe(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&Ols(n)?!1:n!=null))}function zls(s,t){var n;const r=dxt(s),{nodeExtensions:a,markExtensions:i}=ave(s),l=(n=a.find(d=>di(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(j=>j.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},p=s.reduce((j,_)=>{const S=di(_,"extendNodeSchema",h);return{...j,...S?S(d):{}}},{}),f=Jqe({...p,content:el(di(d,"content",h)),marks:el(di(d,"marks",h)),group:el(di(d,"group",h)),inline:el(di(d,"inline",h)),atom:el(di(d,"atom",h)),selectable:el(di(d,"selectable",h)),draggable:el(di(d,"draggable",h)),code:el(di(d,"code",h)),whitespace:el(di(d,"whitespace",h)),linebreakReplacement:el(di(d,"linebreakReplacement",h)),defining:el(di(d,"defining",h)),isolating:el(di(d,"isolating",h)),attrs:Object.fromEntries(u.map(j=>{var _;return[j.name,{default:(_=j==null?void 0:j.attribute)===null||_===void 0?void 0:_.default}]}))}),g=el(di(d,"parseHTML",h));g&&(f.parseDOM=g.map(j=>Xqe(j,u)));const b=di(d,"renderHTML",h);b&&(f.toDOM=j=>b({node:j,HTMLAttributes:UCe(j,u)}));const v=di(d,"renderText",h);return v&&(f.toText=v),[d.name,f]})),c=Object.fromEntries(i.map(d=>{const u=r.filter(v=>v.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},p=s.reduce((v,j)=>{const _=di(j,"extendMarkSchema",h);return{...v,..._?_(d):{}}},{}),f=Jqe({...p,inclusive:el(di(d,"inclusive",h)),excludes:el(di(d,"excludes",h)),group:el(di(d,"group",h)),spanning:el(di(d,"spanning",h)),code:el(di(d,"code",h)),attrs:Object.fromEntries(u.map(v=>{var j;return[v.name,{default:(j=v==null?void 0:v.attribute)===null||j===void 0?void 0:j.default}]}))}),g=el(di(d,"parseHTML",h));g&&(f.parseDOM=g.map(v=>Xqe(v,u)));const b=di(d,"renderHTML",h);return b&&(f.toDOM=v=>b({mark:v,HTMLAttributes:UCe(v,u)})),[d.name,f]}));return new rft({topNode:l,nodes:o,marks:c})}function l2e(s,t){return t.nodes[s]||t.marks[s]||null}function eVe(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function H6e(s,t){const n=YM.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const Bls=(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 G6e(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class ive{constructor(t){this.find=t.find,this.handler=t.handler}}const $ls=(s,t)=>{if(G6e(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 bH(s){var t;const{editor:n,from:r,to:a,text:i,rules:l,plugin:o}=s,{view:c}=n;if(c.composing)return!1;const d=c.state.doc.resolve(r);if(d.parent.type.spec.code||!((t=d.nodeBefore||d.nodeAfter)===null||t===void 0)&&t.marks.find(p=>p.type.spec.code))return!1;let u=!1;const h=Bls(d)+i;return l.forEach(p=>{if(u)return;const f=$ls(h,p.find);if(!f)return;const g=c.state.tr,b=nve({state:c.state,transaction:g}),v={from:r-(f[0].length-i.length),to:a},{commands:j,chain:_,can:S}=new rve({editor:n,state:b});p.handler({state:b,range:v,match:f,commands:j,chain:_,can:S})===null||!g.steps.length||(g.setMeta(o,{transform:g,from:r,to:a,text:i}),c.dispatch(g),u=!0)}),u}function Uls(s){const{editor:t,rules:n}=s,r=new Zm({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=H6e(Vr.from(u),l.schema);const{from:h}=c,p=h+u.length;bH({editor:t,from:h,to:p,text:u,rules:n,plugin:r})}),a.selectionSet||a.docChanged?null:i}},props:{handleTextInput(a,i,l,o){return bH({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&bH({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?bH({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function qls(s){return Object.prototype.toString.call(s).slice(8,-1)}function _H(s){return qls(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function ove(s,t){const n={...s};return _H(s)&&_H(t)&&Object.keys(t).forEach(r=>{_H(t[r])&&_H(s[r])?n[r]=ove(s[r],t[r]):n[r]=t[r]}),n}class Ab{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=el(di(this,"addOptions",{name:this.name}))),this.storage=el(di(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Ab(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>ove(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new Ab(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=el(di(n,"addOptions",{name:n.name})),n.storage=el(di(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 Vls(s){return typeof s=="number"}class Hls{constructor(t){this.find=t.find,this.handler=t.handler}}const Gls=(s,t,n)=>{if(G6e(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 Wls(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new rve({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(f,g)=>{if(!f.isTextblock||f.type.spec.code)return;const b=Math.max(r,g),v=Math.min(a,g+f.content.size),j=f.textBetween(b-g,v-g,void 0,"");Gls(j,i.find,l).forEach(S=>{if(S.index===void 0)return;const A=b+S.index+1,T=A+S[0].length,D={from:n.tr.mapping.map(A),to:n.tr.mapping.map(T)},L=i.handler({state:n,range:D,match:S,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(L)})}),h.every(f=>f!==null)}let wH=null;const Kls=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 Yls(s){const{editor:t,rules:n}=s;let r=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:u,from:h,to:p,rule:f,pasteEvt:g})=>{const b=u.tr,v=nve({state:u,transaction:b});if(!(!Wls({editor:t,state:v,from:Math.max(h-1,0),to:p.b-1,rule:f,pasteEvent:g,dropEvent:o})||!b.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,b}};return n.map(u=>new Zm({view(h){const p=g=>{var b;r=!((b=h.dom.parentElement)===null||b===void 0)&&b.contains(g.target)?h.dom.parentElement:null,r&&(wH=t)},f=()=>{wH&&(wH=null)};return window.addEventListener("dragstart",p),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",p),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(h,p)=>{if(i=r===h.dom.parentElement,o=p,!i){const f=wH;f!=null&&f.isEditable&&setTimeout(()=>{const g=f.state.selection;g&&f.commands.deleteRange({from:g.from,to:g.to})},10)}return!1},paste:(h,p)=>{var f;const g=(f=p.clipboardData)===null||f===void 0?void 0:f.getData("text/html");return l=p,a=!!(g!=null&&g.includes("data-pm-slice")),!1}}},appendTransaction:(h,p,f)=>{const g=h[0],b=g.getMeta("uiEvent")==="paste"&&!a,v=g.getMeta("uiEvent")==="drop"&&!i,j=g.getMeta("applyPasteRules"),_=!!j;if(!b&&!v&&!_)return;if(_){let{text:T}=j;typeof T=="string"?T=T:T=H6e(Vr.from(T),f.schema);const{from:D}=j,L=D+T.length,M=Kls(T);return c({rule:u,state:f,from:D,to:{b:L},pasteEvt:M})}const S=p.doc.content.findDiffStart(f.doc.content),A=p.doc.content.findDiffEnd(f.doc.content);if(!(!Vls(S)||!A||S===A.b))return c({rule:u,state:f,from:S,to:A,pasteEvt:l})}}))}function Zls(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class PP{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=PP.resolve(t),this.schema=zls(this.extensions,n),this.setupExtensions()}static resolve(t){const n=PP.sort(PP.flatten(t)),r=Zls(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=di(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=di(r,"priority")||100,l=di(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:l2e(n.name,this.schema)},a=di(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=PP.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:l2e(l.name,this.schema)},c=[],d=di(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&di(l,"exitable",o)&&(u.ArrowRight=()=>Ab.handleExit({editor:t,mark:l})),d){const b=Object.fromEntries(Object.entries(d()).map(([v,j])=>[v,()=>j({editor:t})]));u={...u,...b}}const h=cls(u);c.push(h);const p=di(l,"addInputRules",o);eVe(l,t.options.enableInputRules)&&p&&r.push(...p());const f=di(l,"addPasteRules",o);eVe(l,t.options.enablePasteRules)&&f&&a.push(...f());const g=di(l,"addProseMirrorPlugins",o);if(g){const b=g();c.push(...b)}return c}).flat();return[Uls({editor:t,rules:r}),...Yls({editor:t,rules:a}),...i]}get attributes(){return dxt(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=ave(this.extensions);return Object.fromEntries(n.filter(r=>!!di(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:Ip(r.name,this.schema)},l=di(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,p)=>{const f=UCe(c,a);return l()({node:c,view:d,getPos:u,decorations:h,innerDecorations:p,editor:t,extension:r,HTMLAttributes:f})};return[r.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var n;this.editor.extensionStorage[t.name]=t.storage;const r={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:l2e(t.name,this.schema)};t.type==="mark"&&(!((n=el(di(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=di(t,"onBeforeCreate",r),i=di(t,"onCreate",r),l=di(t,"onUpdate",r),o=di(t,"onSelectionUpdate",r),c=di(t,"onTransaction",r),d=di(t,"onFocus",r),u=di(t,"onBlur",r),h=di(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 Tf{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=el(di(this,"addOptions",{name:this.name}))),this.storage=el(di(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Tf(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>ove(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new Tf({...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=el(di(n,"addOptions",{name:n.name})),n.storage=el(di(n,"addStorage",{name:n.name,options:n.options})),n}}function hxt(s,t,n){const{from:r,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=n||{};let o="";return s.nodesBetween(r,a,(c,d,u,h)=>{var p;c.isBlock&&d>r&&(o+=i);const f=l==null?void 0:l[c.type.name];if(f)return u&&(o+=f({node:c,pos:d,parent:u,index:h,range:t})),!1;c.isText&&(o+=(p=c==null?void 0:c.text)===null||p===void 0?void 0:p.slice(Math.max(r,d)-d,a-d))}),o}function mxt(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const Qls=Tf.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Zm({key:new dx("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=mxt(n);return hxt(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),Xls=()=>({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),Jls=(s=!1)=>({commands:t})=>t.setContent("",s),ecs=()=>({state:s,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:u}=t,h=d.resolve(u.map(c)),p=d.resolve(u.map(c+o.nodeSize)),f=h.blockRange(p);if(!f)return;const g=eR(f);if(o.type.isTextblock){const{defaultType:b}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(f.start,b)}(g||g===0)&&t.lift(f,g)})}),!0},tcs=s=>t=>s(t),scs=()=>({state:s,dispatch:t})=>wls(s,t),ncs=(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 Ki(r.doc.resolve(Math.max(l-1,0)))),!0},rcs=()=>({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},acs=s=>({tr:t,state:n,dispatch:r})=>{const a=Ip(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},ics=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},ocs=()=>({state:s,dispatch:t})=>dls(s,t),lcs=()=>({commands:s})=>s.keyboardShortcut("Enter"),ccs=()=>({state:s,dispatch:t})=>_ls(s,t);function Wfe(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:G6e(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function pxt(s,t,n={}){return s.find(r=>r.type===t&&Wfe(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function tVe(s,t,n={}){return!!pxt(s,t,n)}function W6e(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),!pxt([...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&&tVe([...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=nC(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=W6e(c,i,t);if(h&&h.from<=d&&h.to>=u){const p=Ki.create(l,h.from,h.to);n.setSelection(p)}}return!0},ucs=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=()=>{(Kfe()||sVe())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),hcs()&&!Kfe()&&!sVe()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!fxt(n.state.selection))return l(),!0;const o=xxt(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},pcs=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),fcs=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),gxt=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&&gxt(r)}return s};function jH(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return gxt(n)}function CB(s,t,n){if(s instanceof g4||s instanceof Vr)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 Vr.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),CB("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new rft({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?oz.fromSchema(c).parseSlice(jH(s),n.parseOptions):oz.fromSchema(c).parse(jH(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=oz.fromSchema(t);return n.slice?i.parseSlice(jH(s),n.parseOptions).content:i.parse(jH(s),n.parseOptions)}return CB("",t,n)}function xcs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(no.near(s.doc.resolve(l),n))}const gcs=s=>!("type"in s),ycs=(s,t,n)=>({tr:r,dispatch:a,editor:i})=>{var l;if(a){n={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let o;const c=v=>{i.emit("contentError",{editor:i,error:v,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{CB(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(v){c(v)}try{o=CB(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(v){return c(v),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},p=!0,f=!0;if((gcs(o)?o:[o]).forEach(v=>{v.check(),p=p?v.isText&&v.marks.length===0:!1,f=f?v.isBlock:!1}),u===h&&f){const{parent:v}=r.doc.resolve(u);v.isTextblock&&!v.type.spec.code&&!v.childCount&&(u-=1,h+=1)}let b;if(p){if(Array.isArray(t))b=t.map(v=>v.text||"").join("");else if(t instanceof Vr){let v="";t.forEach(j=>{j.text&&(v+=j.text)}),b=v}else typeof t=="object"&&t&&t.text?b=t.text:b=t;r.insertText(b,u,h)}else b=o,r.replaceWith(u,h,b);n.updateSelection&&xcs(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:b}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:b})}return!0},vcs=()=>({state:s,dispatch:t})=>gls(s,t),bcs=()=>({state:s,dispatch:t})=>yls(s,t),_cs=()=>({state:s,dispatch:t})=>uls(s,t),wcs=()=>({state:s,dispatch:t})=>fls(s,t),jcs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=Qye(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},Ncs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=Qye(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},kcs=()=>({state:s,dispatch:t})=>hls(s,t),Scs=()=>({state:s,dispatch:t})=>mls(s,t);function yxt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Ccs(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=Ccs(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 TB(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?Ip(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,p)=>{if(h.isText)return;const f=Math.max(r,p),g=Math.min(a,p+h.nodeSize);o.push({node:h,from:f,to:g})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>Wfe(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,p)=>h+p.to-p.from,0)>=c}const Ecs=(s,t={})=>({state:n,dispatch:r})=>{const a=Ip(s,n.schema);return TB(n,a,t)?vls(n,r):!1},Acs=()=>({state:s,dispatch:t})=>jls(s,t),Mcs=s=>({state:t,dispatch:n})=>{const r=Ip(s,t.schema);return Ils(r)(t,n)},Ics=()=>({state:s,dispatch:t})=>bls(s,t);function lve(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function nVe(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 Pcs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=lve(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Ip(s,r.schema)),o==="mark"&&(l=nC(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,nVe(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(nVe(h.attrs,t)))})})}),!0):!1},Lcs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),Dcs=()=>({tr:s,dispatch:t})=>{if(t){const n=new Vv(s.doc);s.setSelection(n)}return!0},Rcs=()=>({state:s,dispatch:t})=>pls(s,t),Ocs=()=>({state:s,dispatch:t})=>xls(s,t),Fcs=()=>({state:s,dispatch:t})=>Nls(s,t),zcs=()=>({state:s,dispatch:t})=>Cls(s,t),Bcs=()=>({state:s,dispatch:t})=>Sls(s,t);function qCe(s,t,n={},r={}){return CB(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const $cs=(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=qCe(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 vxt(s,t){const n=nC(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 Ucs(s,t){const n=new M6e(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function qcs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function bxt(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 K6e(s){return t=>bxt(t.$from,s)}function Hcs(s,t){const n={from:0,to:s.content.size};return hxt(s,n,t)}function Gcs(s,t){const n=Ip(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 _xt(s,t){const n=lve(typeof t=="string"?t:t.name,s.schema);return n==="node"?Gcs(s,t):n==="mark"?vxt(s,t):{}}function Wcs(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 Kcs(s){const t=Wcs(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 Ycs(s){const{mapping:t,steps:n}=s,r=[];return t.maps.forEach((a,i)=>{const l=[];if(a.ranges.length)a.forEach((o,c)=>{l.push({from:o,to:c})});else{const{from:o,to:c}=n[i];if(o===void 0||c===void 0)return;l.push({from:o,to:c})}l.forEach(({from:o,to:c})=>{const d=t.slice(i).map(o,-1),u=t.slice(i).map(c),h=t.invert().map(d,-1),p=t.invert().map(u);r.push({oldRange:{from:h,to:p},newRange:{from:d,to:u}})})}),Kcs(r)}function Y6e(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=W6e(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 Zme(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 VCe(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?nC(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>Wfe(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:p})=>{const f=h.pos,g=p.pos;s.doc.nodesBetween(f,g,(b,v)=>{if(!b.isText&&!b.marks.length)return;const j=Math.max(f,v),_=Math.min(g,v+b.nodeSize),S=_-j;l+=S,o.push(...b.marks.map(A=>({mark:A,from:j,to:_})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>Wfe(h.mark.attrs,n,{strict:!1})).reduce((h,p)=>h+p.to-p.from,0),d=o.filter(h=>i?h.mark.type!==i&&h.mark.type.excludes(i):!0).reduce((h,p)=>h+p.to-p.from,0);return(c>0?c+d:c)>=l}function Zcs(s,t,n={}){if(!t)return TB(s,null,n)||VCe(s,null,n);const r=lve(t,s.schema);return r==="node"?TB(s,t,n):r==="mark"?VCe(s,t,n):!1}function rVe(s,t){const{nodeExtensions:n}=ave(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=el(di(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function Z6e(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&&(Z6e(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function Qcs(s){return s instanceof $i}function Xcs(s,t,n){var r;const{selection:a}=t;let i=null;if(fxt(a)&&(i=a.$cursor),i){const o=(r=s.storedMarks)!==null&&r!==void 0?r:i.marks();return!!n.isInSet(o)||!o.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(n):!1;return s.doc.nodesBetween(o.pos,c.pos,(u,h,p)=>{if(d)return!1;if(u.isInline){const f=!p||p.type.allowsMarkType(n),g=!!n.isInSet(u.marks)||!u.marks.some(b=>b.type.excludes(n));d=f&&g}return!d}),d})}const Jcs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=nC(s,r.schema);if(a)if(l){const d=vxt(r,c);n.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(u,h,(p,f)=>{const g=Math.max(f,u),b=Math.min(f+p.nodeSize,h);p.marks.find(j=>j.type===c)?p.marks.forEach(j=>{c===j.type&&n.addMark(g,b,c.create({...j.attrs,...t}))}):n.addMark(g,b,c.create(t))})});return Xcs(r,n,c)},eds=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),tds=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=Ip(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})=>Qqe(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>Qqe(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},sds=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=JE(s,0,r.content.size),i=$i.create(r,a);t.setSelection(i)}return!0},nds=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Ki.atStart(r).from,o=Ki.atEnd(r).to,c=JE(a,l,o),d=JE(i,l,o),u=Ki.create(r,c,d);t.setSelection(u)}return!0},rds=s=>({state:t,dispatch:n})=>{const r=Ip(s,t.schema);return Dls(r)(t,n)};function aVe(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 ads=({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=Zme(d,o.node().type.name,o.node().attrs);if(i instanceof $i&&i.node.isBlock)return!o.parentOffset||!FL(l,o.pos)?!1:(r&&(s&&aVe(n,a.extensionManager.splittableMarks),t.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,p=o.depth===0?void 0:qcs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let f=h&&p?[{type:p,attrs:u}]:void 0,g=FL(t.doc,t.mapping.map(o.pos),1,f);if(!f&&!g&&FL(t.doc,t.mapping.map(o.pos),1,p?[{type:p}]:void 0)&&(g=!0,f=p?[{type:p,attrs:u}]:void 0),r){if(g&&(i instanceof Ki&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,f),p&&!h&&!o.parentOffset&&o.parent.type!==p)){const b=t.mapping.map(o.before()),v=t.doc.resolve(b);o.node(-1).canReplaceWith(v.index(),v.index()+1,p)&&t.setNodeMarkup(t.mapping.map(o.before()),p)}s&&aVe(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return g},ids=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=Ip(s,r.schema),{$from:c,$to:d}=r.selection,u=r.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const h=c.node(-1);if(h.type!==o)return!1;const p=i.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==o||c.index(-2)!==c.node(-2).childCount-1)return!1;if(a){let j=Vr.empty;const _=c.index(-1)?1:c.index(-2)?2:3;for(let M=c.depth-_;M>=c.depth-3;M-=1)j=Vr.from(c.node(M).copy(j));const S=c.indexAfter(-1){if(L>-1)return!1;M.isTextblock&&M.content.size===0&&(L=F+1)}),L>-1&&n.setSelection(Ki.near(n.doc.resolve(L))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,g={...Zme(p,h.type.name,h.attrs),...t},b={...Zme(p,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const v=f?[{type:o,attrs:g},{type:f,attrs:b}]:[{type:o,attrs:g}];if(!FL(n.doc,c.pos,2))return!1;if(a){const{selection:j,storedMarks:_}=r,{splittableMarks:S}=i.extensionManager,A=_||j.$to.parentOffset&&j.$from.marks();if(n.split(c.pos,2,v).scrollIntoView(),!A||!a)return!0;const T=A.filter(D=>S.includes(D.type.name));n.ensureMarks(T)}return!0},c2e=(s,t)=>{const n=K6e(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)&&tC(s.doc,n.pos)&&s.join(n.pos),!0},d2e=(s,t)=>{const n=K6e(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)&&tC(s.doc,r)&&s.join(r),!0},ods=(s,t,n,r={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:u})=>{const{extensions:h,splittableMarks:p}=a.extensionManager,f=Ip(s,l.schema),g=Ip(t,l.schema),{selection:b,storedMarks:v}=l,{$from:j,$to:_}=b,S=j.blockRange(_),A=v||b.$to.parentOffset&&b.$from.marks();if(!S)return!1;const T=K6e(D=>rVe(D.type.name,h))(b);if(S.depth>=1&&T&&S.depth-T.depth<=1){if(T.node.type===f)return d.liftListItem(g);if(rVe(T.node.type.name,h)&&f.validContent(T.node.content)&&o)return c().command(()=>(i.setNodeMarkup(T.pos,f),!0)).command(()=>c2e(i,f)).command(()=>d2e(i,f)).run()}return!n||!A||!o?c().command(()=>u().wrapInList(f,r)?!0:d.clearNodes()).wrapInList(f,r).command(()=>c2e(i,f)).command(()=>d2e(i,f)).run():c().command(()=>{const D=u().wrapInList(f,r),L=A.filter(M=>p.includes(M.type.name));return i.ensureMarks(L),D?!0:d.clearNodes()}).wrapInList(f,r).command(()=>c2e(i,f)).command(()=>d2e(i,f)).run()},lds=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=nC(s,r.schema);return VCe(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},cds=(s,t,n={})=>({state:r,commands:a})=>{const i=Ip(s,r.schema),l=Ip(t,r.schema),o=TB(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})},dds=(s,t={})=>({state:n,commands:r})=>{const a=Ip(s,n.schema);return TB(n,a,t)?r.lift(a):r.wrapIn(a,t)},uds=()=>({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},hds=()=>({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},mds=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=nC(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:p,to:f}=o;const g=(i=d.marks().find(v=>v.type===c))===null||i===void 0?void 0:i.attrs,b=W6e(d,c,g);b&&(p=b.from,f=b.to),n.removeMark(p,f,c)}else h.forEach(p=>{n.removeMark(p.$from.pos,p.$to.pos,c)});return n.removeStoredMark(c),!0},pds=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=lve(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Ip(s,r.schema)),o==="mark"&&(l=nC(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,p,f,g;n.selection.empty?r.doc.nodesBetween(d,u,(b,v)=>{i&&i===b.type&&(f=Math.max(v,d),g=Math.min(v+b.nodeSize,u),h=v,p=b)}):r.doc.nodesBetween(d,u,(b,v)=>{v=d&&v<=u&&(i&&i===b.type&&n.setNodeMarkup(v,void 0,{...b.attrs,...t}),l&&b.marks.length&&b.marks.forEach(j=>{if(l===j.type){const _=Math.max(v,d),S=Math.min(v+b.nodeSize,u);n.addMark(_,S,l.create({...j.attrs,...t}))}}))}),p&&(h!==void 0&&n.setNodeMarkup(h,void 0,{...p.attrs,...t}),l&&p.marks.length&&p.marks.forEach(b=>{l===b.type&&n.addMark(f,g,l.create({...b.attrs,...t}))}))}),!0):!1},fds=(s,t={})=>({state:n,dispatch:r})=>{const a=Ip(s,n.schema);return Tls(a,t)(n,r)},xds=(s,t={})=>({state:n,dispatch:r})=>{const a=Ip(s,n.schema);return Els(a,t)(n,r)};var gds=Object.freeze({__proto__:null,blur:Xls,clearContent:Jls,clearNodes:ecs,command:tcs,createParagraphNear:scs,cut:ncs,deleteCurrentNode:rcs,deleteNode:acs,deleteRange:ics,deleteSelection:ocs,enter:lcs,exitCode:ccs,extendMarkRange:dcs,first:ucs,focus:mcs,forEach:pcs,insertContent:fcs,insertContentAt:ycs,joinBackward:_cs,joinDown:bcs,joinForward:wcs,joinItemBackward:jcs,joinItemForward:Ncs,joinTextblockBackward:kcs,joinTextblockForward:Scs,joinUp:vcs,keyboardShortcut:Tcs,lift:Ecs,liftEmptyBlock:Acs,liftListItem:Mcs,newlineInCode:Ics,resetAttributes:Pcs,scrollIntoView:Lcs,selectAll:Dcs,selectNodeBackward:Rcs,selectNodeForward:Ocs,selectParentNode:Fcs,selectTextblockEnd:zcs,selectTextblockStart:Bcs,setContent:$cs,setMark:Jcs,setMeta:eds,setNode:tds,setNodeSelection:sds,setTextSelection:nds,sinkListItem:rds,splitBlock:ads,splitListItem:ids,toggleList:ods,toggleMark:lds,toggleNode:cds,toggleWrap:dds,undoInputRule:uds,unsetAllMarks:hds,unsetMark:mds,updateAttributes:pds,wrapIn:fds,wrapInList:xds});const yds=Tf.create({name:"commands",addCommands(){return{...gds}}}),vds=Tf.create({name:"drop",addProseMirrorPlugins(){return[new Zm({key:new dx("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),bds=Tf.create({name:"editable",addProseMirrorPlugins(){return[new Zm({key:new dx("editable"),props:{editable:()=>this.editor.options.editable}})]}}),_ds=new dx("focusEvents"),wds=Tf.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new Zm({key:_ds,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}}}})]}}),jds=Tf.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:u,$anchor:h}=c,{pos:p,parent:f}=h,g=h.parent.isTextblock&&p>0?o.doc.resolve(p-1):h,b=g.parent.type.spec.isolating,v=h.pos-h.parentOffset,j=b&&g.parent.childCount===1?v===h.pos:no.atStart(d).from===p;return!u||!f.type.isTextblock||f.textContent.length||!j||j&&h.parent.type.name==="paragraph"?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:s,"Mod-Backspace":s,"Shift-Backspace":s,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...r},i={...r,"Ctrl-h":s,"Alt-Backspace":s,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Kfe()||yxt()?i:a},addProseMirrorPlugins(){return[new Zm({key:new dx("clearDocument"),appendTransaction:(s,t,n)=>{if(s.some(b=>b.getMeta("composition")))return;const r=s.some(b=>b.docChanged)&&!t.doc.eq(n.doc),a=s.some(b=>b.getMeta("preventClearDocument"));if(!r||a)return;const{empty:i,from:l,to:o}=t.selection,c=no.atStart(t.doc).from,d=no.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!Z6e(n.doc))return;const p=n.tr,f=nve({state:n,transaction:p}),{commands:g}=new rve({editor:this.editor,state:f});if(g.clearNodes(),!!p.steps.length)return p}})]}}),Nds=Tf.create({name:"paste",addProseMirrorPlugins(){return[new Zm({key:new dx("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),kds=Tf.create({name:"tabindex",addProseMirrorPlugins(){return[new Zm({key:new dx("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class UE{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 UE(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 UE(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 UE(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 UE(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new UE(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 Sds=`.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 Cds(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 Tds extends Rls{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=Cds(Sds,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=uxt(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?[bds,Qls.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),yds,wds,jds,kds,vds,Nds].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 PP(a,this)}createCommandManager(){this.commandManager=new rve({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=qCe(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=qCe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=xxt(n,this.options.autofocus);this.view=new nxt(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:IP.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 _xt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return Zcs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return H6e(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return Hcs(this.state.doc,{blockSeparator:n,textSerializers:{...mxt(this.schema),...r}})}get isEmpty(){return Z6e(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 UE(n,this)}get $doc(){return this.$pos(0)}}function D8(s){return new ive({find:s.find,handler:({state:t,range:n,match:r})=>{const a=el(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(Y6e(n.from,n.to,t.doc).filter(f=>f.mark.type.excluded.find(b=>b===s.type&&b!==f.mark.type)).filter(f=>f.to>d).length)return null;un.from&&i.delete(n.from+c,d);const p=n.from+c+l.length;i.addMark(n.from+c,p,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function wxt(s){return new ive({find:s.find,handler:({state:t,range:n,match:r})=>{const a=el(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 HCe(s){return new ive({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=el(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 EB(s){return new ive({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=el(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&A6e(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:p}=t,{splittableMarks:f}=s.editor.extensionManager,g=p||h.$to.parentOffset&&h.$from.marks();if(g){const b=g.filter(v=>f.includes(v.type.name));l.ensureMarks(b)}}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&&tC(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let ux=class GCe{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=el(di(this,"addOptions",{name:this.name}))),this.storage=el(di(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new GCe(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>ove(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new GCe(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=el(di(n,"addOptions",{name:n.name})),n.storage=el(di(n,"addStorage",{name:n.name,options:n.options})),n}};function SM(s){return new Hls({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=el(s.getAttributes,void 0,r,a);if(i===!1||i===null)return null;const{tr:l}=t,o=r[r.length-1],c=r[0];let d=n.to;if(o){const u=c.search(/\S/),h=n.from+c.indexOf(o),p=h+o.length;if(Y6e(n.from,n.to,t.doc).filter(g=>g.mark.type.excluded.find(v=>v===s.type&&v!==g.mark.type)).filter(g=>g.to>h).length)return null;pn.from&&l.delete(n.from+u,h),d=n.from+u+o.length,l.addMark(n.from+u,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function Eds(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof $i){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 Ads(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var jxt={exports:{}},u2e={};/** * @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 iVe;function Mds(){if(iVe)return u2e;iVe=1;var s=Nt;function t(h,p){return h===p&&(h!==0||1/h===1/p)||h!==h&&p!==p}var n=typeof Object.is=="function"?Object.is:t,r=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(h,p){var f=p(),g=r({inst:{value:f,getSnapshot:p}}),b=g[0].inst,v=g[1];return i(function(){b.value=f,b.getSnapshot=p,c(b)&&v({inst:b})},[h,f,p]),a(function(){return c(b)&&v({inst:b}),h(function(){c(b)&&v({inst:b})})},[h]),l(f),f}function c(h){var p=h.getSnapshot;h=h.value;try{var f=p();return!n(h,f)}catch{return!0}}function d(h,p){return p()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return u2e.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,u2e}jxt.exports=Mds();var Q6e=jxt.exports;const Ids=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},Pds=({contentComponent:s})=>{const t=Q6e.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Nt.createElement(Nt.Fragment,null,Object.values(t))};function Lds(){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]:dAe.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 Dds extends Nt.Component{constructor(t){var n;super(t),this.editorContentRef=Nt.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=Lds(),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 Nt.createElement(Nt.Fragment,null,Nt.createElement("div",{ref:Ids(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&Nt.createElement(Pds,{contentComponent:t.contentComponent}))}}const Rds=N.forwardRef((s,t)=>{const n=Nt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Nt.createElement(Dds,{key:n,innerRef:t,...s})}),X6e=Nt.memo(Rds);var Ods=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},Fds=Ads(Ods),Nxt={exports:{}},h2e={};/** * @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 oVe;function zds(){if(oVe)return h2e;oVe=1;var s=Nt,t=Q6e;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 h2e.useSyncExternalStoreWithSelector=function(d,u,h,p,f){var g=i(null);if(g.current===null){var b={hasValue:!1,value:null};g.current=b}else b=g.current;g=o(function(){function j(D){if(!_){if(_=!0,S=D,D=p(D),f!==void 0&&b.hasValue){var L=b.value;if(f(L,D))return A=L}return A=D}if(L=A,r(S,D))return L;var M=p(D);return f!==void 0&&f(L,M)?L:(S=D,A=M)}var _=!1,S,A,T=h===void 0?null:h;return[function(){return j(u())},T===null?void 0:function(){return j(T())}]},[u,h,p,f]);var v=a(d,g[0],g[1]);return l(function(){b.hasValue=!0,b.value=v},[v]),c(v),v},h2e}Nxt.exports=zds();var Bds=Nxt.exports;const $ds=typeof window<"u"?N.useLayoutEffect:N.useEffect;class Uds{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 qds(s){var t;const[n]=N.useState(()=>new Uds(s.editor)),r=Bds.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:Fds);return $ds(()=>n.watch(s.editor),[s.editor,n]),N.useDebugValue(r),r}const Vds=!1,WCe=typeof window>"u",Hds=WCe||!!(typeof window<"u"&&window.next);class J6e{constructor(t){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=t,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(t){this.editor=t,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(n=>n())}getInitialEditor(){if(this.options.current.immediatelyRender===void 0)return WCe||Hds?null:this.createEditor();if(this.options.current.immediatelyRender&&WCe&&Vds)throw new Error("Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches.");return this.options.current.immediatelyRender?this.createEditor():null}createEditor(){const t={...this.options.current,onBeforeCreate:(...r)=>{var a,i;return(i=(a=this.options.current).onBeforeCreate)===null||i===void 0?void 0:i.call(a,...r)},onBlur:(...r)=>{var a,i;return(i=(a=this.options.current).onBlur)===null||i===void 0?void 0:i.call(a,...r)},onCreate:(...r)=>{var a,i;return(i=(a=this.options.current).onCreate)===null||i===void 0?void 0:i.call(a,...r)},onDestroy:(...r)=>{var a,i;return(i=(a=this.options.current).onDestroy)===null||i===void 0?void 0:i.call(a,...r)},onFocus:(...r)=>{var a,i;return(i=(a=this.options.current).onFocus)===null||i===void 0?void 0:i.call(a,...r)},onSelectionUpdate:(...r)=>{var a,i;return(i=(a=this.options.current).onSelectionUpdate)===null||i===void 0?void 0:i.call(a,...r)},onTransaction:(...r)=>{var a,i;return(i=(a=this.options.current).onTransaction)===null||i===void 0?void 0:i.call(a,...r)},onUpdate:(...r)=>{var a,i;return(i=(a=this.options.current).onUpdate)===null||i===void 0?void 0:i.call(a,...r)},onContentError:(...r)=>{var a,i;return(i=(a=this.options.current).onContentError)===null||i===void 0?void 0:i.call(a,...r)},onDrop:(...r)=>{var a,i;return(i=(a=this.options.current).onDrop)===null||i===void 0?void 0:i.call(a,...r)},onPaste:(...r)=>{var a,i;return(i=(a=this.options.current).onPaste)===null||i===void 0?void 0:i.call(a,...r)}};return new Tds(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?J6e.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 eIe(s={},t=[]){const n=N.useRef(s);n.current=s;const[r]=N.useState(()=>new J6e(n)),a=Q6e.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return N.useDebugValue(a),N.useEffect(r.onRender(t)),qds({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const Gds=N.createContext({editor:null});Gds.Consumer;const Wds=N.createContext({onDragStart:void 0}),Kds=()=>N.useContext(Wds);Nt.forwardRef((s,t)=>{const{onDragStart:n}=Kds(),r=s.as||"div";return Nt.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const Yds=/^\s*>\s$/,Zds=ux.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",xu(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[EB({find:Yds,type:this.type})]}}),Qds=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,Xds=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,Jds=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,eus=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,tus=Ab.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",xu(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[D8({find:Qds,type:this.type}),D8({find:Jds,type:this.type})]},addPasteRules(){return[SM({find:Xds,type:this.type}),SM({find:eus,type:this.type})]}}),sus="listItem",lVe="textStyle",cVe=/^\s*([-+*])\s$/,nus=ux.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",xu(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(sus,this.editor.getAttributes(lVe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=EB({find:cVe,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=EB({find:cVe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(lVe),editor:this.editor})),[s]}}),rus=/(^|[^`])`([^`]+)`(?!`)/,aus=/(^|[^`])`([^`]+)`(?!`)/g,ius=Ab.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",xu(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[D8({find:rus,type:this.type})]},addPasteRules(){return[SM({find:aus,type:this.type})]}}),ous=/^```([a-z]+)?[\s\n]$/,lus=/^~~~([a-z]+)?[\s\n]$/,cus=ux.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",xu(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(no.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[HCe({find:ous,type:this.type,getAttributes:s=>({language:s[1]})}),HCe({find:lus,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new Zm({key:new dx("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(Ki.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),dus=ux.create({name:"doc",topNode:!0,content:"block+"});function uus(s={}){return new Zm({view(t){return new hus(t,s)}})}class hus{constructor(t,n){var r;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(a=>{let i=l=>{this[a](l)};return t.dom.addEventListener(a,i),{name:a,handler:i}})}destroy(){this.handlers.forEach(({name:t,handler:n})=>this.editorView.dom.removeEventListener(t,n))}update(t,n){this.cursorPos!=null&&n.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),n=!t.parent.inlineContent,r,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(n){let h=t.nodeBefore,p=t.nodeAfter;if(h||p){let f=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(f){let g=f.getBoundingClientRect(),b=h?g.bottom:g.top;h&&p&&(b=(b+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let v=this.width/2*o;r={left:g.left,right:g.right,top:b-v,bottom:b+v}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),p=this.width/2*l;r={left:h.left-p,right:h.left+p,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),p=h.width/c.offsetWidth,f=h.height/c.offsetHeight;d=h.left-c.scrollLeft*p,u=h.top-c.scrollTop*f}this.element.style.left=(r.left-d)/l+"px",this.element.style.top=(r.top-u)/o+"px",this.element.style.width=(r.right-r.left)/l+"px",this.element.style.height=(r.bottom-r.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),a=r&&r.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,n,t):a;if(n&&!i){let l=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=fft(this.editorView.state.doc,l,this.editorView.dragging.slice);o!=null&&(l=o)}this.setCursor(l),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(t){this.editorView.dom.contains(t.relatedTarget)||this.setCursor(null)}}const mus=Tf.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[uus(this.options)]}});class lh extends no{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return lh.valid(r)?new lh(r):no.near(r)}content(){return ka.empty}eq(t){return t instanceof lh&&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 lh(t.resolve(n.pos))}getBookmark(){return new tIe(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!pus(t)||!fus(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&&lh.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(lh.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!$i.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(lh.valid(o))return o}return null}}}lh.prototype.visible=!1;lh.findFrom=lh.findGapCursorFrom;no.jsonID("gapcursor",lh);class tIe{constructor(t){this.pos=t}map(t){return new tIe(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return lh.valid(n)?new lh(n):no.near(n)}}function kxt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function pus(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||kxt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function fus(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||kxt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function xus(){return new Zm({props:{decorations:bus,createSelectionBetween(s,t,n){return t.pos==n.pos&&lh.valid(n)?new lh(n):null},handleClick:yus,handleKeyDown:gus,handleDOMEvents:{beforeinput:vus}}})}const gus=U6e({ArrowLeft:NH("horiz",-1),ArrowRight:NH("horiz",1),ArrowUp:NH("vert",-1),ArrowDown:NH("vert",1)});function NH(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 Ki){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=lh.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new lh(d))),!0):!1}}function yus(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!lh.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&$i.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new lh(r))),!0)}function vus(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof lh))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=Vr.empty;for(let l=r.length-1;l>=0;l--)a=Vr.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new ka(a,0,0));return i.setSelection(Ki.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function bus(s){if(!(s.selection instanceof lh))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",oh.create(s.doc,[Qx.widget(s.selection.head,t,{key:"gapcursor"})])}const _us=Tf.create({name:"gapCursor",addProseMirrorPlugins(){return[xus()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=el(di(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),wus=ux.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",xu(this.options.HTMLAttributes,s)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:s,chain:t,state:n,editor:r})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:a,storedMarks:i}=n;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=r.extensionManager,c=i||a.$to.parentOffset&&a.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&l){const h=c.filter(p=>o.includes(p.type.name));d.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),jus=ux.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]}`,xu(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=>HCe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var Yfe=200,Mp=function(){};Mp.prototype.append=function(t){return t.length?(t=Mp.from(t),!this.length&&t||t.length=n?Mp.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Mp.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Mp.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)};Mp.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};Mp.from=function(t){return t instanceof Mp?t:t&&t.length?new Sxt(t):Mp.empty};var Sxt=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<=Yfe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=Yfe)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}(Mp);Mp.empty=new Sxt([]);var Nus=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}(Mp);const kus=500;class ib{constructor(t,n){this.items=t,this.eventCount=n}popEvent(t,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let a,i;n&&(a=this.remapping(r,this.items.length),i=a.maps.length);let l=t.tr,o,c,d=[],u=[];return this.items.forEach((h,p)=>{if(!h.step){a||(a=this.remapping(r,p+1),i=a.maps.length),i--,u.push(h);return}if(a){u.push(new Tk(h.map));let f=h.step.map(a.slice(i)),g;f&&l.maybeStep(f).doc&&(g=l.mapping.maps[l.mapping.maps.length-1],d.push(new Tk(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 ib(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;uCus&&(o=Sus(o,d),l-=d),new ib(o.append(i),l)}remapping(t,n){let r=new wB;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 ib(this.items.append(t.map(n=>new Tk(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(p=>{p.selection&&o--},a);let c=n;this.items.forEach(p=>{let f=i.getMirror(--c);if(f==null)return;l=Math.min(l,f);let g=i.maps[f];if(p.step){let b=t.steps[f].invert(t.docs[f]),v=p.selection&&p.selection.map(i.slice(c+1,f));v&&o++,r.push(new Tk(g,b,v))}else r.push(new Tk(g))},a);let d=[];for(let p=n;pkus&&(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 Tk(d.invert(),c,u),p,f=a.length-1;(p=a.length&&a[f].merge(h))?a[f]=p:a.push(h)}}else l.map&&r--},this.items.length,0),new ib(Mp.from(a.reverse()),i)}}ib.empty=new ib(Mp.empty,0);function Sus(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let Tk=class Cxt{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 Cxt(n.getMap().invert(),n,this.selection)}}};class eS{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const Cus=20;function Tus(s,t,n,r){let a=n.getMeta(QA),i;if(a)return a.historyState;n.getMeta(Mus)&&(s=new eS(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(QA))return l.getMeta(QA).redo?new eS(s.done.addTransform(n,void 0,r,Qme(t)),s.undone,dVe(n.mapping.maps),s.prevTime,s.prevComposition):new eS(s.done,s.undone.addTransform(n,void 0,r,Qme(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||!Eus(n,s.prevRanges)),d=l?m2e(s.prevRanges,n.mapping):dVe(n.mapping.maps);return new eS(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,Qme(t)),ib.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new eS(s.done.rebased(n,i),s.undone.rebased(n,i),m2e(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new eS(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),m2e(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function Eus(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 dVe(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 m2e(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=QA.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=Aus(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const Ext=Txt(!1,!0),Axt=Txt(!0,!0),Pus=Tf.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>Ext(s,t),redo:()=>({state:s,dispatch:t})=>Axt(s,t)}},addProseMirrorPlugins(){return[Ius(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()}}}),Lus=ux.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",xu(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!Eds(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}):Qcs(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(Ki.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection($i.create(l.doc,d.pos)):l.setSelection(Ki.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(Ki.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[wxt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Dus=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Rus=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Ous=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Fus=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,zus=Ab.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",xu(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[D8({find:Dus,type:this.type}),D8({find:Ous,type:this.type})]},addPasteRules(){return[SM({find:Rus,type:this.type}),SM({find:Fus,type:this.type})]}}),Bus=ux.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",xu(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)}}}),$us="listItem",hVe="textStyle",mVe=/^(\d+)\.\s$/,Uus=ux.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",xu(this.options.HTMLAttributes,n),0]:["ol",xu(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($us,this.editor.getAttributes(hVe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=EB({find:mVe,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=EB({find:mVe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(hVe)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),qus=ux.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",xu(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Vus=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Hus=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Gus=Ab.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",xu(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[D8({find:Vus,type:this.type})]},addPasteRules(){return[SM({find:Hus,type:this.type})]}}),Wus=ux.create({name:"text",group:"inline"}),sIe=Tf.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(tus.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(Zds.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(nus.configure(this.options.bulletList)),this.options.code!==!1&&s.push(ius.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(cus.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(dus.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(mus.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(_us.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(wus.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(jus.configure(this.options.heading)),this.options.history!==!1&&s.push(Pus.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(Lus.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(zus.configure(this.options.italic)),this.options.listItem!==!1&&s.push(Bus.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(Uus.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(qus.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(Gus.configure(this.options.strike)),this.options.text!==!1&&s.push(Wus.configure(this.options.text)),s}}),Kus="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",Yus="ελ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",KCe="numeric",YCe="ascii",ZCe="alpha",uz="asciinumeric",b7="alphanumeric",QCe="domain",Mxt="emoji",Zus="scheme",Qus="slashscheme",f2e="whitespace";function Xus(s,t){return s in t||(t[s]=[]),t[s]}function eA(s,t,n){t[KCe]&&(t[uz]=!0,t[b7]=!0),t[YCe]&&(t[uz]=!0,t[ZCe]=!0),t[uz]&&(t[b7]=!0),t[ZCe]&&(t[b7]=!0),t[b7]&&(t[QCe]=!0),t[Mxt]&&(t[QCe]=!0);for(const r in t){const a=Xus(r,n);a.indexOf(s)<0&&a.push(s)}}function Jus(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function Rg(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}Rg.groups={};Rg.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),Ju=(s,t,n,r,a)=>s.tr(t,n,r,a),pVe=(s,t,n,r,a)=>s.ts(t,n,r,a),Yr=(s,t,n,r,a)=>s.tt(t,n,r,a),g2="WORD",XCe="UWORD",Ixt="ASCIINUMERICAL",Pxt="ALPHANUMERICAL",AB="LOCALHOST",JCe="TLD",e3e="UTLD",Xme="SCHEME",uP="SLASH_SCHEME",nIe="NUM",t3e="WS",rIe="NL",hz="OPENBRACE",mz="CLOSEBRACE",Zfe="OPENBRACKET",Qfe="CLOSEBRACKET",Xfe="OPENPAREN",Jfe="CLOSEPAREN",exe="OPENANGLEBRACKET",txe="CLOSEANGLEBRACKET",sxe="FULLWIDTHLEFTPAREN",nxe="FULLWIDTHRIGHTPAREN",rxe="LEFTCORNERBRACKET",axe="RIGHTCORNERBRACKET",ixe="LEFTWHITECORNERBRACKET",oxe="RIGHTWHITECORNERBRACKET",lxe="FULLWIDTHLESSTHAN",cxe="FULLWIDTHGREATERTHAN",dxe="AMPERSAND",uxe="APOSTROPHE",hxe="ASTERISK",tS="AT",mxe="BACKSLASH",pxe="BACKTICK",fxe="CARET",pS="COLON",aIe="COMMA",xxe="DOLLAR",$_="DOT",gxe="EQUALS",iIe="EXCLAMATION",fv="HYPHEN",pz="PERCENT",yxe="PIPE",vxe="PLUS",bxe="POUND",fz="QUERY",oIe="QUOTE",Lxt="FULLWIDTHMIDDLEDOT",lIe="SEMI",U_="SLASH",xz="TILDE",_xe="UNDERSCORE",Dxt="EMOJI",wxe="SYM";var Rxt=Object.freeze({__proto__:null,ALPHANUMERICAL:Pxt,AMPERSAND:dxe,APOSTROPHE:uxe,ASCIINUMERICAL:Ixt,ASTERISK:hxe,AT:tS,BACKSLASH:mxe,BACKTICK:pxe,CARET:fxe,CLOSEANGLEBRACKET:txe,CLOSEBRACE:mz,CLOSEBRACKET:Qfe,CLOSEPAREN:Jfe,COLON:pS,COMMA:aIe,DOLLAR:xxe,DOT:$_,EMOJI:Dxt,EQUALS:gxe,EXCLAMATION:iIe,FULLWIDTHGREATERTHAN:cxe,FULLWIDTHLEFTPAREN:sxe,FULLWIDTHLESSTHAN:lxe,FULLWIDTHMIDDLEDOT:Lxt,FULLWIDTHRIGHTPAREN:nxe,HYPHEN:fv,LEFTCORNERBRACKET:rxe,LEFTWHITECORNERBRACKET:ixe,LOCALHOST:AB,NL:rIe,NUM:nIe,OPENANGLEBRACKET:exe,OPENBRACE:hz,OPENBRACKET:Zfe,OPENPAREN:Xfe,PERCENT:pz,PIPE:yxe,PLUS:vxe,POUND:bxe,QUERY:fz,QUOTE:oIe,RIGHTCORNERBRACKET:axe,RIGHTWHITECORNERBRACKET:oxe,SCHEME:Xme,SEMI:lIe,SLASH:U_,SLASH_SCHEME:uP,SYM:wxe,TILDE:xz,TLD:JCe,UNDERSCORE:_xe,UTLD:e3e,UWORD:XCe,WORD:g2,WS:t3e});const i2=/[a-z]/,vF=new RegExp("\\p{L}","u"),x2e=new RegExp("\\p{Emoji}","u"),o2=/\d/,g2e=/\s/,fVe="\r",y2e=` `,ehs="️",ths="‍",v2e="";let kH=null,SH=null;function shs(s=[]){const t={};Rg.groups=t;const n=new Rg;kH==null&&(kH=xVe(Kus)),SH==null&&(SH=xVe(Yus)),Yr(n,"'",uxe),Yr(n,"{",hz),Yr(n,"}",mz),Yr(n,"[",Zfe),Yr(n,"]",Qfe),Yr(n,"(",Xfe),Yr(n,")",Jfe),Yr(n,"<",exe),Yr(n,">",txe),Yr(n,"(",sxe),Yr(n,")",nxe),Yr(n,"「",rxe),Yr(n,"」",axe),Yr(n,"『",ixe),Yr(n,"』",oxe),Yr(n,"<",lxe),Yr(n,">",cxe),Yr(n,"&",dxe),Yr(n,"*",hxe),Yr(n,"@",tS),Yr(n,"`",pxe),Yr(n,"^",fxe),Yr(n,":",pS),Yr(n,",",aIe),Yr(n,"$",xxe),Yr(n,".",$_),Yr(n,"=",gxe),Yr(n,"!",iIe),Yr(n,"-",fv),Yr(n,"%",pz),Yr(n,"|",yxe),Yr(n,"+",vxe),Yr(n,"#",bxe),Yr(n,"?",fz),Yr(n,'"',oIe),Yr(n,"/",U_),Yr(n,";",lIe),Yr(n,"~",xz),Yr(n,"_",_xe),Yr(n,"\\",mxe),Yr(n,"・",Lxt);const r=Ju(n,o2,nIe,{[KCe]:!0});Ju(r,o2,r);const a=Ju(r,i2,Ixt,{[uz]:!0}),i=Ju(r,vF,Pxt,{[b7]:!0}),l=Ju(n,i2,g2,{[YCe]:!0});Ju(l,o2,a),Ju(l,i2,l),Ju(a,o2,a),Ju(a,i2,a);const o=Ju(n,vF,XCe,{[ZCe]:!0});Ju(o,i2),Ju(o,o2,i),Ju(o,vF,o),Ju(i,o2,i),Ju(i,i2),Ju(i,vF,i);const c=Yr(n,y2e,rIe,{[f2e]:!0}),d=Yr(n,fVe,t3e,{[f2e]:!0}),u=Ju(n,g2e,t3e,{[f2e]:!0});Yr(n,v2e,u),Yr(d,y2e,c),Yr(d,v2e,u),Ju(d,g2e,u),Yr(u,fVe),Yr(u,y2e),Ju(u,g2e,u),Yr(u,v2e,u);const h=Ju(n,x2e,Dxt,{[Mxt]:!0});Yr(h,"#"),Ju(h,x2e,h),Yr(h,ehs,h);const p=Yr(h,ths);Yr(p,"#"),Ju(p,x2e,h);const f=[[i2,l],[o2,a]],g=[[i2,null],[vF,o],[o2,i]];for(let b=0;bb[0]>v[0]?1:-1);for(let b=0;b=0?_[QCe]=!0:i2.test(v)?o2.test(v)?_[uz]=!0:_[YCe]=!0:_[KCe]=!0,pVe(n,v,v,_)}return pVe(n,"localhost",AB,{ascii:!0}),n.jd=new Rg(wxe),{start:n,tokens:Object.assign({groups:t},Rxt)}}function Oxt(s,t){const n=nhs(t.replace(/[A-Z]/g,o=>o.toLowerCase())),r=n.length,a=[];let i=0,l=0;for(;l=0&&(h+=n[l].length,p++),d+=n[l].length,i+=n[l].length,l++;i-=h,l-=p,d-=h,a.push({t:u.t,v:t.slice(i-d,i),s:i-d,e:i})}return a}function nhs(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 Ek(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 MB={defaultProtocol:"http",events:null,format:gVe,formatHref:gVe,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function cIe(s,t=null){let n=Object.assign({},MB);s&&(n=Object.assign(n,s instanceof cIe?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=MB.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 cve(s,t){class n extends Fxt{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 yVe=cve("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),vVe=cve("text"),rhs=cve("nl"),CH=cve("url",{isLink:!0,toHref(s=MB.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==AB&&s[1].t===pS}}),av=s=>new Rg(s);function ahs({groups:s}){const t=s.domain.concat([dxe,hxe,tS,mxe,pxe,fxe,xxe,gxe,fv,nIe,pz,yxe,vxe,bxe,U_,wxe,xz,_xe]),n=[uxe,pS,aIe,$_,iIe,pz,fz,oIe,lIe,exe,txe,hz,mz,Qfe,Zfe,Xfe,Jfe,sxe,nxe,rxe,axe,ixe,oxe,lxe,cxe],r=[dxe,uxe,hxe,mxe,pxe,fxe,xxe,gxe,fv,hz,mz,pz,yxe,vxe,bxe,fz,U_,wxe,xz,_xe],a=av(),i=Yr(a,xz);Jo(i,r,i),Jo(i,s.domain,i);const l=av(),o=av(),c=av();Jo(a,s.domain,l),Jo(a,s.scheme,o),Jo(a,s.slashscheme,c),Jo(l,r,i),Jo(l,s.domain,l);const d=Yr(l,tS);Yr(i,tS,d),Yr(o,tS,d),Yr(c,tS,d);const u=Yr(i,$_);Jo(u,r,i),Jo(u,s.domain,i);const h=av();Jo(d,s.domain,h),Jo(h,s.domain,h);const p=Yr(h,$_);Jo(p,s.domain,h);const f=av(yVe);Jo(p,s.tld,f),Jo(p,s.utld,f),Yr(d,AB,f);const g=Yr(h,fv);Yr(g,fv,g),Jo(g,s.domain,h),Jo(f,s.domain,h),Yr(f,$_,p),Yr(f,fv,g);const b=Yr(f,pS);Jo(b,s.numeric,yVe);const v=Yr(l,fv),j=Yr(l,$_);Yr(v,fv,v),Jo(v,s.domain,l),Jo(j,r,i),Jo(j,s.domain,l);const _=av(CH);Jo(j,s.tld,_),Jo(j,s.utld,_),Jo(_,s.domain,l),Jo(_,r,i),Yr(_,$_,j),Yr(_,fv,v),Yr(_,tS,d);const S=Yr(_,pS),A=av(CH);Jo(S,s.numeric,A);const T=av(CH),D=av();Jo(T,t,T),Jo(T,n,D),Jo(D,t,T),Jo(D,n,D),Yr(_,U_,T),Yr(A,U_,T);const L=Yr(o,pS),M=Yr(c,pS),F=Yr(M,U_),z=Yr(F,U_);Jo(o,s.domain,l),Yr(o,$_,j),Yr(o,fv,v),Jo(c,s.domain,l),Yr(c,$_,j),Yr(c,fv,v),Jo(L,s.domain,T),Yr(L,U_,T),Yr(L,fz,T),Jo(z,s.domain,T),Jo(z,t,T),Yr(z,U_,T);const V=[[hz,mz],[Zfe,Qfe],[Xfe,Jfe],[exe,txe],[sxe,nxe],[rxe,axe],[ixe,oxe],[lxe,cxe]];for(let W=0;W=0&&p++,a++,u++;if(p<0)a-=u,a0&&(i.push(b2e(vVe,t,l)),l=[]),a-=p,u-=p;const f=h.t,g=n.slice(a-u,a);i.push(b2e(f,t,g))}}return l.length>0&&i.push(b2e(vVe,t,l)),i}function b2e(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 ohs=typeof console<"u"&&console&&console.warn||(()=>{}),lhs="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Od={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function chs(){return Rg.groups={},Od.scanner=null,Od.parser=null,Od.tokenQueue=[],Od.pluginQueue=[],Od.customSchemes=[],Od.initialized=!1,Od}function bVe(s,t=!1){if(Od.initialized&&ohs(`linkifyjs: already initialized - will not register custom scheme "${s}" ${lhs}`),!/^[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`);Od.customSchemes.push([s,t])}function dhs(){Od.scanner=shs(Od.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=Ucs(n.doc,[...t]);if(Ycs(o).forEach(({newRange:d})=>{const u=Vcs(r.doc,d,f=>f.isTextblock);let h,p;if(u.length>1)h=u[0],p=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(u.length){const f=r.doc.textBetween(d.from,d.to," "," ");if(!hhs.test(f))return;h=u[0],p=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&p){const f=p.split(uhs).filter(Boolean);if(f.length<=0)return!1;const g=f[f.length-1],b=h.pos+p.lastIndexOf(g);if(!g)return!1;const v=dIe(g).map(j=>j.toObject(s.defaultProtocol));if(!phs(v))return!1;v.filter(j=>j.isLink).map(j=>({...j,from:b+j.start+1,to:b+j.end+1})).filter(j=>r.schema.marks.code?!r.doc.rangeHasMark(j.from,j.to,r.schema.marks.code):!0).filter(j=>s.validate(j.value)).filter(j=>s.shouldAutoLink(j.value)).forEach(j=>{Y6e(j.from,j.to,r.doc).some(_=>_.mark.type===s.type)||l.addMark(j.from,j.to,s.type.create({href:j.href}))})}}),!!l.steps.length)return l}})}function xhs(s){return new Zm({key:new dx("handleClickLink"),props:{handleClick:(t,n,r)=>{var a,i;if(r.button!==0||!t.editable)return!1;let l=r.target;const o=[];for(;l.nodeName!=="DIV";)o.push(l),l=l.parentNode;if(!o.find(p=>p.nodeName==="A"))return!1;const c=_xt(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 ghs(s){return new Zm({key:new dx("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=zxt(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 h3(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(mhs,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const hIe=Ab.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"){bVe(s);return}bVe(s.scheme,s.optionalSlashes)})},onDestroy(){chs()},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)=>!!h3(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=>!!h3(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=>!!h3(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",xu(this.options.HTMLAttributes,s),0]:["a",xu(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!h3(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=>!!h3(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[SM({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=zxt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!h3(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(fhs({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!h3(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(xhs({type:this.type})),this.options.linkOnPaste&&s.push(ghs({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),mIe=Tf.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")}}}),yhs=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}`)})},pIe=Ab.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&yhs(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",xu(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}}}}),vhs=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,bhs=ux.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",xu(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[wxt({find:vhs,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let s3e,n3e;if(typeof WeakMap<"u"){let s=new WeakMap;s3e=t=>s.get(t),n3e=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;s3e=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var ch=class{constructor(s,t,n,r){this.width=s,this.height=t,this.map=n,this.problems=r}findCell(s){for(let t=0;t=n){(i||(i=[])).push({type:"overlong_rowspan",pos:u,n:j-S});break}const A=a+S*t;for(let T=0;Tr&&(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 jhs(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 khs(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 Lb(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 dve(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=CM(t.$head)||Shs(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function Shs(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 r3e(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function Chs(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function fIe(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function Bxt(s,t,n){const r=s.node(-1),a=ch.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 TM(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 $xt(s,t,n=1){const r={...s,colspan:s.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let a=0;au!=n.pos-i);c.unshift(n.pos-i);const d=c.map(u=>{const h=r.nodeAt(u);if(!h)throw new RangeError(`No cell with offset ${u} found`);const p=i+u+1;return new bft(o.resolve(p),o.resolve(p+h.content.size))});super(d[0].$from,d[0].$to,d),this.$anchorCell=t,this.$headCell=n}map(t,n){const r=t.resolve(n.map(this.$anchorCell.pos)),a=t.resolve(n.map(this.$headCell.pos));if(r3e(r)&&r3e(a)&&fIe(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?y2.rowSelection(r,a):i&&this.isColSelection()?y2.colSelection(r,a):new y2(r,a)}return Ki.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=ch.get(t),r=this.$anchorCell.start(-1),a=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),i={},l=[];for(let c=a.top;c0||v>0){let j=g.attrs;if(b>0&&(j=TM(j,0,b)),v>0&&(j=TM(j,j.colspan-v,v)),f.lefta.bottom){const j={...g.attrs,rowspan:Math.min(f.bottom,a.bottom)-Math.max(f.top,a.top)};f.top0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,a)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){const r=t.node(-1),a=ch.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 y2&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=ch.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(Qx.node(r,r+n.nodeSize,{class:"selectedCell"}))}),oh.create(s.doc,t)}function Mhs({$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 Ihs({$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 Phs(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof $i&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=jd.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=jd.rowSelection(o,o)}else if(!n){const o=ch.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=jd.create(a,c+1,d)}}else r instanceof Ki&&Mhs(r)?i=Ki.create(a,r.from):r instanceof Ki&&Ihs(r)&&(i=Ki.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const Lhs=new dx("fix-tables");function qxt(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=Dhs(s,a,i,n))};return t?t.doc!=s.doc&&qxt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function Dhs(s,t,n,r){const a=ch.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let f="cell";u.firstChild&&(f=u.firstChild.type.spec.tableRole);const g=[];for(let v=0;v0?-1:0;Ths(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;Bhs(t,r,a+o)&&(o=a==0||a==t.height?null:0);for(let d=0,u=t.width*a;d0&&a0&&h==t.map[u-t.width]){const p=n.nodeAt(h).attrs;s.setNodeMarkup(s.mapping.slice(o).map(h+r),null,{...p,rowspan:p.rowspan-1}),d+=p.colspan-1}else if(a0&&n[i]==n[i-1]||r.right0&&n[a]==n[a-s]||r.bottom0){const u=c+1+d.content.size,h=_Ve(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new jd(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function jVe(s,t){const n=ix(s.schema);return Ghs(({node:r})=>n[r.type.spec.tableRole])(s,t)}function Ghs(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof jd){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=khs(r.$from),!a)return!1;i=(l=CM(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=Xw(t),h=t.tr;for(let f=0;f{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),r(i)}return!0}}function Khs(s){return function(t,n){if(!Lb(t))return!1;if(n){const r=ix(t.schema),a=Xw(t),i=t.tr,l=a.map.cellsInRect(s=="column"?{left:a.left,top:0,right:a.right,bottom:a.map.height}:s=="row"?{left:0,top:a.top,right:a.map.width,bottom:a.bottom}:a),o=l.map(c=>a.table.nodeAt(c));for(let c=0;c{const f=p+i.tableStart,g=l.doc.nodeAt(f);g&&l.setNodeMarkup(f,h,g.attrs)}),r(l)}return!0}}IB("row",{useDeprecatedLogic:!0});IB("column",{useDeprecatedLogic:!0});const Yhs=IB("cell",{useDeprecatedLogic:!0});function Zhs(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 TH(s,t){const n=s.selection;if(!(n instanceof jd))return!1;if(t){const r=s.tr,a=ix(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 ka(a,0,0))}),r.docChanged&&t(r)}return!0}function Xhs(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(Vr.empty),n[a]r&&(p=p.type.createChecked(TM(p.attrs,p.attrs.colspan,u+p.attrs.colspan-r),p.content)),d.push(p),u+=p.attrs.colspan;for(let f=1;fa&&(h=h.type.create({...h.attrs,rowspan:Math.max(1,a-h.attrs.rowspan)},h.content)),c.push(h)}i.push(Vr.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function tms(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=ix(o);let d,u;if(a>t.width)for(let h=0,p=0;ht.height){const h=[];for(let g=0,b=(t.height-1)*t.width;g=t.width?!1:n.nodeAt(t.map[b+g]).type==c.header_cell;h.push(v?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const p=c.row.create(null,Vr.from(h)),f=[];for(let g=t.height;g{if(!a)return!1;const i=n.selection;if(i instanceof jd)return Jme(n,r,no.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=Wxt(a,s,t);if(l==null)return!1;if(s=="horiz")return Jme(n,r,no.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=Bxt(o,s,t);let d;return c?d=no.near(c,1):t<0?d=no.near(n.doc.resolve(o.before(-1)),-1):d=no.near(n.doc.resolve(o.after(-1)),1),Jme(n,r,d)}}}function AH(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof jd)l=i;else{const c=Wxt(a,s,t);if(c==null)return!1;l=new jd(n.doc.resolve(c))}const o=Bxt(l.$headCell,s,t);return o?Jme(n,r,new jd(l.$anchorCell,o)):!1}}function nms(s,t){const n=s.state.doc,r=CM(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new jd(r))),!0):!1}function rms(s,t,n){if(!Lb(s.state))return!1;let r=Xhs(n);const a=s.state.selection;if(a instanceof jd){r||(r={width:1,height:1,rows:[Vr.from(a3e(ix(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=ch.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=ems(r,o.right-o.left,o.bottom-o.top),TVe(s.state,s.dispatch,l,o,r),!0}else if(r){const i=dve(s.state),l=i.start(-1);return TVe(s.state,s.dispatch,l,ch.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function ams(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=EVe(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof jd)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=CM(s.state.selection.$anchor))!=null&&((n=_2e(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=_2e(s,d);const h=fS.getState(s.state)==null;if(!u||!fIe(c,u))if(h)u=c;else return;const p=new jd(c,u);if(h||!s.state.selection.eq(p)){const f=s.state.tr.setSelection(p);h&&f.setMeta(fS,c.pos),s.dispatch(f)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),fS.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(fS,-1))}function o(c){const d=c,u=fS.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(EVe(s,d.target)!=r&&(h=_2e(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 Wxt(s,t,n){if(!(s.state.selection instanceof Ki))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 EVe(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function _2e(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&&CM(s.state.doc.resolve(r))||CM(s.state.doc.resolve(a))}var ims=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")),i3e(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,i3e(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function i3e(s,t,n,r,a,i){let l=0,o=!0,c=t.firstChild;const d=s.firstChild;if(d){for(let h=0,p=0;hnew r(h,n,p)),new lms(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=X0.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{cms(l,o,s,a)},mouseleave:l=>{dms(l)},mousedown:(l,o)=>{ums(l,o,t,n)}},decorations:l=>{const o=X0.getState(l);if(o&&o.activeHandle>-1)return xms(l,o.activeHandle)},nodeViews:{}}});return i}var lms=class epe{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(X0);if(r&&r.setHandle!=null)return new epe(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new epe(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return r3e(t.doc.resolve(a))||(a=-1),new epe(a,n.dragging)}return n}};function cms(s,t,n,r){if(!s.editable)return;const a=X0.getState(s.state);if(a&&!a.dragging){const i=mms(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=AVe(s,t,"left",n):c-t.clientX<=n&&(l=AVe(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=ch.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}Kxt(s,l)}}}function dms(s){if(!s.editable)return;const t=X0.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&Kxt(s,-1)}function ums(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=X0.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=hms(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(X0,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const p=X0.getState(s.state);p!=null&&p.dragging&&(pms(s,p.activeHandle,MVe(p.dragging,h,n)),s.dispatch(s.state.tr.setMeta(X0,{setDragging:null})))}function u(h){if(!h.which)return d(h);const p=X0.getState(s.state);if(p&&p.dragging){const f=MVe(p.dragging,h,n);IVe(s,p.activeHandle,f,r)}}return IVe(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function hms(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 _ms(s,t,n,r,a){const i=bms(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!wms(t))return!1;let n=0;const r=bxt(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},jms=ux.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:yms,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}=vms(s,this.options.cellMinWidth),i=["table",xu(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=_ms(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(Ki.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>Rhs(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>Ohs(s,t),deleteColumn:()=>({state:s,dispatch:t})=>zhs(s,t),addRowBefore:()=>({state:s,dispatch:t})=>$hs(s,t),addRowAfter:()=>({state:s,dispatch:t})=>Uhs(s,t),deleteRow:()=>({state:s,dispatch:t})=>Vhs(s,t),deleteTable:()=>({state:s,dispatch:t})=>Qhs(s,t),mergeCells:()=>({state:s,dispatch:t})=>wVe(s,t),splitCell:()=>({state:s,dispatch:t})=>jVe(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>IB("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>IB("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>Yhs(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>wVe(s,t)?!0:jVe(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>Whs(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>kVe(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>kVe(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&Vxt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=jd.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:MH,"Mod-Backspace":MH,Delete:MH,"Mod-Delete":MH}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[oms({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],gms({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:el(di(s,"tableRole",t))}}}),Nms=ux.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",xu(this.options.HTMLAttributes,s),0]}}),kms=ux.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",xu(this.options.HTMLAttributes,s),0]}}),Sms=ux.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",xu(this.options.HTMLAttributes,s),0]}});function Db({content:s,onChange:t,placeholder:n="Enter content...",minHeight:r="150px",compact:a=!1}){const[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState(!0),h=eIe({extensions:[sIe,hIe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),mIe.configure({types:["heading","paragraph"]}),pIe,bhs.extend({addAttributes(){var b;return{...(b=this.parent)==null?void 0:b.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),jms.extend({addAttributes(){var b;return{...(b=this.parent)==null?void 0:b.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),Nms.extend({addAttributes(){var b;return{...(b=this.parent)==null?void 0:b.call(this),style:{default:null}}}}),kms.extend({addAttributes(){var b;return{...(b=this.parent)==null?void 0:b.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),Sms.extend({addAttributes(){var b;return{...(b=this.parent)==null?void 0:b.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:b})=>{t(b.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":n},handlePaste:(b,v)=>{var _;const j=(_=v.clipboardData)==null?void 0:_.items;if(!j)return!1;for(const S of Array.from(j))if(S.type.startsWith("image/")){v.preventDefault();const A=S.getAsFile();if(!A)continue;const T=new FileReader;return T.onload=D=>{var M;const L=(M=D.target)==null?void 0:M.result;b.dispatch(b.state.tr.replaceSelectionWith(b.state.schema.nodes.image.create({src:L})))},T.readAsDataURL(A),!0}return!1}}});N.useEffect(()=>{h&&s!==h.getHTML()&&h.commands.setContent(s)},[s,h]);const p=()=>{if(!h)return;const b=h.getAttributes("link").href||"",v=h.getAttributes("link").target;c(b),u(v==="_blank"),l(!0)},f=()=>{h&&(o===""?h.chain().focus().extendMarkRange("link").unsetLink().run():h.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},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(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:1}).run(),className:h.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(aL,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:2}).run(),className:h.isActive("heading",{level:2})?"bg-muted":"",title:"Heading 2",children:e.jsx(iL,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBold().run(),className:h.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(YS,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleItalic().run(),className:h.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(e4,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBulletList().run(),className:h.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(Ep,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleOrderedList().run(),className:h.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(zv,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("left").run(),className:h.isActive({textAlign:"left"})?"bg-muted":"",title:"Align Left",children:e.jsx(wA,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("center").run(),className:h.isActive({textAlign:"center"})?"bg-muted":"",title:"Align Center",children:e.jsx(_A,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("right").run(),className:h.isActive({textAlign:"right"})?"bg-muted":"",title:"Align Right",children:e.jsx(jA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:p,className:h.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(tl,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:g,title:"Remove Link",children:e.jsx(tl,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().undo().run(),disabled:!h.can().undo(),title:"Undo",children:e.jsx(u4,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().redo().run(),disabled:!h.can().redo(),title:"Redo",children:e.jsx(l4,{className:"h-4 w-4"})})]}),e.jsx(X6e,{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(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{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(se,{htmlFor:"link-url",children:"URL"}),e.jsx(ge,{id:"link-url",value:o,onChange:b=>c(b.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(vn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(se,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:f,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var Cms=Object.defineProperty,Tms=(s,t,n)=>t in s?Cms(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,au=(s,t,n)=>Tms(s,typeof t!="symbol"?t+"":t,n);const jxe={x:0,y:0,width:0,height:0,unit:"px"},CI=(s,t,n)=>Math.min(Math.max(s,t),n),Ems=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),DVe=(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 Ams(s,t,n,r){const a=q_(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==="%"?sS(a,n,r):a}function Mms(s,t,n){const r=q_(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?sS(r,t,n):r}function sS(s,t,n){return s.unit==="%"?{...jxe,...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 q_(s,t,n){return s.unit?s.unit==="px"?{...jxe,...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}:{...jxe,...s,unit:"px"}}function RVe(s,t,n,r,a,i=0,l=0,o=r,c=a){const d={...s};let u=Math.min(i,r),h=Math.min(l,a),p=Math.min(o,r),f=Math.min(c,a);t&&(t>1?(u=l?l*t:u,h=u/t,p=o*t):(h=i?i/t:h,u=h*t,f=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,h),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);const g=r-(d.x+d.width);g<0&&(d.x=Math.min(d.x,r-u),d.width+=g);const b=a-(d.y+d.height);if(b<0&&(d.y=Math.min(d.y,a-h),d.height+=b),d.widthp&&((n==="sw"||n=="nw")&&(d.x-=p-d.width),d.width=p),d.height>f&&((n==="nw"||n=="ne")&&(d.y-=f-d.height),d.height=f),t){const v=d.width/d.height;if(vt){const j=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=j-d.width),d.width=j}}return d}function Ims(s,t,n,r){const a={...s};return t==="ArrowLeft"?r==="nw"?(a.x-=n,a.y-=n,a.width+=n,a.height+=n):r==="w"?(a.x-=n,a.width+=n):r==="sw"?(a.x-=n,a.width+=n,a.height+=n):r==="ne"?(a.y+=n,a.width-=n,a.height-=n):r==="e"?a.width-=n:r==="se"&&(a.width-=n,a.height-=n):t==="ArrowRight"&&(r==="nw"?(a.x+=n,a.y+=n,a.width-=n,a.height-=n):r==="w"?(a.x+=n,a.width-=n):r==="sw"?(a.x+=n,a.width-=n,a.height-=n):r==="ne"?(a.y-=n,a.width+=n,a.height+=n):r==="e"?a.width+=n:r==="se"&&(a.width+=n,a.height+=n)),t==="ArrowUp"?r==="nw"?(a.x-=n,a.y-=n,a.width+=n,a.height+=n):r==="n"?(a.y-=n,a.height+=n):r==="ne"?(a.y-=n,a.width+=n,a.height+=n):r==="sw"?(a.x+=n,a.width-=n,a.height-=n):r==="s"?a.height-=n:r==="se"&&(a.width-=n,a.height-=n):t==="ArrowDown"&&(r==="nw"?(a.x+=n,a.y+=n,a.width-=n,a.height-=n):r==="n"?(a.y+=n,a.height-=n):r==="ne"?(a.y+=n,a.width-=n,a.height-=n):r==="sw"?(a.x-=n,a.width+=n,a.height+=n):r==="s"?a.height+=n:r==="se"&&(a.width+=n,a.height+=n)),a}const TI={capture:!0,passive:!1};let Pms=0;const Vk=class U1 extends N.PureComponent{constructor(){super(...arguments),au(this,"docMoveBound",!1),au(this,"mouseDownOnCrop",!1),au(this,"dragStarted",!1),au(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),au(this,"componentRef",N.createRef()),au(this,"mediaRef",N.createRef()),au(this,"resizeObserver"),au(this,"initChangeCalled",!1),au(this,"instanceId",`rc-${Pms++}`),au(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),au(this,"onCropPointerDown",t=>{const{crop:n,disabled:r}=this.props,a=this.getBox();if(!n)return;const i=q_(n,a.width,a.height);if(r)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const l=t.target.dataset.ord,o=!!l;let c=t.clientX,d=t.clientY,u=i.x,h=i.y;if(l){const p=t.clientX-a.x,f=t.clientY-a.y;let g=0,b=0;l==="ne"||l=="e"?(g=p-(i.x+i.width),b=f-i.y,u=i.x,h=i.y+i.height):l==="se"||l==="s"?(g=p-(i.x+i.width),b=f-(i.y+i.height),u=i.x,h=i.y):l==="sw"||l=="w"?(g=p-i.x,b=f-(i.y+i.height),u=i.x+i.width,h=i.y):(l==="nw"||l=="n")&&(g=p-i.x,b=f-i.y,u=i.x+i.width,h=i.y+i.height),c=u+a.x+g,d=h+a.y+b}this.evData={startClientX:c,startClientY:d,startCropX:u,startCropY:h,clientX:t.clientX,clientY:t.clientY,isResize:o,ord:l},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})}),au(this,"onComponentPointerDown",t=>{const{crop:n,disabled:r,locked:a,keepSelection:i,onChange:l}=this.props,o=this.getBox();if(r||a||i&&n)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const c=t.clientX-o.x,d=t.clientY-o.y,u={unit:"px",x:c,y:d,width:0,height:0};this.evData={startClientX:t.clientX,startClientY:t.clientY,startCropX:c,startCropY:d,clientX:t.clientX,clientY:t.clientY,isResize:!0},this.mouseDownOnCrop=!0,l(q_(u,o.width,o.height),sS(u,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),au(this,"onDocPointerMove",t=>{const{crop:n,disabled:r,onChange:a,onDragStart:i}=this.props,l=this.getBox();if(r||!n||!this.mouseDownOnCrop)return;t.cancelable&&t.preventDefault(),this.dragStarted||(this.dragStarted=!0,i&&i(t));const{evData:o}=this;o.clientX=t.clientX,o.clientY=t.clientY;let c;o.isResize?c=this.resizeCrop():c=this.dragCrop(),DVe(n,c)||a(q_(c,l.width,l.height),sS(c,l.width,l.height))}),au(this,"onComponentKeyDown",t=>{const{crop:n,disabled:r,onChange:a,onComplete:i}=this.props;if(r)return;const l=t.key;let o=!1;if(!n)return;const c=this.getBox(),d=this.makePixelCrop(c),u=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?U1.nudgeStepLarge:t.shiftKey?U1.nudgeStepMedium:U1.nudgeStep;if(l==="ArrowLeft"?(d.x-=u,o=!0):l==="ArrowRight"?(d.x+=u,o=!0):l==="ArrowUp"?(d.y-=u,o=!0):l==="ArrowDown"&&(d.y+=u,o=!0),o){t.cancelable&&t.preventDefault(),d.x=CI(d.x,0,c.width-d.width),d.y=CI(d.y,0,c.height-d.height);const h=q_(d,c.width,c.height),p=sS(d,c.width,c.height);a(h,p),i&&i(h,p)}}),au(this,"onHandlerKeyDown",(t,n)=>{const{aspect:r=0,crop:a,disabled:i,minWidth:l=0,minHeight:o=0,maxWidth:c,maxHeight:d,onChange:u,onComplete:h}=this.props,p=this.getBox();if(i||!a)return;if(t.key==="ArrowUp"||t.key==="ArrowDown"||t.key==="ArrowLeft"||t.key==="ArrowRight")t.stopPropagation(),t.preventDefault();else return;const f=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?U1.nudgeStepLarge:t.shiftKey?U1.nudgeStepMedium:U1.nudgeStep,g=q_(a,p.width,p.height),b=Ims(g,t.key,f,n),v=RVe(b,r,n,p.width,p.height,l,o,c,d);if(!DVe(a,v)){const j=sS(v,p.width,p.height);u(v,j),h&&h(v,j)}}),au(this,"onDocPointerDone",t=>{const{crop:n,disabled:r,onComplete:a,onDragEnd:i}=this.props,l=this.getBox();this.unbindDocMove(),!(r||!n)&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,i&&i(t),a&&a(q_(n,l.width,l.height),sS(n,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),au(this,"onDragFocus",()=>{var t;(t=this.componentRef.current)==null||t.scrollTo(0,0)})}get document(){return document}getBox(){const t=this.mediaRef.current;if(!t)return{x:0,y:0,width:0,height:0};const{x:n,y:r,width:a,height:i}=t.getBoundingClientRect();return{x:n,y:r,width:a,height:i}}componentDidUpdate(t){const{crop:n,onComplete:r}=this.props;if(r&&!t.crop&&n){const{width:a,height:i}=this.getBox();a&&i&&r(q_(n,a,i),sS(n,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,TI),this.document.addEventListener("pointerup",this.onDocPointerDone,TI),this.document.addEventListener("pointercancel",this.onDocPointerDone,TI),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,TI),this.document.removeEventListener("pointerup",this.onDocPointerDone,TI),this.document.removeEventListener("pointercancel",this.onDocPointerDone,TI),this.docMoveBound=!1)}getCropStyle(){const{crop:t}=this.props;if(t)return{top:`${t.y}${t.unit}`,left:`${t.x}${t.unit}`,width:`${t.width}${t.unit}`,height:`${t.height}${t.unit}`}}dragCrop(){const{evData:t}=this,n=this.getBox(),r=this.makePixelCrop(n),a=t.clientX-t.startClientX,i=t.clientY-t.startClientY;return r.x=CI(t.startCropX+a,0,n.width-r.width),r.y=CI(t.startCropY+i,0,n.height-r.height),r}getPointRegion(t,n,r,a){const{evData:i}=this,l=i.clientX-t.x,o=i.clientY-t.y;let c;a&&n?c=n==="nw"||n==="n"||n==="ne":c=o1?i?[i,i/n]:[l*n,l]:l?[l*n,l]:[i,i/n]}resizeCrop(){const{evData:t}=this,{aspect:n=0,maxWidth:r,maxHeight:a}=this.props,i=this.getBox(),[l,o]=this.resolveMinDimensions(i,n,this.props.minWidth,this.props.minHeight);let c=this.makePixelCrop(i);const d=this.getPointRegion(i,t.ord,l,o),u=t.ord||d;let h=t.clientX-t.startClientX,p=t.clientY-t.startClientY;(l&&u==="nw"||u==="w"||u==="sw")&&(h=Math.min(h,-l)),(o&&u==="nw"||u==="n"||u==="ne")&&(p=Math.min(p,-o));const f={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(f.x=t.startCropX,f.width=h,n?(f.height=f.width/n,f.y=t.startCropY-f.height):(f.height=Math.abs(p),f.y=t.startCropY-f.height)):d==="se"?(f.x=t.startCropX,f.y=t.startCropY,f.width=h,n?f.height=f.width/n:f.height=p):d==="sw"?(f.x=t.startCropX+h,f.y=t.startCropY,f.width=Math.abs(h),n?f.height=f.width/n:f.height=p):d==="nw"&&(f.x=t.startCropX+h,f.width=Math.abs(h),n?(f.height=f.width/n,f.y=t.startCropY-f.height):(f.height=Math.abs(p),f.y=t.startCropY+p));const g=RVe(f,n,d,i.width,i.height,l,o,r,a);return n||U1.xyOrds.indexOf(u)>-1?c=g:U1.xOrds.indexOf(u)>-1?(c.x=g.x,c.width=g.width):U1.yOrds.indexOf(u)>-1&&(c.y=g.y,c.height=g.height),c.x=CI(c.x,0,i.width-c.width),c.y=CI(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=U1.defaultProps.ariaLabels,disabled:n,locked:r,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return Nt.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!n&&!r&&Nt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Nt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Nt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Nt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Nt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-nw","data-ord":"nw",tabIndex:0,"aria-label":t.nwDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"nw"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-n","data-ord":"n",tabIndex:0,"aria-label":t.nDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"n"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-ne","data-ord":"ne",tabIndex:0,"aria-label":t.neDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"ne"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-e","data-ord":"e",tabIndex:0,"aria-label":t.eDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"e"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-se","data-ord":"se",tabIndex:0,"aria-label":t.seDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"se"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-s","data-ord":"s",tabIndex:0,"aria-label":t.sDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"s"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-sw","data-ord":"sw",tabIndex:0,"aria-label":t.swDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"sw"),role:"button"}),Nt.createElement("div",{className:"ReactCrop__drag-handle ord-w","data-ord":"w",tabIndex:0,"aria-label":t.wDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"w"),role:"button"})),a&&Nt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&Nt.createElement(Nt.Fragment,null,Nt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Nt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const n={...jxe,...this.props.crop||{}};return q_(n,t.width,t.height)}render(){const{aspect:t,children:n,circularCrop:r,className:a,crop:i,disabled:l,locked:o,style:c,ruleOfThirds:d}=this.props,{cropIsActive:u,newCropIsBeingDrawn:h}=this.state,p=i?this.renderCropSelection():null,f=Ems("ReactCrop",a,u&&"ReactCrop--active",l&&"ReactCrop--disabled",o&&"ReactCrop--locked",h&&"ReactCrop--new-crop",i&&t&&"ReactCrop--fixed-aspect",i&&r&&"ReactCrop--circular-crop",i&&d&&"ReactCrop--rule-of-thirds",!this.dragStarted&&i&&!i.width&&!i.height&&"ReactCrop--invisible-crop",r&&"ReactCrop--no-animate");return Nt.createElement("div",{ref:this.componentRef,className:f,style:c},Nt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},n),i?Nt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Nt.createElement("defs",null,Nt.createElement("mask",{id:`hole-${this.instanceId}`},Nt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),r?Nt.createElement("ellipse",{cx:`${i.x+i.width/2}${i.unit}`,cy:`${i.y+i.height/2}${i.unit}`,rx:`${i.width/2}${i.unit}`,ry:`${i.height/2}${i.unit}`,fill:"black"}):Nt.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),Nt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,p)}};au(Vk,"xOrds",["e","w"]),au(Vk,"yOrds",["n","s"]),au(Vk,"xyOrds",["nw","ne","se","sw"]),au(Vk,"nudgeStep",1),au(Vk,"nudgeStepMedium",10),au(Vk,"nudgeStepLarge",100),au(Vk,"defaultProps",{ariaLabels:{cropArea:"Use the arrow keys to move the crop selection area",nwDragHandle:"Use the arrow keys to move the north west drag handle to change the crop selection area",nDragHandle:"Use the up and down arrow keys to move the north drag handle to change the crop selection area",neDragHandle:"Use the arrow keys to move the north east drag handle to change the crop selection area",eDragHandle:"Use the up and down arrow keys to move the east drag handle to change the crop selection area",seDragHandle:"Use the arrow keys to move the south east drag handle to change the crop selection area",sDragHandle:"Use the up and down arrow keys to move the south drag handle to change the crop selection area",swDragHandle:"Use the arrow keys to move the south west drag handle to change the crop selection area",wDragHandle:"Use the up and down arrow keys to move the west drag handle to change the crop selection area"}});let Lms=Vk;function Dms(s,t,n){return Mms(Ams({unit:"%",width:90},n,s,t),s,t)}const xIe=({open:s,onClose:t,imageSrc:n,onCropComplete:r,aspectRatio:a=1})=>{const i=N.useRef(null),[l,o]=N.useState(),[c,d]=N.useState(),[u,h]=N.useState(1),[p,f]=N.useState(0),g=N.useCallback(j=>{const{width:_,height:S}=j.currentTarget;o(Dms(_,S,a))},[a]),b=N.useCallback(async()=>{const j=i.current;if(!j||!c)return;const _=document.createElement("canvas"),S=_.getContext("2d");if(!S)return;const A=j.naturalWidth/j.width,T=j.naturalHeight/j.height,D=400;_.width=D,_.height=D,S.imageSmoothingQuality="high";const L=c.x*A,M=c.y*T,F=c.width*A,z=c.height*T,V=p*Math.PI/180,W=_.width/2,K=_.height/2;return S.save(),S.translate(W,K),S.rotate(V),S.scale(u,u),S.translate(-W,-K),S.drawImage(j,L,M,F,z,0,0,D,D),S.restore(),new Promise((Y,ee)=>{_.toBlob(ne=>{ne?Y(ne):ee(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,p]),v=async()=>{try{const j=await b();j&&(r(j),t())}catch(j){console.error("Error cropping image:",j)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{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(Lms,{crop:l,onChange:(j,_)=>o(_),onComplete:j=>d(j),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:n,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${p}deg)`,maxHeight:"400px",width:"auto"},onLoad:g})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(CL,{className:"h-4 w-4 text-muted-foreground"}),e.jsx($m,{value:[u],min:.5,max:3,step:.1,onValueChange:([j])=>h(j),className:"flex-1"}),e.jsx(h4,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(BA,{className:"h-4 w-4 text-muted-foreground"}),e.jsx($m,{value:[p],min:-180,max:180,step:1,onValueChange:([j])=>f(j),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[p,"°"]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:v,children:"Save Photo"})]})]})})},Rms=()=>{const{user:s}=gs(),{toast:t}=Ua(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(null);N.useEffect(()=>{s&&c()},[s]);const c=async()=>{r(!0);try{const{data:h}=await q.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",s==null?void 0:s.id).single();h&&o({status:h.subscription_status||"none",productId:h.subscription_product_id,endDate:h.subscription_end_date,isGrandfathered:h.is_grandfathered||!1})}catch(h){console.error("Error loading subscription:",h)}finally{r(!1)}},d=async()=>{i(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)throw new Error("Not authenticated");const{data:p,error:f}=await q.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${h.access_token}`}});if(f)throw f;p!=null&&p.url&&window.open(p.url,"_blank")}catch(h){console.error("Error opening customer portal:",h),t({title:"Error",description:h.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},u=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(ze,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(ze,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(ze,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(ze,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(ze,{variant:"secondary",children:"Canceled"});default:return e.jsx(ze,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(ff,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(ff,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Hn,{children:"Manage your subscription and billing"})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Status"}),e.jsx("div",{className:"mt-1",children:u()})]}),(l==null?void 0:l.endDate)&&l.status==="active"&&e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Next billing date"}),e.jsx("p",{className:"font-medium",children:new Date(l.endDate).toLocaleDateString()})]})]}),l!=null&&l.isGrandfathered?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your account was upgraded from LevelUp 1.0. To update/manage your subscription please reach out to support."}):(l==null?void 0:l.status)==="active"||(l==null?void 0:l.status)==="trialing"?e.jsxs(e.Fragment,{children:[(l==null?void 0:l.status)==="trialing"&&(l==null?void 0:l.endDate)&&e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Your trial ends on ",new Date(l.endDate).toLocaleDateString(),". After the trial, you'll be charged automatically."]}),e.jsxs(B,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(ss,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tr,{className:"mr-2 h-4 w-4"}),"Manage Billing"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"You don't have an active subscription."})]})]})},Oms=()=>{const{user:s}=gs(),t=In(),{toast:n}=Ua(),[r]=yl(),a=r.get("setup")==="true",i=r.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:u}=qmt(),[h,p]=N.useState(!1),[f,g]=N.useState(""),[b,v]=N.useState(!1),[j,_]=N.useState(!1),[S,A]=N.useState(""),[T,D]=N.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[L,M]=N.useState(!1),[F,z]=N.useState(!1),[V,W]=N.useState(!1),[K,Y]=N.useState(!1),[ee,ne]=N.useState(!1),[oe,pe]=N.useState({newPassword:"",confirmPassword:""});N.useEffect(()=>{s&&ce()},[s]),N.useEffect(()=>{i&&s&&setTimeout(()=>{var Me;(Me=document.getElementById("change-password-section"))==null||Me.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const ce=async()=>{var Me,Te,Ce,Ee;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:De,error:Ie}=await q.from("profiles").select("name, email, phone, digest_opt_out, event_invite_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(Ie)throw console.error("Profile query error:",Ie),Ie;if(De){console.log("Profile loaded successfully:",De);const qe=((Me=De.brokerages)==null?void 0:Me.name)||"";M(!!De.brokerage_id),D({name:De.name||"",email:De.email||"",phone:De.phone||"",title:De.title||"",bio:De.bio||"",areas_served:De.areas_served||"",years_experience:((Te=De.years_experience)==null?void 0:Te.toString())||"",brokerage_name:De.brokerage_id?qe:De.brokerage_name||"",instagram_url:De.instagram_url||"",facebook_url:De.facebook_url||"",linkedin_url:De.linkedin_url||"",email_signature:De.email_signature||"",use_email_signature:De.use_email_signature||!1}),z(De.digest_opt_out||!1),Y(De.event_invite_opt_out||!1)}else console.warn("No profile found for user"),D({name:((Ce=s.user_metadata)==null?void 0:Ce.name)||((Ee=s.email)==null?void 0:Ee.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:Fe}=await q.storage.from("avatars").list(`${s.id}`);if(Fe&&Fe.length>0){const{data:qe}=q.storage.from("avatars").getPublicUrl(`${s.id}/${Fe[0].name}`);g(qe.publicUrl)}}catch(De){console.error("Error loading profile:",De),n({title:"Error",description:De.message||"Failed to load profile",variant:"destructive"})}},de=Me=>{var Ee;const Te=(Ee=Me.target.files)==null?void 0:Ee[0];if(!Te)return;const Ce=new FileReader;Ce.onloadend=()=>{A(Ce.result),_(!0)},Ce.readAsDataURL(Te),Me.target.value=""},ie=async Me=>{if(s){v(!0);try{const{data:Te}=await q.storage.from("avatars").list(`${s.id}`);Te&&Te.length>0&&await q.storage.from("avatars").remove(Te.map(qe=>`${s.id}/${qe.name}`));const Ee=`${s.id}/avatar.jpg`,{error:De}=await q.storage.from("avatars").upload(Ee,Me,{upsert:!0,contentType:"image/jpeg"});if(De)throw De;const{data:Ie}=q.storage.from("avatars").getPublicUrl(Ee),Fe=Ie.publicUrl;g(`${Fe}?t=${Date.now()}`),await q.from("profiles").update({avatar_url:Fe}).eq("id",s.id),n({title:"Success",description:"Profile photo updated successfully"})}catch(Te){console.error("Error uploading avatar:",Te),n({title:"Error",description:Te.message||"Failed to upload photo",variant:"destructive"})}finally{v(!1)}}},ye=async()=>{if(!T.name.trim()||!T.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}p(!0);try{const{error:Me}=await q.from("profiles").update({name:T.name.trim(),email:T.email.trim(),phone:T.phone.trim()||null,title:T.title.trim()||null,bio:T.bio.trim()||null,areas_served:T.areas_served.trim()||null,years_experience:T.years_experience?parseInt(T.years_experience):null,...L?{}:{brokerage_name:T.brokerage_name.trim()||null},instagram_url:T.instagram_url.trim()||null,facebook_url:T.facebook_url.trim()||null,linkedin_url:T.linkedin_url.trim()||null,email_signature:T.email_signature||"",use_email_signature:T.use_email_signature}).eq("id",s==null?void 0:s.id);if(Me)throw Me;n({title:"Success",description:"Profile updated successfully"})}catch(Me){console.error("Error updating profile:",Me),n({title:"Error",description:Me.message||"Failed to update profile",variant:"destructive"})}finally{p(!1)}},_e=async()=>{if(!oe.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(oe.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(oe.newPassword!==oe.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}p(!0);try{const{error:Me}=await q.auth.updateUser({password:oe.newPassword});if(Me)throw Me;n({title:"Success",description:"Password updated successfully"}),pe({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(Me){console.error("Error updating password:",Me),n({title:"Error",description:Me.message||"Failed to update password",variant:"destructive"})}finally{p(!1)}};return e.jsx(Cs,{title:a?"Complete Your Profile":i?"Reset Your Password":"Profile Settings",description:a?"Welcome! Please complete your profile setup":i?"Please set a new password for your account":"Manage your account information and password",children:e.jsxs("div",{className:"mx-auto max-w-4xl",children:[!a&&!i&&e.jsx("div",{className:"mb-6",children:e.jsxs(B,{variant:"outline",onClick:()=>{var Me;(Me=document.getElementById("change-password-section"))==null||Me.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(PA,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Profile Photo"}),e.jsx(Hn,{children:"Upload a professional photo for your profile"})]}),e.jsxs(Ae,{className:"flex items-center gap-6",children:[e.jsxs(aa,{className:"h-24 w-24",children:[e.jsx(ri,{src:f}),e.jsx(ia,{className:"text-2xl",children:T.name.split(" ").map(Me=>Me[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:de,disabled:b}),e.jsxs(B,{variant:"outline",onClick:()=>{var Me;return(Me=document.getElementById("avatar-upload"))==null?void 0:Me.click()},disabled:b,children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),b?"Uploading...":"Upload Photo"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Upload an image and crop it to your liking."})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Personal Information"}),e.jsx(Hn,{children:"Update your profile details"})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ge,{id:"name",value:T.name,onChange:Me=>D({...T,name:Me.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ge,{id:"email",type:"email",value:T.email,onChange:Me=>D({...T,email:Me.target.value}),maxLength:255})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"phone",children:"Phone Number"}),e.jsx(ge,{id:"phone",type:"tel",value:T.phone,onChange:Me=>D({...T,phone:Me.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(se,{htmlFor:"title",children:"Job Title"}),e.jsx(ge,{id:"title",value:T.title,onChange:Me=>D({...T,title:Me.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"bio",children:"Bio"}),e.jsx(Ts,{id:"bio",value:T.bio,onChange:Me=>D({...T,bio:Me.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(se,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(ge,{id:"areas_served",value:T.areas_served,onChange:Me=>D({...T,areas_served:Me.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(ge,{id:"years_experience",type:"number",min:"0",value:T.years_experience,onChange:Me=>D({...T,years_experience:Me.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"brokerage_name",children:["Brokerage ",L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(ge,{id:"brokerage_name",value:T.brokerage_name,onChange:Me=>D({...T,brokerage_name:Me.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:L,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:L?"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(se,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(ge,{value:T.linkedin_url,onChange:Me=>D({...T,linkedin_url:Me.target.value}),placeholder:"LinkedIn URL"}),e.jsx(ge,{value:T.instagram_url,onChange:Me=>D({...T,instagram_url:Me.target.value}),placeholder:"Instagram URL"}),e.jsx(ge,{value:T.facebook_url,onChange:Me=>D({...T,facebook_url:Me.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs(B,{onClick:ye,disabled:h,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(nb,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(Hn,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Ae,{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:T.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(vn,{checked:T.use_email_signature,onCheckedChange:Me=>D({...T,use_email_signature:Me})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Signature"}),e.jsx(Db,{content:T.email_signature,onChange:Me=>D({...T,email_signature:Me}),placeholder:"Paste your Gmail signature here or create one...",minHeight:"120px",compact:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tip: Copy your signature from Gmail Settings and paste it here — images and formatting will be preserved."})]}),e.jsxs(B,{onClick:ye,disabled:h,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsxs(fe,{id:"change-password-section",children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:a?"Set Your Password":"Change Password"}),e.jsx(Hn,{children:a?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"newPassword",children:"New Password"}),e.jsx(ge,{id:"newPassword",type:"password",value:oe.newPassword,onChange:Me=>pe({...oe,newPassword:Me.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(ge,{id:"confirmPassword",type:"password",value:oe.confirmPassword,onChange:Me=>pe({...oe,confirmPassword:Me.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(B,{onClick:_e,disabled:h,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx(B,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[o?e.jsx(lm,{className:"h-5 w-5"}):e.jsx(fw,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Hn,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Ae,{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(vn,{checked:o,onCheckedChange:Me=>{Me?d():u()},disabled:c})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[F?e.jsx(uL,{className:"h-5 w-5"}):e.jsx(Hs,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Hn,{children:"Manage your email subscription settings"})]}),e.jsxs(Ae,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:F?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(vn,{checked:!F,onCheckedChange:async Me=>{W(!0);try{const{error:Te}=await q.from("profiles").update({digest_opt_out:!Me}).eq("id",s==null?void 0:s.id);if(Te)throw Te;z(!Me),n({title:Me?"Subscribed":"Unsubscribed",description:Me?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(Te){n({title:"Error",description:Te.message||"Failed to update preference",variant:"destructive"})}finally{W(!1)}},disabled:V})]}),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:K?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(vn,{checked:!K,onCheckedChange:async Me=>{ne(!0);try{const{error:Te}=await q.from("profiles").update({event_invite_opt_out:!Me}).eq("id",s==null?void 0:s.id);if(Te)throw Te;Y(!Me),n({title:Me?"Subscribed":"Unsubscribed",description:Me?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(Te){n({title:"Error",description:Te.message||"Failed to update preference",variant:"destructive"})}finally{ne(!1)}},disabled:ee})]})]})]}),e.jsx(kas,{}),e.jsx(Rms,{})]}),e.jsx(xIe,{open:j,onClose:()=>_(!1),imageSrc:S,onCropComplete:ie,aspectRatio:1})]})})};var Fms="AspectRatio",Yxt=N.forwardRef((s,t)=>{const{ratio:n=1/1,style:r,...a}=s;return e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:`${100/n}%`},"data-radix-aspect-ratio-wrapper":"",children:e.jsx(sa.div,{...a,ref:t,style:{...r,position:"absolute",top:0,right:0,bottom:0,left:0}})})});Yxt.displayName=Fms;var zms=Yxt;const Bms=zms;function $ms(){const{user:s}=gs(),t=Gt(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),{data:l,isLoading:o}=lt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:b}=await q.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(b)throw b;return g},enabled:!!s&&a}),c=gt({mutationFn:async()=>{const g=new Uint8Array(12);crypto.getRandomValues(g);const b=btoa(String.fromCharCode(...g)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:v}=await q.from("profiles").update({calendar_token:b}).eq("id",s==null?void 0:s.id);if(v)throw v;return b},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://"))},p=()=>{if(d){const g=d.replace("https://","webcal://"),b=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(g)}`;window.open(b,"_blank")}},f=()=>{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(bs,{open:a,onOpenChange:i,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Qn,{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(ss,{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(ge,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(B,{variant:"outline",size:"icon",onClick:u,children:n?e.jsx(Lr,{className:"h-4 w-4 text-green-500"}):e.jsx(ta,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Quick Add"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-2",onClick:h,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"})}),"Add to Apple Calendar",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-2",onClick:p,children:[e.jsxs("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M19.5 22h-15A2.5 2.5 0 0 1 2 19.5v-15A2.5 2.5 0 0 1 4.5 2H9v2H4.5a.5.5 0 0 0-.5.5v15a.5.5 0 0 0 .5.5h15a.5.5 0 0 0 .5-.5V15h2v4.5a2.5 2.5 0 0 1-2.5 2.5z"}),e.jsx("path",{d:"M12 2v8.5a1.5 1.5 0 0 0 1.5 1.5H22V2h-10z",fill:"#4285F4"}),e.jsx("path",{d:"M12 12V2H4.5A2.5 2.5 0 0 0 2 4.5V12h10z",fill:"#34A853"}),e.jsx("path",{d:"M2 12v7.5A2.5 2.5 0 0 0 4.5 22H12v-10H2z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 22h7.5a2.5 2.5 0 0 0 2.5-2.5V12h-10v10z",fill:"#EA4335"})]}),"Add to Google Calendar",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-2",onClick:f,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M7.88 12.04q0 .45-.11.87-.1.41-.33.74-.22.33-.58.52-.37.2-.87.2t-.85-.2q-.35-.21-.57-.55-.22-.33-.33-.75-.1-.42-.1-.86t.1-.87q.1-.43.34-.76.22-.34.59-.54.36-.2.87-.2t.86.2q.35.21.57.55.22.34.31.77.1.43.1.88zM24 12v9.38q0 .46-.33.8-.33.32-.8.32H7.13q-.46 0-.8-.33-.32-.33-.32-.8V18H1q-.41 0-.7-.3-.3-.29-.3-.7V7q0-.41.3-.7Q.58 6 1 6h6.5V2.55q0-.44.3-.75.3-.3.75-.3h12.9q.44 0 .75.3.3.3.3.75V12zm-6-8.25v3h3v-3zm0 4.5v3h3v-3zm0 4.5v1.83l3.05-1.83zm-5.25-9v3h3.75v-3zm0 4.5v3h3.75v-3zm0 4.5v2.03l2.41 1.5 1.34-.81v-2.72zM9 3.75V6h2l.13.01.12.04v-2.3zM5.98 15.98q.9 0 1.6-.3.7-.32 1.19-.86.48-.55.73-1.28.25-.74.25-1.61 0-.83-.25-1.55-.24-.71-.71-1.24t-1.15-.83q-.68-.3-1.55-.3-.92 0-1.64.3-.71.3-1.2.85-.5.54-.75 1.3-.25.74-.25 1.63 0 .85.26 1.56.26.72.74 1.23.48.52 1.17.81.69.3 1.56.3zM7.5 21h12.39L12 16.08V17q0 .41-.3.7-.29.3-.7.3H7.5zm15-.13v-7.24l-5.9 3.54Z"})}),"Add to Outlook",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center pt-2",children:"Events sync automatically. If your membership expires, the calendar will show as empty."})]}):e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate your personal calendar subscription URL to get started."}),e.jsx(B,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const Ums={first_timer:ua,regular:X2,dedicated:vc,veteran:vo,streak_master:_c,century:vo},qms={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 OVe(s){return s===1?e.jsx(vo,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(X2,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(vc,{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 Zxt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=gs(),{data:i,isLoading:l}=xpt(t?5:10,n),{data:o}=gpt(a==null?void 0:a.id),{data:c}=vpt(a==null?void 0:a.id),{data:d}=ypt(a==null?void 0:a.id);return l?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(Ae,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(Ws,{className:"h-12 w-full"},h))})})]}):e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(Ae,{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(ze,{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(_c,{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=Ums[u.badge_type]||ua;return e.jsxs(ze,{variant:"outline",className:`text-xs ${qms[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(ze,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs($r,{defaultValue:"points",className:"w-full",children:[e.jsxs(Ur,{className:"w-full mb-3",children:[e.jsx(Zt,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Zt,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(ls,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var p,f,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:OVe(h+1)}),e.jsx(aa,{className:"h-8 w-8",children:e.jsx(ia,{className:"text-xs",children:((f=(p=u.profile)==null?void 0:p.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((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(ls,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((u,h)=>h.total_events_attended-u.total_events_attended).map((u,h)=>{var p,f,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:OVe(h+1)}),e.jsx(aa,{className:"h-8 w-8",children:e.jsx(ia,{className:"text-xs",children:((f=(p=u.profile)==null?void 0:p.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((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 Vms(){const s=In(),{user:t,isAdmin:n}=gs(),r=Gt(),{data:a,isLoading:i}=lt({queryKey:["public-events"],queryFn:async()=>{const{data:b,error:v}=await q.from("events").select("*").order("event_date",{ascending:!0});if(v)throw v;return b}}),{data:l}=lt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:b,error:v}=await q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(v)throw v;return b},enabled:!!t}),{data:o}=lt({queryKey:["event-registration-counts"],queryFn:async()=>{let b=[],v=0;const j=1e3;for(;;){const{data:S,error:A}=await q.from("event_registrations").select("event_id").range(v,v+j-1);if(A)throw A;if(!S||S.length===0||(b=b.concat(S),S.length{_[S.event_id]=(_[S.event_id]||0)+1}),_}}),c=gt({mutationFn:async b=>{await q.auth.refreshSession();const{data:v,error:j}=await q.functions.invoke("zoom-register",{body:{event_id:b}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:b=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),b!=null&&b.join_url?ae.success("Successfully registered! You'll receive a Zoom confirmation email."):ae.success("Successfully registered for the event!")},onError:b=>{ae.error("Failed to register: "+b.message)}}),d=gt({mutationFn:async b=>{const{data:v,error:j}=await q.functions.invoke("zoom-unregister",{body:{event_id:b}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),ae.success("Registration cancelled and removed from Zoom")},onError:b=>{ae.error("Failed to cancel: "+b.message)}}),u=b=>l==null?void 0:l.some(v=>v.event_id===b),h=b=>{const v=l==null?void 0:l.find(j=>j.event_id===b);return v==null?void 0:v.zoom_join_url},p=b=>b.capacity?((o==null?void 0:o[b.id])||0)>=b.capacity:!1,f=(a==null?void 0:a.filter(b=>RL(b.event_date)!=="ended"))||[],g=(a==null?void 0:a.filter(b=>RL(b.event_date)==="ended"))||[];return e.jsx(Cs,{title:"Events",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Events"}),e.jsx("p",{className:"text-muted-foreground",children:"Browse and register for upcoming events"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($ms,{}),n&&e.jsx(B,{variant:"outline",onClick:()=>s("/admin/events"),children:"Manage Events"})]})]}),e.jsxs("div",{className:`grid grid-cols-1 ${n?"lg:grid-cols-3":""} gap-6`,children:[e.jsxs("div",{className:n?"lg:col-span-2":"",children:[i?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading events..."}):f.length===0?e.jsx(fe,{className:"text-center py-12",children:e.jsx(Ae,{children:e.jsx("p",{className:"text-muted-foreground",children:"No upcoming events at the moment. Check back soon!"})})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:f.map(b=>{const v=RL(b.event_date),j=b6e(b.event_date),_=v==="live",S=v==="starting_soon";return e.jsxs(fe,{className:`flex flex-col overflow-hidden cursor-pointer hover:shadow-lg transition-all ${_?"border-red-500 ring-2 ring-red-500/20":S?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${b.id}`),children:[j&&e.jsxs("div",{className:`${_?"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"})]}),_?e.jsxs(e.Fragment,{children:[e.jsx(wf,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),b.image_url&&e.jsxs(Bms,{ratio:16/9,className:"overflow-hidden relative bg-neutral-900",children:[e.jsx("img",{src:b.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:b.image_url,alt:b.title,className:"relative w-full h-full object-contain group-hover:scale-[1.03] transition-transform"})]}),e.jsxs(Mt,{children:[e.jsx(Pt,{className:"line-clamp-2",children:b.title}),b.description&&e.jsx(Hn,{className:"line-clamp-2",children:b.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Ae,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(yr,{className:"h-4 w-4"}),new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(b.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(gr,{className:"h-4 w-4"}),vB(new Date(b.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(_n,{className:"h-4 w-4"}),(o==null?void 0:o[b.id])||0," registered",b.capacity&&` / ${b.capacity} spots`]})]}),e.jsx(nz,{className:"flex gap-2",onClick:A=>A.stopPropagation(),children:u(b.id)?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>d.mutate(b.id),disabled:d.isPending,children:[e.jsx(Fn,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(B,{className:"flex-1",onClick:()=>window.open(h(b.id)||b.zoom_link,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx(B,{className:"w-full",onClick:()=>c.mutate(b.id),disabled:c.isPending||p(b),children:p(b)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},b.id)})}),g.length>0&&e.jsxs("div",{className:"mt-12",children:[e.jsx("h3",{className:"text-xl font-semibold mb-4 text-muted-foreground",children:"Past Events"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:g.map(b=>e.jsx(fe,{className:"opacity-60 cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>s(`/events/${b.id}`),children:e.jsxs(Mt,{children:[e.jsx(Pt,{className:"text-base line-clamp-1",children:b.title}),e.jsx(Hn,{children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(b.event_date))})]})},b.id))})]})]}),n&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(Zxt,{showUserStats:!0})})]})]})})}const w2e=[{value:"all",label:"All Roles",icon:_n},{value:"newest",label:"Newest Members",icon:gr},{value:"brokerage_manager",label:"Brokerage Managers",icon:B9},{value:"admin",label:"Admins",icon:hh}];function Hms({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Fe,qe;const{user:i,isAdmin:l,isBrokerageManager:o}=gs(),[c,d]=N.useState([]),[u,h]=N.useState([]),[p,f]=N.useState([]),[g,b]=N.useState([]),[v,j]=N.useState(""),[_,S]=N.useState(""),[A,T]=N.useState(""),[D,L]=N.useState(!1),[M,F]=N.useState(!1),[z,V]=N.useState("agents"),[W,K]=N.useState("all"),[Y,ee]=N.useState({}),ne=l||o;N.useEffect(()=>{s&&i&&(l?oe():pe())},[s,i,l]),N.useEffect(()=>{s||(f([]),b([]),j(""),S(""),T(""),V("agents"),K("all"))},[s]);const oe=async()=>{if(i){L(!0);try{const{data:ve,error:Je}=await q.from("brokerages").select("id, name").order("name");if(Je)throw Je;const we=1e3,it={};let Ne=0,He=!0;for(;He;){const{data:Ke,error:rt}=await q.from("profiles").select("brokerage_id").range(Ne*we,(Ne+1)*we-1);if(rt)throw rt;Ke==null||Ke.forEach(tt=>{tt.brokerage_id&&(it[tt.brokerage_id]=(it[tt.brokerage_id]||0)+1)}),He=(Ke==null?void 0:Ke.length)===we,Ne++}h((ve==null?void 0:ve.map(Ke=>({...Ke,agent_count:it[Ke.id]||0})))||[]);const $e=[];for(Ne=0,He=!0;He;){const{data:Ke,error:rt}=await q.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Ne*we,(Ne+1)*we-1);if(rt)throw rt;Ke&&$e.push(...Ke),He=(Ke==null?void 0:Ke.length)===we,Ne++}const Ye={};for(Ne=0,He=!0;He;){const{data:Ke,error:rt}=await q.from("user_roles").select("user_id, role").range(Ne*we,(Ne+1)*we-1);if(rt)throw rt;Ke==null||Ke.forEach(tt=>{Ye[tt.user_id]||(Ye[tt.user_id]=[]),Ye[tt.user_id].push(tt.role)}),He=(Ke==null?void 0:Ke.length)===we,Ne++}ee(Ye),d($e.map(Ke=>{var rt;return{id:Ke.id,name:Ke.name,email:Ke.email,brokerage_name:((rt=Ke.brokerages)==null?void 0:rt.name)||"No Brokerage",roles:Ye[Ke.id]||[],created_at:Ke.created_at}}))}catch(ve){console.error("Error loading data:",ve),ae.error("Failed to load agents and brokerages")}finally{L(!1)}}},pe=async()=>{if(i){L(!0);try{const{data:ve}=await q.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(ve!=null&&ve.brokerage_id)){ae.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Je,error:we}=await q.from("profiles").select("id, name, email").eq("brokerage_id",ve.brokerage_id).neq("id",i.id).order("name");if(we)throw we;d(Je||[])}catch(ve){console.error("Error loading agents:",ve),ae.error("Failed to load agents")}finally{L(!1)}}},ce=c.filter(ve=>{var we;const Je=ve.name.toLowerCase().includes(v.toLowerCase())||ve.email.toLowerCase().includes(v.toLowerCase())||((we=ve.brokerage_name)==null?void 0:we.toLowerCase().includes(v.toLowerCase()));if(l&&W!=="all"&&W!=="newest"){const it=Y[ve.id]||[];return Je&&it.includes(W)}return Je}).sort((ve,Je)=>W==="newest"?(Je.created_at||"").localeCompare(ve.created_at||""):0),de=u.filter(ve=>ve.name.toLowerCase().includes(_.toLowerCase())),ie=()=>{p.length===ce.length?f([]):f(ce.map(ve=>ve.id))},ye=()=>{g.length===de.length?b([]):b(de.map(ve=>ve.id))},_e=ve=>{if(!ne){f([ve]);return}f(Je=>Je.includes(ve)?Je.filter(we=>we!==ve):[...Je,ve])},Me=ve=>{b(Je=>Je.includes(ve)?Je.filter(we=>we!==ve):[...Je,ve])},Te=async()=>{if(!(p.length>0||g.length>0)){ae.error("Please select at least one agent or brokerage to share with");return}F(!0);try{const{data:Je,error:we}=await q.functions.invoke("send-share-notification",{body:{recipientIds:p,brokerageIds:g,resourceType:n,resourceId:r,resourceTitle:a,message:A.trim()||void 0}});if(we)throw we;const it=(Je==null?void 0:Je.sharesCreated)||p.length;ae.success(`Shared with ${it} agent${it!==1?"s":""}`),t(!1)}catch(Je){console.error("Error sharing resource:",Je),ae.error("Failed to share resource")}finally{F(!1)}},Ce=ve=>ve.split(" ").map(Je=>Je[0]).join("").toUpperCase().slice(0,2),Ee=ve=>{const Je=Y[ve]||[];return Je.includes("admin")?e.jsx(ze,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Je.includes("brokerage_manager")?e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},De=p.length+g.length,Ie=W!=="all"&&W!=="newest"?ce.length:null;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{className:"flex-shrink-0",children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Qn,{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($r,{value:z,onValueChange:V,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Zt,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),p.length>0&&e.jsx(ze,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:p.length})]}),e.jsxs(Zt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),g.length>0&&e.jsx(ze,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:g.length})]})]}),e.jsxs(ls,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name, email, or brokerage...",value:v,onChange:ve=>j(ve.target.value),className:"pl-9"})]}),e.jsxs(us,{value:W,onValueChange:K,children:[e.jsxs(cs,{className:"w-[180px]",children:[e.jsx(Fv,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(hs,{placeholder:"Filter by role"})]}),e.jsx(ds,{children:w2e.map(ve=>e.jsx(Ze,{value:ve.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ve.icon,{className:"h-4 w-4"}),e.jsx("span",{children:ve.label})]})},ve.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:ie,className:"text-xs h-8",disabled:ce.length===0,children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1.5"}),p.length===ce.length&&ce.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Ie!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Ie," ",(Fe=w2e.find(ve=>ve.value===W))==null?void 0:Fe.label]}),e.jsxs("span",{className:"font-medium",children:[p.length," selected"]})]})]}),e.jsx(mi,{className:"h-[300px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ce.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(_n,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:W!=="all"?`No ${(qe=w2e.find(ve=>ve.value===W))==null?void 0:qe.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ce.map(ve=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${p.includes(ve.id)?"bg-accent":""}`,onClick:()=>_e(ve.id),children:[e.jsx(hi,{checked:p.includes(ve.id),onCheckedChange:()=>_e(ve.id),className:"flex-shrink-0"}),e.jsx(aa,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(ia,{className:"text-xs bg-primary/10 text-primary",children:Ce(ve.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ve.name}),Ee(ve.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ve.email,ve.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",ve.brokerage_name]})]})]})]},ve.id))})})]}),e.jsxs(ls,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search brokerages...",value:_,onChange:ve=>S(ve.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:ye,className:"text-xs h-8",disabled:de.length===0,children:[e.jsx(Ga,{className:"h-3.5 w-3.5 mr-1.5"}),g.length===de.length&&de.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(mi,{className:"h-[250px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):de.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(Ga,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No brokerages found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:de.map(ve=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${g.includes(ve.id)?"bg-accent":""}`,onClick:()=>Me(ve.id),children:[e.jsx(hi,{checked:g.includes(ve.id),onCheckedChange:()=>Me(ve.id),className:"flex-shrink-0"}),e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Ga,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ve.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ve.agent_count," agent",ve.agent_count!==1?"s":""]})]})]},ve.id))})})]})]}):e.jsxs("div",{className:"flex-1 flex flex-col space-y-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search agents...",value:v,onChange:ve=>j(ve.target.value),className:"pl-9"})]}),ne&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:ie,className:"text-xs h-8",disabled:ce.length===0,children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1.5"}),p.length===ce.length&&ce.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[p.length," selected"]})]}),e.jsx(mi,{className:"h-[300px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ce.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(_n,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ce.map(ve=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${p.includes(ve.id)?"bg-accent":""}`,onClick:()=>_e(ve.id),children:[e.jsx(hi,{checked:p.includes(ve.id),onCheckedChange:()=>_e(ve.id),className:"flex-shrink-0"}),e.jsx(aa,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(ia,{className:"text-xs bg-primary/10 text-primary",children:Ce(ve.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ve.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ve.email})]})]},ve.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(se,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Ts,{id:"message",placeholder:"I thought you might find this useful...",value:A,onChange:ve=>T(ve.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:Te,disabled:De===0||M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function tR({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=N.useState(!1),{user:c}=gs();return c?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(Hl,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(Hms,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function Gms(){const{eventId:s}=_i(),t=In(),{user:n}=gs(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(0),[d,u]=N.useState(!0),[h,p]=N.useState(!1);N.useEffect(()=>{s&&f()},[s,n]);const f=async()=>{try{const{data:S,error:A}=await q.from("events").select("*").eq("id",s).single();if(A)throw A;a(S);const{count:T}=await q.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(T||0),n){const{data:D}=await q.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",n.id).maybeSingle();l(D)}}catch(S){console.error("Error loading event:",S),ae.error("Failed to load event"),t("/events")}finally{u(!1)}},g=async()=>{if(!(!n||!r)){p(!0);try{const{error:S}=await q.auth.refreshSession();if(S){console.error("Session refresh failed:",S),ae.error("Your session has expired. Please log in again.");return}if(i){const{error:A}=await q.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(A)throw A;ae.success("Successfully cancelled registration"),l(null),c(T=>T-1)}else{const{data:A,error:T}=await q.functions.invoke("zoom-register",{body:{event_id:r.id}});if(T)throw T;ae.success("Successfully registered for event!"),l({id:A.registration_id,zoom_join_url:A.zoom_join_url}),c(D=>D+1)}}catch(S){console.error("Registration error:",S),ae.error(i?"Failed to cancel registration":"Failed to register for event")}finally{p(!1)}}},b=S=>{var A,T,D;if(S.includes("iframe.mediadelivery.net")||S.includes("video.bunnycdn.com")){const L=S.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(L)return`https://iframe.mediadelivery.net/embed/${L[1]}/${L[2]}?autoplay=false&preload=true`}if(S.includes("youtube.com")||S.includes("youtu.be")){const L=S.includes("youtu.be")?(A=S.split("youtu.be/")[1])==null?void 0:A.split("?")[0]:(T=S.split("v=")[1])==null?void 0:T.split("&")[0];if(L)return`https://www.youtube.com/embed/${L}`}if(S.includes("vimeo.com")){const L=(D=S.split("vimeo.com/")[1])==null?void 0:D.split("?")[0];if(L)return`https://player.vimeo.com/video/${L}`}return S};if(d)return e.jsx(Cs,{title:"Event",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading event..."})]})})});if(!r)return e.jsx(Cs,{title:"Event Not Found",children:e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),e.jsx(B,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const v=jw(new Date(r.event_date)),j=r.capacity&&o>=r.capacity,_=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(Cs,{title:r.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs(B,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(Wr,{className:"h-4 w-4"}),"Back to Events"]}),r.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:r.image_url,alt:r.title,className:"w-full h-full object-cover"}),v&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(ze,{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(tR,{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(Pu,{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:b(r.video_url),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Event Preview Video"})})]})]}),e.jsx("div",{className:"space-y-4",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(yr,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(r.event_date))}),e.jsx("p",{className:"text-sm text-muted-foreground",children:vB(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(_n,{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(zi,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"text-sm font-medium text-green-700",children:"You're registered!"})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[!v&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"w-full gap-2",onClick:()=>window.open(_,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:g,disabled:h,children:[h?e.jsx(ss,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(B,{className:"w-full gap-2",onClick:g,disabled:h||(j??!1),children:h?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):j?"Event Full":"Register Now"})}),v&&i&&e.jsxs(B,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const Wms=[{id:"quickvid",name:"QuickVid",description:"Record, manage, and share personalized video messages",icon:e.jsx(vr,{className:"h-6 w-6"}),path:"/mission-control/video/record",category:"Marketing",color:"bg-rose-500/15 text-rose-600"},{id:"smart-card",name:"Smart Card",description:"Your digital business card — share your info with a single link",icon:e.jsx(ff,{className:"h-6 w-6"}),path:"/mission-control/my-card",category:"Marketing",color:"bg-sky-500/15 text-sky-600"},{id:"smart-presentations",name:"Smart Presentations",description:"Create beautiful listing and buyer presentations",icon:e.jsx(oy,{className:"h-6 w-6"}),path:"/mission-control/presentations",category:"Marketing",color:"bg-amber-500/15 text-amber-600"},{id:"landing-pages",name:"Landing Pages",description:"Build custom landing pages to capture leads",icon:e.jsx(Nr,{className:"h-6 w-6"}),path:"/mission-control/landing-pages",category:"Marketing",color:"bg-emerald-500/15 text-emerald-600"},{id:"guest-book",name:"Guest Book",description:"Digital open house sign-in to capture visitor info",icon:e.jsx($u,{className:"h-6 w-6"}),path:"/mission-control/guest-book",category:"Open House",color:"bg-orange-500/15 text-orange-600"},{id:"card-studio",name:"Card Studio",description:"Send beautiful animated digital cards for birthdays, anniversaries & milestones",icon:e.jsx(un,{className:"h-6 w-6"}),path:"/mission-control/card-studio",category:"Marketing",color:"bg-pink-500/15 text-pink-600"},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts via direct mail",icon:e.jsx(Hs,{className:"h-6 w-6"}),path:"/mission-control/direct-mail",category:"Marketing",adminOnly:!0,beta:!0,color:"bg-indigo-500/15 text-indigo-600"},{id:"reelflow",name:"ReelFlow",description:"Turn property photos into cinematic video clips and reels — powered by AI",icon:e.jsx(Ph,{className:"h-6 w-6"}),path:"/admin/beta/homereel",category:"Marketing",beta:!0,isNew:!0,color:"bg-violet-500/15 text-violet-600"},{id:"mass-emails",name:"Mass Emails",description:"Create and send bulk email campaigns to your contacts",icon:e.jsx(cr,{className:"h-6 w-6"}),path:"/admin/email-campaigns",category:"Marketing",beta:!0,color:"bg-teal-500/15 text-teal-600"},{id:"listing-studio",name:"Listing Studio",description:"Generate MLS descriptions, luxury copy, open house blurbs and more — powered by AI",icon:e.jsx(nb,{className:"h-6 w-6"}),path:"/mission-control/listing-studio",category:"Marketing",isNew:!0,color:"bg-fuchsia-500/15 text-fuchsia-600"},{id:"website-apps",name:"Website Apps",description:"Drop-in conversion widgets for your website — Video Greeter & more",icon:e.jsx(fL,{className:"h-6 w-6"}),path:"/website-apps",category:"Website",isNew:!0,color:"bg-cyan-500/15 text-cyan-600"},{id:"newsletter-pro",name:"Newsletter Pro",description:"Design and send beautiful branded newsletters to your database",icon:e.jsx(iy,{className:"h-6 w-6"}),path:"/newsletters",category:"Marketing",color:"bg-yellow-500/15 text-yellow-600"},{id:"cma",name:"CMA Reports",description:"Build interactive CMAs with live comps, share with clients, and auto-create deals",icon:e.jsx(yo,{className:"h-6 w-6"}),path:"/mission-control/cma",category:"Marketing",isNew:!0,requiresLeadSiteMLS:!0,color:"bg-blue-500/15 text-blue-600"}],Kms=()=>{const{user:s,isAdmin:t}=gs(),n=In(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,p]=N.useState(new Set),[f,g]=N.useState(new Set),[b,v]=N.useState(!1);N.useEffect(()=>{j()},[s]);const j=async()=>{try{const{data:V}=await q.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),W=(V==null?void 0:V.map(_e=>_e.tag))||[],{data:K,error:Y}=await q.from("app_tiles").select("*").order("name");if(Y)throw Y;const[{data:ee},{data:ne},{data:oe}]=await Promise.all([q.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),q.from("user_tool_favorites").select("tool_id").eq("user_id",s==null?void 0:s.id),q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s==null?void 0:s.id)]),pe=(oe||[]).some(_e=>_e.is_active&&_e.mls_provider_id&&!_e.no_mls_mode);v(pe);const ce=new Set((ee==null?void 0:ee.map(_e=>_e.app_id))||[]);p(ce);const de=new Set((ne||[]).map(_e=>_e.tool_id));g(de);const ye=((K==null?void 0:K.filter(_e=>_e.app_id==="newsletter_studio"?!1:!_e.required_tags||_e.required_tags.length===0?!0:_e.required_tags.some(Me=>W.includes(Me))))||[]).sort((_e,Me)=>_e.name==="LevelUp Members Portal"?-1:Me.name==="LevelUp Members Portal"?1:0);a(ye)}catch(V){console.error("Error loading apps:",V),ae.error("Failed to load apps")}finally{l(!1)}},_=async V=>{var K;try{const Y=new URL(V.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(Y.hostname)){await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:V.app_id,app_name:V.name,user_agent:navigator.userAgent}),n(Y.pathname+Y.search+Y.hash);return}}catch{}const W=window.open("about:blank","_blank");try{const{data:Y,error:ee}=await q.auth.getSession();if(ee||!Y.session){W==null||W.close(),ae.error("Session expired. Please refresh the page and try again.");return}const ne=Y.session.access_token;await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:V.app_id,app_name:V.name,user_agent:navigator.userAgent});const{data:oe,error:pe}=await q.functions.invoke("sso-launch",{body:{app_id:V.app_id},headers:{Authorization:`Bearer ${ne}`}});if(pe)throw pe;oe!=null&&oe.redirect_url?W&&!W.closed?(W.location.href=oe.redirect_url,(K=W.focus)==null||K.call(W)):window.location.assign(oe.redirect_url):(W==null||W.close(),ae.error("Launch link unavailable"))}catch(Y){W==null||W.close(),console.error("Error launching app:",Y),ae.error("Failed to launch app. Please try again.")}},S=async(V,W)=>{V.stopPropagation();const K=h.has(W);try{if(K){const{error:Y}=await q.from("user_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("app_id",W);if(Y)throw Y;p(ee=>{const ne=new Set(ee);return ne.delete(W),ne}),ae.success("Removed from favorites")}else{const{error:Y}=await q.from("user_favorites").insert({user_id:s==null?void 0:s.id,app_id:W});if(Y)throw Y;p(ee=>new Set(ee).add(W)),ae.success("Added to favorites")}}catch(Y){console.error("Error toggling favorite:",Y),ae.error("Failed to update favorites")}},A=async(V,W)=>{V.stopPropagation();const K=f.has(W);try{if(K){const{error:Y}=await q.from("user_tool_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("tool_id",W);if(Y)throw Y;g(ee=>{const ne=new Set(ee);return ne.delete(W),ne}),ae.success("Removed from favorites")}else{const{error:Y}=await q.from("user_tool_favorites").insert({user_id:s==null?void 0:s.id,tool_id:W});if(Y)throw Y;g(ee=>new Set(ee).add(W)),ae.success("Added to favorites")}}catch(Y){console.error("Error toggling tool favorite:",Y),ae.error("Failed to update favorites")}},T=r.filter(V=>{var K;const W=V.name.toLowerCase().includes(o.toLowerCase())||((K=V.description)==null?void 0:K.toLowerCase().includes(o.toLowerCase()));return d==="favorites"?W&&h.has(V.id):W}),D=Wms.filter(V=>{if(V.adminOnly&&!t||V.requiresLeadSiteMLS&&!b&&!t)return!1;const W=V.name.toLowerCase().includes(o.toLowerCase())||V.description.toLowerCase().includes(o.toLowerCase());return d==="favorites"?W&&f.has(V.id):W}),L=D.reduce((V,W)=>(V[W.category]||(V[W.category]=[]),V[W.category].push(W),V),{}),M=[{id:"all",label:"All"},{id:"tools",label:"Built-in Tools"},{id:"apps",label:"Connected Apps"},{id:"favorites",label:"Favorites"}];if(i)return e.jsx(Cs,{title:"Apps & Tools",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading apps & tools..."})]})})});const F=d==="all"||d==="tools"||d==="favorites",z=d==="all"||d==="apps"||d==="favorites";return e.jsxs(Cs,{title:"Apps & Tools",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Apps & Tools"}),e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search apps & tools...",className:"pl-10 bg-muted/50 border-0 focus-visible:ring-1",value:o,onChange:V=>c(V.target.value)})]})]}),e.jsx("div",{className:"flex gap-6 border-b border-border mb-8",children:M.map(V=>e.jsxs("button",{onClick:()=>u(V.id),className:Et("pb-3 text-sm font-medium transition-colors relative",d===V.id?"text-primary":"text-muted-foreground hover:text-foreground"),children:[V.label,d===V.id&&e.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary"})]},V.id))}),F&&Object.keys(L).length>0&&e.jsxs("div",{className:"mb-10",children:[d==="all"&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(wb,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Built-in Tools"})]}),Object.entries(L).map(([V,W])=>e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground bg-muted px-2.5 py-1 rounded-full",children:V})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:W.map(K=>{const Y=f.has(K.id);return e.jsxs("div",{onClick:()=>n(K.path),className:Et("group flex items-start gap-4 p-5 bg-card rounded-xl border transition-all duration-200 hover:shadow-lg cursor-pointer relative overflow-hidden",K.isNew?"border-primary/40 ring-1 ring-primary/20 hover:border-primary/60":"border-border hover:border-primary/30"),children:[K.isNew&&e.jsx("div",{className:"absolute top-0 right-0 bg-gradient-to-r from-violet-500 to-indigo-500 text-white text-[10px] font-bold uppercase px-3 py-0.5 rounded-bl-lg tracking-wider shadow-sm",children:"✨ New"}),e.jsx("div",{className:Et("flex-shrink-0 w-14 h-14 rounded-xl flex items-center justify-center transition-transform group-hover:scale-105",K.color||"bg-primary/10 text-primary"),children:K.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate flex items-center gap-2",children:[K.name,K.beta&&e.jsx("span",{className:"text-[10px] font-semibold bg-amber-100 text-amber-700 px-1.5 py-0.5 rounded-full border border-amber-200",children:"Beta"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:K.description})]}),e.jsx("button",{className:Et("flex-shrink-0 p-1 transition-colors",Y?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:ee=>A(ee,K.id),children:e.jsx(Rv,{className:Et("h-5 w-5",Y&&"fill-current")})})]},K.id)})})]},V))]}),z&&e.jsxs("div",{children:[d==="all"&&T.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(tr,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Connected Apps"})]}),T.length===0&&d!=="all"&&!(d==="favorites"&&D.length>0)?e.jsx("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:d==="favorites"?e.jsxs(e.Fragment,{children:[e.jsx(Rv,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No favorites yet"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Click the bookmark icon on any app or tool to add it to your favorites"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Rc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No apps available"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:t?"Get started by adding apps in the admin panel":"Contact your administrator to get access to apps"}),t&&e.jsx(B,{className:"mt-4",onClick:()=>n("/admin/apps"),children:"Add Apps"})]})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:T.map(V=>{const W=h.has(V.id),K=V.name.toLowerCase().includes("agent review")||V.app_id==="agent_review";return e.jsxs("div",{className:"group flex flex-col p-5 bg-card rounded-xl border border-border transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"flex items-start gap-4 cursor-pointer",onClick:()=>_(V),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:V.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:V.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:V.description})]}),e.jsx("button",{className:Et("flex-shrink-0 p-1 transition-colors",W?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:Y=>S(Y,V.id),children:e.jsx(Rv,{className:Et("h-5 w-5",W&&"fill-current")})})]}),K&&e.jsx("a",{href:"https://forms.gle/vXnrzgSnPbw7CKPV6",target:"_blank",rel:"noopener noreferrer",onClick:Y=>Y.stopPropagation(),className:"mt-3 text-sm text-primary hover:underline flex items-center gap-1",children:"Create your account with this link →"})]},V.id)})})]}),F&&z&&T.length===0&&D.length===0&&o&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:[e.jsx(_r,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No results found"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Try a different search term"})]})]})},Yms=()=>{var S;const s=In(),{isAdmin:t}=gs(),[n,r]=N.useState(""),[a,i]=N.useState("all"),[l,o]=N.useState("all"),[c,d]=N.useState("grid"),{data:u=[]}=lt({queryKey:["template-categories"],queryFn:async()=>{const{data:A,error:T}=await q.from("template_categories").select("*").order("name");if(T)throw T;return A}}),{data:h=[]}=lt({queryKey:["template-types"],queryFn:async()=>{const{data:A,error:T}=await q.from("template_types").select("*").order("name");if(T)throw T;return A}}),{data:p=[],isLoading:f}=lt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:A,error:T}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(T)throw T;const{data:D,error:L}=await q.from("template_links").select("*").order("sort_order");if(L)throw L;const M=async ee=>{let oe=0;const pe=[];for(;;){const{data:ce,error:de}=await ee().range(oe,oe+1e3-1);if(de)throw de;if(!ce||ce.length===0||(pe.push(...ce),ce.length<1e3))break;oe+=1e3}return pe},F=await M(()=>q.from("template_likes").select("template_id")),z=await M(()=>q.from("template_comments").select("template_id")),V=new Map;F.forEach(ee=>{V.set(ee.template_id,(V.get(ee.template_id)||0)+1)});const W=new Map;z.forEach(ee=>{W.set(ee.template_id,(W.get(ee.template_id)||0)+1)});const K=new Map;return t&&(await M(()=>q.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(ne=>{K.set(ne.resource_id,(K.get(ne.resource_id)||0)+1)}),(A||[]).map(ee=>({...ee,links:(D||[]).filter(ne=>ne.template_id===ee.id)||[],likesCount:V.get(ee.id)||0,commentsCount:W.get(ee.id)||0,viewsCount:K.get(ee.id)||0}))}}),g=p.filter(A=>{var M;const T=A.name.toLowerCase().includes(n.toLowerCase())||((M=A.description)==null?void 0:M.toLowerCase().includes(n.toLowerCase())),D=a==="all"||A.category_id===a,L=l==="all"||A.type_id===l;return T&&D&&L}),b=()=>{r(""),i("all"),o("all")},v=n||a!=="all"||l!=="all",j=(S=[...p].sort((A,T)=>new Date(T.publish_date||T.created_at).getTime()-new Date(A.publish_date||A.created_at).getTime())[0])==null?void 0:S.id,_=A=>{s(`/templates/${A}`)};return e.jsx(Cs,{title:"Canva Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Canva Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse and use our collection of professionally designed templates"})]}),!f&&p.filter(A=>A.is_featured).length>0&&e.jsxs("div",{className:"rounded-xl p-5 space-y-3",style:{backgroundColor:"#9aa8b2"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-5 w-5 fill-foreground text-foreground"}),e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Featured Templates"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:p.filter(A=>A.is_featured).slice(0,4).map(A=>e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>_(A.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[A.id===j&&e.jsx(ze,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})]}),e.jsxs(Ae,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:tB(A.description)})]})]},A.id))})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search templates...",value:n,onChange:A=>r(A.target.value),className:"pl-9"})]}),e.jsxs(us,{value:a,onValueChange:i,children:[e.jsx(cs,{className:"w-full sm:w-48",children:e.jsx(hs,{placeholder:"All Categories"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Categories"}),u.map(A=>e.jsx(Ze,{value:A.id,children:A.name},A.id))]})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(cs,{className:"w-full sm:w-48",children:e.jsx(hs,{placeholder:"All Types"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),h.map(A=>e.jsx(Ze,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[v&&e.jsx(B,{variant:"outline",size:"sm",onClick:b,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(vf,{className:"h-4 w-4"})}),e.jsx(B,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(Ep,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[g.length," template",g.length!==1?"s":""," found"]}),f&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((A,T)=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ws,{className:"h-5 w-16"}),e.jsx(Ws,{className:"h-5 w-20"})]})]})},T))}),!f&&g.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:v?"No templates match your filters":"No templates available yet"}),v&&e.jsx(B,{variant:"outline",onClick:b,children:"Clear Filters"})]}),!f&&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(A=>e.jsxs(fe,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>_(A.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[A.id===j&&e.jsx(ze,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),A.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(ze,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(tl,{className:"h-3 w-3"}),A.links.length]})})]}),e.jsxs(Ae,{className:`p-4 flex flex-col ${c==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:A.name}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:tB(A.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[A.category&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:A.category.name}),A.type&&e.jsx(ze,{variant:"outline",className:"text-xs",children:A.type.name})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hm,{className:"h-3.5 w-3.5"}),A.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),A.commentsCount]}),t&&e.jsxs("span",{className:"flex items-center gap-1",title:"Total views (admin only)",children:[e.jsx(Ir,{className:"h-3.5 w-3.5"}),A.viewsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:T=>{T.stopPropagation(),_(A.id)},children:[e.jsx(tr,{className:"h-4 w-4"}),"View Template"]})]})]},A.id))})]})})};var Zms="Separator",FVe="horizontal",Qms=["horizontal","vertical"],Qxt=N.forwardRef((s,t)=>{const{decorative:n,orientation:r=FVe,...a}=s,i=Xms(r)?r:FVe,o=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(sa.div,{"data-orientation":i,...o,...a,ref:t})});Qxt.displayName=Zms;function Xms(s){return Qms.includes(s)}var Xxt=Qxt;const cl=N.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(Xxt,{ref:a,decorative:n,orientation:t,className:Et("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));cl.displayName=Xxt.displayName;const Jms=()=>{const{templateId:s}=_i(),t=In(),{user:n,isAdmin:r}=gs(),{toast:a}=Ua(),i=Gt(),{trackEngagement:l}=QD(),[o,c]=N.useState(""),{data:d,isLoading:u}=lt({queryKey:["template-detail",s],queryFn:async()=>{const{data:A,error:T}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(T)throw T;const{data:D}=await q.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:L}=await q.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...A,links:D||[],guides:L||[]}},enabled:!!s}),{data:h=[]}=lt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:A,error:T}=await q.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(T)throw T;return(A||[]).map(D=>D.resource_kits).filter(Boolean)},enabled:!!s});N.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:p=[]}=lt({queryKey:["template-likes",s],queryFn:async()=>{const{data:A,error:T}=await q.from("template_likes").select("*").eq("template_id",s);if(T)throw T;return A},enabled:!!s}),{data:f=[]}=lt({queryKey:["template-comments",s],queryFn:async()=>{const{data:A,error:T}=await q.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(T)throw T;const D=[...new Set(A.map(F=>F.user_id))],{data:L}=await q.from("profiles").select("id, name").in("id",D),M=new Map((L==null?void 0:L.map(F=>[F.id,F.name]))||[]);return A.map(F=>({...F,user_name:M.get(F.user_id)||"Unknown User"}))},enabled:!!s}),g=gt({mutationFn:async A=>{const{error:T}=await q.from("template_comments").insert({template_id:s,user_id:n.id,content:A});if(T)throw T},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:A=>{a({title:"Error adding comment",description:A.message,variant:"destructive"})}}),b=gt({mutationFn:async A=>{const{error:T}=await q.from("template_comments").delete().eq("id",A);if(T)throw T},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),v=gt({mutationFn:async()=>{const A=p.find(T=>T.user_id===(n==null?void 0:n.id));if(A){const{error:T}=await q.from("template_likes").delete().eq("id",A.id);if(T)throw T}else{const{error:T}=await q.from("template_likes").insert({template_id:s,user_id:n.id});if(T)throw T}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),j=p.some(A=>A.user_id===(n==null?void 0:n.id)),_=A=>A.split(" ").map(T=>T[0]).join("").toUpperCase().slice(0,2),S=A=>{A.preventDefault(),!(!o.trim()||!n)&&g.mutate(o.trim())};return u?e.jsx(Cs,{title:"Templates",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):d?e.jsx(Cs,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Ln,{to:"/templates",children:[e.jsx(Wr,{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(ze,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(ze,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx(B,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Ln,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(ja,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(tR,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(B,{variant:j?"default":"outline",className:"gap-2 rounded-full",onClick:()=>v.mutate(),disabled:!n||v.isPending,children:[e.jsx(Hm,{className:`h-4 w-4 ${j?"fill-current":""}`}),p.length," ",p.length===1?"Like":"Likes"]})]})]}),d.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&>p]:mb-4 [&>p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:d.description}})]}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(tl,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(A=>e.jsxs(B,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_canva"),window.open(A.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:A.title}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),d.video_url&&e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsx("div",{className:"aspect-video w-full rounded-lg overflow-hidden",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})}),d.guides&&d.guides.length>0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(A=>e.jsxs(B,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(A.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:A.name}),A.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(A.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),h.length>0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Oc,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(A=>e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${A.id}`),children:[A.featured_image_url?e.jsx("img",{src:A.featured_image_url,alt:"",className:"w-10 h-10 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Oc,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:A.name})]},A.id))})]})}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ql,{className:"h-5 w-5"}),"Comments (",f.length,")"]}),n?e.jsxs("form",{onSubmit:S,className:"flex gap-2",children:[e.jsx(Ts,{placeholder:"Add a comment...",value:o,onChange:A=>c(A.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||g.isPending,children:e.jsx(cr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:f.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):f.map(A=>e.jsx(fe,{children:e.jsx(Ae,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(aa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(ia,{className:"text-sm",children:_(A.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:A.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Go(new Date(A.created_at),{addSuffix:!0})}),A.user_id===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>b.mutate(A.id),children:e.jsx(bn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:A.content})]})]})})},A.id))})]})]})}):e.jsx(Cs,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(tl,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Template not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This template may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(Ln,{to:"/templates",children:"Back to Templates"})})]})})},eps=["reserved","scheduled_for_charge","paid","payment_failed","completed"],PB=s=>!!s&&(s.access_override||eps.includes(s.status)),Iu=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),LB=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`},l3e=(s,t="usd",n)=>`One-time payment: ${Iu(s,t)} for the ${LB(n)}`,Jxt=[{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}],Nxe=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:[]}},tps=(s,t)=>!s.hidden.includes(t),zVe=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),Vl=(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,uve=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&&rlt({queryKey:["programs"],queryFn:async()=>{const{data:s,error:t}=await q.from("programs").select("*").eq("status","published").order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0});if(t)throw t;return s||[]}}),gIe=s=>lt({queryKey:["program",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("programs").select("*").eq("slug",s).maybeSingle();if(n)throw n;return t||null}}),egt=s=>lt({queryKey:["program-seats",s],enabled:!!s,refetchInterval:6e4,queryFn:async()=>{const{data:t,error:n}=await q.rpc("program_seats_remaining",{_program_id:s});if(n)throw n;return t??0}}),tgt=()=>{const{user:s}=gs();return lt({queryKey:["program-enrollments",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await q.from("program_enrollments").select("*").eq("user_id",s.id);if(n)throw n;return t||[]}})},yIe=s=>{const{data:t=[],...n}=tgt();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},nps=()=>{const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("program_intake_responses").upsert({...n,user_id:s.id},{onConflict:"program_id,user_id"}).select("*").single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["program-intake"]}),onError:n=>ae.error(n.message||"Could not save your answers")})},rps=s=>{const{user:t}=gs();return lt({queryKey:["program-intake",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await q.from("program_intake_responses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n}})},aps=()=>{const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("program_claim_seat",{_program_id:t});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["program-enrollments"]}),s.invalidateQueries({queryKey:["program-seats"]})}})},ips=s=>{const{user:t}=gs();return lt({queryKey:["program-workspace",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const[n,r,a,i,l,o,c,d,u,h]=await Promise.all([q.from("program_weeks").select("*").eq("program_id",s).order("week_number"),q.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),q.from("program_resources").select("*").eq("program_id",s).order("sort_order"),q.from("program_events").select("*").eq("program_id",s).order("starts_at"),q.from("program_announcements").select("*").eq("program_id",s).order("published_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s).eq("user_id",t.id),q.from("program_weekly_progress").select("*").eq("program_id",s).eq("user_id",t.id).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s).eq("user_id",t.id).order("posted_at",{ascending:!1}),q.from("program_badge_awards").select("*").eq("program_id",s).eq("user_id",t.id),q.from("program_profile_analyses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle()]);return{weeks:n.data||[],lessons:r.data||[],resources:a.data||[],events:i.data||[],announcements:l.data||[],completions:o.data||[],progress:c.data||[],videoLogs:d.data||[],badges:u.data||[],analysis:h.data||null}}})},ops=s=>{const{user:t}=gs(),n=Gt();return gt({mutationFn:async({lessonId:r,done:a})=>{if(a){const{error:i}=await q.from("program_lesson_completions").insert({lesson_id:r,program_id:s,user_id:t.id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await q.from("program_lesson_completions").delete().eq("lesson_id",r).eq("user_id",t.id);if(i)throw i}},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>ae.error(r.message||"Could not update progress")})},lps=s=>{const{user:t}=gs(),n=Gt();return gt({mutationFn:async r=>{const{error:a}=await q.from("program_video_logs").insert({...r,program_id:s,user_id:t.id});if(a)throw a},onSuccess:()=>{ae.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ae.error(r.message||"Could not log the video")})},cps=s=>{const{user:t}=gs(),n=Gt();return gt({mutationFn:async r=>{const{error:a}=await q.from("program_weekly_progress").upsert({...r,program_id:s,user_id:t.id},{onConflict:"program_id,user_id,week_number"});if(a)throw a},onSuccess:()=>{ae.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ae.error(r.message||"Could not save your check-in")})},dps=s=>{const{user:t}=gs(),n=Gt();return gt({mutationFn:async({eventId:r,optIn:a})=>{const{error:i}=await q.from("program_event_attendance").upsert({event_id:r,program_id:s,user_id:t.id,reminder_opt_in:a},{onConflict:"event_id,user_id"});if(i)throw i},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>ae.error(r.message||"Could not update your RSVP")})},ups=s=>lt({queryKey:["program-discount-codes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_discount_codes").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}}),hps=s=>{const t=Gt();return gt({mutationFn:async n=>{const r={program_id:s,code:(n.code||"").trim().toUpperCase(),label:n.label||null,percent_off:n.percent_off??null,amount_off_cents:n.amount_off_cents??null,max_redemptions:n.max_redemptions??null,starts_at:n.starts_at||null,expires_at:n.expires_at||null,is_active:n.is_active??!0};if(n.id){const{error:a}=await q.from("program_discount_codes").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_discount_codes").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return ae.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},mps=()=>{const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>ae.error(t.message||"Could not delete the code")})},pps=()=>gt({mutationFn:async({enrollmentId:s,code:t})=>{const{data:n,error:r}=await q.rpc("program_apply_discount",{_enrollment_id:s,_code:t});if(r)throw r;const a=n;if(!(a!=null&&a.ok))throw new Error((a==null?void 0:a.error)||"That code could not be applied");return a}}),fps=()=>gt({mutationFn:async s=>{const{error:t}=await q.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),xps=s=>lt({queryKey:["admin-program-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_events").select("*").eq("program_id",s).order("starts_at",{ascending:!0});if(n)throw n;return t||[]}}),gps=s=>{const t=Gt();return gt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,event_kind:n.event_kind||"mastermind",starts_at:n.starts_at,duration_minutes:n.duration_minutes??60,speaker:n.speaker||null,meeting_link:n.meeting_link||null,replay_url:n.replay_url||null,is_published:n.is_published??!0};if(n.id){const{error:a}=await q.from("program_events").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_events").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the session")})},yps=()=>{const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the session")})},vps=s=>lt({queryKey:["admin-program-lessons",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([q.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),q.from("program_weeks").select("id, week_number, title").eq("program_id",s).order("week_number")]);if(t.error)throw t.error;return{lessons:t.data||[],weeks:n.data||[]}}}),bps=s=>{const t=Gt();return gt({mutationFn:async n=>{const r={program_id:s,week_id:n.week_id||null,title:(n.title||"").trim(),summary:n.summary||null,duration_minutes:n.duration_minutes??null,video_url:n.video_url||null,worksheet_url:n.worksheet_url||null,action_assignment:n.action_assignment||null,status:n.status||"published",publish_at:n.publish_at||null,sort_order:n.sort_order??0};if(n.id){const{error:a}=await q.from("program_lessons").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_lessons").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the video")})},_ps=()=>{const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the video")})},sgt=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},wps=[{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"}],vIe="event-images",ngt=s=>{if(s.file_path){const{data:t}=q.storage.from(vIe).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},jps=s=>lt({queryKey:["admin-program-resources",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_resources").select("*").eq("program_id",s).order("sort_order");if(n)throw n;return t||[]}}),Nps=s=>{const t=Gt();return gt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,category:(n.category||"Resources").trim()||"Resources",resource_kind:n.resource_kind||"pdf",url:n.url||null,file_path:n.file_path||null,status:n.status||"published",sort_order:n.sort_order??0};if(n.id){const{error:a}=await q.from("program_resources").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_resources").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the resource")})},kps=()=>{const s=Gt();return gt({mutationFn:async t=>{t.file_path&&await q.storage.from(vIe).remove([t.file_path]);const{error:n}=await q.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ae.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the resource")})},Sps=s=>{const{user:t}=gs();return lt({queryKey:["program-interest",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await q.from("program_interest").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})},Cps=s=>{const t=Gt(),{user:n}=gs();return gt({mutationFn:async r=>{if(!(n!=null&&n.id)||!s)throw new Error("You need to be signed in.");if(r){const{error:a}=await q.from("program_interest").upsert({program_id:s,user_id:n.id,source:"program_detail"},{onConflict:"program_id,user_id"});if(a)throw a}else{const{error:a}=await q.from("program_interest").delete().eq("program_id",s).eq("user_id",n.id);if(a)throw a}return r},onSuccess:r=>{ae.success(r?"You're on the list — we'll email you when enrollment opens.":"Removed from the notify list"),t.invalidateQueries({queryKey:["program-interest"]}),t.invalidateQueries({queryKey:["admin-program-interest"]})},onError:r=>ae.error(r.message||"Could not update your notify preference")})},Tps=s=>lt({queryKey:["admin-program-interest",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_interest").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;const r=t||[];if(!r.length)return[];const a=Array.from(new Set(r.map(o=>o.user_id))),{data:i}=await q.from("profiles").select("id, name, email, phone, brokerage_name").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>{const c=l.get(o.user_id)||{};return{...o,full_name:c.name??null,email:c.email??null,phone:c.phone??null,brokerage:c.brokerage_name??null}})}}),BVe=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=uve(s);return e.jsxs(fe,{className:"group overflow-hidden border-border/60 transition-all hover:border-primary/40 hover:shadow-lg",children:[e.jsxs("div",{className:"relative aspect-[16/9] overflow-hidden bg-muted",children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:`${s.name} program cover`,loading:"lazy",className:"h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/15 via-background to-accent/20",children:e.jsx(un,{className:"h-10 w-10 text-primary/60"})}),e.jsxs("div",{className:"absolute left-3 top-3 flex gap-2",children:[s.is_featured&&e.jsx(ze,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs(ze,{variant:"secondary",className:"shadow-sm",children:[e.jsx(xr,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(Ae,{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(gr,{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(Tl,{className:"h-3.5 w-3.5"}),"Starts ",Vl(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(_n,{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":Iu(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 ",LB(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${Vl(s.charge_at)}`:""]}):null]}),e.jsx(B,{asChild:!0,size:"sm",children:e.jsxs(Ln,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(za,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},Eps=()=>{const{data:s=[],isLoading:t}=sps(),{data:n=[]}=tgt(),r=new Set(n.filter(l=>PB(l)).map(l=>l.program_id)),a=s.filter(l=>r.has(l.id)),i=s.filter(l=>!r.has(l.id));return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-10 p-4 md:p-8",children:[e.jsxs("header",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-primary",children:"LevelUp Programs"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight md:text-4xl",children:"Go deeper than the membership"}),e.jsx("p",{className:"max-w-2xl text-muted-foreground",children:"Time-bound coaching programs, masterminds and challenges built to move one specific part of your business forward — with a real cohort, a real roadmap and real accountability."})]}),t?e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(l=>e.jsx(Ws,{className:"h-80 rounded-xl"},l))}):e.jsxs(e.Fragment,{children:[a.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Your programs"}),e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:a.map(l=>e.jsx(BVe,{program:l,enrolled:!0},l.id))})]}),e.jsxs("section",{className:"space-y-4",children:[a.length>0&&e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Open for enrollment"}),i.length===0&&a.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No programs are open right now"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"New cohorts are announced inside the Hub. Check back soon — seats are limited when they open."})]})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:i.map(l=>e.jsx(BVe,{program:l,enrolled:!1},l.id))})]})]})]})})},Aps=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},Mps=({url:s,headline:t,posterUrl:n})=>{const[r,a]=N.useState(!1),i=(s||"").trim();if(!i)return null;const l=Aps(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(Pu,{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 Rb="Accordion",Ips=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[bIe,Pps,Lps]=MD(Rb),[hve,ign]=gu(Rb,[Lps,tmt]),_Ie=tmt(),rgt=Nt.forwardRef((s,t)=>{const{type:n,...r}=s,a=r,i=r;return e.jsx(bIe.Provider,{scope:s.__scopeAccordion,children:n==="multiple"?e.jsx(Fps,{...i,ref:t}):e.jsx(Ops,{...a,ref:t})})});rgt.displayName=Rb;var[agt,Dps]=hve(Rb),[igt,Rps]=hve(Rb,{collapsible:!1}),Ops=Nt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},collapsible:i=!1,...l}=s,[o,c]=mm({prop:n,defaultProp:r??"",onChange:a,caller:Rb});return e.jsx(agt,{scope:s.__scopeAccordion,value:Nt.useMemo(()=>o?[o]:[],[o]),onItemOpen:c,onItemClose:Nt.useCallback(()=>i&&c(""),[i,c]),children:e.jsx(igt,{scope:s.__scopeAccordion,collapsible:i,children:e.jsx(ogt,{...l,ref:t})})})}),Fps=Nt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=mm({prop:n,defaultProp:r??[],onChange:a,caller:Rb}),c=Nt.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Nt.useCallback(u=>o((h=[])=>h.filter(p=>p!==u)),[o]);return e.jsx(agt,{scope:s.__scopeAccordion,value:l,onItemOpen:c,onItemClose:d,children:e.jsx(igt,{scope:s.__scopeAccordion,collapsible:!0,children:e.jsx(ogt,{...i,ref:t})})})}),[zps,mve]=hve(Rb),ogt=Nt.forwardRef((s,t)=>{const{__scopeAccordion:n,disabled:r,dir:a,orientation:i="vertical",...l}=s,o=Nt.useRef(null),c=Ti(o,t),d=Pps(n),h=kN(a)==="ltr",p=wr(s.onKeyDown,f=>{var M;if(!Ips.includes(f.key))return;const g=f.target,b=d().filter(F=>{var z;return!((z=F.ref.current)!=null&&z.disabled)}),v=b.findIndex(F=>F.ref.current===g),j=b.length;if(v===-1)return;f.preventDefault();let _=v;const S=0,A=j-1,T=()=>{_=v+1,_>A&&(_=S)},D=()=>{_=v-1,_{const{__scopeAccordion:n,value:r,...a}=s,i=mve(kxe,n),l=Dps(kxe,n),o=_Ie(n),c=um(),d=r&&l.value.includes(r)||!1,u=i.disabled||s.disabled;return e.jsx(Bps,{scope:n,open:d,disabled:u,triggerId:c,children:e.jsx(rmt,{"data-orientation":i.orientation,"data-state":pgt(d),...o,...a,ref:t,disabled:u,open:d,onOpenChange:h=>{h?l.onItemOpen(r):l.onItemClose(r)}})})});lgt.displayName=kxe;var cgt="AccordionHeader",dgt=Nt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=mve(Rb,n),i=wIe(cgt,n);return e.jsx(sa.h3,{"data-orientation":a.orientation,"data-state":pgt(i.open),"data-disabled":i.disabled?"":void 0,...r,ref:t})});dgt.displayName=cgt;var c3e="AccordionTrigger",ugt=Nt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=mve(Rb,n),i=wIe(c3e,n),l=Rps(c3e,n),o=_Ie(n);return e.jsx(bIe.ItemSlot,{scope:n,children:e.jsx(Aes,{"aria-disabled":i.open&&!l.collapsible||void 0,"data-orientation":a.orientation,id:i.triggerId,...o,...r,ref:t})})});ugt.displayName=c3e;var hgt="AccordionContent",mgt=Nt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=mve(Rb,n),i=wIe(hgt,n),l=_Ie(n);return e.jsx(Mes,{role:"region","aria-labelledby":i.triggerId,"data-orientation":a.orientation,...l,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...s.style}})});mgt.displayName=hgt;function pgt(s){return s?"open":"closed"}var $ps=rgt,Ups=lgt,qps=dgt,fgt=ugt,xgt=mgt;const jIe=$ps,pve=N.forwardRef(({className:s,...t},n)=>e.jsx(Ups,{ref:n,className:Et("border-b",s),...t}));pve.displayName="AccordionItem";const fve=N.forwardRef(({className:s,children:t,...n},r)=>e.jsx(qps,{className:"flex",children:e.jsxs(fgt,{ref:r,className:Et("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(io,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));fve.displayName=fgt.displayName;const xve=N.forwardRef(({className:s,children:t,...n},r)=>e.jsx(xgt,{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:Et("pb-4 pt-0",s),children:t})}));xve.displayName=xgt.displayName;const Vps=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=Sps(s),a=Cps(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(KS,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"space-y-0.5 text-sm",children:[e.jsx("p",{className:"font-semibold",children:i?"You're on the notify list":"Want a heads-up when enrollment opens?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i?`We'll email you the moment seats go live${t?` (${t})`:""}.`:`Seats are limited — we'll email you the moment enrollment opens${t?` ${t}`:""}.`})]})]}),e.jsxs(B,{variant:i?"outline":"default",size:"sm",disabled:r||a.isPending,onClick:()=>a.mutate(!i),className:"shrink-0",children:[a.isPending?e.jsx(ss,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(Lr,{className:"mr-2 h-4 w-4"}):e.jsx(KS,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},Hps=()=>{const{slug:s}=_i(),{data:t,isLoading:n}=gIe(s),{data:r}=egt(t==null?void 0:t.id),{data:a}=yIe(t==null?void 0:t.id),i=PB(a),l=(t==null?void 0:t.sales_copy)||{},o=l.outcomes||[],c=l.included||[],d=l.for_who||[],u=l.not_for||[],h=l.faqs||[],p=l.phases||[];if(n)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-8",children:[e.jsx(Ws,{className:"h-64 w-full rounded-xl"}),e.jsx(Ws,{className:"h-40 w-full rounded-xl"})]})});if(!t)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:"This program may have been closed or unpublished."}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(Ln,{to:"/programs",children:"Back to Programs"})})]})});const f=typeof r=="number"&&r<=0&&!i,{notOpenYet:g,closed:b,opensLabel:v}=uve(t),j=!i&&(f||b||g),_=i?"Open your program":g?`Enrollment opens ${Vl(t.enrollment_open_at)}`:f?"Cohort is full":b?"Enrollment closed":t.payment_mode==="delayed"?"Reserve my seat":"Enroll now",S=i?`/programs/${t.slug}/workspace`:`/programs/${t.slug}/enroll`;return e.jsxs(Cs,{children:[e.jsxs(Yo,{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(Mps,{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(ze,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx(ze,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs(ze,{children:[e.jsx(xr,{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":Iu(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 ",LB(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:Vl(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(ff,{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:[l3e(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:Vl(t.charge_at)}),". Cancel any time before then and you won't be billed."]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No recurring billing, no monthly installments, and no automatic renewal."})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(B,{asChild:!j,size:"lg",disabled:j,children:j?e.jsx("span",{children:_}):e.jsxs(Ln,{to:S,children:[_,e.jsx(za,{className:"ml-2 h-4 w-4"})]})}),e.jsx(B,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(Ln,{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(Tl,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}),e.jsx(Vps,{programId:t.id,opensLabel:v})]})]})]}),t.description&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What this program is"}),e.jsx("div",{className:"whitespace-pre-line text-muted-foreground",children:t.description})]}),o.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What you'll walk away with"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.map((A,T)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(xr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:A})]},T))})]}),p.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-xl font-semibold",children:["How the ",t.duration_weeks," weeks flow"]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:p.map((A,T)=>e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ae,{className:"space-y-2 p-5",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:["Phase ",T+1]}),e.jsx("h3",{className:"font-semibold",children:A.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:A.detail})]})},T))})]}),c.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What's included"}),e.jsx("ul",{className:"grid gap-2 sm:grid-cols-2",children:c.map((A,T)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm",children:[e.jsx(un,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),A]},T))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ae,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This is for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:d.map((A,T)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(xr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),A]},T))})]})}),u.length>0&&e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ae,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This isn't for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:u.map((A,T)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(gr,{className:"mt-0.5 h-4 w-4 shrink-0"}),A]},T))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(jIe,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((A,T)=>e.jsxs(pve,{value:`faq-${T}`,children:[e.jsx(fve,{className:"text-left text-sm font-medium",children:A.q}),e.jsx(xve,{className:"text-sm text-muted-foreground",children:A.a})]},T))})]}),e.jsxs("section",{className:"rounded-2xl border border-border/60 bg-muted/40 p-6 text-center md:p-10",children:[e.jsx(vr,{className:"mx-auto h-8 w-8 text-primary"}),e.jsx("h2",{className:"mt-4 text-2xl font-bold",children:l.closing_headline||"Ready to commit?"}),e.jsx("p",{className:"mx-auto mt-2 max-w-xl text-muted-foreground",children:l.closing_body||`Seats are capped at ${t.capacity} so every member gets attention. Reserve yours and we'll take it from there.`}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-center justify-center gap-3",children:[e.jsx(B,{asChild:!j,size:"lg",disabled:j,children:j?e.jsx("span",{children:_}):e.jsxs(Ln,{to:S,children:[_,e.jsx(za,{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(_n,{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(Tl,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}):t.enrollment_close_at?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Tl,{className:"h-3.5 w-3.5"}),"Enrollment closes ",Vl(t.enrollment_close_at)]}):null)]})]})]})},IH=["Your business","Your content","Your goals","Reserve your seat"],Gps=()=>{const{slug:s}=_i(),t=In(),[n,r]=yl(),{user:a}=gs(),{data:i,isLoading:l}=gIe(s),{data:o}=egt(i==null?void 0:i.id),{data:c,refetch:d}=yIe(i==null?void 0:i.id),{data:u}=rps(i==null?void 0:i.id),h=nps(),p=aps(),f=pps(),g=fps(),[b,v]=N.useState(0),[j,_]=N.useState(!1),[S,A]=N.useState(!1),[T,D]=N.useState(!1),[L,M]=N.useState(!1),[F,z]=N.useState(""),[V,W]=N.useState(null),K=N.useRef({}),[Y,ee]=N.useState({}),ne=N.useRef(!1),oe=($e,Ye)=>{K.current={...K.current,[$e]:Ye},ee(K.current)};N.useEffect(()=>{ne.current||(u?(K.current={...u},ee(K.current),ne.current=!0):a&&(K.current={email:a.email,...K.current},ee(K.current)))},[u,a]),N.useEffect(()=>{const $e=c;!i||!($e!=null&&$e.discount_code)||V||W({code:$e.discount_code,discount_cents:$e.discount_cents||0,amount_cents:$e.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,V]);const pe=V?V.amount_cents:(i==null?void 0:i.price_cents)??0,ce=N.useMemo(()=>Nxe(i),[i]),de=$e=>tps(ce,$e),ie=$e=>zVe(ce,$e)?e.jsx("span",{className:"text-destructive",children:" *"}):null,ye=($e,Ye)=>{const Ke={...K.current.extra||{},[$e]:Ye};oe("extra",Ke)},_e=$e=>ce.custom.filter((Ye,Ke)=>Ke%3===$e),Me=$e=>{const Ye=_e($e);if(!Ye.length)return null;const Ke=Y.extra||{};return e.jsx("div",{className:"space-y-4",children:Ye.map(rt=>e.jsxs("div",{className:"space-y-2",children:[rt.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(hi,{id:rt.id,checked:!!Ke[rt.id],onCheckedChange:tt=>ye(rt.id,!!tt)}),e.jsxs(se,{htmlFor:rt.id,className:"text-sm font-normal leading-relaxed",children:[rt.label,rt.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(se,{htmlFor:rt.id,children:[rt.label,rt.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),rt.type==="long_text"?e.jsx(Ts,{id:rt.id,rows:3,value:Ke[rt.id]||"",onChange:tt=>ye(rt.id,tt.target.value)}):rt.type==="select"?e.jsxs(us,{value:Ke[rt.id]||"",onValueChange:tt=>ye(rt.id,tt),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(ds,{children:(rt.options||[]).map(tt=>e.jsx(Ze,{value:tt,children:tt},tt))})]}):e.jsx(ge,{id:rt.id,value:Ke[rt.id]||"",onChange:tt=>ye(rt.id,tt.target.value)})]}),rt.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:rt.help})]},rt.id))})},Te=$e=>{const Ye=K.current,Ke=Ge=>Ge==null||Ge===""||Ge===!1,rt=Jxt.find(Ge=>Ge.step===$e&&zVe(ce,Ge.key)&&Ke(Ge.key==="timezone"?Ye.timezone||(i==null?void 0:i.timezone):Ye[Ge.key]));if(rt)return rt.label;const tt=Ye.extra||{},at=_e($e).find(Ge=>Ge.required&&Ke(tt[Ge.id]));return at?at.label:null},Ce=()=>{if(b<=2){const $e=Te(b);if($e)return ae.error(`Please answer: ${$e}`)}v($e=>$e+1)},Ee=async()=>{if(!(!i||!F.trim()))try{let $e=c==null?void 0:c.id;(!$e||(c==null?void 0:c.status)==="canceled")&&($e=await p.mutateAsync(i.id));const Ye=await f.mutateAsync({enrollmentId:$e,code:F});W(Ye),z(""),await d(),ae.success(`Code applied — you save ${Iu(Ye.discount_cents,i.currency)}`)}catch($e){ae.error($e.message||"That code could not be applied")}},De=async()=>{if(!(c!=null&&c.id))return W(null);try{await g.mutateAsync(c.id),W(null),await d()}catch($e){ae.error($e.message||"Could not remove the code")}},Ie=n.get("setup"),Fe=n.get("session_id"),qe=N.useRef(!1);N.useEffect(()=>{Ie!=="success"||!Fe||!(c!=null&&c.id)||qe.current||(qe.current=!0,A(!0),(async()=>{const{data:$e,error:Ye}=await q.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Fe}});if(A(!1),Ye||$e!=null&&$e.error||($e==null?void 0:$e.success)===!1){ae.error(($e==null?void 0:$e.error)||(Ye==null?void 0:Ye.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,Fe,c==null?void 0:c.id]),N.useEffect(()=>{Ie==="cancelled"&&ae.info("Checkout cancelled — your seat is held for a short while.")},[Ie]);const ve=N.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Je=async()=>{if(i){if(!T||i.payment_mode!=="free"&&!L){ae.error("Please confirm the checkboxes to continue");return}_(!0);try{let $e=c==null?void 0:c.id;(!$e||(c==null?void 0:c.status)==="canceled")&&($e=await p.mutateAsync(i.id)),await h.mutateAsync({...K.current,id:void 0,program_id:i.id,enrollment_id:$e,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:Ye,error:Ke}=await q.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:$e}});if(Ke||Ye!=null&&Ye.error)throw new Error((Ye==null?void 0:Ye.error)||(Ke==null?void 0:Ke.message));if(Ye!=null&&Ye.free){await d(),ae.success("You're in"),t(`/programs/${i.slug}/workspace`);return}Ye!=null&&Ye.url&&(window.location.href=Ye.url)}catch($e){ae.error($e.message||"Could not start enrollment")}finally{_(!1)}}};if(l)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(Ws,{className:"h-10 w-1/2"}),e.jsx(Ws,{className:"h-64 w-full rounded-xl"})]})});if(!i)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(Ln,{to:"/programs",children:"Back to Programs"})})]})});if(PB(c)&&ve&&Ie!=="success")return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(xr,{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 ${Vl(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(Ln,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const we=typeof o=="number"&&o<=0,{notOpenYet:it,closed:Ne,opensLabel:He}=uve(i);return it||Ne?e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-xl space-y-4 p-8 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:it?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:it?`Enrollment for ${i.name} opens ${He}. Come back then to reserve your seat.`:`Enrollment for ${i.name} has closed. Watch the Hub for the next cohort.`}),e.jsx(B,{asChild:!0,children:e.jsx(Ln,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx(B,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(Ln,{to:`/programs/${i.slug}`,children:[e.jsx(Wr,{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?`${l3e(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${Vl(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:IH[b]}),e.jsxs("span",{children:["Step ",b+1," of ",IH.length]})]}),e.jsx(xi,{value:(b+1)/IH.length*100})]}),S&&e.jsx(fe,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ae,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(ss,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-5 p-6",children:[b===0&&ce.intro&&e.jsx("p",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground",children:ce.intro}),b===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[de("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"full_name",children:["Full name",ie("full_name")]}),e.jsx(ge,{id:"full_name",value:Y.full_name||"",onChange:$e=>oe("full_name",$e.target.value)})]}),de("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"phone",children:["Mobile number",ie("phone")]}),e.jsx(ge,{id:"phone",value:Y.phone||"",onChange:$e=>oe("phone",$e.target.value)})]}),de("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"instagram_handle",children:["Instagram handle",ie("instagram_handle")]}),e.jsx(ge,{id:"instagram_handle",placeholder:"@yourhandle",value:Y.instagram_handle||"",onChange:$e=>oe("instagram_handle",$e.target.value)})]}),de("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"city",children:["Primary city / market",ie("city")]}),e.jsx(ge,{id:"city",value:Y.city||"",onChange:$e=>oe("city",$e.target.value)})]})]}),de("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",ie("service_areas")]}),e.jsx(Ts,{id:"service_areas",rows:2,value:Y.service_areas||"",onChange:$e=>oe("service_areas",$e.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[de("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["Years in real estate",ie("years_experience")]}),e.jsxs(us,{value:Y.years_experience||"",onValueChange:$e=>oe("years_experience",$e),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(ds,{children:["Less than 1","1-3","4-7","8-15","15+"].map($e=>e.jsx(Ze,{value:$e,children:$e},$e))})]})]}),de("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"specialty",children:["Specialty or niche",ie("specialty")]}),e.jsx(ge,{id:"specialty",value:Y.specialty||"",onChange:$e=>oe("specialty",$e.target.value)})]})]}),Me(0)]}),b===1&&e.jsxs(e.Fragment,{children:[de("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"target_audience",children:["Who are you trying to reach?",ie("target_audience")]}),e.jsx(Ts,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:Y.target_audience||"",onChange:$e=>oe("target_audience",$e.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[de("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["How comfortable are you on camera?",ie("video_comfort")]}),e.jsxs(us,{value:Y.video_comfort||"",onValueChange:$e=>oe("video_comfort",$e),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(ds,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map($e=>e.jsx(Ze,{value:$e,children:$e},$e))})]})]}),de("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["How often do you post today?",ie("posting_frequency")]}),e.jsxs(us,{value:Y.posting_frequency||"",onValueChange:$e=>oe("posting_frequency",$e),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(ds,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map($e=>e.jsx(Ze,{value:$e,children:$e},$e))})]})]})]}),de("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"content_style",children:["What content style feels like you?",ie("content_style")]}),e.jsx(Ts,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:Y.content_style||"",onChange:$e=>oe("content_style",$e.target.value)})]}),de("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",ie("personal_interests")]}),e.jsx(Ts,{id:"personal_interests",rows:2,value:Y.personal_interests||"",onChange:$e=>oe("personal_interests",$e.target.value)})]}),Me(1)]}),b===2&&e.jsxs(e.Fragment,{children:[de("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"primary_goal",children:["Your #1 goal for this program",ie("primary_goal")]}),e.jsx(Ts,{id:"primary_goal",rows:3,value:Y.primary_goal||"",onChange:$e=>oe("primary_goal",$e.target.value)})]}),de("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",ie("topics_to_avoid")]}),e.jsx(Ts,{id:"topics_to_avoid",rows:2,value:Y.topics_to_avoid||"",onChange:$e=>oe("topics_to_avoid",$e.target.value)})]}),de("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["Your time zone",ie("timezone")]}),e.jsxs(us,{value:Y.timezone||i.timezone,onValueChange:$e=>oe("timezone",$e),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(ds,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map($e=>e.jsx(Ze,{value:$e,children:$e.replace("America/","").replace("_"," ")},$e))})]})]}),Me(2),de("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(hi,{id:"consent_public_profile",checked:!!Y.consent_public_profile,onCheckedChange:$e=>oe("consent_public_profile",!!$e)}),e.jsx(se,{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."})]})]}),b===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":V?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:Iu(V.original_cents,i.currency)}),Iu(pe,i.currency)]}):Iu(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l3e(pe,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:V?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(mh,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:V.code})," applied — you save ",Iu(V.discount_cents,i.currency)]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:De,disabled:g.isPending,children:[e.jsx(Fn,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:F,onChange:$e=>z($e.target.value.toUpperCase()),onKeyDown:$e=>{$e.key==="Enter"&&($e.preventDefault(),Ee())}}),e.jsx(B,{variant:"outline",onClick:Ee,disabled:!F.trim()||f.isPending||p.isPending,children:f.isPending||p.isPending?e.jsx(ss,{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(ff,{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:Vl(i.charge_at||i.kickoff_at)||"the program start date"}),". No recurring billing, installments, or renewal. Cancel any time before then at no cost."]})]}),typeof o=="number"&&e.jsx("p",{className:"mt-3 text-xs text-muted-foreground",children:o>0?`${o} of ${i.capacity} seats left`:"This cohort is full"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(hi,{id:"terms",checked:T,onCheckedChange:$e=>D(!!$e)}),e.jsx(se,{htmlFor:"terms",className:"text-sm font-normal leading-relaxed",children:"I agree to the program terms, including the attendance and participation expectations, and understand seats are limited."})]}),i.payment_mode!=="free"&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(hi,{id:"charge",checked:L,onCheckedChange:$e=>M(!!$e)}),e.jsx(se,{htmlFor:"charge",className:"text-sm font-normal leading-relaxed",children:i.payment_mode==="delayed"?`I authorize LevelUp to charge my saved card one time — ${Iu(pe,i.currency)} for the ${LB(i.duration_weeks)} — on ${Vl(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 — ${Iu(pe,i.currency)} for the ${LB(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(ng,{className:"h-3.5 w-3.5"}),"Card details are handled by Stripe — LevelUp never sees or stores them."]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-5",children:[e.jsxs(B,{variant:"ghost",onClick:()=>v($e=>Math.max(0,$e-1)),disabled:b===0||j,children:[e.jsx(Wr,{className:"mr-1.5 h-4 w-4"})," Back"]}),bs.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",Wps=(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:${j2e(new Date)}`,`DTSTART:${j2e(n)}`,`DTEND:${j2e(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)},Kps={pdf:Nr,document:yw,checklist:pu,template_link:s4,video:Ph,external:El},Yps=()=>{var pe;const{slug:s}=_i(),[t]=yl(),{isAdmin:n}=gs(),r=n&&t.get("preview")==="1",{data:a,isLoading:i}=gIe(s),{data:l}=yIe(a==null?void 0:a.id),{data:o,isLoading:c}=ips(a==null?void 0:a.id),d=ops(a==null?void 0:a.id),u=lps(a==null?void 0:a.id),h=cps(a==null?void 0:a.id),p=dps(a==null?void 0:a.id),[f,g]=N.useState(!1),[b,v]=N.useState({title:"",instagram_url:""}),[j,_]=N.useState({}),[S,A]=N.useState(null),T=N.useMemo(()=>{if(!(a!=null&&a.kickoff_at))return 1;const ce=Math.floor((Date.now()-new Date(a.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(ce/7)+1,1),a.duration_weeks)},[a]),D=new Set(((o==null?void 0:o.completions)||[]).map(ce=>ce.lesson_id)),L=(o==null?void 0:o.lessons)||[],M=L.length?Math.round(D.size/L.length*100):0,F=((o==null?void 0:o.videoLogs)||[]).filter(ce=>ce.week_number===T).length,z=((o==null?void 0:o.videoLogs)||[]).length,V=(a==null?void 0:a.weekly_video_goal)||3,W=N.useMemo(()=>{const ce=new Map;((o==null?void 0:o.videoLogs)||[]).forEach(ie=>ce.set(ie.week_number,(ce.get(ie.week_number)||0)+1));let de=0;for(let ie=T;ie>=1;ie--)if((ce.get(ie)||0)>=V)de++;else if(ie!==T)break;return de},[o==null?void 0:o.videoLogs,T,V]);if(i||c)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(Ws,{className:"h-28 w-full rounded-xl"}),e.jsx(Ws,{className:"h-64 w-full rounded-xl"})]})});if(!a)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(Ln,{to:"/programs",children:"Back to Programs"})})]})});if(!PB(l)&&!r)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"You're not enrolled yet"}),e.jsxs("p",{className:"text-muted-foreground",children:["Reserve your seat in ",a.name," to unlock the roadmap, lessons and mastermind sessions."]}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(Ln,{to:`/programs/${a.slug}`,children:"View the program"})})]})});const K=((o==null?void 0:o.events)||[]).filter(ce=>new Date(ce.starts_at)>=new Date),Y=((o==null?void 0:o.events)||[]).filter(ce=>new Date(ce.starts_at)ce.is_pinned),ne=((o==null?void 0:o.resources)||[]).reduce((ce,de)=>{var ie;return(ce[ie=de.category]||(ce[ie]=[])).push(de),ce},{}),oe=((o==null?void 0:o.progress)||[]).find(ce=>ce.week_number===T)||{};return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-8 p-4 md:p-8",children:[r&&!PB(l)&&e.jsx(fe,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ae,{className:"flex flex-wrap items-center justify-between gap-3 p-4 text-sm",children:[e.jsxs("span",{children:[e.jsx("strong",{children:"Admin preview"})," — this is exactly what an enrollee sees. Your own progress, check-ins and video logs are empty because you're not enrolled."]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ln,{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(ze,{variant:"secondary",children:["Week ",T," of ",a.duration_weeks]}),(l==null?void 0:l.status)==="scheduled_for_charge"&&l.charge_scheduled_at&&e.jsxs(ze,{variant:"outline",children:["Billing ",Vl(l.charge_scheduled_at)]}),(l==null?void 0:l.status)==="payment_failed"&&e.jsx(ze,{variant:"destructive",children:"Payment issue"})]}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:a.name}),a.subtitle&&e.jsx("p",{className:"text-muted-foreground",children:a.subtitle})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(wc,{className:"h-3.5 w-3.5"})," This week"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[F,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",V]})]}),e.jsx(xi,{value:Math.min(F/V*100,100),className:"h-1.5"})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(Ph,{className:"h-3.5 w-3.5"})," Videos posted"]}),e.jsx("p",{className:"text-2xl font-bold",children:z}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"since kickoff"})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(_c,{className:"h-3.5 w-3.5"})," Streak"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[W," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(mo,{className:"h-3.5 w-3.5"})," Curriculum"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[M,"%"]}),e.jsx(xi,{value:M,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(bs,{open:f,onOpenChange:g,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(As,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(vs,{children:[e.jsx(ws,{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(se,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(ge,{id:"v-title",value:b.title,onChange:ce=>v(de=>({...de,title:ce.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(ge,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:b.instagram_url,onChange:ce=>v(de=>({...de,instagram_url:ce.target.value}))})]})]}),e.jsx(Xn,{children:e.jsx(B,{onClick:async()=>{await u.mutateAsync({week_number:T,...b}),v({title:"",instagram_url:""}),g(!1)},children:"Log video"})})]})]}),((pe=K[0])==null?void 0:pe.meeting_link)&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:K[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(Pu,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),ee.length>0&&e.jsx(fe,{className:"border-primary/30 bg-primary/5",children:e.jsx(Ae,{className:"space-y-3 p-5",children:ee.map(ce=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(qd,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ce.title}),ce.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ce.body})]})]},ce.id))})}),e.jsxs($r,{defaultValue:"roadmap",children:[e.jsxs(Ur,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Zt,{value:"roadmap",children:"Roadmap"}),e.jsx(Zt,{value:"lessons",children:"Lessons"}),e.jsx(Zt,{value:"checkin",children:"Weekly check-in"}),e.jsx(Zt,{value:"events",children:"Sessions"}),e.jsx(Zt,{value:"resources",children:"Resources"}),e.jsx(Zt,{value:"profile",children:"Profile review"})]}),e.jsxs(ls,{value:"roadmap",className:"mt-6 space-y-4",children:[((o==null?void 0:o.weeks)||[]).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"The roadmap will appear here before kickoff."}),((o==null?void 0:o.weeks)||[]).map(ce=>{const de=ce.release_at&&new Date(ce.release_at)>new Date;return e.jsx(fe,{className:de?"opacity-60":ce.week_number===T?"border-primary/50":"",children:e.jsxs(Ae,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ze,{variant:"outline",children:["Week ",ce.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:ce.phase}),ce.week_number===T&&e.jsx(ze,{children:"Current"}),de&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(gr,{className:"h-3 w-3"})," Unlocks ",Vl(ce.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:ce.title}),ce.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ce.learning_goal}),!de&&Array.isArray(ce.tasks)&&ce.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:ce.tasks.map((ie,ye)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(xr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ie=="string"?ie:ie.label]},ye))})]})},ce.id)})]}),e.jsxs(ls,{value:"lessons",className:"mt-6 space-y-3",children:[L.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),L.map(ce=>{const de=sgt(ce.video_url),ie=S===ce.id;return e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(hi,{checked:D.has(ce.id),onCheckedChange:ye=>d.mutate({lessonId:ce.id,done:!!ye}),"aria-label":`Mark ${ce.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ce.title}),ce.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ce.summary}),ce.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",ce.action_assignment]})]}),ce.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(gr,{className:"h-3 w-3"})," ",ce.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[ce.video_url&&de&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>A(ie?null:ce.id),children:[e.jsx(Pu,{className:"mr-1.5 h-3.5 w-3.5"})," ",ie?"Close":"Watch"]}),ce.video_url&&!de&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ce.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Pu,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),ce.worksheet_url&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:ce.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Da,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),ie&&de&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:de,title:ce.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})})]})},ce.id)})]}),e.jsx(ls,{value:"checkin",className:"mt-6",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-5 p-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold",children:["Week ",T," check-in"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Two minutes of honesty here is what makes the next week better."})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["videos_planned","Videos planned"],["videos_recorded","Videos recorded"],["videos_posted","Videos posted"]].map(([ce,de])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:ce,children:de}),e.jsx(ge,{id:ce,type:"number",min:0,defaultValue:oe[ce]??"",onChange:ie=>_(ye=>({...ye,[ce]:Number(ie.target.value)}))})]},ce))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([ce,de])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:ce,children:de}),e.jsx(Ts,{id:ce,rows:2,defaultValue:oe[ce]??"",onChange:ie=>_(ye=>({...ye,[ce]:ie.target.value}))})]},ce)),e.jsx(B,{onClick:()=>h.mutate({week_number:T,goal_videos:V,...j}),children:"Save check-in"})]})})}),e.jsxs(ls,{value:"events",className:"mt-6 space-y-4",children:[K.length===0&&Y.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),K.map(ce=>e.jsx(fe,{className:"border-primary/30",children:e.jsxs(Ae,{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(ze,{variant:"secondary",className:"capitalize",children:String(ce.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Tl,{className:"h-3 w-3"})," ",Vl(ce.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:ce.title}),ce.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",ce.speaker]}),ce.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:ce.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>p.mutate({eventId:ce.id,optIn:!0}),children:"Remind me"}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>Wps(ce,a.name),children:[e.jsx(Tl,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),ce.meeting_link&&e.jsx(B,{size:"sm",asChild:!0,children:e.jsxs("a",{href:ce.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(tr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},ce.id)),Y.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"}),Y.map(ce=>e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ce.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Vl(ce.starts_at,!0)})]}),ce.replay_url?e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ce.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Pu,{className:"mr-1.5 h-3.5 w-3.5"})," Watch replay"]})}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Replay coming soon"})]})},ce.id))]})]}),e.jsxs(ls,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(ne).length===0&&e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(Nr,{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(ne).map(([ce,de])=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:ce}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[de.length," item",de.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:de.map(ie=>{const ye=ngt(ie),_e=Kps[ie.resource_kind]||Nr;return e.jsxs("a",{href:ye||"#",target:"_blank",rel:"noreferrer",onClick:Me=>{ye||Me.preventDefault()},className:"group relative flex flex-col gap-3 overflow-hidden rounded-2xl border border-border/60 bg-card p-5 transition-all hover:-translate-y-0.5 hover:border-primary/50 hover:shadow-lg",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary",children:e.jsx(_e,{className:"h-5 w-5"})}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:String(ie.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:ie.title}),ie.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:ie.description})]}),e.jsx("span",{className:"mt-auto inline-flex items-center gap-1.5 text-sm font-medium text-primary",children:ie.file_path?e.jsxs(e.Fragment,{children:[e.jsx(Da,{className:"h-3.5 w-3.5"})," Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-3.5 w-3.5"})," Open"]})})]},ie.id)})})]},ce))]}),e.jsx(ls,{value:"profile",className:"mt-6",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mu,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Your profile review"})]}),!(o!=null&&o.analysis)||o.analysis.status==="not_submitted"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Instagram review hasn't been submitted yet. Your coach will request screenshots during onboarding week."}):o.analysis.status==="in_review"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your profile is in review — you'll get a notification when the report is ready."}):e.jsxs("div",{className:"space-y-4",children:[o.analysis.scores&&Object.keys(o.analysis.scores).length>0&&e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Object.entries(o.analysis.scores).map(([ce,de])=>e.jsxs("div",{className:"space-y-1 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:ce.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[de,"/10"]})]}),e.jsx(xi,{value:Number(de)*10,className:"h-1.5"})]},ce))}),Array.isArray(o.analysis.top_priorities)&&o.analysis.top_priorities.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Top priorities"}),e.jsx("ul",{className:"space-y-1.5",children:o.analysis.top_priorities.map((ce,de)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(vc,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ce=="string"?ce:ce.label]},de))})]}),o.analysis.member_notes&&e.jsx("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm leading-relaxed whitespace-pre-line",children:o.analysis.member_notes}),o.analysis.report_url&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:o.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Da,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})},ha=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:n,className:Et("w-full caption-bottom text-sm",s),...t})}));ha.displayName="Table";const ma=N.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Et("[&_tr]:border-b",s),...t}));ma.displayName="TableHeader";const pa=N.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Et("[&_tr:last-child]:border-0",s),...t}));pa.displayName="TableBody";const Zps=N.forwardRef(({className:s,...t},n)=>e.jsx("tfoot",{ref:n,className:Et("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));Zps.displayName="TableFooter";const Gs=N.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:Et("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));Gs.displayName="TableRow";const Ct=N.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:Et("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Ct.displayName="TableHead";const ut=N.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:Et("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));ut.displayName="TableCell";const Qps=N.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Et("mt-4 text-sm text-muted-foreground",s),...t}));Qps.displayName="TableCaption";const PH=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())}`},LH=s=>s?new Date(s).toISOString():null,N2e=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:PH(s.enrollment_open_at),enrollment_close_at:PH(s.enrollment_close_at),kickoff_at:PH(s.kickoff_at),charge_at:PH(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),Xps=({program:s,onSaved:t})=>{const[n,r]=N.useState(()=>N2e(s)),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null),h=N.useRef(null);N.useEffect(()=>{r(N2e(s)),i(!1)},[s.id,s.updated_at]);const p=(v,j)=>{r(_=>({..._,[v]:j})),i(!0)},f=async(v,j)=>{if(!v.type.startsWith("image/")){ae.error("Please choose an image file");return}if(v.size>8*1024*1024){ae.error("Image must be under 8MB");return}d(j);try{const _=v.name.split(".").pop()||"jpg",S=`programs/${s.id}/${j}-${Date.now()}.${_}`,{error:A}=await q.storage.from("event-images").upload(S,v,{cacheControl:"31536000",upsert:!0});if(A)throw A;const{data:T}=q.storage.from("event-images").getPublicUrl(S);p(j==="cover"?"cover_image_url":"hero_image_url",T.publicUrl),ae.success(`${j==="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 v={name:n.name.trim(),slug:n.slug.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),subtitle:n.subtitle||null,tagline:n.tagline||null,short_description:n.short_description||null,description:n.description||null,price_cents:Math.max(0,Math.round(n.price_cents)),currency:n.currency||"usd",capacity:Math.max(0,Math.round(n.capacity)),duration_weeks:Math.max(1,Math.round(n.duration_weeks)),weekly_video_goal:Math.max(0,Math.round(n.weekly_video_goal)),payment_mode:n.payment_mode,payment_grace_days:Math.max(0,Math.round(n.payment_grace_days)),timezone:n.timezone||"America/New_York",accent_color:n.accent_color||null,cover_image_url:n.cover_image_url||null,hero_image_url:n.hero_image_url||null,promo_video_url:n.promo_video_url.trim()||null,promo_video_headline:n.promo_video_headline.trim()||null,enrollment_open_at:LH(n.enrollment_open_at),enrollment_close_at:LH(n.enrollment_close_at),kickoff_at:LH(n.kickoff_at),charge_at:LH(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:j}=await q.from("programs").update(v).eq("id",s.id);if(j)throw j;ae.success("Program saved"),i(!1),t()}catch(v){ae.error(v.message||"Could not save the program")}finally{o(!1)}},b=({kind:v,label:j,hint:_})=>{const S=v==="cover"?n.cover_image_url:n.hero_image_url,A=v==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:j}),e.jsxs("div",{className:"flex flex-wrap items-start gap-4",children:[e.jsx("div",{className:"relative h-28 w-48 shrink-0 overflow-hidden rounded-lg border border-border bg-muted/40",children:S?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:S,alt:`${j} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>p(v==="cover"?"cover_image_url":"hero_image_url",""),className:"absolute right-1.5 top-1.5 rounded-full bg-background/90 p-1 text-foreground shadow","aria-label":`Remove ${j}`,children:e.jsx(Fn,{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(ay,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"No image"})]})}),e.jsxs("div",{className:"min-w-[220px] flex-1 space-y-2",children:[e.jsx("input",{ref:A,type:"file",accept:"image/*",className:"hidden",onChange:T=>{var L;const D=(L=T.target.files)==null?void 0:L[0];D&&f(D,v),T.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var T;return(T=A.current)==null?void 0:T.click()},disabled:c===v,children:[c===v?e.jsx(ss,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Sa,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(ge,{placeholder:"…or paste an image URL",value:S,onChange:T=>p(v==="cover"?"cover_image_url":"hero_image_url",T.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(B,{variant:"ghost",onClick:()=>{r(N2e(s)),i(!1)},children:"Discard"}),e.jsxs(B,{onClick:g,disabled:l||!a,children:[l?e.jsx(ss,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(fe,{children:e.jsxs(Ae,{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(se,{children:"Program name"}),e.jsx(ge,{value:n.name,onChange:v=>p("name",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Slug (public URL)"}),e.jsx(ge,{value:n.slug,onChange:v=>p("slug",v.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["/programs/",n.slug||"slug"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subtitle"}),e.jsx(ge,{value:n.subtitle,onChange:v=>p("subtitle",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Tagline"}),e.jsx(ge,{value:n.tagline,onChange:v=>p("tagline",v.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Short description (cards & previews)"}),e.jsx(Ts,{rows:2,value:n.short_description,onChange:v=>p("short_description",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Full program description (sales page)"}),e.jsx(Ts,{rows:8,value:n.description,onChange:v=>p("description",v.target.value)})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{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(b,{kind:"cover",label:"Program cover image",hint:"Shown on the Programs list and enrollment cards. 1200×630 works great."}),e.jsx(b,{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(se,{children:"Promo video URL (optional)"}),e.jsx(ge,{placeholder:"https://youtu.be/… , Vimeo, or a direct .mp4 link",value:n.promo_video_url,onChange:v=>p("promo_video_url",v.target.value)}),e.jsx(ge,{placeholder:"Video headline (e.g. Watch: what 90 days inside Reel Estate looks like)",value:n.promo_video_headline,onChange:v=>p("promo_video_headline",v.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(se,{children:"Accent color"}),e.jsx(ge,{placeholder:"#406E71",value:n.accent_color,onChange:v=>p("accent_color",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Sort order"}),e.jsx(ge,{type:"number",value:n.sort_order,onChange:v=>p("sort_order",Number(v.target.value))})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{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(se,{children:"One-time price (USD)"}),e.jsx(ge,{type:"number",min:0,step:"1",value:n.price_cents/100,onChange:v=>p("price_cents",Math.round(Number(v.target.value)*100))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Seats (capacity)"}),e.jsx(ge,{type:"number",min:0,value:n.capacity,onChange:v=>p("capacity",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Billing mode"}),e.jsxs(us,{value:n.payment_mode,onValueChange:v=>p("payment_mode",v),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"delayed",children:"Save card, charge once later"}),e.jsx(Ze,{value:"immediate",children:"Charge once at checkout"}),e.jsx(Ze,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Charge date (one-time)"}),e.jsx(ge,{type:"datetime-local",value:n.charge_at,onChange:v=>p("charge_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Payment grace days"}),e.jsx(ge,{type:"number",min:0,value:n.payment_grace_days,onChange:v=>p("payment_grace_days",Number(v.target.value))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Days of access kept after a failed charge before access is paused."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Currency"}),e.jsx(ge,{value:n.currency,onChange:v=>p("currency",v.target.value)})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{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(se,{children:"Enrollment opens"}),e.jsx(ge,{type:"datetime-local",value:n.enrollment_open_at,onChange:v=>p("enrollment_open_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Enrollment closes"}),e.jsx(ge,{type:"datetime-local",value:n.enrollment_close_at,onChange:v=>p("enrollment_close_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Kickoff"}),e.jsx(ge,{type:"datetime-local",value:n.kickoff_at,onChange:v=>p("kickoff_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Length (weeks)"}),e.jsx(ge,{type:"number",min:1,value:n.duration_weeks,onChange:v=>p("duration_weeks",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Videos per week goal"}),e.jsx(ge,{type:"number",min:0,value:n.weekly_video_goal,onChange:v=>p("weekly_video_goal",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Timezone"}),e.jsx(ge,{value:n.timezone,onChange:v=>p("timezone",v.target.value)})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{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(se,{children:"Status"}),e.jsxs(us,{value:n.status,onValueChange:v=>p("status",v),children:[e.jsx(cs,{className:"sm:max-w-xs",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ze,{value:"published",children:"Published (members can enroll)"}),e.jsx(Ze,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pin this program to the top."})]}),e.jsx(vn,{checked:n.is_featured,onCheckedChange:v=>p("is_featured",v)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Visible to all members"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn off to keep it invite-only via a direct link."})]}),e.jsx(vn,{checked:n.is_public,onCheckedChange:v=>p("is_public",v)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs(B,{onClick:g,disabled:l||!a,size:"lg",children:[l?e.jsx(ss,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},Jps=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var ee,ne,oe,pe,ce,de,ie;const i=t==null?void 0:t.user_id,[l,o]=N.useState((t==null?void 0:t.admin_notes)||""),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(!1),[g,b]=N.useState(!1),v=N.useRef(null),{data:j,isLoading:_,refetch:S}=lt({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[ye,_e,Me,Te,Ce,Ee,De,Ie]=await Promise.all([q.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),q.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_lessons").select("id").eq("program_id",s.id),q.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:ye.data||[],videos:_e.data||[],completions:Me.data||[],badges:Te.data||[],intake:Ce.data,attendance:Ee.data||[],lessonCount:(De.data||[]).length,analysis:Ie.data}}});N.useEffect(()=>{var ye;h(((ye=j==null?void 0:j.analysis)==null?void 0:ye.member_notes)||"")},[(ee=j==null?void 0:j.analysis)==null?void 0:ee.id]);const A=N.useMemo(()=>{var Me;const ye=Nxe(s),_e=((Me=j==null?void 0:j.intake)==null?void 0:Me.extra)||{};return ye.custom.map(Te=>({label:Te.label,value:typeof _e[Te.id]=="boolean"?_e[Te.id]?"Yes":"No":_e[Te.id]||""})).filter(Te=>!!Te.value)},[s,j==null?void 0:j.intake]),T=async ye=>i?q.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...ye},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},D=async ye=>{if(ye.type!=="application/pdf")return ae.error("Please choose a PDF file");if(ye.size>25*1024*1024)return ae.error("PDF must be under 25MB");b(!0);try{const _e=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:Me}=await q.storage.from("event-images").upload(_e,ye,{contentType:"application/pdf",upsert:!0});if(Me)throw Me;const{data:Te}=q.storage.from("event-images").getPublicUrl(_e),{error:Ce}=await T({report_url:Te.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Ce)throw Ce;ae.success("Profile review uploaded"),await S()}catch(_e){ae.error(_e.message||"Upload failed")}finally{b(!1)}},L=async()=>{const{error:ye}=await T({report_url:null,status:"in_review"});if(ye)return ae.error(ye.message);ae.success("Review removed"),await S()},M=async()=>{f(!0);const{error:ye}=await T({member_notes:u});if(f(!1),ye)return ae.error(ye.message);ae.success("Review notes saved"),await S()},F=async()=>{if(!t)return;d(!0);const{error:ye}=await q.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),ye)return ae.error(ye.message);ae.success("Notes saved"),a()},z=((j==null?void 0:j.videos)||[]).filter(ye=>ye.posted).length,V=(s.weekly_video_goal||0)*(s.duration_weeks||0),W=j!=null&&j.lessonCount?Math.round(((j==null?void 0:j.completions.length)||0)/j.lessonCount*100):0,K=V?Math.min(100,Math.round(z/V*100)):0,Y=((j==null?void 0:j.attendance)||[]).filter(ye=>ye.attended).length;return e.jsx(ug,{open:n,onOpenChange:r,children:e.jsxs(ox,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(r0,{className:"mb-4",children:[e.jsxs(a0,{children:[((ne=t==null?void 0:t.profile)==null?void 0:ne.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(oe=t==null?void 0:t.profile)==null?void 0:oe.email})]}),t?_?e.jsx(Ws,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4 pb-8",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx(ze,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[Iu(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${Vl(t.charged_at)}`:`Charge ${Vl(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{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:Vl(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",Vl(t.created_at)]})]})})]}),e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-4 p-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Videos posted"}),e.jsxs("span",{className:"text-muted-foreground",children:[z," / ",V||"—"]})]}),e.jsx(xi,{value:K})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Curriculum completed"}),e.jsxs("span",{className:"text-muted-foreground",children:[(j==null?void 0:j.completions.length)||0," / ",(j==null?void 0:j.lessonCount)||0]})]}),e.jsx(xi,{value:W})]}),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: "}),Y]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Badges: "}),(j==null?void 0:j.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(j==null?void 0:j.weekly.length)||0]})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((j==null?void 0:j.weekly.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No weekly check-ins yet."}):e.jsx("div",{className:"space-y-3",children:j.weekly.map(ye=>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 ",ye.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ye.videos_posted,"/",ye.goal_videos||s.weekly_video_goal," posted ·"," ",ye.stories_posted," stories"]})]}),ye.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",ye.biggest_win]}),ye.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",ye.biggest_challenge]})]},ye.id))})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((j==null?void 0:j.videos.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No videos logged yet."}):e.jsx("div",{className:"space-y-2",children:j.videos.slice(0,25).map(ye=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(vr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:ye.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",ye.week_number," · ",Vl(ye.posted_at)]}),ye.instagram_url&&e.jsx("a",{href:ye.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})]},ye.id))})]})}),(j==null?void 0:j.intake)&&e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",j.intake.full_name],["Email",j.intake.email],["Phone",j.intake.phone],["Instagram",j.intake.instagram_handle],["City / market",j.intake.city],["Areas served",j.intake.service_areas],["Years in real estate",j.intake.years_experience],["Specialty",j.intake.specialty],["Target audience",j.intake.target_audience],["On camera",j.intake.video_comfort],["Posts today",j.intake.posting_frequency],["Content style",j.intake.content_style],["Interests",j.intake.personal_interests],["#1 goal",j.intake.primary_goal],["Topics to avoid",j.intake.topics_to_avoid],["Time zone",j.intake.timezone]].filter(([,ye])=>!!ye).map(([ye,_e])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ye,": "]}),_e]},ye)),A.map(({label:ye,value:_e})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ye,": "]}),_e]},ye)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",j.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{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."})]}),((pe=j==null?void 0:j.analysis)==null?void 0:pe.status)&&e.jsx(ze,{variant:"secondary",className:"capitalize",children:String(j.analysis.status).replace(/_/g," ")})]}),(ce=j==null?void 0:j.analysis)!=null&&ce.report_url?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border/60 p-3 text-sm",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:j.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(tr,{className:"h-3.5 w-3.5"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No review uploaded yet."}),e.jsx("input",{ref:v,type:"file",accept:"application/pdf",className:"hidden",onChange:ye=>{var Me;const _e=(Me=ye.target.files)==null?void 0:Me[0];_e&&D(_e),ye.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{var ye;return(ye=v.current)==null?void 0:ye.click()},disabled:g,children:[e.jsx(Sa,{className:"mr-1.5 h-3.5 w-3.5"}),g?"Uploading…":(de=j==null?void 0:j.analysis)!=null&&de.report_url?"Replace PDF":"Upload PDF"]}),((ie=j==null?void 0:j.analysis)==null?void 0:ie.report_url)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:L,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(se,{children:"Review summary shown to the agent (optional)"}),e.jsx(Ts,{rows:3,value:u,onChange:ye=>h(ye.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",variant:"outline",onClick:M,disabled:p,children:"Save review notes"})})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-3 p-5",children:[e.jsx(se,{children:"Coach notes (internal)"}),e.jsx(Ts,{rows:4,value:l,onChange:ye=>o(ye.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",onClick:F,disabled:c,children:"Save notes"})})]})})]}):null]})})},$Ve={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},UVe=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},efs=({program:s})=>{const{data:t=[],isLoading:n}=ups(s.id),r=hps(s.id),a=mps(),[i,l]=N.useState(!1),[o,c]=N.useState({...$Ve}),d=()=>{c({...$Ve}),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:UVe(g.starts_at),expires_at:UVe(g.expires_at),is_active:g.is_active}),l(!0)},h=N.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),b=Math.min(Math.max(g,0),s.price_cents);return{discount:b,final:s.price_cents-b}},[o,s.price_cents]),p=async()=>{if(!o.code.trim())return ae.error("Give the code a name, e.g. FOUNDER50");await r.mutateAsync({id:o.id,code:o.code,label:o.label||null,percent_off:o.kind==="percent"?Number(o.percent_off)||0:null,amount_off_cents:o.kind==="amount"?Math.round(Number(o.amount_off||0)*100):null,max_redemptions:o.max_redemptions?Number(o.max_redemptions):null,starts_at:o.starts_at?new Date(o.starts_at).toISOString():null,expires_at:o.expires_at?new Date(o.expires_at).toISOString():null,is_active:o.is_active}),l(!1)},f=g=>{const b=g.percent_off!=null?Math.floor(s.price_cents*Number(g.percent_off)/100):g.amount_off_cents||0,v=Math.max(s.price_cents-Math.min(b,s.price_cents),0);return{off:g.percent_off!=null?`${Number(g.percent_off)}% off`:`${Iu(g.amount_off_cents||0,s.currency)} off`,final:Iu(v,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{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 ",Iu(s.price_cents,s.currency)," charge."]})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{onClick:d,children:[e.jsx(As,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(vs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Code"}),e.jsx(ge,{placeholder:"FOUNDER50",value:o.code,onChange:g=>c({...o,code:g.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Internal label (optional)"}),e.jsx(ge,{placeholder:"Founding cohort",value:o.label,onChange:g=>c({...o,label:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Discount type"}),e.jsxs(us,{value:o.kind,onValueChange:g=>c({...o,kind:g}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"percent",children:"Percent off"}),e.jsx(Ze,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Percent off"}),e.jsx(ge,{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(se,{children:"Amount off (USD)"}),e.jsx(ge,{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(se,{children:"Max redemptions (blank = unlimited)"}),e.jsx(ge,{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(se,{children:"Active from (optional)"}),e.jsx(ge,{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(se,{children:"Expires (optional)"}),e.jsx(ge,{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(vn,{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:[Iu(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Iu(h.final,s.currency)})," ","(",Iu(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:p,disabled:r.isPending,children:[r.isPending&&e.jsx(ss,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(Ws,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(mh,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No discount codes yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Create a code for early birds, brokerage partners or a founding cohort. Codes are entered by the enrollee at checkout and change the one-time price."})]})}):e.jsx(fe,{children:e.jsx(Ae,{className:"overflow-x-auto p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Code"}),e.jsx(Ct,{children:"Discount"}),e.jsx(Ct,{children:"Price after"}),e.jsx(Ct,{children:"Used"}),e.jsx(Ct,{children:"Window"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:t.map(g=>{const b=f(g);return e.jsxs(Gs,{children:[e.jsxs(ut,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:g.code}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(g.code),ae.success("Code copied")},children:e.jsx(ta,{className:"h-3.5 w-3.5"})})]}),g.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:g.label})]}),e.jsx(ut,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(i4,{className:"h-3.5 w-3.5 text-muted-foreground"}),b.off]})}),e.jsx(ut,{className:"font-medium",children:b.final}),e.jsxs(ut,{children:[g.times_redeemed,g.max_redemptions?` / ${g.max_redemptions}`:""]}),e.jsxs(ut,{className:"text-xs text-muted-foreground",children:[g.starts_at?`From ${Vl(g.starts_at)}`:"Anytime",g.expires_at?` · until ${Vl(g.expires_at)}`:""]}),e.jsx(ut,{children:e.jsx(ze,{variant:g.is_active?"default":"secondary",children:g.is_active?"Active":"Paused"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(g),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm(`Delete ${g.code}?`)&&a.mutate(g.id)},children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},g.id)})})]})})})]})},E_=({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(xr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(Dl,{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})]})]}),tfs=({program:s})=>{var c,d;const{data:t,isLoading:n}=lt({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,p,f,g]=await Promise.all([q.from("program_weeks").select("id, week_number, title").eq("program_id",s.id),q.from("program_lessons").select("id, title").eq("program_id",s.id),q.from("program_resources").select("id, title").eq("program_id",s.id),q.from("program_events").select("id, title, starts_at").eq("program_id",s.id),q.from("program_announcements").select("id, title").eq("program_id",s.id)]);return{weeks:u.data||[],lessons:h.data||[],resources:p.data||[],events:f.data||[],announcements:g.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=uve(s),l=`/programs/${s.slug}`,o=[{icon:un,title:"1 · Sales page",body:`${s.name} — hero image, ${s.subtitle?"subtitle":"no subtitle"}, description, price, dates, seats left and FAQ.`,href:l,cta:"Preview sales page"},{icon:k9,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:ff,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 ${Iu(s.price_cents,s.currency)} charge runs on ${Vl(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Iu(s.price_cents,s.currency)} once at checkout.`},{icon:Hs,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:fL,title:"5 · Program workspace",body:`Their home base: progress dashboard, ${s.duration_weeks}-week roadmap, lessons, resources, events, weekly check-ins and video logging (${s.weekly_video_goal}/week goal).`,href:`${l}/workspace?preview=1`,cta:"Preview workspace as an enrollee"}];return e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-wrap items-center justify-between gap-4 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"What enrollees see"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Walk the exact member journey end to end. Workspace preview opens in read-only admin mode — it does not create an enrollment."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",children:["Sales page ",e.jsx(tr,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(B,{asChild:!0,children:e.jsxs("a",{href:`${l}/workspace?preview=1`,target:"_blank",rel:"noreferrer",children:["Workspace preview ",e.jsx(tr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})}),(s.status!=="published"||r||a)&&e.jsx(fe,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Ae,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx(Dl,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Members can't enroll right now"}),e.jsx("p",{className:"text-muted-foreground",children:s.status!=="published"?`This program is ${s.status} — it isn't listed on the member Programs page yet.`:r?`Enrollment opens ${i}. CTAs are disabled until then.`:"Enrollment has closed for this cohort."})]})]})}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-3 p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"The enrollee journey"}),e.jsx("div",{className:"space-y-4",children:o.map(u=>e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(u.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:u.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:u.body}),u.href&&e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:u.href,target:"_blank",rel:"noreferrer",children:[u.cta," ",e.jsx(tr,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Premium-experience checklist"}),n?e.jsx(Ws,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(E_,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(E_,{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(E_,{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(E_,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Iu(s.price_cents,s.currency)}),e.jsx(E_,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${Vl(s.kickoff_at)||"not set"} · charge ${Vl(s.charge_at)||"not set"}`}),e.jsx(E_,{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(E_,{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(E_,{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(E_,{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 ${Vl(t.events[0].starts_at)}`:""}`}),e.jsx(E_,{ok:((t==null?void 0:t.announcements.length)||0)>0,label:"Welcome announcement",detail:`${(t==null?void 0:t.announcements.length)||0} announcements — a day-one welcome post makes the workspace feel alive`})]})]})})]}),t&&e.jsx(fe,{children:e.jsx(Ae,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:Tl,label:"Weeks",value:t.weeks.length},{icon:Nr,label:"Lessons",value:t.lessons.length},{icon:Nr,label:"Resources",value:t.resources.length},{icon:Tl,label:"Events",value:t.events.length},{icon:qd,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(ze,{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."})]})},sfs=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],nfs={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},rfs=({program:s,onSaved:t})=>{const[n,r]=N.useState(()=>Nxe(s)),[a,i]=N.useState(!1),[l,o]=N.useState(!1);N.useEffect(()=>{r(Nxe(s)),i(!1)},[s.id,s.updated_at]);const c=v=>{r(j=>({...j,...v})),i(!0)},d=(v,j)=>{const _=j?n.hidden.filter(A=>A!==v):[...new Set([...n.hidden,v])],S=j?n.required:n.required.filter(A=>A!==v);c({hidden:_,required:S})},u=(v,j)=>{c({required:j?[...new Set([...n.required,v])]:n.required.filter(_=>_!==v)})},h=()=>{const v={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,v]})},p=(v,j)=>c({custom:n.custom.map(_=>_.id===v?{..._,...j}:_)}),f=v=>c({custom:n.custom.filter(j=>j.id!==v)}),g=(v,j)=>{const _=[...n.custom],S=v+j;S<0||S>=_.length||([_[v],_[S]]=[_[S],_[v]],c({custom:_}))},b=async()=>{if(n.custom.find(S=>!S.label.trim()))return ae.error("Every custom question needs a label");o(!0);const j={...s.sales_copy||{},intake:n},{error:_}=await q.from("programs").update({sales_copy:j}).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(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/enroll`,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"mr-1.5 h-3.5 w-3.5"})," Preview form"]})}),e.jsxs(B,{size:"sm",onClick:b,disabled:!a||l,children:[e.jsx(Ho,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(Pt,{className:"text-sm",children:"Intro message"})}),e.jsx(Ae,{children:e.jsx(Ts,{rows:3,placeholder:"Shown at the top of the intake — e.g. “Answer a few questions so we can personalize your 90 days.”",value:n.intro||"",onChange:v=>c({intro:v.target.value})})})]}),[0,1,2].map(v=>e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(Pt,{className:"text-sm",children:sfs[v]})}),e.jsxs(Ae,{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"})]}),Jxt.filter(j=>j.step===v).map(j=>{const _=!n.hidden.includes(j.key);return e.jsxs("div",{className:"grid grid-cols-[1fr,auto,auto] items-center gap-4 rounded-lg border border-border/60 px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:j.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(vn,{checked:_,onCheckedChange:S=>d(j.key,S),"aria-label":`Show ${j.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(vn,{checked:n.required.includes(j.key),disabled:!_,onCheckedChange:S=>u(j.key,S),"aria-label":`Require ${j.label}`})})]},j.key)})]})]},v)),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Pt,{className:"text-sm",children:["Custom questions"," ",e.jsx(ze,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(As,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(Ae,{className:"space-y-3",children:[n.custom.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No custom questions yet. Add program-specific questions here — answers appear on each agent's dashboard."}),n.custom.map((v,j)=>e.jsxs("div",{className:"space-y-3 rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"flex flex-col pt-1.5",children:e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>g(j,-1),"aria-label":"Move up",children:e.jsx(Uu,{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(se,{className:"text-xs",children:"Question"}),e.jsx(ge,{value:v.label,placeholder:"What is your biggest content roadblock?",onChange:_=>p(v.id,{label:_.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Answer type"}),e.jsxs(us,{value:v.type,onValueChange:_=>p(v.id,{type:_}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:Object.entries(nfs).map(([_,S])=>e.jsx(Ze,{value:_,children:S},_))})]})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>f(v.id),"aria-label":"Delete question",children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]}),v.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Ts,{rows:3,value:(v.options||[]).join(` `),onChange:_=>p(v.id,{options:_.target.value.split(` `).map(S=>S.trim()).filter(Boolean)})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr,auto]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(ge,{value:v.help||"",onChange:_=>p(v.id,{help:_.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(vn,{checked:!!v.required,onCheckedChange:_=>p(v.id,{required:_}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},v.id))]})]})]})},afs=[{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"}],ifs=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},qVe={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},ofs=({programId:s})=>{const{data:t=[],isLoading:n}=xps(s),r=gps(s),a=yps(),[i,l]=N.useState(!1),[o,c]=N.useState({...qVe}),d=()=>{c({...qVe}),l(!0)},u=v=>{c({id:v.id,title:v.title,description:v.description||"",event_kind:v.event_kind,starts_at:ifs(v.starts_at),duration_minutes:v.duration_minutes,speaker:v.speaker||"",meeting_link:v.meeting_link||"",replay_url:v.replay_url||"",is_published:v.is_published}),l(!0)},h=async()=>{if(!o.title.trim())return ae.error("Give the session a title");if(!o.starts_at)return ae.error("Pick a date and time");await r.mutateAsync({...o,starts_at:new Date(o.starts_at).toISOString(),duration_minutes:Number(o.duration_minutes)||60}),l(!1)},p=Date.now(),f=t.filter(v=>new Date(v.starts_at).getTime()>=p),g=t.filter(v=>new Date(v.starts_at).getTime()e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ae,{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(ze,{variant:"secondary",className:"capitalize",children:v.event_kind.replace("_"," ")}),!v.is_published&&e.jsx(ze,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Vl(v.starts_at,!0)," · ",v.duration_minutes," min",v.speaker?` · ${v.speaker}`:""]}),v.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.description}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[v.meeting_link?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3 w-3"})," Join link"]}),e.jsxs("button",{className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground",onClick:()=>{navigator.clipboard.writeText(v.meeting_link),ae.success("Join link copied")},children:[e.jsx(ta,{className:"h-3 w-3"})," Copy"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"No meeting link yet"}),v.replay_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(vr,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(v),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{confirm(`Remove "${v.title}"?`)&&a.mutate(v.id)},children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Live sessions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add your Zoom (or Meet / Teams) sessions here. Enrolled members see them in the Sessions tab with the join button, RSVP reminders and an add-to-calendar link."})]}),e.jsxs(B,{onClick:d,children:[e.jsx(As,{className:"mr-1.5 h-4 w-4"})," Add session"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading sessions…"}):t.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(cm,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No live sessions scheduled"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Paste your recurring Zoom link once for each call — kickoff, weekly masterminds, workshops and office hours."})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Upcoming (",f.length,")"]}),f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing upcoming."}):f.map(v=>e.jsx(b,{e:v},v.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(v=>e.jsx(b,{e:v},v.id))]})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Title"}),e.jsx(ge,{placeholder:"Week 1 Mastermind — Content that converts",value:o.title,onChange:v=>c({...o,title:v.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Type"}),e.jsxs(us,{value:o.event_kind,onValueChange:v=>c({...o,event_kind:v}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:afs.map(v=>e.jsx(Ze,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Host / speaker"}),e.jsx(ge,{value:o.speaker,onChange:v=>c({...o,speaker:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Starts (your local time)"}),e.jsx(ge,{type:"datetime-local",value:o.starts_at,onChange:v=>c({...o,starts_at:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Length (minutes)"}),e.jsx(ge,{type:"number",value:o.duration_minutes,onChange:v=>c({...o,duration_minutes:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Zoom / meeting link"}),e.jsx(ge,{placeholder:"https://us02web.zoom.us/j/1234567890?pwd=…",value:o.meeting_link,onChange:v=>c({...o,meeting_link:v.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see this after they're enrolled. A recurring Zoom link can be reused on every session."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Replay link (after the call)"}),e.jsx(ge,{placeholder:"YouTube, Vimeo, Loom or Zoom cloud recording URL",value:o.replay_url,onChange:v=>c({...o,replay_url:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"What we'll cover"}),e.jsx(Ts,{rows:3,value:o.description,onChange:v=>c({...o,description:v.target.value})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Visible to members"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to draft a session privately."})]}),e.jsx(vn,{checked:o.is_published,onCheckedChange:v=>c({...o,is_published:v})})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(ss,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},VVe={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},lfs=({programId:s})=>{const{data:t,isLoading:n}=vps(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],i=bps(s),l=_ps(),[o,c]=N.useState(!1),[d,u]=N.useState({...VVe}),h=()=>{u({...VVe,sort_order:r.length}),c(!0)},p=v=>{u({id:v.id,title:v.title,summary:v.summary||"",week_id:v.week_id||"none",duration_minutes:v.duration_minutes??"",video_url:v.video_url||"",worksheet_url:v.worksheet_url||"",action_assignment:v.action_assignment||"",status:v.status,sort_order:v.sort_order}),c(!0)},f=async()=>{if(!d.title.trim())return ae.error("Give the video a title");await i.mutateAsync({...d,week_id:d.week_id==="none"?null:d.week_id,duration_minutes:d.duration_minutes===""?null:Number(d.duration_minutes),sort_order:Number(d.sort_order)||0}),c(!1)},g=v=>{const j=a.find(_=>_.id===v);return j?`Week ${j.week_number}`:"Unassigned"},b=sgt(d.video_url);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"On-demand videos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your program's video library. Paste a YouTube, Vimeo or Loom link and it plays inline in the member workspace, grouped by week, with completion tracking."})]}),e.jsxs(B,{onClick:h,children:[e.jsx(As,{className:"mr-1.5 h-4 w-4"})," Add video"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading library…"}):r.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Ph,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No on-demand videos yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add training videos members can watch any time — assign each one to a week to build the roadmap."})]})}):e.jsx("div",{className:"space-y-3",children:r.map(v=>e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ae,{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(ze,{variant:"secondary",children:g(v.week_id)}),v.status!=="published"&&e.jsx(ze,{variant:"outline",className:"capitalize",children:v.status}),v.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v.duration_minutes," min"]}):null]}),v.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[v.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3 w-3"})," Video"]}):e.jsx("span",{className:"text-muted-foreground",children:"No video link"}),v.worksheet_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>p(v),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{confirm(`Remove "${v.title}"?`)&&l.mutate(v.id)},children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})},v.id))}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:d.id?"Edit video":"Add an on-demand video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Title"}),e.jsx(ge,{placeholder:"How to script a 30-second listing reel",value:d.title,onChange:v=>u({...d,title:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video link"}),e.jsx(ge,{placeholder:"https://youtu.be/… , Vimeo or Loom URL",value:d.video_url,onChange:v=>u({...d,video_url:v.target.value})}),d.video_url&&!b&&e.jsx("p",{className:"text-xs text-muted-foreground",children:`We can't embed this link — members will get an "Open video" button instead.`})]}),b&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:b,title:"Video preview",className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Week"}),e.jsxs(us,{value:d.week_id,onValueChange:v=>u({...d,week_id:v}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"Unassigned (library)"}),a.map(v=>e.jsxs(Ze,{value:v.id,children:["Week ",v.week_number," — ",v.title]},v.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Length (minutes)"}),e.jsx(ge,{type:"number",value:d.duration_minutes,onChange:v=>u({...d,duration_minutes:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(us,{value:d.status,onValueChange:v=>u({...d,status:v}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"published",children:"Published (visible)"}),e.jsx(Ze,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ze,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Order"}),e.jsx(ge,{type:"number",value:d.sort_order,onChange:v=>u({...d,sort_order:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Summary"}),e.jsx(Ts,{rows:3,value:d.summary,onChange:v=>u({...d,summary:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Worksheet / download link"}),e.jsx(ge,{value:d.worksheet_url,onChange:v=>u({...d,worksheet_url:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Action assignment"}),e.jsx(Ts,{rows:2,placeholder:"Post one reel using this hook before your next mastermind.",value:d.action_assignment,onChange:v=>u({...d,action_assignment:v.target.value})})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:f,disabled:i.isPending,children:[i.isPending&&e.jsx(ss,{className:"mr-1.5 h-4 w-4 animate-spin"}),d.id?"Save video":"Add video"]})})]})})]})},HVe={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},cfs=({programId:s})=>{const{data:t=[],isLoading:n}=jps(s),r=Nps(s),a=kps(),[i,l]=N.useState(!1),[o,c]=N.useState({...HVe}),[d,u]=N.useState(!1),h=N.useRef(null),p=Array.from(new Set(t.map(j=>j.category))).filter(Boolean),f=()=>{c({...HVe,sort_order:t.length}),l(!0)},g=j=>{c({id:j.id,title:j.title,description:j.description||"",category:j.category||"Resources",resource_kind:j.resource_kind,url:j.url||"",file_path:j.file_path||"",status:j.status,sort_order:j.sort_order}),l(!0)},b=async j=>{if(!(!j||!s)){if(j.size>50*1024*1024)return ae.error("File must be under 50MB");u(!0);try{const _=j.name.split(".").pop()||"pdf",S=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${_}`,{error:A}=await q.storage.from(vIe).upload(S,j,{contentType:j.type||"application/pdf",upsert:!1});if(A)throw A;c(T=>({...T,file_path:S,url:"",title:T.title||j.name.replace(/\.[^.]+$/,""),resource_kind:j.type==="application/pdf"?"pdf":T.resource_kind})),ae.success("File uploaded")}catch(_){ae.error(_.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},v=async()=>{if(!o.title.trim())return ae.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return ae.error("Upload a file or paste a link");await r.mutateAsync({...o,sort_order:Number(o.sort_order)||0}),l(!1)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Resources"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload PDFs, worksheets and checklists — or link to Canva/Google templates. Enrollees see them grouped by category in their program dashboard."})]}),e.jsxs(B,{onClick:f,children:[e.jsx(As,{className:"mr-1.5 h-4 w-4"})," Add resource"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading resources…"}):t.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Nr,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No resources yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the swipe files, scripts and worksheets that make this program feel premium."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(j=>{const _=ngt(j);return e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ae,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:j.title}),e.jsx(ze,{variant:"secondary",children:j.category}),e.jsx(ze,{variant:"outline",className:"capitalize",children:j.resource_kind.replace("_"," ")}),j.status!=="published"&&e.jsx(ze,{variant:"outline",className:"capitalize",children:j.status})]}),j.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:j.description}),_&&e.jsxs("a",{href:_,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(tr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(j),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm(`Remove "${j.title}"?`)&&a.mutate(j)},children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})]})},j.id)})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{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(se,{children:"Title"}),e.jsx(ge,{value:o.title,onChange:j=>c({...o,title:j.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{rows:2,value:o.description,onChange:j=>c({...o,description:j.target.value}),placeholder:"What this is and how to use it"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsx(ge,{value:o.category,onChange:j=>c({...o,category:j.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:p.map(j=>e.jsx("option",{value:j},j))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Type"}),e.jsxs(us,{value:o.resource_kind,onValueChange:j=>c({...o,resource_kind:j}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:wps.map(j=>e.jsx(Ze,{value:j.value,children:j.label},j.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(se,{children:"File"}),e.jsx("input",{ref:h,type:"file",className:"hidden",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.zip,image/*",onChange:j=>{var _;return b((_=j.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(B,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{var j;return(j=h.current)==null?void 0:j.click()},disabled:d,children:[d?e.jsx(ss,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Sa,{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(ge,{value:o.url,onChange:j=>c({...o,url:j.target.value,file_path:""}),placeholder:"https://…",disabled:!!o.file_path})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Status"}),e.jsxs(us,{value:o.status,onValueChange:j=>c({...o,status:j}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"published",children:"Published (visible)"}),e.jsx(Ze,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ze,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Sort order"}),e.jsx(ge,{type:"number",value:o.sort_order,onChange:j=>c({...o,sort_order:j.target.value})})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:v,disabled:r.isPending||d,children:[r.isPending&&e.jsx(ss,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},dfs=({programId:s})=>{const{data:t=[],isLoading:n}=Tps(s),r=N.useMemo(()=>{const l=Date.now()-6048e5;return t.filter(o=>new Date(o.created_at).getTime()>=l).length},[t]),a=t.map(l=>l.email).filter(Boolean).join(", "),i=()=>{const l=`Name,Email,Phone,Brokerage,Joined `,o=t.map(u=>[u.full_name,u.email,u.phone,u.brokerage,u.created_at].map(h=>`"${(h??"").toString().replace(/"/g,'""')}"`).join(",")).join(` `),c=URL.createObjectURL(new Blob([l+o],{type:"text/csv"})),d=document.createElement("a");d.href=c,d.download="program-interest.csv",d.click(),URL.revokeObjectURL(c)};return n?e.jsx(Ws,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"flex items-center gap-3 p-4",children:[e.jsx(KS,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:t.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On the notify list"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"flex items-center gap-3 p-4",children:[e.jsx(_n,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:r}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signed up in last 7 days"})]})]})}),e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center gap-3 p-4",children:e.jsxs(ze,{variant:"secondary",children:[t.filter(l=>l.notified_at).length," notified"]})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:!a,onClick:()=>{navigator.clipboard.writeText(a),ae.success("Emails copied")},children:[e.jsx(ta,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs(B,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(Da,{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(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Member"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Phone"}),e.jsx(Ct,{children:"Brokerage"}),e.jsx(Ct,{children:"Joined"})]})}),e.jsx(pa,{children:t.map(l=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:l.full_name||"—"}),e.jsx(ut,{children:l.email||"—"}),e.jsx(ut,{children:l.phone||"—"}),e.jsx(ut,{children:l.brokerage||"—"}),e.jsx(ut,{className:"text-muted-foreground",children:Vl(l.created_at)})]},l.id))})]})})]})},GVe={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:""},ufs=()=>{const s=Gt(),[t,n]=N.useState(null),[r,a]=N.useState(!1),[i,l]=N.useState({...GVe}),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState(null),{data:f=[],isLoading:g}=lt({queryKey:["admin-programs"],queryFn:async()=>{const{data:M,error:F}=await q.from("programs").select("*").order("created_at",{ascending:!1});if(F)throw F;return M||[]}}),b=f.find(M=>M.id===t)||f[0]||null,{data:v=[]}=lt({queryKey:["admin-program-enrollments",b==null?void 0:b.id],enabled:!!(b!=null&&b.id),queryFn:async()=>{const{data:M,error:F}=await q.from("program_enrollments").select("*").eq("program_id",b.id).order("created_at",{ascending:!1});if(F)throw F;const z=(M||[]).map(K=>K.user_id),{data:V}=z.length?await q.from("profiles").select("id, name, email").in("id",z):{data:[]},W=new Map((V||[]).map(K=>[K.id,K]));return(M||[]).map(K=>({...K,profile:W.get(K.user_id)}))}}),{data:j=[]}=lt({queryKey:["admin-program-intakes",b==null?void 0:b.id],enabled:!!(b!=null&&b.id),queryFn:async()=>{const{data:M,error:F}=await q.from("program_intake_responses").select("*").eq("program_id",b.id);if(F)throw F;return M||[]}}),{data:_=[]}=lt({queryKey:["admin-program-audit",b==null?void 0:b.id],enabled:!!(b!=null&&b.id),queryFn:async()=>{const{data:M,error:F}=await q.from("program_audit_logs").select("*").eq("program_id",b.id).order("created_at",{ascending:!1}).limit(100);if(F)throw F;return M||[]}}),S=async()=>{c(!0);try{const M={...i,slug:i.slug||i.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),kickoff_at:i.kickoff_at||null,charge_at:i.charge_at||null,enrollment_close_at:i.enrollment_close_at||null},{error:F}=await q.from("programs").insert(M);if(F)throw F;ae.success("Program created"),a(!1),l({...GVe}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(M){ae.error(M.message||"Could not create the program")}finally{c(!1)}},A=async M=>{if(!b)return;const{error:F}=await q.from("programs").update(M).eq("id",b.id);if(F)return ae.error(F.message);s.invalidateQueries({queryKey:["admin-programs"]})},T=async(M,F)=>{const{error:z}=await q.from("program_enrollments").update(F).eq("id",M);if(z)return ae.error(z.message);ae.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},D=async M=>{u(!0);const{data:F,error:z}=await q.functions.invoke("program-charge-due",{body:M?{enrollment_id:M}:{}});if(u(!1),z||F!=null&&F.error)return ae.error((F==null?void 0:F.error)||(z==null?void 0:z.message));ae.success(`Processed ${(F==null?void 0:F.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},L=M=>M==="paid"||M==="completed"?"default":M==="payment_failed"?"destructive":"secondary";return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-7xl space-y-6 p-4 md:p-8",children:[e.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Programs"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage cohorts, enrollments, delayed billing and program content."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>D(),disabled:d,children:[d?e.jsx(ss,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ff,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(bs,{open:r,onOpenChange:a,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(As,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(vs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Name"}),e.jsx(ge,{value:i.name,onChange:M=>l({...i,name:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Slug (URL)"}),e.jsx(ge,{placeholder:"reel-estate-90",value:i.slug,onChange:M=>l({...i,slug:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subtitle"}),e.jsx(ge,{value:i.subtitle,onChange:M=>l({...i,subtitle:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{rows:4,value:i.description,onChange:M=>l({...i,description:M.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"One-time price (USD)"}),e.jsx(ge,{type:"number",value:i.price_cents/100,onChange:M=>l({...i,price_cents:Math.round(Number(M.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(se,{children:"Seats"}),e.jsx(ge,{type:"number",value:i.capacity,onChange:M=>l({...i,capacity:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Weeks"}),e.jsx(ge,{type:"number",value:i.duration_weeks,onChange:M=>l({...i,duration_weeks:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Videos per week"}),e.jsx(ge,{type:"number",value:i.weekly_video_goal,onChange:M=>l({...i,weekly_video_goal:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Billing"}),e.jsxs(us,{value:i.payment_mode,onValueChange:M=>l({...i,payment_mode:M}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"delayed",children:"Save card, charge later"}),e.jsx(Ze,{value:"immediate",children:"Charge at checkout"}),e.jsx(Ze,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Kickoff"}),e.jsx(ge,{type:"datetime-local",value:i.kickoff_at,onChange:M=>l({...i,kickoff_at:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Charge date"}),e.jsx(ge,{type:"datetime-local",value:i.charge_at,onChange:M=>l({...i,charge_at:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Enrollment closes"}),e.jsx(ge,{type:"datetime-local",value:i.enrollment_close_at,onChange:M=>l({...i,enrollment_close_at:M.target.value})})]})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:S,disabled:o||!i.name,children:[o&&e.jsx(ss,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),g?e.jsx(Ws,{className:"h-40 w-full rounded-xl"}):f.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsx(Ae,{className:"p-12 text-center text-sm text-muted-foreground",children:"No programs yet. Create your first cohort to get started."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(M=>e.jsxs(B,{variant:(b==null?void 0:b.id)===M.id?"default":"outline",size:"sm",onClick:()=>n(M.id),children:[M.name,e.jsx(ze,{variant:"secondary",className:"ml-2 capitalize",children:M.status})]},M.id))}),b&&e.jsxs($r,{defaultValue:"overview",children:[e.jsxs(Ur,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Zt,{value:"overview",children:"Overview"}),e.jsx(Zt,{value:"details",children:"Details & pricing"}),e.jsx(Zt,{value:"sessions",children:"Live sessions"}),e.jsx(Zt,{value:"videos",children:"On-demand videos"}),e.jsx(Zt,{value:"resources",children:"Resources"}),e.jsx(Zt,{value:"intake-form",children:"Intake form"}),e.jsx(Zt,{value:"discounts",children:"Discount codes"}),e.jsx(Zt,{value:"experience",children:"Enrollee experience"}),e.jsx(Zt,{value:"interest",children:"Interest list"}),e.jsxs(Zt,{value:"enrollments",children:["Enrollments (",v.length,")"]}),e.jsxs(Zt,{value:"intake",children:["Intake (",j.length,")"]}),e.jsx(Zt,{value:"audit",children:"Audit"})]}),e.jsxs(ls,{value:"overview",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Seats filled"}),e.jsxs("p",{className:"mt-1 text-2xl font-bold",children:[v.filter(M=>["reserved","scheduled_for_charge","paid","completed"].includes(M.status)).length,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",b.capacity]})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Paid"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:v.filter(M=>M.status==="paid").length})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Failed payments"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:v.filter(M=>M.status==="payment_failed").length})]})}),e.jsx(fe,{children:e.jsxs(Ae,{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:Iu(v.filter(M=>["scheduled_for_charge","paid","completed"].includes(M.status)).reduce((M,F)=>M+(F.amount_cents||0),0),b.currency)})]})})]}),e.jsx(fe,{children:e.jsxs(Ae,{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(vn,{checked:b.status==="published",onCheckedChange:M=>A({status:M?"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(vn,{checked:b.is_featured,onCheckedChange:M=>A({is_featured:M})})]}),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:Iu(b.price_cents,b.currency)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"font-medium",children:Vl(b.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:Vl(b.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(ls,{value:"details",className:"mt-6",children:e.jsx(Xps,{program:b,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(ls,{value:"sessions",className:"mt-6",children:e.jsx(ofs,{programId:b.id})}),e.jsx(ls,{value:"videos",className:"mt-6",children:e.jsx(lfs,{programId:b.id})}),e.jsx(ls,{value:"resources",className:"mt-6",children:e.jsx(cfs,{programId:b.id})}),e.jsx(ls,{value:"discounts",className:"mt-6",children:e.jsx(efs,{program:b})}),e.jsx(ls,{value:"intake-form",className:"mt-6",children:e.jsx(rfs,{program:b,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(ls,{value:"experience",className:"mt-6",children:e.jsx(tfs,{program:b})}),e.jsx(ls,{value:"interest",className:"mt-6",children:e.jsx(dfs,{programId:b.id})}),e.jsx(ls,{value:"enrollments",className:"mt-6",children:e.jsx(fe,{children:e.jsx(Ae,{className:"overflow-x-auto p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Member"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Charge date"}),e.jsx(Ct,{children:"Amount"}),e.jsx(Ct,{children:"Access"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsxs(pa,{children:[v.length===0&&e.jsx(Gs,{children:e.jsxs(ut,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(_n,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),v.map(M=>{var F,z;return e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("button",{type:"button",className:"text-left hover:underline",onClick:()=>p(M),children:[e.jsx("p",{className:"font-medium",children:((F=M.profile)==null?void 0:F.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(z=M.profile)==null?void 0:z.email})]})}),e.jsxs(ut,{children:[e.jsx(ze,{variant:L(M.status),className:"capitalize",children:String(M.status).replace(/_/g," ")}),M.last_payment_error&&e.jsx("p",{className:"mt-1 max-w-[200px] truncate text-xs text-destructive",children:M.last_payment_error})]}),e.jsx(ut,{className:"text-sm",children:Vl(M.charge_scheduled_at)||"—"}),e.jsx(ut,{className:"text-sm",children:Iu(M.amount_cents,M.currency)}),e.jsx(ut,{children:e.jsx(vn,{checked:M.access_override,onCheckedChange:V=>T(M.id,{access_override:V})})}),e.jsxs(ut,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(M.status)&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>D(M.id),disabled:d,children:[e.jsx(Ai,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(M.status)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>T(M.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},M.id)})]})]})})})}),e.jsxs(ls,{value:"intake",className:"mt-6 space-y-3",children:[j.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No intake responses yet."}),j.map(M=>e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-2 p-5 text-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-semibold",children:M.full_name||M.email||"Member"}),M.instagram_handle&&e.jsx(ze,{variant:"outline",children:M.instagram_handle}),M.city&&e.jsx("span",{className:"text-xs text-muted-foreground",children:M.city})]}),M.primary_goal&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Goal: "}),M.primary_goal]}),e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-1 text-xs text-muted-foreground",children:[M.years_experience&&e.jsxs("span",{children:["Experience: ",M.years_experience]}),M.video_comfort&&e.jsxs("span",{children:["On camera: ",M.video_comfort]}),M.posting_frequency&&e.jsxs("span",{children:["Posts: ",M.posting_frequency]})]})]})},M.id))]}),e.jsx(ls,{value:"audit",className:"mt-6",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"space-y-2 p-5 text-sm",children:[_.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No activity yet."}),_.map(M=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 py-2 last:border-0",children:[e.jsx(ze,{variant:"outline",className:"capitalize",children:String(M.action).replace(/_/g," ")}),e.jsx("span",{className:"text-muted-foreground",children:M.actor_label||"system"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:Vl(M.created_at,!0)})]},M.id))]})})})]}),b&&e.jsx(Jps,{program:b,enrollment:h,open:!!h,onOpenChange:M=>!M&&p(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},hfs=()=>{const{user:s}=gs(),[t,n]=N.useState(""),[r,a]=N.useState("all"),{data:i=[]}=lt({queryKey:["academy-categories"],queryFn:async()=>{const{data:p,error:f}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(f)throw f;return p}}),{data:l=[],isLoading:o}=lt({queryKey:["academy-videos"],queryFn:async()=>{const{data:p,error:f}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(f)throw f;const{data:g,error:b}=await q.from("academy_resources").select("*").order("sort_order");if(b)throw b;return p.map(j=>({...j,resources:(g==null?void 0:g.filter(_=>_.video_id===j.id))||[]}))}}),{data:c=[]}=lt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:p,error:f}=await q.from("academy_video_likes").select("video_id, user_id");if(f)throw f;return p}}),d=l.filter(p=>{var b;const f=t===""||p.title.toLowerCase().includes(t.toLowerCase())||((b=p.description)==null?void 0:b.toLowerCase().includes(t.toLowerCase())),g=r==="all"||p.category_id===r;return f&&g}),u=p=>c.filter(f=>f.video_id===p).length,h=p=>c.some(f=>f.video_id===p&&f.user_id===(s==null?void 0:s.id));return e.jsx(Cs,{title:"Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Academy"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"On-demand training videos and resources"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search videos...",value:t,onChange:p=>n(p.target.value),className:"pl-10"})]})}),e.jsx($r,{value:r,onValueChange:a,children:e.jsxs(Ur,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Zt,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(p=>e.jsx(Zt,{value:p.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:p.name},p.id))]})}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(vr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No videos found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:t?"Try adjusting your search terms":"Check back soon for new content"})]})}):e.jsx("div",{className:"grid gap-6 sm:grid-cols-2 lg:grid-cols-3",children:d.map(p=>e.jsx(Ln,{to:`/academy/${p.id}`,children:e.jsxs(fe,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",children:[p.thumbnail_url?e.jsx("img",{src:p.thumbnail_url,alt:p.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(vr,{className:"h-12 w-12 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/90 flex items-center justify-center",children:e.jsx(Al,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),p.duration&&e.jsxs("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),p.duration]})]}),e.jsxs(Mt,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(Pt,{className:"text-lg line-clamp-2",children:p.title})}),p.category&&e.jsx(ze,{variant:"secondary",className:"w-fit",children:p.category.name})]}),e.jsxs(Ae,{className:"pt-0",children:[p.description&&e.jsx(Hn,{className:"line-clamp-2",children:p.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hm,{className:`h-4 w-4 ${h(p.id)?"fill-primary text-primary":""}`}),u(p.id)]}),p.resources&&p.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nr,{className:"h-4 w-4"}),p.resources.length]})]})]})]})},p.id))})]})})};function ggt({resourceType:s,resourceId:t}){const{data:n=[]}=lt({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:r,error:a}=await q.from("academy_video_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("video_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:r,error:a}=await q.from("resource_kit_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("kit_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}},enabled:!!t});return n.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-sm",children:[e.jsx(xl,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(Ln,{to:`/templates/${r.id}`,children:e.jsxs(ze,{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(xl,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const mfs=(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},pfs=()=>{const{videoId:s}=_i();In();const{user:t,isAdmin:n}=gs(),{toast:r}=Ua(),a=Gt(),{trackEngagement:i}=QD(),[l,o]=N.useState(""),{data:c,isLoading:d}=lt({queryKey:["academy-video",s],queryFn:async()=>{const{data:S,error:A}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:T}=await q.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...S,resources:T||[]}},enabled:!!s});N.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=lt({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:S,error:A}=await q.from("academy_video_likes").select("*").eq("video_id",s);if(A)throw A;return S},enabled:!!s}),{data:h=[]}=lt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:S,error:A}=await q.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(A)throw A;const T=[...new Set(S.map(M=>M.user_id))],{data:D}=await q.from("profiles").select("id, name").in("id",T),L=new Map((D==null?void 0:D.map(M=>[M.id,M.name]))||[]);return S.map(M=>({...M,user_name:L.get(M.user_id)||"Unknown User"}))},enabled:!!s}),p=gt({mutationFn:async S=>{const{error:A}=await q.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:S});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),r({title:"Comment added!"})},onError:S=>{r({title:"Error adding comment",description:S.message,variant:"destructive"})}}),f=gt({mutationFn:async S=>{const{error:A}=await q.from("academy_video_comments").delete().eq("id",S);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),g=gt({mutationFn:async()=>{const S=u.find(A=>A.user_id===(t==null?void 0:t.id));if(S){const{error:A}=await q.from("academy_video_likes").delete().eq("id",S.id);if(A)throw A}else{const{error:A}=await q.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),b=u.some(S=>S.user_id===(t==null?void 0:t.id)),v=S=>{switch(S==null?void 0:S.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},j=S=>S.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),_=S=>{S.preventDefault(),!(!l.trim()||!t)&&p.mutate(l.trim())};return d?e.jsx(Cs,{title:"Academy",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(Cs,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Ln,{to:"/academy",children:[e.jsx(Wr,{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:mfs(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(vr,{className:"h-16 w-16 opacity-50"}),e.jsx(B,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(tr,{className:"h-4 w-4"}),"Open Video"]})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.title}),c.category&&e.jsx(ze,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(B,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Ln,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(ja,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(tR,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(B,{variant:b?"default":"outline",className:"gap-2 w-fit",onClick:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(Hm,{className:`h-4 w-4 ${b?"fill-current":""}`}),u.length," ",u.length===1?"Like":"Likes"]})]})]}),c.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:c.description}})]}),c.resources&&c.resources.length>0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(S=>e.jsxs("a",{href:S.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors",children:[e.jsx("span",{className:"text-2xl",children:v(S.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:S.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:S.file_type})]}),e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),e.jsx(ggt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ql,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:_,className:"flex gap-2",children:[e.jsx(Ts,{placeholder:"Add a comment...",value:l,onChange:S=>o(S.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||p.isPending,children:e.jsx(cr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:h.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(S=>e.jsx(fe,{children:e.jsx(Ae,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(aa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(ia,{className:"text-sm",children:j(S.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:S.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Go(new Date(S.created_at),{addSuffix:!0})}),S.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(S.id),children:e.jsx(bn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:S.content})]})]})})},S.id))})]})]})}):e.jsx(Cs,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(vr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Video not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This video may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(Ln,{to:"/academy",children:"Back to Academy"})})]})})},EI="https://dashboard.relevelup.com",ffs=(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},xfs=[{icon:Pu,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:ph,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:_n,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:vo,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function gfs(){var i;const{slug:s}=_i(),{data:t,isLoading:n,error:r}=lt({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await q.from("academy_videos").select("id, title, description, video_url, video_type, thumbnail_url, duration, category:academy_categories(name)").eq("public_slug",s).eq("is_public",!0).maybeSingle();if(o)throw o;return l},enabled:!!s});N.useEffect(()=>{if(t&&s){q.rpc("increment_academy_public_view",{_slug:s}),document.title=`${t.title} | LevelUp Academy`;const l=(t.description||"").replace(/<[^>]+>/g,"").slice(0,155),o=document.querySelector('meta[name="description"]');if(o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy."),t.thumbnail_url){let c=document.querySelector('meta[property="og:image"]');c||(c=document.createElement("meta"),c.setAttribute("property","og:image"),document.head.appendChild(c)),c.setAttribute("content",t.thumbnail_url)}}},[t,s]);const a=N.useMemo(()=>t?ffs(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:EI,children:e.jsx(B,{className:"bg-[#406E71] hover:bg-[#4d8285] text-white",children:"Go to LevelUp"})})]}):e.jsxs("div",{className:"min-h-screen bg-[#0a1520] text-[#e8ecf1] overflow-x-hidden",children:[e.jsxs("div",{className:"pointer-events-none fixed inset-0 z-0",children:[e.jsx("div",{className:"absolute -top-40 -left-40 w-[600px] h-[600px] rounded-full bg-[#406E71]/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/2 -right-40 w-[500px] h-[500px] rounded-full bg-[#2a4c64]/30 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 left-1/3 w-[400px] h-[400px] rounded-full bg-[#406E71]/10 blur-3xl"})]}),e.jsx("header",{className:"relative z-10 border-b border-white/5 backdrop-blur-sm bg-[#0a1520]/70",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] flex items-center justify-center",children:e.jsx(un,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-lg tracking-tight",children:"LevelUp"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-[#5a9ea1] -mt-1",children:"Academy"})]})]}),e.jsx("a",{href:EI,children:e.jsx(B,{variant:"ghost",className:"text-[#e8ecf1] hover:bg-white/5 hover:text-white",children:"Sign In"})})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pt-12 pb-16",children:[e.jsxs("div",{className:"text-center mb-8 space-y-4",children:[e.jsxs(ze,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(Pu,{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(nx,{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:EI,className:"w-full sm:w-auto",children:e.jsxs(B,{size:"lg",className:"w-full sm:w-auto bg-[#f5f0e0] hover:bg-white text-[#0d1b26] font-semibold text-base h-12 px-8 shadow-xl",children:["Start Free Trial",e.jsx(za,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:EI,className:"w-full sm:w-auto",children:e.jsx(B,{size:"lg",variant:"outline",className:"w-full sm:w-auto bg-transparent border-white/20 text-white hover:bg-white/10 hover:text-white h-12 px-8",children:"Join LevelUp"})})]}),e.jsx("p",{className:"text-xs text-[#7a8a99] mt-5",children:"No credit card required to preview the platform"})]})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pb-20",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.25em] text-[#5a9ea1] mb-2",children:"What's inside"}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold",children:"Built for agents who want more"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:xfs.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(xr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:EI,children:e.jsxs(B,{size:"lg",className:"bg-[#406E71] hover:bg-[#4d8285] text-white h-12 px-10 shadow-lg",children:["Get Started at LevelUp",e.jsx(za,{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:EI,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function yfs(){const s=In(),[t,n]=N.useState(""),{data:r,isLoading:a}=lt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(g)throw g;return f}}),{data:i}=lt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(g)throw g;return f}}),{data:l}=lt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kit_likes").select("kit_id");if(g)throw g;return f}}),{data:o}=lt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kit_comments").select("kit_id");if(g)throw g;return f}}),c=r==null?void 0:r.filter(f=>{var g;return f.name.toLowerCase().includes(t.toLowerCase())||((g=f.description)==null?void 0:g.toLowerCase().includes(t.toLowerCase()))}),d=f=>(i==null?void 0:i.filter(g=>g.kit_id===f))||[],u=f=>(l==null?void 0:l.filter(g=>g.kit_id===f).length)||0,h=f=>(o==null?void 0:o.filter(g=>g.kit_id===f).length)||0,p=f=>{s(`/toolbox/${f}`)};return e.jsx(Cs,{title:"Toolbox",description:"Download resource kits and tools to help grow your business",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Toolbox"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Download resource kits and tools to help grow your business"})]}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search resource kits...",value:t,onChange:f=>n(f.target.value),className:"pl-10"})]}),!a&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(c==null?void 0:c.length)||0," resource kit",(c==null?void 0:c.length)!==1?"s":""," available"]}),a?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((f,g)=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"}),e.jsx(Ws,{className:"h-4 w-2/3"})]})},g))}):(c==null?void 0:c.length)===0?e.jsxs(fe,{className:"p-12 text-center",children:[e.jsx(Oc,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resource kits found"}),e.jsx("p",{className:"text-muted-foreground",children:t?"Try adjusting your search terms":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:c==null?void 0:c.map(f=>{const g=d(f.id).length,b=u(f.id),v=h(f.id);return e.jsxs(fe,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>p(f.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:f.featured_image_url?e.jsx("img",{src:f.featured_image_url,alt:f.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Oc,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Ae,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:f.name}),f.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:tB(f.description)}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nr,{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(Hm,{className:"h-3.5 w-3.5"}),b]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),v]})]})]})]})]},f.id)})})]})})}const vfs=()=>{const{kitId:s}=_i(),{user:t,isAdmin:n}=gs(),{toast:r}=Ua(),a=Gt(),{trackEngagement:i}=QD(),[l,o]=N.useState(""),{data:c,isLoading:d}=lt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:S,error:A}=await q.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:T}=await q.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:D}=await q.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...S,files:T||[],links:D||[]}},enabled:!!s});N.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=lt({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:S,error:A}=await q.from("resource_kit_likes").select("*").eq("kit_id",s);if(A)throw A;return S},enabled:!!s}),{data:h=[]}=lt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:S,error:A}=await q.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(A)throw A;const T=[...new Set(S.map(M=>M.user_id))],{data:D}=await q.from("profiles").select("id, name").in("id",T),L=new Map((D==null?void 0:D.map(M=>[M.id,M.name]))||[]);return S.map(M=>({...M,user_name:L.get(M.user_id)||"Unknown User"}))},enabled:!!s}),p=gt({mutationFn:async S=>{const{error:A}=await q.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:S});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),r({title:"Comment added!"})},onError:S=>{r({title:"Error adding comment",description:S.message,variant:"destructive"})}}),f=gt({mutationFn:async S=>{const{error:A}=await q.from("resource_kit_comments").delete().eq("id",S);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),g=gt({mutationFn:async()=>{const S=u.find(A=>A.user_id===(t==null?void 0:t.id));if(S){const{error:A}=await q.from("resource_kit_likes").delete().eq("id",S.id);if(A)throw A}else{const{error:A}=await q.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),b=u.some(S=>S.user_id===(t==null?void 0:t.id)),v=S=>S.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),j=S=>S?S<1024?S+" B":S<1024*1024?(S/1024).toFixed(1)+" KB":(S/(1024*1024)).toFixed(1)+" MB":"",_=S=>{S.preventDefault(),!(!l.trim()||!t)&&p.mutate(l.trim())};return d?e.jsx(Cs,{title:"Toolbox",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(Cs,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Ln,{to:"/toolbox",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Back to Toolbox"]})}),c.featured_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.featured_image_url,alt:c.name,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.name})}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsx(B,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Ln,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(ja,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(tR,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs(B,{variant:b?"default":"outline",className:"gap-2 rounded-full",onClick:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(Hm,{className:`h-4 w-4 ${b?"fill-current":""}`}),u.length," ",u.length===1?"Like":"Likes"]})]})]}),c.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:c.description}})]}),c.files&&c.files.length>0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(S=>e.jsxs("a",{href:S.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_pdf"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Nr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:S.name}),S.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:j(S.file_size)})]})]}),e.jsx(Da,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},S.id))})]})}),c.links&&c.links.length>0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(tr,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(S=>e.jsxs("a",{href:S.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_canva"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-purple-500/10",children:e.jsx(tr,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:S.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},S.id))})]})}),e.jsx(ggt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ql,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:_,className:"flex gap-2",children:[e.jsx(Ts,{placeholder:"Add a comment...",value:l,onChange:S=>o(S.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||p.isPending,children:e.jsx(cr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:h.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(S=>e.jsx(fe,{children:e.jsx(Ae,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(aa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(ia,{className:"text-sm",children:v(S.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:S.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Go(new Date(S.created_at),{addSuffix:!0})}),S.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(S.id),children:e.jsx(bn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:S.content})]})]})})},S.id))})]})]})}):e.jsx(Cs,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Oc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource kit not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource kit may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(Ln,{to:"/toolbox",children:"Back to Toolbox"})})]})})},bfs=()=>{const s=In(),[t,n]=N.useState(""),[r,a]=N.useState("grid"),{data:i=[],isLoading:l}=lt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await q.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:h,error:p}=await q.from("social_swag_links").select("*").order("sort_order");if(p)throw p;const{data:f}=await q.from("social_swag_likes").select("swag_id"),{data:g}=await q.from("social_swag_comments").select("swag_id"),b=new Map;f==null||f.forEach(_=>{b.set(_.swag_id,(b.get(_.swag_id)||0)+1)});const v=new Map;return g==null||g.forEach(_=>{v.set(_.swag_id,(v.get(_.swag_id)||0)+1)}),(d||[]).map(_=>({..._,links:(h||[]).filter(S=>S.swag_id===_.id)||[],likesCount:b.get(_.id)||0,commentsCount:v.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(Cs,{title:"Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Social Swag"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse our collection of social media content and graphics"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search social swag...",value:t,onChange:d=>n(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(vf,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Ep,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," item",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((d,u)=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"})]})},u))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No items match your search":"No social swag available yet"}),t&&e.jsx(B,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(d=>e.jsxs(fe,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${r==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[d.preview_image_url?e.jsx("img",{src:d.preview_image_url,alt:d.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),d.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(ze,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(tl,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Ae,{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(Hm,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:u=>{u.stopPropagation(),c(d.id)},children:[e.jsx(tr,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var ao=function(){return ao=Object.assign||function(t){for(var n,r=1,a=arguments.length;r1&&(c||!d),h=t>1&&(d||!c),p=function(){r&&i(r)},f=function(){a&&i(a)};return e.jsx(Jfs,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:p,onNextClick:f})}function exs(s){var t,n=kd(),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:bgt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(WVe,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(WVe,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(KVe,{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(KVe,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function txs(s){var t=kd(),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 sxs(s,t,n){for(var r=n?fN(new Date):Km(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Ul(r,i);a.push(l)}return a}function nxs(){var s=kd(),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=sxs(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 rxs(){var s,t=kd(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:nxs;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function axs(s){var t=kd(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var NIe=N.createContext(void 0);function ixs(s){if(!_U(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(NIe.Provider,{value:t,children:s.children})}return e.jsx(oxs,{initialProps:s.initialProps,children:s.children})}function oxs(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var p,f;(p=t.onDayClick)===null||p===void 0||p.call(t,d,u,h);var g=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!g){var b=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!b){var v=r?ygt([],r):[];if(u.selected){var j=v.findIndex(function(_){return Rl(d,_)});v.splice(j,1)}else v.push(d);(f=t.onSelect)===null||f===void 0||f.call(t,v,d,u,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var u=i&&r.length>i-1,h=r.some(function(p){return Rl(p,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(NIe.Provider,{value:c,children:n})}function kIe(){var s=N.useContext(NIe);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function lxs(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?Rl(a,s)&&Rl(r,s)?void 0:Rl(a,s)?{from:a,to:void 0}:Rl(r,s)?void 0:Uv(r,s)?{from:s,to:a}:{from:r,to:s}:a?Uv(s,a)?{from:a,to:s}:{from:s,to:a}:r?jb(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var SIe=N.createContext(void 0);function cxs(s){if(!wU(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(SIe.Provider,{value:t,children:s.children})}return e.jsx(dxs,{initialProps:s.initialProps,children:s.children})}function dxs(s){var t=s.initialProps,n=s.children,r=t.selected,a=r||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(f,g,b){var v,j;(v=t.onDayClick)===null||v===void 0||v.call(t,f,g,b);var _=lxs(f,r);(j=t.onSelect)===null||j===void 0||j.call(t,_,f,g,b)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],Rl(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:Y9(i,o-1),before:Ul(i,o-1)}),i&&l&&u.disabled.push({after:i,before:Ul(i,o-1)}),!i&&l&&u.disabled.push({after:Y9(l,o-1),before:Ul(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:Ul(i,-c+1)}),u.disabled.push({after:Ul(i,c-1)})),i&&l){var h=Wx(l,i)+1,p=c-h;u.disabled.push({before:Y9(i,p)}),u.disabled.push({after:Ul(l,p)})}!i&&l&&(u.disabled.push({before:Ul(l,-c+1)}),u.disabled.push({after:Ul(l,c-1)}))}return e.jsx(SIe.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function CIe(){var s=N.useContext(SIe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function tpe(s){return Array.isArray(s)?ygt([],s):s!==void 0?[s]:[]}function uxs(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=tpe(a)}),t}var Mb;(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"})(Mb||(Mb={}));var hxs=Mb.Selected,l2=Mb.Disabled,mxs=Mb.Hidden,pxs=Mb.Today,k2e=Mb.RangeEnd,S2e=Mb.RangeMiddle,C2e=Mb.RangeStart,fxs=Mb.Outside;function xxs(s,t,n){var r,a=(r={},r[hxs]=tpe(s.selected),r[l2]=tpe(s.disabled),r[mxs]=tpe(s.hidden),r[pxs]=[s.today],r[k2e]=[],r[S2e]=[],r[C2e]=[],r[fxs]=[],r);return s.fromDate&&a[l2].push({before:s.fromDate}),s.toDate&&a[l2].push({after:s.toDate}),_U(s)?a[l2]=a[l2].concat(t.modifiers[l2]):wU(s)&&(a[l2]=a[l2].concat(n.modifiers[l2]),a[C2e]=n.modifiers[C2e],a[S2e]=n.modifiers[S2e],a[k2e]=n.modifiers[k2e]),a}var jgt=N.createContext(void 0);function gxs(s){var t=kd(),n=kIe(),r=CIe(),a=xxs(t,n,r),i=uxs(t.modifiers),l=ao(ao({},a),i);return e.jsx(jgt.Provider,{value:l,children:s.children})}function Ngt(){var s=N.useContext(jgt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function yxs(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function vxs(s){return!!(s&&typeof s=="object"&&"from"in s)}function bxs(s){return!!(s&&typeof s=="object"&&"after"in s)}function _xs(s){return!!(s&&typeof s=="object"&&"before"in s)}function wxs(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function jxs(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=Wx(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=Wx(s,r)>=0&&Wx(a,s)>=0;return l}return a?Rl(a,s):r?Rl(r,s):!1}function Nxs(s){return oMe(s)}function kxs(s){return Array.isArray(s)&&s.every(oMe)}function Sxs(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(Nxs(n))return Rl(s,n);if(kxs(n))return n.includes(s);if(vxs(n))return jxs(s,n);if(wxs(n))return n.dayOfWeek.includes(s.getDay());if(yxs(n)){var r=Wx(n.before,s),a=Wx(n.after,s),i=r>0,l=a<0,o=Uv(n.before,n.after);return o?l&&i:i||l}return bxs(n)?Wx(s,n.after)>0:_xs(n)?Wx(n.before,s)>0:typeof n=="function"?n(s):!1})}function TIe(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return Sxs(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!aU(s,n)&&(a.outside=!0),a}function Cxs(s,t){for(var n=Bd(s[0]),r=H0(s[s.length-1]),a,i,l=n;l<=r;){var o=TIe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Ul(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Ul(l,1)}return i||a}var Txs=365;function kgt(s,t){var n=t.moveBy,r=t.direction,a=t.context,i=t.modifiers,l=t.retry,o=l===void 0?{count:0,lastFocused:s}:l,c=a.weekStartsOn,d=a.fromDate,u=a.toDate,h=a.locale,p={day:Ul,week:F2,month:kf,year:UBt,startOfWeek:function(v){return a.ISOWeek?fN(v):Km(v,{locale:h,weekStartsOn:c})},endOfWeek:function(v){return a.ISOWeek?Bct(v):k8(v,{locale:h,weekStartsOn:c})}},f=p[n](s,r==="after"?1:-1);r==="before"&&d?f=qBt([d,f]):r==="after"&&u&&(f=VBt([u,f]));var g=!0;if(i){var b=TIe(f,i);g=!b.disabled&&!b.hidden}return g?f:o.count>Txs?o.lastFocused:kgt(f,{moveBy:n,direction:r,context:a,modifiers:i,retry:ao(ao({},o),{count:o.count+1})})}var Sgt=N.createContext(void 0);function Exs(s){var t=jU(),n=Ngt(),r=N.useState(),a=r[0],i=r[1],l=N.useState(),o=l[0],c=l[1],d=Cxs(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},p=function(v){i(v)},f=kd(),g=function(v,j){if(a){var _=kgt(a,{moveBy:v,direction:j,context:f,modifiers:n});Rl(a,_)||(t.goToDate(_,a),p(_))}},b={focusedDay:a,focusTarget:u,blur:h,focus:p,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(Sgt.Provider,{value:b,children:s.children})}function EIe(){var s=N.useContext(Sgt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function Axs(s,t){var n=Ngt(),r=TIe(s,n,t);return r}var AIe=N.createContext(void 0);function Mxs(s){if(!gve(s.initialProps)){var t={selected:void 0};return e.jsx(AIe.Provider,{value:t,children:s.children})}return e.jsx(Ixs,{initialProps:s.initialProps,children:s.children})}function Ixs(s){var t=s.initialProps,n=s.children,r=function(i,l,o){var c,d,u;if((c=t.onDayClick)===null||c===void 0||c.call(t,i,l,o),l.selected&&!t.required){(d=t.onSelect)===null||d===void 0||d.call(t,void 0,i,l,o);return}(u=t.onSelect)===null||u===void 0||u.call(t,i,i,l,o)},a={selected:t.selected,onDayClick:r};return e.jsx(AIe.Provider,{value:a,children:n})}function Cgt(){var s=N.useContext(AIe);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function Pxs(s,t){var n=kd(),r=Cgt(),a=kIe(),i=CIe(),l=EIe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,p=l.focus,f=l.focusMonthBefore,g=l.focusMonthAfter,b=l.focusYearBefore,v=l.focusYearAfter,j=l.focusStartOfWeek,_=l.focusEndOfWeek,S=function(oe){var pe,ce,de,ie;gve(n)?(pe=r.onDayClick)===null||pe===void 0||pe.call(r,s,t,oe):_U(n)?(ce=a.onDayClick)===null||ce===void 0||ce.call(a,s,t,oe):wU(n)?(de=i.onDayClick)===null||de===void 0||de.call(i,s,t,oe):(ie=n.onDayClick)===null||ie===void 0||ie.call(n,s,t,oe)},A=function(oe){var pe;p(s),(pe=n.onDayFocus)===null||pe===void 0||pe.call(n,s,t,oe)},T=function(oe){var pe;h(),(pe=n.onDayBlur)===null||pe===void 0||pe.call(n,s,t,oe)},D=function(oe){var pe;(pe=n.onDayMouseEnter)===null||pe===void 0||pe.call(n,s,t,oe)},L=function(oe){var pe;(pe=n.onDayMouseLeave)===null||pe===void 0||pe.call(n,s,t,oe)},M=function(oe){var pe;(pe=n.onDayPointerEnter)===null||pe===void 0||pe.call(n,s,t,oe)},F=function(oe){var pe;(pe=n.onDayPointerLeave)===null||pe===void 0||pe.call(n,s,t,oe)},z=function(oe){var pe;(pe=n.onDayTouchCancel)===null||pe===void 0||pe.call(n,s,t,oe)},V=function(oe){var pe;(pe=n.onDayTouchEnd)===null||pe===void 0||pe.call(n,s,t,oe)},W=function(oe){var pe;(pe=n.onDayTouchMove)===null||pe===void 0||pe.call(n,s,t,oe)},K=function(oe){var pe;(pe=n.onDayTouchStart)===null||pe===void 0||pe.call(n,s,t,oe)},Y=function(oe){var pe;(pe=n.onDayKeyUp)===null||pe===void 0||pe.call(n,s,t,oe)},ee=function(oe){var pe;switch(oe.key){case"ArrowLeft":oe.preventDefault(),oe.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":oe.preventDefault(),oe.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":oe.preventDefault(),oe.stopPropagation(),d();break;case"ArrowUp":oe.preventDefault(),oe.stopPropagation(),u();break;case"PageUp":oe.preventDefault(),oe.stopPropagation(),oe.shiftKey?b():f();break;case"PageDown":oe.preventDefault(),oe.stopPropagation(),oe.shiftKey?v():g();break;case"Home":oe.preventDefault(),oe.stopPropagation(),j();break;case"End":oe.preventDefault(),oe.stopPropagation(),_();break}(pe=n.onDayKeyDown)===null||pe===void 0||pe.call(n,s,t,oe)},ne={onClick:S,onFocus:A,onBlur:T,onKeyDown:ee,onKeyUp:Y,onMouseEnter:D,onMouseLeave:L,onPointerEnter:M,onPointerLeave:F,onTouchCancel:z,onTouchEnd:V,onTouchMove:W,onTouchStart:K};return ne}function Lxs(){var s=kd(),t=Cgt(),n=kIe(),r=CIe(),a=gve(s)?t.selected:_U(s)?n.selected:wU(s)?r.selected:void 0;return a}function Dxs(s){return Object.values(Mb).includes(s)}function Rxs(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(Dxs(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function Oxs(s,t){var n=ao({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=ao(ao({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function Fxs(s,t,n){var r,a,i,l=kd(),o=EIe(),c=Axs(s,t),d=Pxs(s,c),u=Lxs(),h=!!(l.onDayClick||l.mode!=="default");N.useEffect(function(){var D;c.outside||o.focusedDay&&h&&Rl(o.focusedDay,s)&&((D=n.current)===null||D===void 0||D.focus())},[o.focusedDay,s,n,h,c.outside]);var p=Rxs(l,c).join(" "),f=Oxs(l,c),g=!!(c.outside&&!l.showOutsideDays||c.hidden),b=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:axs,v=e.jsx(b,{date:s,displayMonth:t,activeModifiers:c}),j={style:f,className:p,children:v,role:"gridcell"},_=o.focusTarget&&Rl(o.focusTarget,s)&&!c.outside,S=o.focusedDay&&Rl(o.focusedDay,s),A=ao(ao(ao({},j),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=S||_?0:-1,r)),d),T={isButton:h,isHidden:g,activeModifiers:c,selectedDays:u,buttonProps:A,divProps:j};return T}function zxs(s){var t=N.useRef(null),n=Fxs(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(Sxe,ao({name:"day",ref:t},n.buttonProps)):e.jsx("div",ao({},n.divProps))}function Bxs(s){var t=s.number,n=s.dates,r=kd(),a=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,u=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:u});var h=c(Number(t),{locale:o}),p=function(f){a(t,n,f)};return e.jsx(Sxe,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:p,children:u})}function $xs(s){var t,n,r=kd(),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:zxs,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:Bxs,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})},W$t(h))})]})}function YVe(s,t,n){for(var r=n!=null&&n.ISOWeek?Bct(t):k8(t,n),a=n!=null&&n.ISOWeek?fN(s):Km(s,n),i=Wx(r,a),l=[],o=0;o<=i;o++)l.push(Ul(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?lMe(u):dMe(u,n),p=d.find(function(f){return f.weekNumber===h});return p?(p.dates.push(u),d):(d.push({weekNumber:h,dates:[u]}),d)},[]);return c}function Uxs(s,t){var n=YVe(Bd(s),H0(s),t);if(t!=null&&t.useFixedWeeks){var r=Y$t(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=F2(i,6-r),o=YVe(F2(i,1),l,t);n.push.apply(n,o)}}return n}function qxs(s){var t,n,r,a=kd(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,p=a.firstWeekContainsDate,f=a.ISOWeek,g=Uxs(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:f,locale:i,weekStartsOn:h,firstWeekContainsDate:p}),b=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:rxs,v=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:$xs,j=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:txs;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(b,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:g.map(function(_){return e.jsx(v,{displayMonth:s.displayMonth,dates:_.dates,weekNumber:_.weekNumber},_.weekNumber)})}),e.jsx(j,{displayMonth:s.displayMonth})]})}function Vxs(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Hxs=Vxs()?N.useLayoutEffect:N.useEffect,T2e=!1,Gxs=0;function ZVe(){return"react-day-picker-".concat(++Gxs)}function Wxs(s){var t,n=s??(T2e?ZVe():null),r=N.useState(n),a=r[0],i=r[1];return Hxs(function(){a===null&&i(ZVe())},[]),N.useEffect(function(){T2e===!1&&(T2e=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function Kxs(s){var t,n,r=kd(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=jU().displayMonths,d=Wxs(r.id?"".concat(r.id,"-").concat(s.displayIndex):void 0),u=r.id?"".concat(r.id,"-grid-").concat(s.displayIndex):void 0,h=[i.month],p=l.month,f=s.displayIndex===0,g=s.displayIndex===c.length-1,b=!f&&!g;a==="rtl"&&(t=[f,g],g=t[0],f=t[1]),f&&(h.push(i.caption_start),p=ao(ao({},p),l.caption_start)),g&&(h.push(i.caption_end),p=ao(ao({},p),l.caption_end)),b&&(h.push(i.caption_between),p=ao(ao({},p),l.caption_between));var v=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:exs;return e.jsxs("div",{className:h.join(" "),style:p,children:[e.jsx(v,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(qxs,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function Yxs(s){var t=kd(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function Zxs(s){var t,n,r=s.initialProps,a=kd(),i=EIe(),l=jU(),o=N.useState(!1),c=o[0],d=o[1];N.useEffect(function(){a.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[a.initialFocus,c,i.focus,i.focusTarget,i]);var u=[a.classNames.root,a.className];a.numberOfMonths>1&&u.push(a.classNames.multiple_months),a.showWeekNumber&&u.push(a.classNames.with_weeknumber);var h=ao(ao({},a.styles.root),a.style),p=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,b){var v;return ao(ao({},g),(v={},v[b]=r[b],v))},{}),f=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:Yxs;return e.jsx("div",ao({className:u.join(" "),style:h,dir:a.dir,id:a.id,nonce:r.nonce,title:r.title,lang:r.lang},p,{children:e.jsx(f,{children:l.displayMonths.map(function(g,b){return e.jsx(Kxs,{displayIndex:b,displayMonth:g},b)})})}))}function Qxs(s){var t=s.children,n=_fs(s,["children"]);return e.jsx(Bfs,{initialProps:n,children:e.jsx(Zfs,{children:e.jsx(Mxs,{initialProps:n,children:e.jsx(ixs,{initialProps:n,children:e.jsx(cxs,{initialProps:n,children:e.jsx(gxs,{children:e.jsx(Exs,{children:t})})})})})})})}function Xxs(s){return e.jsx(Qxs,ao({},s,{children:e.jsx(Zxs,{initialProps:s})}))}function ag({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(Xxs,{showOutsideDays:n,className:Et("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:Et(w8({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:Et(w8({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(fl,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(ga,{className:"h-4 w-4"})},...r})}ag.displayName="Calendar";var yve="Popover",[Tgt,ogn]=gu(yve,[Ww]),NU=Ww(),[Jxs,rC]=Tgt(yve),Egt=s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=NU(t),c=N.useRef(null),[d,u]=N.useState(!1),[h,p]=mm({prop:r,defaultProp:a??!1,onChange:i,caller:yve});return e.jsx(V$,{...o,children:e.jsx(Jxs,{scope:t,contentId:um(),triggerRef:c,open:h,onOpenChange:p,onOpenToggle:N.useCallback(()=>p(f=>!f),[p]),hasCustomAnchor:d,onCustomAnchorAdd:N.useCallback(()=>u(!0),[]),onCustomAnchorRemove:N.useCallback(()=>u(!1),[]),modal:l,children:n})})};Egt.displayName=yve;var Agt="PopoverAnchor",egs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=rC(Agt,n),i=NU(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return N.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(RD,{...i,...r,ref:t})});egs.displayName=Agt;var Mgt="PopoverTrigger",Igt=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=rC(Mgt,n),i=NU(n),l=Ti(t,a.triggerRef),o=e.jsx(sa.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":Ogt(a.open),...r,ref:l,onClick:wr(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(RD,{asChild:!0,...i,children:o})});Igt.displayName=Mgt;var MIe="PopoverPortal",[tgs,sgs]=Tgt(MIe,{forceMount:void 0}),Pgt=s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=rC(MIe,t);return e.jsx(tgs,{scope:t,forceMount:n,children:e.jsx(Bh,{present:n||i.open,children:e.jsx(ID,{asChild:!0,container:a,children:r})})})};Pgt.displayName=MIe;var R8="PopoverContent",Lgt=N.forwardRef((s,t)=>{const n=sgs(R8,s.__scopePopover),{forceMount:r=n.forceMount,...a}=s,i=rC(R8,s.__scopePopover);return e.jsx(Bh,{present:r||i.open,children:i.modal?e.jsx(rgs,{...a,ref:t}):e.jsx(ags,{...a,ref:t})})});Lgt.displayName=R8;var ngs=C4("PopoverContent.RemoveScroll"),rgs=N.forwardRef((s,t)=>{const n=rC(R8,s.__scopePopover),r=N.useRef(null),a=Ti(t,r),i=N.useRef(!1);return N.useEffect(()=>{const l=r.current;if(l)return J0e(l)},[]),e.jsx(Q$,{as:ngs,allowPinchZoom:!0,children:e.jsx(Dgt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:wr(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=n.triggerRef.current)==null||o.focus()}),onPointerDownOutside:wr(s.onPointerDownOutside,l=>{const o=l.detail.originalEvent,c=o.button===0&&o.ctrlKey===!0,d=o.button===2||c;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:wr(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),ags=N.forwardRef((s,t)=>{const n=rC(R8,s.__scopePopover),r=N.useRef(!1),a=N.useRef(!1);return e.jsx(Dgt,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(r.current||(o=n.triggerRef.current)==null||o.focus(),i.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=n.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),Dgt=N.forwardRef((s,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...h}=s,p=rC(R8,n),f=NU(n);return Z0e(),e.jsx(Y$,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(G4,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>p.onOpenChange(!1),children:e.jsx(H$,{"data-state":Ogt(p.open),role:"dialog",id:p.contentId,...f,...h,ref:t,style:{...h.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Rgt="PopoverClose",igs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=rC(Rgt,n);return e.jsx(sa.button,{type:"button",...r,ref:t,onClick:wr(s.onClick,()=>a.onOpenChange(!1))})});igs.displayName=Rgt;var ogs="PopoverArrow",lgs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=NU(n);return e.jsx(G$,{...a,...r,ref:t})});lgs.displayName=ogs;function Ogt(s){return s?"open":"closed"}var cgs=Egt,dgs=Igt,ugs=Pgt,Fgt=Lgt;const Wo=cgs,Ko=dgs,zo=N.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(ugs,{children:e.jsx(Fgt,{ref:a,align:t,sideOffset:n,className:Et("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})}));zo.displayName=Fgt.displayName;const hgs=qM("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"}}),IIe=N.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Et(hgs({variant:t}),s),...n}));IIe.displayName="Alert";const mgs=N.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Et("mb-1 font-medium leading-none tracking-tight",s),...t}));mgs.displayName="AlertTitle";const PIe=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("text-sm [&_p]:leading-relaxed",s),...t}));PIe.displayName="AlertDescription";function pgs({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=Gt(),{user:c}=gs(),d=(c==null?void 0:c.id)??null,[u,h]=N.useState(a),[p,f]=N.useState([]),[g,b]=N.useState(null),[v,j]=N.useState("now"),[_,S]=N.useState(xBe(wBe(new Date),1)),[A,T]=N.useState("12"),[D,L]=N.useState("00"),[M,F]=N.useState("PM");N.useEffect(()=>{if(s){h(a),j("now"),f([]);const Te=xBe(wBe(new Date),1);S(Te);const Ce=Te.getHours();T(String(Ce>12?Ce-12:Ce===0?12:Ce)),L("00"),F(Ce>=12?"PM":"AM")}},[s,a]);const z=()=>{if(!_)return null;let Te=parseInt(A);const Ce=parseInt(D);return M==="PM"&&Te!==12&&(Te+=12),M==="AM"&&Te===12&&(Te=0),Q9(Z9(_,Te),Ce)},{data:V,isLoading:W}=lt({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:Te}}=await q.auth.getUser();if(!Te)return[];const{data:Ce,error:Ee}=await q.from("social_accounts").select("*").eq("user_id",Te.id).eq("is_active",!0).order("platform",{ascending:!0});if(Ee)throw Ee;return console.log("Fetched social accounts for posting:",Ce),Ce},enabled:s,staleTime:0}),K=gt({mutationFn:async({accountId:Te,platform:Ce})=>{b(Te);const{data:Ee,error:De}=await q.functions.invoke("social-post",{body:{platform:Ce,accountId:Te,imageUrl:n,caption:u}});if(De)throw De;if(Ee!=null&&Ee.error)throw new Error(Ee.error);return Ee},onSuccess:Te=>{const Ce=Te.platform==="facebook"?"Facebook":Te.platform==="instagram"?"Instagram":Te.platform==="linkedin"?"LinkedIn":"Google Business";ae.success(`Posted to ${Ce}!`)},onError:Te=>{ae.error(`Failed to post: ${Te.message}`)},onSettled:()=>{b(null)}}),Y=gt({mutationFn:async({accountId:Te,platform:Ce,scheduledFor:Ee})=>{const{data:{user:De}}=await q.auth.getUser();if(!De)throw new Error("Not authenticated");const{error:Ie}=await q.from("scheduled_posts").insert({user_id:De.id,social_account_id:Te,platform:Ce,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:Ee.toISOString(),status:"scheduled"});if(Ie)throw Ie;return{platform:Ce}},onSuccess:Te=>{const Ce=Te.platform==="facebook"?"Facebook":Te.platform==="instagram"?"Instagram":"LinkedIn";ae.success(`Post scheduled for ${Ce}!`)},onError:Te=>{ae.error(`Failed to schedule: ${Te.message}`)}}),ee=async()=>{if(p.length===0){ae.error("Please select at least one account");return}if(v==="schedule"){const Te=z();if(!Te||Te<=new Date){ae.error("Please select a future date and time");return}for(const Ce of p){const Ee=V==null?void 0:V.find(De=>De.id===Ce);Ee&&await Y.mutateAsync({accountId:Ce,platform:Ee.platform,scheduledFor:Te})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),ae.success(`${p.length} post(s) scheduled for ${ks(Te,"PPp")}`)}else for(const Te of p){const Ce=V==null?void 0:V.find(Ee=>Ee.id===Te);Ce&&await K.mutateAsync({accountId:Te,platform:Ce.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),f([]),t(!1)},ne=Te=>{f(Ce=>Ce.includes(Te)?Ce.filter(Ee=>Ee!==Te):[...Ce,Te])},oe=(V==null?void 0:V.filter(Te=>Te.platform==="facebook"))||[],pe=(V==null?void 0:V.filter(Te=>Te.platform==="instagram"))||[],ce=(V==null?void 0:V.filter(Te=>Te.platform==="linkedin"))||[],de=(V==null?void 0:V.filter(Te=>Te.platform==="google_business"))||[],ie=((V==null?void 0:V.length)||0)>0,ye=K.isPending||Y.isPending,_e=Array.from({length:12},(Te,Ce)=>String(Ce+1)),Me=["00","15","30","45"];return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create Social Post"}),e.jsx(Qn,{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(se,{htmlFor:"caption",children:"Caption"}),e.jsx(Ts,{id:"caption",placeholder:"Write a caption for your post...",value:u,onChange:Te=>h(Te.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(se,{children:"Publish Time"}),e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsx("button",{type:"button",onClick:()=>j("now"),className:Et("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",v==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>j("schedule"),className:Et("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",v==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),v==="schedule"&&e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(gr,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("justify-start text-left font-normal flex-1",!_&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),_?ks(_,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:_,onSelect:S,disabled:Te=>Tee.jsx(Ze,{value:Te,children:Te},Te))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(us,{value:D,onValueChange:L,children:[e.jsx(cs,{className:"w-[70px]",children:e.jsx(hs,{})}),e.jsx(ds,{children:Me.map(Te=>e.jsx(Ze,{value:Te,children:Te},Te))})]}),e.jsxs(us,{value:M,onValueChange:Te=>F(Te),children:[e.jsx(cs,{className:"w-[70px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"AM",children:"AM"}),e.jsx(Ze,{value:"PM",children:"PM"})]})]})]})]}),_&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",ks(z()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Post to"}),W&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ss,{className:"h-6 w-6 animate-spin"})}),!W&&!ie&&e.jsxs(IIe,{children:[e.jsx(Gi,{className:"h-4 w-4"}),e.jsxs(PIe,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(Ln,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(Vo,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),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(Oh,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),oe.map(Te=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(hi,{checked:p.includes(Te.id),onCheckedChange:()=>ne(Te.id),disabled:g===Te.id}),e.jsxs(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:Te.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(Oh,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:Te.page_name||Te.platform_username}),g===Te.id&&e.jsx(ss,{className:"h-4 w-4 animate-spin"})]},Te.id))]}),pe.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(mu,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),pe.map(Te=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(hi,{checked:p.includes(Te.id),onCheckedChange:()=>ne(Te.id),disabled:g===Te.id}),e.jsxs(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:Te.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(mu,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",Te.platform_username]}),g===Te.id&&e.jsx(ss,{className:"h-4 w-4 animate-spin"})]},Te.id))]}),ce.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(bf,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ce.map(Te=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(hi,{checked:p.includes(Te.id),onCheckedChange:()=>ne(Te.id),disabled:g===Te.id}),e.jsxs(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:Te.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(bf,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:Te.platform_username}),g===Te.id&&e.jsx(ss,{className:"h-4 w-4 animate-spin"})]},Te.id))]}),de.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ca,{className:"h-4 w-4 text-red-600"})," Google Business"]}),de.map(Te=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(hi,{checked:p.includes(Te.id),onCheckedChange:()=>ne(Te.id),disabled:g===Te.id}),e.jsxs(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:Te.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(Ca,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:Te.page_name||Te.platform_username}),g===Te.id&&e.jsx(ss,{className:"h-4 w-4 animate-spin"})]},Te.id))]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:ee,disabled:p.length===0||ye,className:"gap-2",children:[ye?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):v==="schedule"?e.jsx(yr,{className:"h-4 w-4"}):e.jsx(cr,{className:"h-4 w-4"}),v==="schedule"?`Schedule ${p.length} post${p.length!==1?"s":""}`:`Post to ${p.length} account${p.length!==1?"s":""}`]})]})]})})}function fgs(){const{user:s}=gs(),t=(s==null?void 0:s.id)??null,n=Gt(),[r,a]=N.useState(void 0),[i,l]=N.useState("all"),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,p]=N.useState(void 0),[f,g]=N.useState("12"),[b,v]=N.useState("00"),[j,_]=N.useState("PM"),{data:S=[],isLoading:A}=lt({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:de,error:ie}=await q.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).eq("user_id",t).order("scheduled_for",{ascending:!1});if(ie)throw ie;return de}}),T=S.filter(de=>{if(i!=="all"&&de.status!==i)return!1;if(r&&de.scheduled_for){const ie=new Date(de.scheduled_for);if(!Rl(ie,r))return!1}return!0}),D=S.filter(de=>de.scheduled_for).map(de=>Sf(new Date(de.scheduled_for))),L=gt({mutationFn:async de=>{const{error:ie}=await q.from("scheduled_posts").update({caption:de.caption,scheduled_for:de.scheduled_for}).eq("id",de.id);if(ie)throw ie},onSuccess:()=>{ae.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:de=>{ae.error(`Failed to update: ${de.message}`)}}),M=gt({mutationFn:async de=>{const{error:ie}=await q.from("scheduled_posts").update({status:"cancelled"}).eq("id",de);if(ie)throw ie},onSuccess:()=>{ae.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:de=>{ae.error(`Failed to cancel: ${de.message}`)}}),F=gt({mutationFn:async de=>{const{error:ie}=await q.from("scheduled_posts").delete().eq("id",de);if(ie)throw ie},onSuccess:()=>{ae.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:de=>{ae.error(`Failed to delete: ${de.message}`)}}),z=gt({mutationFn:async de=>{const{data:ie,error:ye}=await q.functions.invoke("social-post",{body:{platform:de.platform,accountId:de.social_account_id,imageUrl:de.image_url,caption:de.caption}});if(ye)throw ye;if(ie!=null&&ie.error)throw new Error(ie.error);return await q.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:ie.postId}).eq("id",de.id),ie},onSuccess:de=>{const ie=de.platform==="facebook"?"Facebook":de.platform==="instagram"?"Instagram":"LinkedIn";ae.success(`Posted to ${ie}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:de=>{ae.error(`Failed to post: ${de.message}`)}}),V=de=>{if(c(de),u(de.caption||""),de.scheduled_for){const ie=new Date(de.scheduled_for);p(ie);const ye=ie.getHours();g(String(ye>12?ye-12:ye===0?12:ye)),v(String(ie.getMinutes()).padStart(2,"0")),_(ye>=12?"PM":"AM")}},W=()=>{if(!o||!h)return;let de=parseInt(f);const ie=parseInt(b);j==="PM"&&de!==12&&(de+=12),j==="AM"&&de===12&&(de=0);const ye=Q9(Z9(h,de),ie);L.mutate({id:o.id,caption:d,scheduled_for:ye.toISOString()})},K=de=>{switch(de){case"facebook":return e.jsx(Oh,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(mu,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(bf,{className:"h-4 w-4 text-blue-700"});default:return null}},Y=de=>{switch(de){case"scheduled":return e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(ze,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(zi,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(ze,{variant:"destructive",className:"gap-1",children:[e.jsx(Gc,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(ze,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Gi,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(ze,{variant:"outline",children:de})}},ee=Array.from({length:12},(de,ie)=>String(ie+1)),ne=["00","15","30","45"],oe=S.filter(de=>de.status==="scheduled").length,pe=S.filter(de=>de.status==="posted").length,ce=S.filter(de=>de.status==="scheduled"&&de.scheduled_for&&Z$t(new Date(de.scheduled_for))).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:oe}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ce}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:pe}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:S.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"})]})]}),e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs(fe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Tl,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(ag,{mode:"single",selected:r,onSelect:a,className:Et("pointer-events-auto"),modifiers:{hasPost:D},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),r&&e.jsx(B,{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(Fv,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(de=>e.jsx(B,{variant:i===de?"default":"outline",size:"sm",onClick:()=>l(de),className:"capitalize",children:de},de))})]}),A&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!A&&T.length===0&&e.jsxs(fe,{className:"p-8 text-center",children:[e.jsx(yr,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"font-medium mb-2",children:"No posts found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?`No posts scheduled for ${ks(r,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:T.map(de=>{var ie,ye;return e.jsx(fe,{className:"overflow-hidden",children:e.jsxs("div",{className:"flex flex-col sm:flex-row",children:[e.jsx("div",{className:"sm:w-32 h-32 sm:h-auto bg-muted flex-shrink-0",children:e.jsx("img",{src:de.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Ae,{className:"flex-1 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[K(de.platform),e.jsx("span",{className:"font-medium",children:((ie=de.social_accounts)==null?void 0:ie.page_name)||((ye=de.social_accounts)==null?void 0:ye.platform_username)||"Unknown"}),Y(de.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[de.status==="scheduled"&&e.jsxs(Kw,{children:[e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>V(de),children:e.jsx(ja,{className:"h-4 w-4"})})}),e.jsx(yc,{children:"Edit post"})]}),e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>z.mutate(de),disabled:z.isPending,children:z.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"})})}),e.jsx(yc,{children:"Post now"})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Cancel this scheduled post?"}),e.jsx(Mo,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep"}),e.jsx(jo,{onClick:()=>M.mutate(de.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(jo,{onClick:()=>F.mutate(de.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(de.status==="posted"||de.status==="cancelled"||de.status==="failed")&&e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this post?"}),e.jsx(Mo,{children:"This will permanently remove this post from your history."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>F.mutate(de.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),de.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:de.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),de.status==="posted"&&de.posted_at?`Posted ${ks(new Date(de.posted_at),"PPp")}`:de.scheduled_for?`Scheduled for ${ks(new Date(de.scheduled_for),"PPp")}`:"Not scheduled"]}),de.status==="failed"&&de.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",de.error_message]})]})]})},de.id)})})]})]}),e.jsx(bs,{open:!!o,onOpenChange:de=>!de&&c(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Scheduled Post"}),e.jsx(Qn,{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(se,{children:"Caption"}),e.jsx(Ts,{value:d,onChange:de=>u(de.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(se,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),h?ks(h,"PPP"):"Pick a date"]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:h,onSelect:p,disabled:de=>dee.jsx(Ze,{value:de,children:de},de))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(us,{value:b,onValueChange:v,children:[e.jsx(cs,{className:"w-[70px]",children:e.jsx(hs,{})}),e.jsx(ds,{children:ne.map(de=>e.jsx(Ze,{value:de,children:de},de))})]}),e.jsxs(us,{value:j,onValueChange:de=>_(de),children:[e.jsx(cs,{className:"w-[70px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"AM",children:"AM"}),e.jsx(Ze,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsxs(B,{onClick:W,disabled:L.isPending,children:[L.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function DH(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 zgt={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 DH=="function"&&DH;if(!u&&h)return h(d,!0);if(o)return o(d,!0);var p=new Error("Cannot find module '"+d+"'");throw p.code="MODULE_NOT_FOUND",p}var f=a[d]={exports:{}};r[d][0].call(f.exports,function(g){var b=r[d][1][g];return l(b||g)},f,f.exports,n,r,a,i)}return a[d].exports}for(var o=typeof DH=="function"&&DH,c=0;c>2,f=(3&d)<<4|u>>4,g=1>6:64,b=2>4,u=(15&p)<<4|(f=o.indexOf(c.charAt(b++)))>>2,h=(3&f)<<6|(g=o.indexOf(c.charAt(b++))),_[v++]=d,f!==64&&(_[v++]=u),g!==64&&(_[v++]=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,p,f,g){this.compressedSize=u,this.uncompressedSize=h,this.crc32=p,this.compression=f,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,p){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(h.compressWorker(p)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,a){var i=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,a){var i=n("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();r.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,u,h,p){var f=l,g=p+h;d^=-1;for(var b=p;b>>8^f[255&(d^u[b])];return-1^d}(0|c,o,o.length,0):function(d,u,h,p){var f=l,g=p+h;d^=-1;for(var b=p;b>>8^f[255&(d^u.charCodeAt(b))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(n,r,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(n,r,a){var i=null;i=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:i}},{lie:37}],7:[function(n,r,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=n("pako"),o=n("./utils"),c=n("./stream/GenericWorker"),d=i?"uint8array":"array";function u(h,p){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=p,this.meta={}}a.magic="\b\0",o.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(p){h.push({data:p,meta:h.meta})}},a.compressWorker=function(h){return new u("Deflate",h)},a.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,a){function i(f,g){var b,v="";for(b=0;b>>=8;return v}function l(f,g,b,v,j,_){var S,A,T=f.file,D=f.compression,L=_!==d.utf8encode,M=o.transformTo("string",_(T.name)),F=o.transformTo("string",d.utf8encode(T.name)),z=T.comment,V=o.transformTo("string",_(z)),W=o.transformTo("string",d.utf8encode(z)),K=F.length!==T.name.length,Y=W.length!==z.length,ee="",ne="",oe="",pe=T.dir,ce=T.date,de={crc32:0,compressedSize:0,uncompressedSize:0};g&&!b||(de.crc32=f.crc32,de.compressedSize=f.compressedSize,de.uncompressedSize=f.uncompressedSize);var ie=0;g&&(ie|=8),L||!K&&!Y||(ie|=2048);var ye=0,_e=0;pe&&(ye|=16),j==="UNIX"?(_e=798,ye|=function(Te,Ce){var Ee=Te;return Te||(Ee=Ce?16893:33204),(65535&Ee)<<16}(T.unixPermissions,pe)):(_e=20,ye|=function(Te){return 63&(Te||0)}(T.dosPermissions)),S=ce.getUTCHours(),S<<=6,S|=ce.getUTCMinutes(),S<<=5,S|=ce.getUTCSeconds()/2,A=ce.getUTCFullYear()-1980,A<<=4,A|=ce.getUTCMonth()+1,A<<=5,A|=ce.getUTCDate(),K&&(ne=i(1,1)+i(u(M),4)+F,ee+="up"+i(ne.length,2)+ne),Y&&(oe=i(1,1)+i(u(V),4)+W,ee+="uc"+i(oe.length,2)+oe);var Me="";return Me+=` \0`,Me+=i(ie,2),Me+=D.magic,Me+=i(S,2),Me+=i(A,2),Me+=i(de.crc32,4),Me+=i(de.compressedSize,4),Me+=i(de.uncompressedSize,4),Me+=i(M.length,2),Me+=i(ee.length,2),{fileRecord:h.LOCAL_FILE_HEADER+Me+M+ee,dirRecord:h.CENTRAL_FILE_HEADER+i(_e,2)+Me+i(V.length,2)+"\0\0\0\0"+i(ye,4)+i(v,4)+M+ee+V}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function p(f,g,b,v){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=b,this.encodeFileName=v,this.streamFiles=f,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(p,c),p.prototype.push=function(f){var g=f.meta.percent||0,b=this.entriesCount,v=this._sources.length;this.accumulate?this.contentBuffer.push(f):(this.bytesWritten+=f.data.length,c.prototype.push.call(this,{data:f.data,meta:{currentFile:this.currentFile,percent:b?(g+100*(b-v-1))/b:100}}))},p.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var g=this.streamFiles&&!f.file.dir;if(g){var b=l(f,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:b.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(f){this.accumulate=!1;var g=this.streamFiles&&!f.file.dir,b=l(f,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(b.dirRecord),g)this.push({data:function(v){return h.DATA_DESCRIPTOR+i(v.crc32,4)+i(v.compressedSize,4)+i(v.uncompressedSize,4)}(f),meta:{percent:100}});else for(this.push({data:b.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var f=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 p=i.getTypeOf(h);return i.checkSupport(p),p!=="string"||l.uint8array?p==="nodebuffer"?new d(h):l.uint8array?new u(i.transformTo("uint8array",h)):new o(i.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,a){var i=n("./GenericWorker"),l=n("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},r.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,a){var i=n("./GenericWorker"),l=n("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},r.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=i.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}i.inherits(o,l),o.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},r.exports=i},{}],29:[function(n,r,a){var i=n("../utils"),l=n("./ConvertWorker"),o=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),h=null;if(d.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(g,b){return new u.Promise(function(v,j){var _=[],S=g._internalType,A=g._outputType,T=g._mimeType;g.on("data",function(D,L){_.push(D),b&&b(L)}).on("error",function(D){_=[],j(D)}).on("end",function(){try{var D=function(L,M,F){switch(L){case"blob":return i.newBlob(i.transformTo("arraybuffer",M),F);case"base64":return c.encode(M);default:return i.transformTo(L,M)}}(A,function(L,M){var F,z=0,V=null,W=0;for(F=0;F"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,a){for(var i=n("./utils"),l=n("./support"),o=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function p(){c.call(this,"utf-8 encode")}a.utf8encode=function(f){return l.nodebuffer?o.newBufferFrom(f,"utf-8"):function(g){var b,v,j,_,S,A=g.length,T=0;for(_=0;_>>6:(v<65536?b[S++]=224|v>>>12:(b[S++]=240|v>>>18,b[S++]=128|v>>>12&63),b[S++]=128|v>>>6&63),b[S++]=128|63&v);return b}(f)},a.utf8decode=function(f){return l.nodebuffer?i.transformTo("nodebuffer",f).toString("utf-8"):function(g){var b,v,j,_,S=g.length,A=new Array(2*S);for(b=v=0;b>10&1023,A[v++]=56320|1023&j)}return A.length!==v&&(A.subarray?A=A.subarray(0,v):A.length=v),i.applyFromCharCode(A)}(f=i.transformTo(l.uint8array?"uint8array":"array",f))},i.inherits(h,c),h.prototype.processChunk=function(f){var g=i.transformTo(l.uint8array?"uint8array":"array",f.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var b=g;(g=new Uint8Array(b.length+this.leftOver.length)).set(this.leftOver,0),g.set(b,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var v=function(_,S){var A;for((S=S||_.length)>_.length&&(S=_.length),A=S-1;0<=A&&(192&_[A])==128;)A--;return A<0||A===0?S:A+d[_[A]]>S?A:S}(g),j=g;v!==g.length&&(l.uint8array?(j=g.subarray(0,v),this.leftOver=g.subarray(v,g.length)):(j=g.slice(0,v),this.leftOver=g.slice(v,g.length))),this.push({data:a.utf8decode(j),meta:f.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=h,i.inherits(p,c),p.prototype.processChunk=function(f){this.push({data:a.utf8encode(f.data),meta:f.meta})},a.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,a){var i=n("./support"),l=n("./base64"),o=n("./nodejsUtils"),c=n("./external");function d(b){return b}function u(b,v){for(var j=0;j>8;this.dir=!!(16&this.externalFileAttributes),f==0&&(this.dosPermissions=63&this.externalFileAttributes),f==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var f=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=f.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=f.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=f.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=f.readInt(4))}},readExtraFields:function(f){var g,b,v,j=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4>>6:(f<65536?p[v++]=224|f>>>12:(p[v++]=240|f>>>18,p[v++]=128|f>>>12&63),p[v++]=128|f>>>6&63),p[v++]=128|63&f);return p},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var p=new i.Buf8(h.length),f=0,g=p.length;f>10&1023,_[g++]=56320|1023&b)}return u(_,g)},a.utf8border=function(h,p){var f;for((p=p||h.length)>h.length&&(p=h.length),f=p-1;0<=f&&(192&h[f])==128;)f--;return f<0||f===0?p:f+c[h[f]]>p?f:p}},{"./common":41}],43:[function(n,r,a){r.exports=function(i,l,o,c){for(var d=65535&i|0,u=i>>>16&65535|0,h=0;o!==0;){for(o-=h=2e3>>1:l>>>1;o[c]=l}return o}();r.exports=function(l,o,c,d){var u=i,h=d+c;l^=-1;for(var p=d;p>>8^u[255&(l^o[p])];return-1^l}},{}],46:[function(n,r,a){var i,l=n("../utils/common"),o=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),h=0,p=4,f=0,g=-2,b=-1,v=4,j=2,_=8,S=9,A=286,T=30,D=19,L=2*A+1,M=15,F=3,z=258,V=z+F+1,W=42,K=113,Y=1,ee=2,ne=3,oe=4;function pe(we,it){return we.msg=u[it],it}function ce(we){return(we<<1)-(4we.avail_out&&(Ne=we.avail_out),Ne!==0&&(l.arraySet(we.output,it.pending_buf,it.pending_out,Ne,we.next_out),we.next_out+=Ne,it.pending_out+=Ne,we.total_out+=Ne,we.avail_out-=Ne,it.pending-=Ne,it.pending===0&&(it.pending_out=0))}function ye(we,it){o._tr_flush_block(we,0<=we.block_start?we.block_start:-1,we.strstart-we.block_start,it),we.block_start=we.strstart,ie(we.strm)}function _e(we,it){we.pending_buf[we.pending++]=it}function Me(we,it){we.pending_buf[we.pending++]=it>>>8&255,we.pending_buf[we.pending++]=255&it}function Te(we,it){var Ne,He,$e=we.max_chain_length,Ye=we.strstart,Ke=we.prev_length,rt=we.nice_match,tt=we.strstart>we.w_size-V?we.strstart-(we.w_size-V):0,at=we.window,Ge=we.w_mask,dt=we.prev,Bt=we.strstart+z,kt=at[Ye+Ke-1],Qt=at[Ye+Ke];we.prev_length>=we.good_match&&($e>>=2),rt>we.lookahead&&(rt=we.lookahead);do if(at[(Ne=it)+Ke]===Qt&&at[Ne+Ke-1]===kt&&at[Ne]===at[Ye]&&at[++Ne]===at[Ye+1]){Ye+=2,Ne++;do;while(at[++Ye]===at[++Ne]&&at[++Ye]===at[++Ne]&&at[++Ye]===at[++Ne]&&at[++Ye]===at[++Ne]&&at[++Ye]===at[++Ne]&&at[++Ye]===at[++Ne]&&at[++Ye]===at[++Ne]&&at[++Ye]===at[++Ne]&&Yett&&--$e!=0);return Ke<=we.lookahead?Ke:we.lookahead}function Ce(we){var it,Ne,He,$e,Ye,Ke,rt,tt,at,Ge,dt=we.w_size;do{if($e=we.window_size-we.lookahead-we.strstart,we.strstart>=dt+(dt-V)){for(l.arraySet(we.window,we.window,dt,dt,0),we.match_start-=dt,we.strstart-=dt,we.block_start-=dt,it=Ne=we.hash_size;He=we.head[--it],we.head[it]=dt<=He?He-dt:0,--Ne;);for(it=Ne=dt;He=we.prev[--it],we.prev[it]=dt<=He?He-dt:0,--Ne;);$e+=dt}if(we.strm.avail_in===0)break;if(Ke=we.strm,rt=we.window,tt=we.strstart+we.lookahead,at=$e,Ge=void 0,Ge=Ke.avail_in,at=F)for(Ye=we.strstart-we.insert,we.ins_h=we.window[Ye],we.ins_h=(we.ins_h<=F&&(we.ins_h=(we.ins_h<=F)if(He=o._tr_tally(we,we.strstart-we.match_start,we.match_length-F),we.lookahead-=we.match_length,we.match_length<=we.max_lazy_match&&we.lookahead>=F){for(we.match_length--;we.strstart++,we.ins_h=(we.ins_h<=F&&(we.ins_h=(we.ins_h<=F&&we.match_length<=we.prev_length){for($e=we.strstart+we.lookahead-F,He=o._tr_tally(we,we.strstart-1-we.prev_match,we.prev_length-F),we.lookahead-=we.prev_length-1,we.prev_length-=2;++we.strstart<=$e&&(we.ins_h=(we.ins_h<we.pending_buf_size-5&&(Ne=we.pending_buf_size-5);;){if(we.lookahead<=1){if(Ce(we),we.lookahead===0&&it===h)return Y;if(we.lookahead===0)break}we.strstart+=we.lookahead,we.lookahead=0;var He=we.block_start+Ne;if((we.strstart===0||we.strstart>=He)&&(we.lookahead=we.strstart-He,we.strstart=He,ye(we,!1),we.strm.avail_out===0)||we.strstart-we.block_start>=we.w_size-V&&(ye(we,!1),we.strm.avail_out===0))return Y}return we.insert=0,it===p?(ye(we,!0),we.strm.avail_out===0?ne:oe):(we.strstart>we.block_start&&(ye(we,!1),we.strm.avail_out),Y)}),new Ie(4,4,8,4,Ee),new Ie(4,5,16,8,Ee),new Ie(4,6,32,32,Ee),new Ie(4,4,16,16,De),new Ie(8,16,32,32,De),new Ie(8,16,128,128,De),new Ie(8,32,128,256,De),new Ie(32,128,258,1024,De),new Ie(32,258,258,4096,De)],a.deflateInit=function(we,it){return Je(we,it,_,15,8,0)},a.deflateInit2=Je,a.deflateReset=ve,a.deflateResetKeep=qe,a.deflateSetHeader=function(we,it){return we&&we.state?we.state.wrap!==2?g:(we.state.gzhead=it,f):g},a.deflate=function(we,it){var Ne,He,$e,Ye;if(!we||!we.state||5>8&255),_e(He,He.gzhead.time>>16&255),_e(He,He.gzhead.time>>24&255),_e(He,He.level===9?2:2<=He.strategy||He.level<2?4:0),_e(He,255&He.gzhead.os),He.gzhead.extra&&He.gzhead.extra.length&&(_e(He,255&He.gzhead.extra.length),_e(He,He.gzhead.extra.length>>8&255)),He.gzhead.hcrc&&(we.adler=d(we.adler,He.pending_buf,He.pending,0)),He.gzindex=0,He.status=69):(_e(He,0),_e(He,0),_e(He,0),_e(He,0),_e(He,0),_e(He,He.level===9?2:2<=He.strategy||He.level<2?4:0),_e(He,3),He.status=K);else{var Ke=_+(He.w_bits-8<<4)<<8;Ke|=(2<=He.strategy||He.level<2?0:He.level<6?1:He.level===6?2:3)<<6,He.strstart!==0&&(Ke|=32),Ke+=31-Ke%31,He.status=K,Me(He,Ke),He.strstart!==0&&(Me(He,we.adler>>>16),Me(He,65535&we.adler)),we.adler=1}if(He.status===69)if(He.gzhead.extra){for($e=He.pending;He.gzindex<(65535&He.gzhead.extra.length)&&(He.pending!==He.pending_buf_size||(He.gzhead.hcrc&&He.pending>$e&&(we.adler=d(we.adler,He.pending_buf,He.pending-$e,$e)),ie(we),$e=He.pending,He.pending!==He.pending_buf_size));)_e(He,255&He.gzhead.extra[He.gzindex]),He.gzindex++;He.gzhead.hcrc&&He.pending>$e&&(we.adler=d(we.adler,He.pending_buf,He.pending-$e,$e)),He.gzindex===He.gzhead.extra.length&&(He.gzindex=0,He.status=73)}else He.status=73;if(He.status===73)if(He.gzhead.name){$e=He.pending;do{if(He.pending===He.pending_buf_size&&(He.gzhead.hcrc&&He.pending>$e&&(we.adler=d(we.adler,He.pending_buf,He.pending-$e,$e)),ie(we),$e=He.pending,He.pending===He.pending_buf_size)){Ye=1;break}Ye=He.gzindex$e&&(we.adler=d(we.adler,He.pending_buf,He.pending-$e,$e)),Ye===0&&(He.gzindex=0,He.status=91)}else He.status=91;if(He.status===91)if(He.gzhead.comment){$e=He.pending;do{if(He.pending===He.pending_buf_size&&(He.gzhead.hcrc&&He.pending>$e&&(we.adler=d(we.adler,He.pending_buf,He.pending-$e,$e)),ie(we),$e=He.pending,He.pending===He.pending_buf_size)){Ye=1;break}Ye=He.gzindex$e&&(we.adler=d(we.adler,He.pending_buf,He.pending-$e,$e)),Ye===0&&(He.status=103)}else He.status=103;if(He.status===103&&(He.gzhead.hcrc?(He.pending+2>He.pending_buf_size&&ie(we),He.pending+2<=He.pending_buf_size&&(_e(He,255&we.adler),_e(He,we.adler>>8&255),we.adler=0,He.status=K)):He.status=K),He.pending!==0){if(ie(we),we.avail_out===0)return He.last_flush=-1,f}else if(we.avail_in===0&&ce(it)<=ce(Ne)&&it!==p)return pe(we,-5);if(He.status===666&&we.avail_in!==0)return pe(we,-5);if(we.avail_in!==0||He.lookahead!==0||it!==h&&He.status!==666){var rt=He.strategy===2?function(tt,at){for(var Ge;;){if(tt.lookahead===0&&(Ce(tt),tt.lookahead===0)){if(at===h)return Y;break}if(tt.match_length=0,Ge=o._tr_tally(tt,0,tt.window[tt.strstart]),tt.lookahead--,tt.strstart++,Ge&&(ye(tt,!1),tt.strm.avail_out===0))return Y}return tt.insert=0,at===p?(ye(tt,!0),tt.strm.avail_out===0?ne:oe):tt.last_lit&&(ye(tt,!1),tt.strm.avail_out===0)?Y:ee}(He,it):He.strategy===3?function(tt,at){for(var Ge,dt,Bt,kt,Qt=tt.window;;){if(tt.lookahead<=z){if(Ce(tt),tt.lookahead<=z&&at===h)return Y;if(tt.lookahead===0)break}if(tt.match_length=0,tt.lookahead>=F&&0tt.lookahead&&(tt.match_length=tt.lookahead)}if(tt.match_length>=F?(Ge=o._tr_tally(tt,1,tt.match_length-F),tt.lookahead-=tt.match_length,tt.strstart+=tt.match_length,tt.match_length=0):(Ge=o._tr_tally(tt,0,tt.window[tt.strstart]),tt.lookahead--,tt.strstart++),Ge&&(ye(tt,!1),tt.strm.avail_out===0))return Y}return tt.insert=0,at===p?(ye(tt,!0),tt.strm.avail_out===0?ne:oe):tt.last_lit&&(ye(tt,!1),tt.strm.avail_out===0)?Y:ee}(He,it):i[He.level].func(He,it);if(rt!==ne&&rt!==oe||(He.status=666),rt===Y||rt===ne)return we.avail_out===0&&(He.last_flush=-1),f;if(rt===ee&&(it===1?o._tr_align(He):it!==5&&(o._tr_stored_block(He,0,0,!1),it===3&&(de(He.head),He.lookahead===0&&(He.strstart=0,He.block_start=0,He.insert=0))),ie(we),we.avail_out===0))return He.last_flush=-1,f}return it!==p?f:He.wrap<=0?1:(He.wrap===2?(_e(He,255&we.adler),_e(He,we.adler>>8&255),_e(He,we.adler>>16&255),_e(He,we.adler>>24&255),_e(He,255&we.total_in),_e(He,we.total_in>>8&255),_e(He,we.total_in>>16&255),_e(He,we.total_in>>24&255)):(Me(He,we.adler>>>16),Me(He,65535&we.adler)),ie(we),0=Ne.w_size&&(Ye===0&&(de(Ne.head),Ne.strstart=0,Ne.block_start=0,Ne.insert=0),at=new l.Buf8(Ne.w_size),l.arraySet(at,it,Ge-Ne.w_size,Ne.w_size,0),it=at,Ge=Ne.w_size),Ke=we.avail_in,rt=we.next_in,tt=we.input,we.avail_in=Ge,we.next_in=0,we.input=it,Ce(Ne);Ne.lookahead>=F;){for(He=Ne.strstart,$e=Ne.lookahead-(F-1);Ne.ins_h=(Ne.ins_h<>>=F=M>>>24,S-=F,(F=M>>>16&255)===0)ee[u++]=65535&M;else{if(!(16&F)){if(!(64&F)){M=A[(65535&M)+(_&(1<>>=F,S-=F),S<15&&(_+=Y[c++]<>>=F=M>>>24,S-=F,!(16&(F=M>>>16&255))){if(!(64&F)){M=T[(65535&M)+(_&(1<>>=F,S-=F,(F=u-h)>3,_&=(1<<(S-=z<<3))-1,i.next_in=c,i.next_out=u,i.avail_in=c>>24&255)+(W>>>8&65280)+((65280&W)<<8)+((255&W)<<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 S(W){var K;return W&&W.state?(K=W.state,W.total_in=W.total_out=K.total=0,W.msg="",K.wrap&&(W.adler=1&K.wrap),K.mode=g,K.last=0,K.havedict=0,K.dmax=32768,K.head=null,K.hold=0,K.bits=0,K.lencode=K.lendyn=new i.Buf32(b),K.distcode=K.distdyn=new i.Buf32(v),K.sane=1,K.back=-1,p):f}function A(W){var K;return W&&W.state?((K=W.state).wsize=0,K.whave=0,K.wnext=0,S(W)):f}function T(W,K){var Y,ee;return W&&W.state?(ee=W.state,K<0?(Y=0,K=-K):(Y=1+(K>>4),K<48&&(K&=15)),K&&(K<8||15=oe.wsize?(i.arraySet(oe.window,K,Y-oe.wsize,oe.wsize,0),oe.wnext=0,oe.whave=oe.wsize):(ee<(ne=oe.wsize-oe.wnext)&&(ne=ee),i.arraySet(oe.window,K,Y-ee,ne,oe.wnext),(ee-=ne)?(i.arraySet(oe.window,K,Y-ee,ee,0),oe.wnext=ee,oe.whave=oe.wsize):(oe.wnext+=ne,oe.wnext===oe.wsize&&(oe.wnext=0),oe.whave>>8&255,Y.check=o(Y.check,Ye,2,0),ye=ie=0,Y.mode=2;break}if(Y.flags=0,Y.head&&(Y.head.done=!1),!(1&Y.wrap)||(((255&ie)<<8)+(ie>>8))%31){W.msg="incorrect header check",Y.mode=30;break}if((15&ie)!=8){W.msg="unknown compression method",Y.mode=30;break}if(ye-=4,we=8+(15&(ie>>>=4)),Y.wbits===0)Y.wbits=we;else if(we>Y.wbits){W.msg="invalid window size",Y.mode=30;break}Y.dmax=1<>8&1),512&Y.flags&&(Ye[0]=255&ie,Ye[1]=ie>>>8&255,Y.check=o(Y.check,Ye,2,0)),ye=ie=0,Y.mode=3;case 3:for(;ye<32;){if(ce===0)break e;ce--,ie+=ee[oe++]<>>8&255,Ye[2]=ie>>>16&255,Ye[3]=ie>>>24&255,Y.check=o(Y.check,Ye,4,0)),ye=ie=0,Y.mode=4;case 4:for(;ye<16;){if(ce===0)break e;ce--,ie+=ee[oe++]<>8),512&Y.flags&&(Ye[0]=255&ie,Ye[1]=ie>>>8&255,Y.check=o(Y.check,Ye,2,0)),ye=ie=0,Y.mode=5;case 5:if(1024&Y.flags){for(;ye<16;){if(ce===0)break e;ce--,ie+=ee[oe++]<>>8&255,Y.check=o(Y.check,Ye,2,0)),ye=ie=0}else Y.head&&(Y.head.extra=null);Y.mode=6;case 6:if(1024&Y.flags&&(ce<(Te=Y.length)&&(Te=ce),Te&&(Y.head&&(we=Y.head.extra_len-Y.length,Y.head.extra||(Y.head.extra=new Array(Y.head.extra_len)),i.arraySet(Y.head.extra,ee,oe,Te,we)),512&Y.flags&&(Y.check=o(Y.check,ee,Te,oe)),ce-=Te,oe+=Te,Y.length-=Te),Y.length))break e;Y.length=0,Y.mode=7;case 7:if(2048&Y.flags){if(ce===0)break e;for(Te=0;we=ee[oe+Te++],Y.head&&we&&Y.length<65536&&(Y.head.name+=String.fromCharCode(we)),we&&Te>9&1,Y.head.done=!0),W.adler=Y.check=0,Y.mode=12;break;case 10:for(;ye<32;){if(ce===0)break e;ce--,ie+=ee[oe++]<>>=7&ye,ye-=7&ye,Y.mode=27;break}for(;ye<3;){if(ce===0)break e;ce--,ie+=ee[oe++]<>>=1)){case 0:Y.mode=14;break;case 1:if(z(Y),Y.mode=20,K!==6)break;ie>>>=2,ye-=2;break e;case 2:Y.mode=17;break;case 3:W.msg="invalid block type",Y.mode=30}ie>>>=2,ye-=2;break;case 14:for(ie>>>=7&ye,ye-=7&ye;ye<32;){if(ce===0)break e;ce--,ie+=ee[oe++]<>>16^65535)){W.msg="invalid stored block lengths",Y.mode=30;break}if(Y.length=65535&ie,ye=ie=0,Y.mode=15,K===6)break e;case 15:Y.mode=16;case 16:if(Te=Y.length){if(ce>>=5,ye-=5,Y.ndist=1+(31&ie),ie>>>=5,ye-=5,Y.ncode=4+(15&ie),ie>>>=4,ye-=4,286>>=3,ye-=3}for(;Y.have<19;)Y.lens[Ke[Y.have++]]=0;if(Y.lencode=Y.lendyn,Y.lenbits=7,Ne={bits:Y.lenbits},it=d(0,Y.lens,0,19,Y.lencode,0,Y.work,Ne),Y.lenbits=Ne.bits,it){W.msg="invalid code lengths set",Y.mode=30;break}Y.have=0,Y.mode=19;case 19:for(;Y.have>>16&255,Fe=65535&$e,!((De=$e>>>24)<=ye);){if(ce===0)break e;ce--,ie+=ee[oe++]<>>=De,ye-=De,Y.lens[Y.have++]=Fe;else{if(Fe===16){for(He=De+2;ye>>=De,ye-=De,Y.have===0){W.msg="invalid bit length repeat",Y.mode=30;break}we=Y.lens[Y.have-1],Te=3+(3&ie),ie>>>=2,ye-=2}else if(Fe===17){for(He=De+3;ye>>=De)),ie>>>=3,ye-=3}else{for(He=De+7;ye>>=De)),ie>>>=7,ye-=7}if(Y.have+Te>Y.nlen+Y.ndist){W.msg="invalid bit length repeat",Y.mode=30;break}for(;Te--;)Y.lens[Y.have++]=we}}if(Y.mode===30)break;if(Y.lens[256]===0){W.msg="invalid code -- missing end-of-block",Y.mode=30;break}if(Y.lenbits=9,Ne={bits:Y.lenbits},it=d(u,Y.lens,0,Y.nlen,Y.lencode,0,Y.work,Ne),Y.lenbits=Ne.bits,it){W.msg="invalid literal/lengths set",Y.mode=30;break}if(Y.distbits=6,Y.distcode=Y.distdyn,Ne={bits:Y.distbits},it=d(h,Y.lens,Y.nlen,Y.ndist,Y.distcode,0,Y.work,Ne),Y.distbits=Ne.bits,it){W.msg="invalid distances set",Y.mode=30;break}if(Y.mode=20,K===6)break e;case 20:Y.mode=21;case 21:if(6<=ce&&258<=de){W.next_out=pe,W.avail_out=de,W.next_in=oe,W.avail_in=ce,Y.hold=ie,Y.bits=ye,c(W,Me),pe=W.next_out,ne=W.output,de=W.avail_out,oe=W.next_in,ee=W.input,ce=W.avail_in,ie=Y.hold,ye=Y.bits,Y.mode===12&&(Y.back=-1);break}for(Y.back=0;Ie=($e=Y.lencode[ie&(1<>>16&255,Fe=65535&$e,!((De=$e>>>24)<=ye);){if(ce===0)break e;ce--,ie+=ee[oe++]<>qe)])>>>16&255,Fe=65535&$e,!(qe+(De=$e>>>24)<=ye);){if(ce===0)break e;ce--,ie+=ee[oe++]<>>=qe,ye-=qe,Y.back+=qe}if(ie>>>=De,ye-=De,Y.back+=De,Y.length=Fe,Ie===0){Y.mode=26;break}if(32&Ie){Y.back=-1,Y.mode=12;break}if(64&Ie){W.msg="invalid literal/length code",Y.mode=30;break}Y.extra=15&Ie,Y.mode=22;case 22:if(Y.extra){for(He=Y.extra;ye>>=Y.extra,ye-=Y.extra,Y.back+=Y.extra}Y.was=Y.length,Y.mode=23;case 23:for(;Ie=($e=Y.distcode[ie&(1<>>16&255,Fe=65535&$e,!((De=$e>>>24)<=ye);){if(ce===0)break e;ce--,ie+=ee[oe++]<>qe)])>>>16&255,Fe=65535&$e,!(qe+(De=$e>>>24)<=ye);){if(ce===0)break e;ce--,ie+=ee[oe++]<>>=qe,ye-=qe,Y.back+=qe}if(ie>>>=De,ye-=De,Y.back+=De,64&Ie){W.msg="invalid distance code",Y.mode=30;break}Y.offset=Fe,Y.extra=15&Ie,Y.mode=24;case 24:if(Y.extra){for(He=Y.extra;ye>>=Y.extra,ye-=Y.extra,Y.back+=Y.extra}if(Y.offset>Y.dmax){W.msg="invalid distance too far back",Y.mode=30;break}Y.mode=25;case 25:if(de===0)break e;if(Te=Me-de,Y.offset>Te){if((Te=Y.offset-Te)>Y.whave&&Y.sane){W.msg="invalid distance too far back",Y.mode=30;break}Ce=Te>Y.wnext?(Te-=Y.wnext,Y.wsize-Te):Y.wnext-Te,Te>Y.length&&(Te=Y.length),Ee=Y.window}else Ee=ne,Ce=pe-Y.offset,Te=Y.length;for(deL?(F=Ce[Ee+v[K]],ye[_e+v[K]]):(F=96,0),_=1<>pe)+(S-=_)]=M<<24|F<<16|z|0,S!==0;);for(_=1<>=1;if(_!==0?(ie&=_-1,ie+=_):ie=0,K++,--Me[W]==0){if(W===ee)break;W=h[p+v[K]]}if(ne>>7)]}function _e($e,Ye){$e.pending_buf[$e.pending++]=255&Ye,$e.pending_buf[$e.pending++]=Ye>>>8&255}function Me($e,Ye,Ke){$e.bi_valid>j-Ke?($e.bi_buf|=Ye<<$e.bi_valid&65535,_e($e,$e.bi_buf),$e.bi_buf=Ye>>j-$e.bi_valid,$e.bi_valid+=Ke-j):($e.bi_buf|=Ye<<$e.bi_valid&65535,$e.bi_valid+=Ke)}function Te($e,Ye,Ke){Me($e,Ke[2*Ye],Ke[2*Ye+1])}function Ce($e,Ye){for(var Ke=0;Ke|=1&$e,$e>>>=1,Ke<<=1,0<--Ye;);return Ke>>>1}function Ee($e,Ye,Ke){var rt,tt,at=new Array(v+1),Ge=0;for(rt=1;rt<=v;rt++)at[rt]=Ge=Ge+Ke[rt-1]<<1;for(tt=0;tt<=Ye;tt++){var dt=$e[2*tt+1];dt!==0&&($e[2*tt]=Ce(at[dt]++,dt))}}function De($e){var Ye;for(Ye=0;Ye>1;1<=Ke;Ke--)qe($e,at,Ke);for(tt=Bt;Ke=$e.heap[1],$e.heap[1]=$e.heap[$e.heap_len--],qe($e,at,1),rt=$e.heap[1],$e.heap[--$e.heap_max]=Ke,$e.heap[--$e.heap_max]=rt,at[2*tt]=at[2*Ke]+at[2*rt],$e.depth[tt]=($e.depth[Ke]>=$e.depth[rt]?$e.depth[Ke]:$e.depth[rt])+1,at[2*Ke+1]=at[2*rt+1]=tt,$e.heap[1]=tt++,qe($e,at,1),2<=$e.heap_len;);$e.heap[--$e.heap_max]=$e.heap[1],function(Qt,ns){var $s,Ds,Dt,St,$t,ht,Ut=ns.dyn_tree,Es=ns.max_code,Xt=ns.stat_desc.static_tree,Ys=ns.stat_desc.has_stree,Ss=ns.stat_desc.extra_bits,Bs=ns.stat_desc.extra_base,Us=ns.stat_desc.max_length,sn=0;for(St=0;St<=v;St++)Qt.bl_count[St]=0;for(Ut[2*Qt.heap[Qt.heap_max]+1]=0,$s=Qt.heap_max+1;$s>=7;tt>>=1)if(1&kt&&dt.dyn_ltree[2*Bt]!==0)return l;if(dt.dyn_ltree[18]!==0||dt.dyn_ltree[20]!==0||dt.dyn_ltree[26]!==0)return o;for(Bt=32;Bt>>3,(at=$e.static_len+3+7>>>3)<=tt&&(tt=at)):tt=at=Ke+5,Ke+4<=tt&&Ye!==-1?He($e,Ye,Ke,rt):$e.strategy===4||at===tt?(Me($e,2+(rt?1:0),3),ve($e,V,W)):(Me($e,4+(rt?1:0),3),function(dt,Bt,kt,Qt){var ns;for(Me(dt,Bt-257,5),Me(dt,kt-1,5),Me(dt,Qt-4,4),ns=0;ns>>8&255,$e.pending_buf[$e.d_buf+2*$e.last_lit+1]=255&Ye,$e.pending_buf[$e.l_buf+$e.last_lit]=255&Ke,$e.last_lit++,Ye===0?$e.dyn_ltree[2*Ke]++:($e.matches++,Ye--,$e.dyn_ltree[2*(Y[Ke]+h+1)]++,$e.dyn_dtree[2*ye(Ye)]++),$e.last_lit===$e.lit_bufsize-1},a._tr_align=function($e){Me($e,2,3),Te($e,S,V),function(Ye){Ye.bi_valid===16?(_e(Ye,Ye.bi_buf),Ye.bi_buf=0,Ye.bi_valid=0):8<=Ye.bi_valid&&(Ye.pending_buf[Ye.pending++]=255&Ye.bi_buf,Ye.bi_buf>>=8,Ye.bi_valid-=8)}($e)}},{"../utils/common":41}],53:[function(n,r,a){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,u,h,p=1,f={},g=!1,b=l.document,v=Object.getPrototypeOf&&Object.getPrototypeOf(l);v=v&&v.setTimeout?v:l,c={}.toString.call(l.process)==="[object process]"?function(A){process.nextTick(function(){_(A)})}:function(){if(l.postMessage&&!l.importScripts){var A=!0,T=l.onmessage;return l.onmessage=function(){A=!1},l.postMessage("","*"),l.onmessage=T,A}}()?(h="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",S,!1):l.attachEvent("onmessage",S),function(A){l.postMessage(h+A,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(A){_(A.data)},function(A){u.port2.postMessage(A)}):b&&"onreadystatechange"in b.createElement("script")?(d=b.documentElement,function(A){var T=b.createElement("script");T.onreadystatechange=function(){_(A),T.onreadystatechange=null,d.removeChild(T),T=null},d.appendChild(T)}):function(A){setTimeout(_,0,A)},v.setImmediate=function(A){typeof A!="function"&&(A=new Function(""+A));for(var T=new Array(arguments.length-1),D=0;D"u"?i===void 0?this:i:self)}).call(this,typeof Ih<"u"?Ih:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(zgt);var xgs=zgt.exports;const Bgt=jl(xgs);function E2e(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 ggs=()=>{gs();const[s,t]=N.useState(null),[n,r]=N.useState(null),[a,i]=N.useState("all"),[l,o]=N.useState(new Set),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState("images"),[g,b]=N.useState(null),{data:v=[],isLoading:j}=lt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:pe,error:ce}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(ce)throw ce;return pe}}),{data:_=[]}=lt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:pe,error:ce}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(ce)throw ce;return pe}}),{data:S=[]}=lt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:pe,error:ce}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(ce)throw ce;return pe}}),{data:A=[]}=lt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:pe,error:ce}=await q.from("social_accounts").select("id, platform").eq("is_active",!0);if(ce)throw ce;return pe||[]}}),T=A.length>0,D=N.useMemo(()=>a==="all"?null:S.find(pe=>pe.month===a)||null,[a,S]),L=N.useMemo(()=>[...new Set(v.map(ce=>ce.month))].sort((ce,de)=>de.localeCompare(ce)),[v]);N.useEffect(()=>{L.length>0&&a==="all"&&i(L[0])},[L,a]);const M=pe=>{try{const ce=mMe(pe,"yyyy-MM",new Date);return ks(ce,"MMMM yyyy")}catch{return pe}},F=N.useMemo(()=>a==="all"?v:v.filter(pe=>pe.month===a),[a,v]),z=N.useMemo(()=>{var pe;return a==="all"?null:((pe=_.find(ce=>ce.month===a))==null?void 0:pe.canva_link)||null},[a,_]),V=async pe=>{try{await navigator.clipboard.writeText(pe),ae.success("Caption copied to clipboard!")}catch{ae.error("Failed to copy caption")}},W=async(pe,ce)=>{try{const ie=await(await fetch(pe)).blob(),ye=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),_e=navigator.canShare&&navigator.canShare({files:[new File([ie],"test.jpg",{type:"image/jpeg"})]});if(ye&&_e){const Me=new File([ie],`social-swag-${ce}.jpg`,{type:"image/jpeg"});await navigator.share({files:[Me],title:"Social Swag Image"}),ae.success("Image ready to save!")}else{const Me=window.URL.createObjectURL(ie),Te=document.createElement("a");Te.href=Me,Te.download=`social-swag-${ce}.jpg`,document.body.appendChild(Te),Te.click(),document.body.removeChild(Te),window.URL.revokeObjectURL(Me),ae.success("Image downloaded!")}}catch(de){de.name!=="AbortError"&&ae.error("Failed to download image")}},K=pe=>{o(ce=>{const de=new Set(ce);return de.has(pe)?de.delete(pe):de.add(pe),de})},Y=()=>{o(new Set(F.map(pe=>pe.id)))},ee=()=>{o(new Set),d(!1)},ne=async()=>{const pe=F.filter(ce=>l.has(ce.id));if(pe.length===0){ae.error("No images selected");return}h(!0),ae.info(`Preparing ${pe.length} images for download...`);try{const ce=new Bgt,de=[...pe].sort((Te,Ce)=>Te.sort_order-Ce.sort_order);for(let Te=0;Te{c?K(pe.id):t(pe)};return e.jsx(Cs,{title:"Social Swag 2.0",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary via-primary/80 to-info p-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[e.jsxs(ze,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(ze,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(nl,{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($r,{defaultValue:"gallery",className:"space-y-6",children:[e.jsxs(Ur,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Zt,{value:"gallery",className:"gap-2",children:[e.jsx(nl,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Zt,{value:"scheduled",className:"gap-2",children:[e.jsx(Tl,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(ls,{value:"gallery",className:"space-y-6",children:[T?e.jsx(fe,{className:"border rounded-xl",children:e.jsx(Ae,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-muted text-2xl",children:"📸"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Ready to post!"}),e.jsx("p",{className:"text-muted-foreground",children:'Click any image and use "Create Post" to share directly to your connected accounts.'})]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(Ln,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(fe,{className:"border-2 border-dashed border-primary/30 bg-gradient-to-r from-pink-500/5 via-purple-500/5 to-blue-500/5 rounded-xl",children:e.jsx(Ae,{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(Oh,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(mu,{className:"h-5 w-5 text-pink-600"})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Post directly to social media"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect your Facebook & Instagram accounts to post images with one click!"})]}),e.jsx(B,{asChild:!0,className:"gap-2 bg-gradient-to-r from-pink-500 via-purple-500 to-blue-500 hover:from-pink-600 hover:via-purple-600 hover:to-blue-600",children:e.jsxs(Ln,{to:"/social-connections",children:[e.jsx(El,{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:L.map(pe=>e.jsx("button",{onClick:()=>i(pe),className:Et("px-4 py-2 rounded-full text-sm font-medium transition-all",a===pe?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:M(pe)},pe))}),a!=="all"&&(z?e.jsxs("a",{href:z,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",M(a)," Images in Canva"]}):e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm text-muted-foreground/50",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",M(a)," Images in Canva"]}))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-full",children:[e.jsxs("button",{onClick:()=>{f("images"),ee()},className:Et("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(nl,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{f("reels"),ee()},className:Et("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(Ph,{className:"h-4 w-4"}),"Reels"]})]}),p==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:c?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:Y,className:"gap-2",children:["Select All (",F.length,")"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ee,className:"gap-2",children:[e.jsx(Fn,{className:"h-4 w-4"}),"Cancel"]}),l.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{size:"sm",onClick:ne,disabled:u,className:"gap-2",children:[e.jsx(Da,{className:"h-4 w-4"}),u?"Downloading...":`Download ${l.size} Selected`]}),e.jsx("span",{className:"text-xs text-muted-foreground hidden sm:inline",children:"Please ensure your browser allows downloads from the LevelUp Dashboard."})]})]}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"gap-2",children:[e.jsx(Lr,{className:"h-4 w-4"}),"Select Images"]})})]}),j&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!j&&p==="images"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:F.map(pe=>{const ce=l.has(pe.id);return e.jsx(fe,{className:Et("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",c&&ce&&"ring-2 ring-primary ring-offset-2"),onClick:()=>oe(pe),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:E2e(pe.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"}),pe.post_date&&!c&&e.jsx("div",{className:"absolute top-0 left-0 w-24 h-24 overflow-hidden pointer-events-none",children:e.jsx("div",{className:"absolute flex items-center justify-center text-white font-bold text-[10px] tracking-wider uppercase",style:{top:"20px",left:"-34px",width:"136px",transform:"rotate(-45deg)",backgroundColor:"#2d5052",padding:"5px 0",boxShadow:"0 2px 4px rgba(0,0,0,0.25)"},children:ks(new Date(pe.post_date+"T00:00:00"),"MMM d")})}),c&&e.jsx("div",{className:Et("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",ce?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:ce&&e.jsx(Lr,{className:"h-4 w-4"})}),!c&&e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors duration-300 flex items-center justify-center",children:e.jsx("span",{className:"text-white font-medium opacity-0 group-hover:opacity-100 transition-opacity duration-300 bg-primary px-4 py-2 rounded-full text-sm",children:"View Details"})})]})},pe.id)})}),F.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(nl,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No images available for this month yet."})]})]}),!j&&p==="reels"&&e.jsx(e.Fragment,{children:D?e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4",children:e.jsx(fe,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>r(D),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:E2e(D.image_url,400,75),alt:"Reel preview",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-105",loading:"lazy",decoding:"async"}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsxs(ze,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(Ph,{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(Ph,{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(bs,{open:!!s,onOpenChange:()=>t(null),children:e.jsx(vs,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:s&&e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsx("div",{className:"md:w-1/2 bg-muted",children:e.jsx("div",{className:"aspect-[4/5]",children:e.jsx("img",{src:E2e(s.image_url,900,85),alt:"Social swag",className:"w-full h-full object-cover",decoding:"async"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-muted-foreground mb-4",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(yr,{className:"h-4 w-4"}),ks(new Date(s.created_at),"MMMM d, yyyy")]}),s.post_date&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-medium rounded-full px-3 py-1 text-xs text-white",style:{background:"#406E71"},children:[e.jsx(yr,{className:"h-3.5 w-3.5"}),"Post on ",ks(new Date(s.post_date+"T00:00:00"),"MMMM d, yyyy")]})]}),e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Caption"}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 max-h-64 overflow-y-auto",children:e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:s.caption})})]}),e.jsxs("div",{className:"flex flex-col gap-3 mt-6",children:[e.jsxs(B,{onClick:()=>{b({imageUrl:s.image_url,imageId:s.id,caption:s.caption})},className:"w-full gap-2 bg-gradient-to-r from-pink-500 via-purple-500 to-blue-500 hover:from-pink-600 hover:via-purple-600 hover:to-blue-600 text-white",children:[e.jsx(cr,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(B,{variant:"outline",onClick:()=>V(s.caption),className:"flex-1 gap-2",children:[e.jsx(ta,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(B,{variant:"outline",onClick:()=>W(s.image_url,s.id),className:"flex-1 gap-2",children:[e.jsx(Da,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(bs,{open:!!n,onOpenChange:()=>r(null),children:e.jsx(vs,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:n&&e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsx("div",{className:"md:w-1/2 bg-black flex items-center justify-center",children:e.jsx("div",{className:"aspect-[9/16] max-h-[70vh]",children:e.jsx("img",{src:n.image_url,alt:"Reel preview",className:"w-full h-full object-contain"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-4",children:[e.jsx(Ph,{className:"h-4 w-4"}),"Monthly Reel"]}),n.caption&&e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Caption"}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 max-h-64 overflow-y-auto",children:e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:n.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[n.caption&&e.jsxs(B,{onClick:()=>V(n.caption||""),className:"flex-1 gap-2",children:[e.jsx(ta,{className:"h-4 w-4"}),"Copy Caption"]}),n.canva_link&&e.jsxs(B,{variant:"outline",onClick:()=>window.open(n.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(tr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(pgs,{open:!!g,onOpenChange:pe=>!pe&&b(null),imageUrl:(g==null?void 0:g.imageUrl)||"",imageId:(g==null?void 0:g.imageId)||"",defaultCaption:(g==null?void 0:g.caption)||"",swagItemId:g==null?void 0:g.imageId})]}),e.jsx(ls,{value:"scheduled",children:e.jsx(fgs,{})})]})]})})},ygs=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:nl,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:zr,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:Xi,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:yo,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:hu,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:Mv,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:_w,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function vgs(){return e.jsx(Cs,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"Marketing Studio | LevelUp"}),e.jsx("meta",{name:"description",content:"Brand any image, video, listing, or milestone in seconds — no AI credits used."})]}),e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(ze,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," New"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"Marketing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-2xl mt-1",children:"Your one-stop creative hub. Drop in any photo or video, and walk away with a fully branded export — no design skills, no AI credits."})]}),e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs(Ln,{to:"/marketing-studio/brand-kit",children:[e.jsx(xl,{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:ygs.map(s=>{const t=s.icon,n=e.jsxs(fe,{className:`group relative overflow-hidden transition-all h-full ${s.comingSoon?"opacity-70":"hover:shadow-xl hover:-translate-y-0.5 cursor-pointer"}`,children:[e.jsx("div",{className:`absolute inset-x-0 top-0 h-1 bg-gradient-to-r ${s.color}`}),e.jsxs(Ae,{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(ze,{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(Ln,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function kU(){const s=fa();return lt({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("marketing_brand_presets").select("*").eq("user_id",s).order("is_default",{ascending:!1}).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function bgs(){const{data:s,...t}=kU();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function _gs(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");if(n.is_default&&await q.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),n.id){const{id:r,...a}=n,{data:i,error:l}=await q.from("marketing_brand_presets").update(a).eq("id",r).eq("user_id",s).select().single();if(l)throw l;return i}else{const{data:r,error:a}=await q.from("marketing_brand_presets").insert({...n,user_id:s}).select().single();if(a)throw a;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}function wgs(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{const{error:r}=await q.from("marketing_brand_presets").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function jgs(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await q.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function Ngs({preset:s,onSaved:t,onCancel:n}){var b;const r=fa(),a=_gs(),i=wgs(),l=N.useRef(null),o=N.useRef(null),[c,d]=N.useState(null),[u,h]=N.useState({name:(s==null?void 0:s.name)??"My Brand",is_default:(s==null?void 0:s.is_default)??!0,display_name:(s==null?void 0:s.display_name)??"",phone:(s==null?void 0:s.phone)??"",email:(s==null?void 0:s.email)??"",license_number:(s==null?void 0:s.license_number)??"",tagline:(s==null?void 0:s.tagline)??"",website_url:(s==null?void 0:s.website_url)??"",headshot_url:(s==null?void 0:s.headshot_url)??"",brokerage_logo_url:(s==null?void 0:s.brokerage_logo_url)??"",brand_color:(s==null?void 0:s.brand_color)??"#0f172a",accent_color:(s==null?void 0:s.accent_color)??"#3b82f6"});N.useEffect(()=>{s||(async()=>{if(!r)return;const{supabase:v}=await vi(async()=>{const{supabase:_}=await Promise.resolve().then(()=>dOt);return{supabase:_}},void 0),{data:j}=await v.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();j&&h(_=>({..._,display_name:_.display_name||(j.name??""),email:_.email||(j.email??""),phone:_.phone||(j.phone??""),headshot_url:_.headshot_url||(j.avatar_url??""),website_url:_.website_url||(j.website_url??""),tagline:_.tagline||(j.title??"")}))})()},[r]);const p=async(v,j)=>{if(r){d(v);try{const _=await jgs(r,j,v);h(S=>({...S,[v==="headshot"?"headshot_url":"brokerage_logo_url"]:_}))}catch(_){ae.error(_.message||"Upload failed")}finally{d(null)}}},f=async()=>{try{const v=await a.mutateAsync({id:s==null?void 0:s.id,...u});ae.success("Brand preset saved"),t==null||t(v)}catch(v){ae.error(v.message||"Save failed")}},g=async()=>{s!=null&&s.id&&confirm("Delete this brand preset?")&&(await i.mutateAsync(s.id),ae.success("Preset deleted"),n==null||n())};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Preset name"}),e.jsx(ge,{value:u.name,onChange:v=>h({...u,name:v.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(vn,{checked:u.is_default,onCheckedChange:v=>h({...u,is_default:v})}),e.jsx(se,{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(se,{children:"Display name"}),e.jsx(ge,{value:u.display_name,onChange:v=>h({...u,display_name:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ge,{value:u.phone,onChange:v=>h({...u,phone:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ge,{value:u.email,onChange:v=>h({...u,email:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"License #"}),e.jsx(ge,{value:u.license_number,onChange:v=>h({...u,license_number:v.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Tagline"}),e.jsx(ge,{value:u.tagline,onChange:v=>h({...u,tagline:v.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Website"}),e.jsx(ge,{value:u.website_url,onChange:v=>h({...u,website_url:v.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(aa,{className:"h-16 w-16",children:[e.jsx(ri,{src:u.headshot_url||void 0}),e.jsx(ia,{children:((b=u.display_name)==null?void 0:b[0])??"A"})]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=l.current)==null?void 0:v.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:v=>{var j;return((j=v.target.files)==null?void 0:j[0])&&p("headshot",v.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brokerage logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-16 w-24 bg-muted rounded flex items-center justify-center overflow-hidden border",children:u.brokerage_logo_url?e.jsx("img",{src:u.brokerage_logo_url,alt:"logo",className:"max-h-full max-w-full object-contain"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"No logo"})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=o.current)==null?void 0:v.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:v=>{var j;return((j=v.target.files)==null?void 0:j[0])&&p("logo",v.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Brand color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.brand_color,onChange:v=>h({...u,brand_color:v.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(ge,{value:u.brand_color,onChange:v=>h({...u,brand_color:v.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.accent_color,onChange:v=>h({...u,accent_color:v.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(ge,{value:u.accent_color,onChange:v=>h({...u,accent_color:v.target.value})})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx("div",{children:(s==null?void 0:s.id)&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:g,className:"text-destructive",children:[e.jsx(bn,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs(B,{onClick:f,disabled:a.isPending,children:[a.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function kgs(){const{data:s,isLoading:t}=kU(),[n,r]=N.useState(null);return e.jsx(Cs,{title:"Brand Kit",children:e.jsxs("div",{className:"container max-w-5xl py-6 md:py-8 space-y-6 px-4",children:[e.jsx(Yo,{children:e.jsx("title",{children:"Brand Kit | Marketing Studio"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Ln,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Wr,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Brand Kit"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Save your branding once — apply it across every Marketing Studio module."})]}),e.jsxs(B,{onClick:()=>r("new"),className:"w-full sm:w-auto",children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," New preset"]})]}),t&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading..."}),!t&&s&&s.length===0&&e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"py-12 text-center space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Create your first brand preset"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"We'll pre-fill from your profile. You can have multiple presets — Personal, Team, Luxury division — and switch between them."}),e.jsxs(B,{onClick:()=>r("new"),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Create preset"]})]})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:s==null?void 0:s.map(a=>e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(Mt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(ua,{className:"h-3 w-3"})," Default"]})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(ja,{className:"h-4 w-4"})})]}),e.jsx(Hn,{children:a.display_name})]}),e.jsxs(Ae,{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(bs,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(ws,{children:e.jsx(_s,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(Ngs,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const d3e=[{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"}],Sgs=s=>d3e.find(t=>t.id===s)??d3e[0];function Cgs(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 Tgs({value:s,onChange:t,mediaType:n}){const r=d3e.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:Et("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(Egs,{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 Egs({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 Ags=Math.PI/180;function Mgs(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const tA=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},xa={_global:tA,version:"10.2.5",isBrowser:Mgs(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return xa.angleDeg?s*Ags: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 xa.DD.isDragging},isTransforming(){var s,t;return(t=(s=xa.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!xa.DD.node},releaseCanvasOnDestroy:!0,document:tA.document,_injectGlobal(s){typeof tA.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),tA.Konva=s}},Wu=s=>{xa[s.prototype.getClassName()]=s};xa._injectGlobal(xa);const Igs=`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"; `,QVe=()=>{if(typeof document>"u")throw new Error(Igs)};class J0{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 J0(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const n=this.m;return{x:n[0]*t.x+n[2]*t.y+n[4],y:n[1]*t.x+n[3]*t.y+n[5]}}translate(t,n){return this.m[4]+=this.m[0]*t+this.m[2]*n,this.m[5]+=this.m[1]*t+this.m[3]*n,this}scale(t,n){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=n,this.m[3]*=n,this}rotate(t){const n=Math.cos(t),r=Math.sin(t),a=this.m[0]*n+this.m[2]*r,i=this.m[1]*n+this.m[3]*r,l=this.m[0]*-r+this.m[2]*n,o=this.m[1]*-r+this.m[3]*n;return this.m[0]=a,this.m[1]=i,this.m[2]=l,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,n){const r=this.m[0]+this.m[2]*n,a=this.m[1]+this.m[3]*n,i=this.m[2]+this.m[0]*t,l=this.m[3]+this.m[1]*t;return this.m[0]=r,this.m[1]=a,this.m[2]=i,this.m[3]=l,this}multiply(t){const n=this.m[0]*t.m[0]+this.m[2]*t.m[1],r=this.m[1]*t.m[0]+this.m[3]*t.m[1],a=this.m[0]*t.m[2]+this.m[2]*t.m[3],i=this.m[1]*t.m[2]+this.m[3]*t.m[3],l=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],o=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),n=this.m[3]*t,r=-this.m[1]*t,a=-this.m[2]*t,i=this.m[0]*t,l=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const t=this.m[0],n=this.m[1],r=this.m[2],a=this.m[3],i=this.m[4],l=this.m[5],o=t*a-n*r,c={x:i,y:l,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||n!=0){const d=Math.sqrt(t*t+n*n);c.rotation=n>0?Math.acos(t/d):-Math.acos(t/d),c.scaleX=d,c.scaleY=o/d,c.skewX=(t*r+n*a)/o,c.skewY=0}else if(r!=0||a!=0){const d=Math.sqrt(r*r+a*a);c.rotation=Math.PI/2-(a>0?Math.acos(-r/d):-Math.acos(r/d)),c.scaleX=o/d,c.scaleY=d,c.skewX=0,c.skewY=(t*r+n*a)/o}return c.rotation=yn._getRotation(c.rotation),c}}const Pgs="[object Array]",Lgs="[object Number]",Dgs="[object String]",Rgs="[object Boolean]",Ogs=Math.PI/180,Fgs=180/Math.PI,bF="#",zgs="",Bgs="0",$gs="Konva warning: ",XVe="Konva error: ",Ugs="rgb(",A2e={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},qgs=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let RH=[],_F=null;const Vgs=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},yn={_isElement(s){return!!(s&&s.nodeType==1)},_isFunction(s){return!!(s&&s.constructor&&s.call&&s.apply)},_isPlainObject(s){return!!s&&s.constructor===Object},_isArray(s){return Object.prototype.toString.call(s)===Pgs},_isNumber(s){return Object.prototype.toString.call(s)===Lgs&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===Dgs},_isBoolean(s){return Object.prototype.toString.call(s)===Rgs},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){RH.push(s),RH.length===1&&Vgs(function(){const t=RH;RH=[],t.forEach(function(n){n()})})},createCanvasElement(){QVe();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return QVe(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const n=yn.createImageElement();n.onload=function(){t(n)},n.src=s},_rgbToHex(s,t,n){return((1<<24)+(s<<16)+(t<<8)+n).toString(16).slice(1)},_hexToRgb(s){s=s.replace(bF,zgs);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=Bgs+s;return bF+s},isCanvasFarblingActive(){if(_F!==null)return _F;if(typeof document>"u")return _F=!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 _F=r,this.releaseCanvas(s),_F},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),bF+this._rgbToHex(s,t,n)},getSnappedHexColor(s){const t=this._hexToRgb(s);return bF+this._rgbToHex(Math.round(t.r/5)*5,Math.round(t.g/5)*5,Math.round(t.b/5)*5)},getRGB(s){let t;return s in A2e?(t=A2e[s],{r:t[0],g:t[1],b:t[2]}):s[0]===bF?this._hexToRgb(s.substring(1)):s.substr(0,4)===Ugs?(t=qgs.exec(s.replace(/ /g,"")),{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}):{r:0,g:0,b:0}},colorToRGBA(s){return s=s||"black",yn._namedColorToRBA(s)||yn._hex3ColorToRGBA(s)||yn._hex4ColorToRGBA(s)||yn._hex6ColorToRGBA(s)||yn._hex8ColorToRGBA(s)||yn._rgbColorToRGBA(s)||yn._rgbaColorToRGBA(s)||yn._hslColorToRGBA(s)},_namedColorToRBA(s){const t=A2e[s.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:1}:null},_rgbColorToRGBA(s){if(s.indexOf("rgb(")===0){s=s.match(/rgb\(([^)]+)\)/)[1];const t=s.split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:1}}},_rgbaColorToRGBA(s){if(s.indexOf("rgba(")===0){s=s.match(/rgba\(([^)]+)\)/)[1];const t=s.split(/ *, */).map((n,r)=>n.slice(-1)==="%"?r===3?parseInt(n)/100:parseInt(n)/100*255:Number(n));return{r:t[0],g:t[1],b:t[2],a:t[3]}}},_hex8ColorToRGBA(s){if(s[0]==="#"&&s.length===9)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:parseInt(s.slice(7,9),16)/255}},_hex6ColorToRGBA(s){if(s[0]==="#"&&s.length===7)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:1}},_hex4ColorToRGBA(s){if(s[0]==="#"&&s.length===5)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:parseInt(s[4]+s[4],16)/255}},_hex3ColorToRGBA(s){if(s[0]==="#"&&s.length===4)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:1}},_hslColorToRGBA(s){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(s)){const[t,...n]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(s),r=Number(n[0])/360,a=Number(n[1])/100,i=Number(n[2])/100;let l,o,c;if(a===0)return c=i*255,{r:Math.round(c),g:Math.round(c),b:Math.round(c),a:1};i<.5?l=i*(1+a):l=i+a-i*a;const d=2*i-l,u=[0,0,0];for(let h=0;h<3;h++)o=r+1/3*-(h-1),o<0&&o++,o>1&&o--,6*o<1?c=d+(l-d)*6*o:2*o<1?c=l:3*o<2?c=d+(l-d)*(2/3-o)*6:c=d,u[h]=c*255;return{r:Math.round(u[0]),g:Math.round(u[1]),b:Math.round(u[2]),a:1}}},haveIntersection(s,t){return!(t.x>s.x+s.width||t.x+t.widths.y+s.height||t.y+t.height1?(l=n,o=r,c=(n-a)*(n-a)+(r-i)*(r-i)):(l=s+u*(n-s),o=t+u*(r-t),c=(l-a)*(l-a)+(o-i)*(o-i))}return[l,o,c]},_getProjectionToLine(s,t,n){const r=yn.cloneObject(s);let a=Number.MAX_VALUE;return t.forEach(function(i,l){if(!n&&l===t.length-1)return;const o=t[(l+1)%t.length],c=yn._getProjectionToSegment(i.x,i.y,o.x,o.y,s.x,s.y),d=c[0],u=c[1],h=c[2];ht.length){const l=t;t=s,s=l}for(let l=0;l{t.width=0,t.height=0})},drawRoundedRectPath(s,t,n,r){let a=t<0?t:0,i=n<0?n:0;t=Math.abs(t),n=Math.abs(n);let l=0,o=0,c=0,d=0;typeof r=="number"?l=o=c=d=Math.min(r,t/2,n/2):(l=Math.min(r[0]||0,t/2,n/2),o=Math.min(r[1]||0,t/2,n/2),d=Math.min(r[2]||0,t/2,n/2),c=Math.min(r[3]||0,t/2,n/2)),s.moveTo(a+l,i),s.lineTo(a+t-o,i),s.arc(a+t-o,i+o,o,Math.PI*3/2,0,!1),s.lineTo(a+t,i+n-d),s.arc(a+t-d,i+n-d,d,0,Math.PI/2,!1),s.lineTo(a+c,i+n),s.arc(a+c,i+n-c,c,Math.PI/2,Math.PI,!1),s.lineTo(a,i+l),s.arc(a+l,i+l,l,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(s,t,n,r,a){r=Math.abs(r);for(let i=0;itypeof u=="number"?Math.floor(u):u)),i+=Ggs+d.join(JVe)+Wgs)):(i+=o.property,t||(i+=Xgs+o.val)),i+=Zgs;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=e0s&&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=eHe.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=Hgs(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 $l._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];$l._dragElements.forEach((n,r)=>{const{node:a}=n,i=a.getStage();i.setPointersPositions(s),n.pointerId===void 0&&(n.pointerId=yn._getFirstPointerId(s));const l=i._changedPointerPositions.find(o=>o.id===n.pointerId);if(l){if(n.dragStatus!=="dragging"){const o=a.dragDistance();if(Math.max(Math.abs(l.x-n.startPointerPos.x),Math.abs(l.y-n.startPointerPos.y)){n.getStage()&&n.fire("dragmove",{type:"dragmove",target:n,evt:s},!0)})},_endDragBefore(s){const t=[];$l._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")&&($l.justDragged=!0,xa._mouseListenClick=!1,xa._touchListenClick=!1,xa._pointerListenClick=!1,n.dragStatus="stopped");const l=n.node.getLayer()||n.node instanceof xa.Stage&&n.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(n=>{n.draw()})},_endDragAfter(s){$l._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&$l._dragElements.delete(n)})}};xa.isBrowser&&(window.addEventListener("mouseup",$l._endDragBefore,!0),window.addEventListener("touchend",$l._endDragBefore,!0),window.addEventListener("touchcancel",$l._endDragBefore,!0),window.addEventListener("mousemove",$l._drag),window.addEventListener("touchmove",$l._drag),window.addEventListener("mouseup",$l._endDragAfter,!1),window.addEventListener("touchend",$l._endDragAfter,!1),window.addEventListener("touchcancel",$l._endDragAfter,!1));function aC(s){return yn._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||yn._isBoolean(s)?s:Object.prototype.toString.call(s)}function $gt(s){return s>255?255:s<0?0:Math.round(s)}function oa(){if(xa.isUnminified)return function(s,t){return yn._isNumber(s)||yn.warn(aC(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function bve(s){if(xa.isUnminified)return function(t,n){let r=yn._isNumber(t),a=yn._isArray(t)&&t.length==s;return!r&&!a&&yn.warn(aC(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function RIe(){if(xa.isUnminified)return function(s,t){return yn._isNumber(s)||s==="auto"||yn.warn(aC(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function ZM(){if(xa.isUnminified)return function(s,t){return yn._isString(s)||yn.warn(aC(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function Ugt(){if(xa.isUnminified)return function(s,t){const n=yn._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||yn.warn(aC(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function r0s(){if(xa.isUnminified)return function(s,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&s instanceof n||(yn._isArray(s)?s.forEach(function(r){yn._isNumber(r)||yn.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):yn.warn(aC(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function Ob(){if(xa.isUnminified)return function(s,t){return s===!0||s===!1||yn.warn(aC(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function a0s(s){if(xa.isUnminified)return function(t,n){return t==null||yn.isObject(t)||yn.warn(aC(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const wF="get",jF="set",Ps={addGetterSetter(s,t,n,r,a){Ps.addGetter(s,t,n),Ps.addSetter(s,t,r,a),Ps.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=wF+yn._capitalize(t);s.prototype[r]=s.prototype[r]||function(){const a=this.attrs[t];return a===void 0?n:a}},addSetter(s,t,n,r){const a=jF+yn._capitalize(t);s.prototype[a]||Ps.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=jF+yn._capitalize(t);s.prototype[a]=function(i){return n&&i!==void 0&&i!==null&&(i=n.call(this,i,t)),this._setAttr(t,i),r&&r.call(this),this}},addComponentsGetterSetter(s,t,n,r,a){const i=n.length,l=yn._capitalize,o=wF+l(t),c=jF+l(t);s.prototype[o]=function(){const u={};for(let h=0;h{this._setAttr(t+l(p),void 0)}),this._fireChangeEvent(t,h,u),a&&a.call(this),this},Ps.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=yn._capitalize(t),r=jF+n,a=wF+n;s.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,n,r){yn.error("Adding deprecated "+t);const a=wF+yn._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){yn.error(i);const l=this.attrs[t];return l===void 0?n:l},Ps.addSetter(s,t,r,function(){yn.error(i)}),Ps.addOverloadedGetterSetter(s,t)},backCompat(s,t){yn.each(t,function(n,r){const a=s.prototype[r],i=wF+yn._capitalize(n),l=jF+yn._capitalize(n);function o(){a.apply(this,arguments),yn.error('"'+n+'" method is deprecated and will be removed soon. Use ""'+r+'" instead.')}s.prototype[n]=o,s.prototype[i]=o,s.prototype[l]=o})},afterSetFilter(){this._filterUpToDate=!1}};function i0s(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=xa.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=xa.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=xa.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=xa.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=xa.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=xa.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:yn.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const spe="absoluteOpacity",sHe="allEventListeners",v2="absoluteTransform",nHe="absoluteScale",m3="canvas",o0s="Change",l0s="children",c0s="konva",u3e="listening",d0s="mouseenter",u0s="mouseleave",h0s="pointerenter",m0s="pointerleave",p0s="touchenter",f0s="touchleave",rHe="set",aHe="Shape",npe=" ",iHe="stage",Hk="transform",x0s="Stage",h3e="visible",g0s=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(npe);let y0s=1,wa=class _7{constructor(t){this._id=y0s++,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===Hk||t===v2)&&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===Hk||t===v2)&&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(npe);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(m3)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===v2&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(m3)){const{scene:t,filter:n,hit:r}=this._cache.get(m3);yn.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(m3)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const n=t||{};let r={};(n.x===void 0||n.y===void 0||n.width===void 0||n.height===void 0)&&(r=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let a=Math.ceil(n.width||r.width),i=Math.ceil(n.height||r.height),l=n.pixelRatio,o=n.x===void 0?Math.floor(r.x):n.x,c=n.y===void 0?Math.floor(r.y):n.y,d=n.offset||0,u=n.drawBorder||!1,h=n.hitCanvasPixelRatio||1;if(!a||!i){yn.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const p=Math.abs(Math.round(r.x)-o)>.5?1:0,f=Math.abs(Math.round(r.y)-c)>.5?1:0;a+=d*2+p,i+=d*2+f,o-=d,c-=d;const g=new xS({pixelRatio:l,width:a,height:i}),b=new xS({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),v=new DIe({pixelRatio:h,width:a,height:i}),j=g.getContext(),_=v.getContext(),S=new xS({width:g.width/g.pixelRatio+Math.abs(o),height:g.height/g.pixelRatio+Math.abs(c),pixelRatio:g.pixelRatio}),A=S.getContext();return v.isCache=!0,g.isCache=!0,this._cache.delete(m3),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(g.getContext()._context.imageSmoothingEnabled=!1,b.getContext()._context.imageSmoothingEnabled=!1),j.save(),_.save(),A.save(),j.translate(-o,-c),_.translate(-o,-c),A.translate(-o,-c),S.x=o,S.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(spe),this._clearSelfAndDescendantCache(nHe),this.drawScene(g,this,S),this.drawHit(v,this),this._isUnderCache=!1,j.restore(),_.restore(),u&&(j.save(),j.beginPath(),j.rect(0,0,a,i),j.closePath(),j.setAttr("strokeStyle","red"),j.setAttr("lineWidth",5),j.stroke(),j.restore()),yn.releaseCanvas(S._canvas),this._cache.set(m3,{scene:g,filter:b,hit:v,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(m3)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,n){const r=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}];let a=1/0,i=1/0,l=-1/0,o=-1/0;const c=this.getAbsoluteTransform(n);return r.forEach(function(d){const u=c.point(d);a===void 0&&(a=l=u.x,i=o=u.y),a=Math.min(a,u.x),i=Math.min(i,u.y),l=Math.max(l,u.x),o=Math.max(o,u.y)}),{x:a,y:i,width:l-a,height:o-i}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const n=this._getCanvasCache();t.translate(n.x,n.y);const r=this._getCachedSceneCanvas(),a=r.pixelRatio;t.drawImage(r._canvas,0,0,r.width/a,r.height/a),t.restore()}_drawCachedHitCanvas(t){const n=this._getCanvasCache(),r=n.hit;t.save(),t.translate(n.x,n.y),t.drawImage(r._canvas,0,0,r.width/r.pixelRatio,r.height/r.pixelRatio),t.restore()}_getCachedSceneCanvas(){let t=this.filters(),n=this._getCanvasCache(),r=n.scene,a=n.filter,i=a.getContext(),l,o,c,d;if(!t||t.length===0)return r;if(this._filterUpToDate)return a;let u=!0;for(let p=0;p{this.isAncestorOf(t.node)&&$l._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(v2),this._clearSelfAndDescendantCache(spe),this._clearSelfAndDescendantCache(nHe),this._clearSelfAndDescendantCache(iHe),this._clearSelfAndDescendantCache(h3e),this._clearSelfAndDescendantCache(u3e)}_remove(){this._clearCaches();const t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(t){const n="get"+yn._capitalize(t);return yn._isFunction(this[n])?this[n]():this.attrs[t]}getAncestors(){let t=this.getParent(),n=[];for(;t;)n.push(t),t=t.getParent();return n}getAttrs(){return this.attrs||{}}setAttrs(t){return this._batchTransformChanges(()=>{let n,r;if(!t)return this;for(n in t)n!==l0s&&(r=rHe+yn._capitalize(n),yn._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(u3e,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(h3e,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;$l._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===r)&&(a=!0)});const i=!n&&!xa.hitOnDragEnabled&&(a||xa.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!==x0s&&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(Hk),this._clearSelfAndDescendantCache(v2)),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 J0,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(Hk);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(Hk),this._clearSelfAndDescendantCache(v2),this}_setTransform(t){let n;for(n in t)this.attrs[n]=t[n]}_clearTransform(){const t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){let n=t.x,r=t.y,a=this.x(),i=this.y();return n!==void 0&&(a+=n),r!==void 0&&(i+=r),this.setPosition({x:a,y:i}),this}_eachAncestorReverse(t,n){let r=[],a=this.getParent(),i,l;if(!(n&&n._id===this._id)){for(r.unshift(this);a&&(!n||a._id!==n._id);)r.unshift(a),a=a.parent;for(i=r.length,l=0;l0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return yn.warn("Node has no parent. moveToBottom function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(t){if(!this.parent)return yn.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&yn.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const n=this.index;return this.parent.children.splice(n,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(spe,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let t=this.opacity();const n=this.getParent();return n&&!n._isUnderCache&&(t*=n.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){let t=this.getAttrs(),n,r,a,i,l;const o={attrs:{},className:this.getClassName()};for(n in t)r=t[n],l=yn.isObject(r)&&!yn._isPlainObject(r)&&!yn._isArray(r),!l&&(a=typeof this[n]=="function"&&this[n],delete t[n],i=a?a.call(this):null,t[n]=r,i!==r&&(o.attrs[n]=r));return yn._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,n,r){const a=[];n&&this._isMatch(t)&&a.push(this);let i=this.parent;for(;i;){if(i===r)return a;i._isMatch(t)&&a.push(i),i=i.parent}return a}isAncestorOf(t){return!1}findAncestor(t,n,r){return this.findAncestors(t,n,r)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);let n=t.replace(/ /g,"").split(","),r=n.length,a,i;for(a=0;a{try{const a=t==null?void 0:t.callback;a&&delete t.callback,yn._urlToImage(this.toDataURL(t),function(i){n(i),a==null||a(i)})}catch(a){r(a)}})}toBlob(t){return new Promise((n,r)=>{try{const a=t==null?void 0:t.callback;a&&delete t.callback,this.toCanvas(t).toBlob(i=>{n(i),a==null||a(i)},t==null?void 0:t.mimeType,t==null?void 0:t.quality)}catch(a){r(a)}})}setSize(t){return this.width(t.width),this.height(t.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():xa.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;$l._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=$l._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&$l._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const n=this.getStage();if(!n)return!1;const r={x:-t.x,y:-t.y,width:n.width()+2*t.x,height:n.height()+2*t.y};return yn.haveIntersection(r,this.getClientRect())}static create(t,n){return yn._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=_7.prototype.getClassName.call(t),a=t.children,i,l,o;n&&(t.attrs.container=n),xa[r]||(yn.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const c=xa[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=wa.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=wa.prototype.clone.call(this,t);return this.getChildren().forEach(function(r){n.add(r.clone())}),n}getAllIntersections(t){const n=[];return this.find("Shape").forEach(r=>{r.isVisible()&&r.intersects(t)&&n.push(r)}),n}_clearSelfAndDescendantCache(t){var n;super._clearSelfAndDescendantCache(t),!this.isCached()&&((n=this.children)===null||n===void 0||n.forEach(function(r){r._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;(t=this.children)===null||t===void 0||t.forEach(function(n,r){n.index=r}),this._requestDraw()}drawScene(t,n,r){const a=this.getLayer(),i=t||a&&a.getCanvas(),l=i&&i.getContext(),o=this._getCanvasCache(),c=o&&o.scene,d=i&&i.isCache;if(!this.isVisible()&&!d)return this;if(c){l.save();const u=this.getAbsoluteTransform(n).getMatrix();l.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(l),l.restore()}else this._drawChildren("drawScene",i,n,r);return this}drawHit(t,n){if(!this.shouldDrawHit(n))return this;const r=this.getLayer(),a=t||r&&r.hitCanvas,i=a&&a.getContext(),l=this._getCanvasCache();if(l&&l.hit){i.save();const c=this.getAbsoluteTransform(n).getMatrix();i.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedHitCanvas(i),i.restore()}else this._drawChildren("drawHit",a,n);return this}_drawChildren(t,n,r,a){var i;const l=n&&n.getContext(),o=this.clipWidth(),c=this.clipHeight(),d=this.clipFunc(),u=typeof o=="number"&&typeof c=="number"||d,h=r===this;if(u){l.save();const f=this.getAbsoluteTransform(r);let g=f.getMatrix();l.transform(g[0],g[1],g[2],g[3],g[4],g[5]),l.beginPath();let b;if(d)b=d.call(this,l,this);else{const v=this.clipX(),j=this.clipY();l.rect(v||0,j||0,o,c)}l.clip.apply(l,b),g=f.copy().invert().getMatrix(),l.transform(g[0],g[1],g[2],g[3],g[4],g[5])}const p=!h&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";p&&(l.save(),l._applyGlobalCompositeOperation(this)),(i=this.children)===null||i===void 0||i.forEach(function(f){f[t](n,r,a)}),p&&l.restore(),u&&l.restore()}getClientRect(t={}){var n;const r=t.skipTransform,a=t.relativeTo;let i,l,o,c,d={x:1/0,y:1/0,width:0,height:0};const u=this;(n=this.children)===null||n===void 0||n.forEach(function(f){if(!f.visible())return;const g=f.getClientRect({relativeTo:u,skipShadow:t.skipShadow,skipStroke:t.skipStroke});g.width===0&&g.height===0||(i===void 0?(i=g.x,l=g.y,o=g.x+g.width,c=g.y+g.height):(i=Math.min(i,g.x),l=Math.min(l,g.y),o=Math.max(o,g.x+g.width),c=Math.max(c,g.y+g.height)))});const h=this.find("Shape");let p=!1;for(let f=0;fs.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",AI=s=>{const t=S7(s);if(t==="pointer")return xa.pointerEventsEnabled&&I2e.pointer;if(t==="touch")return I2e.touch;if(t==="mouse")return I2e.mouse};function lHe(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&yn.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const k0s="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);",yz=[];let _ve=class extends py{constructor(t){super(lHe(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),yz.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{lHe(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||yn.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}setContainer(t){if(typeof t===b0s){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&&yz.splice(n,1),yn.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(yn.warn(k0s),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 xS({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+oHe,this.content.style.height=n+oHe),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;aj0s&&yn.warn("The stage has "+r+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),t.setSize({width:this.width(),height:this.height()}),t.draw(),xa.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return Vgt(t,this)}setPointerCapture(t){Hgt(t,this)}releaseCapture(t){gz(t)}getLayers(){return this.children}_bindContentEvents(){xa.isBrowser&&N0s.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this[n](r)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const n=AI(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=AI(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=AI(t.type),r=S7(t.type);if(!n)return;this.setPointersPositions(t);const a=this._getTargetShape(r),i=!(xa.isDragging()||xa.isTransforming())||xa.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=AI(t.type),r=S7(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if($l.justDragged=!1,xa["_"+r+"ListenClick"]=!0,!l||!l.isListening()){this[r+"ClickStartShape"]=void 0;return}xa.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=AI(t.type),r=S7(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(xa.isDragging()&&$l.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(xa.isDragging()||xa.isTransforming())||xa.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(r);this._changedPointerPositions.forEach(d=>{const u=M2e(d.id)||this.getIntersection(d),h=d.id,p={evt:t,pointerId:h},f=c!==u;if(f&&c&&(c._fireAndBubble(n.pointerout,{...p},u),c._fireAndBubble(n.pointerleave,{...p},u)),u){if(l[u._id])return;l[u._id]=!0}u&&u.isListening()?(o=!0,f&&(u._fireAndBubble(n.pointerover,{...p},c),u._fireAndBubble(n.pointerenter,{...p},c),this[r+"targetShape"]=u),u._fireAndBubble(n.pointermove,{...p})):c&&(this._fire(n.pointerover,{evt:t,target:this,currentTarget:this,pointerId:h}),this[r+"targetShape"]=null)}),o||this._fire(n.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const n=AI(t.type),r=S7(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=M2e(c.id)||this.getIntersection(c);if(d){if(d.releaseCapture(c.id),l[d._id])return;l[d._id]=!0}const u=c.id,h={evt:t,pointerId:u};let p=!1;xa["_"+r+"InDblClickWindow"]?(p=!0,clearTimeout(this[r+"DblTimeout"])):$l.justDragged||(xa["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout(function(){xa["_"+r+"InDblClickWindow"]=!1},xa.dblClickWindow),d&&d.isListening()?(o=!0,this[r+"ClickEndShape"]=d,d._fireAndBubble(n.pointerup,{...h}),xa["_"+r+"ListenClick"]&&a&&a===d&&(d._fireAndBubble(n.pointerclick,{...h}),p&&i&&i===d&&d._fireAndBubble(n.pointerdblclick,{...h}))):(this[r+"ClickEndShape"]=null,o||(this._fire(n.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),xa["_"+r+"ListenClick"]&&this._fire(n.pointerclick,{evt:t,target:this,currentTarget:this,pointerId:u}),p&&this._fire(n.pointerdblclick,{evt:t,target:this,currentTarget:this,pointerId:u}))}),o||this._fire(n.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),xa["_"+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(m3e,{evt:t}):this._fire(m3e,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(p3e,{evt:t}):this._fire(p3e,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const n=M2e(t.pointerId)||this.getIntersection(this.getPointerPosition());n&&n._fireAndBubble(LP,OIe(t)),gz(t.pointerId)}_lostpointercapture(t){gz(t.pointerId)}setPointersPositions(t){const n=this._getContentPosition();let r=null,a=null;t=t||window.event,t.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,i=>{this._pointerPositions.push({id:i.identifier,x:(i.clientX-n.left)/n.scaleX,y:(i.clientY-n.top)/n.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,i=>{this._changedPointerPositions.push({id:i.identifier,x:(i.clientX-n.left)/n.scaleX,y:(i.clientY-n.top)/n.scaleY})})):(r=(t.clientX-n.left)/n.scaleX,a=(t.clientY-n.top)/n.scaleY,this.pointerPos={x:r,y:a},this._pointerPositions=[{x:r,y:a,id:yn._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:yn._getFirstPointerId(t)}])}_setPointerPosition(t){yn.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(t)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const t=this.content.getBoundingClientRect();return{top:t.top,left:t.left,scaleX:t.width/this.content.clientWidth||1,scaleY:t.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new xS({width:this.width(),height:this.height()}),this.bufferHitCanvas=new DIe({pixelRatio:1,width:this.width(),height:this.height()}),!xa.isBrowser)return;const t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),t.appendChild(this.content),this._resizeDOM()}cache(){return yn.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(t){t.batchDraw()}),this}};_ve.prototype.nodeType=v0s;Wu(_ve);Ps.addGetterSetter(_ve,"container");xa.isBrowser&&document.addEventListener("visibilitychange",()=>{yz.forEach(s=>{s.batchDraw()})});const s0t="hasShadow",n0t="shadowRGBA",r0t="patternImage",a0t="linearGradient",i0t="radialGradient";let UH;function P2e(){return UH||(UH=yn.createCanvasElement().getContext("2d"),UH)}const vz={};function S0s(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function C0s(s){s.stroke()}function T0s(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function E0s(s){s.stroke()}function A0s(){this._clearCache(s0t)}function M0s(){this._clearCache(n0t)}function I0s(){this._clearCache(r0t)}function P0s(){this._clearCache(a0t)}function L0s(){this._clearCache(i0t)}let Qr=class extends wa{constructor(t){super(t);let n,r=0;for(;n=yn.getHitColor(),!(n&&!(n in vz));)if(r++,r>=1e4){yn.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),n=yn.getRandomColor();break}this.colorKey=n,vz[n]=this}getContext(){return yn.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return yn.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(s0t,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(r0t,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=P2e().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new J0;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(xa.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(a0t,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=P2e(),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 wa.prototype.destroy.call(this),delete vz[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var n;if(!((n=this.attrs.perfectDrawEnabled)!==null&&n!==void 0?n:!0))return!1;const a=t||this.hasFill(),i=this.hasStroke(),l=this.getAbsoluteOpacity()!==1;if(a&&i&&l)return!0;const o=this.hasShadow(),c=this.shadowForStrokeEnabled();return!!(a&&i&&o&&c)}setStrokeHitEnabled(t){yn.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){let n=!1,r=this.getParent();for(;r;){if(r.isCached()){n=!0;break}r=r.getParent()}const a=t.skipTransform,i=t.relativeTo||n&&this.getStage()||void 0,l=this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,d=l.width+c,u=l.height+c,h=!t.skipShadow&&this.hasShadow(),p=h?this.shadowOffsetX():0,f=h?this.shadowOffsetY():0,g=d+Math.abs(p),b=u+Math.abs(f),v=h&&this.shadowBlur()||0,j=g+v*2,_=b+v*2,S={width:j,height:_,x:-(c/2+v)+Math.min(p,0)+l.x,y:-(c/2+v)+Math.min(f,0)+l.y};return a?S:this._transformedRect(S,i)}drawScene(t,n,r){const a=this.getLayer(),i=t||a.getCanvas(),l=i.getContext(),o=this._getCanvasCache(),c=this.getSceneFunc(),d=this.hasShadow();let u;const h=!1,p=n===this;if(!this.isVisible()&&!p)return this;if(o){l.save();const f=this.getAbsoluteTransform(n).getMatrix();return l.transform(f[0],f[1],f[2],f[3],f[4],f[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()&&!h){u=this.getStage();const f=r||u.bufferCanvas,g=f.getContext();r?(g.save(),g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,f.width,f.height),g.restore()):g.clear(),g.save(),g._applyLineJoin(this),g._applyMiterLimit(this);const b=this.getAbsoluteTransform(n).getMatrix();g.transform(b[0],b[1],b[2],b[3],b[4],b[5]),c.call(this,g,this),g.restore();const v=f.pixelRatio;d&&l._applyShadow(this),p||(l._applyOpacity(this),l._applyGlobalCompositeOperation(this)),l.drawImage(f._canvas,f.x||0,f.y||0,f.width/v,f.height/v)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!p){const f=this.getAbsoluteTransform(n).getMatrix();l.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l._applyOpacity(this),l._applyGlobalCompositeOperation(this)}d&&l._applyShadow(this),c.call(this,l,this)}return l.restore(),this}drawHit(t,n,r=!1){if(!this.shouldDrawHit(n,r))return this;const a=this.getLayer(),i=t||a.hitCanvas,l=i&&i.getContext(),o=this.hitFunc()||this.sceneFunc(),c=this._getCanvasCache(),d=c&&c.hit;if(this.colorKey||yn.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),d){l.save();const h=this.getAbsoluteTransform(n).getMatrix();return l.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedHitCanvas(l),l.restore(),this}if(!o)return this;if(l.save(),l._applyLineJoin(this),l._applyMiterLimit(this),!(this===n)){const h=this.getAbsoluteTransform(n).getMatrix();l.transform(h[0],h[1],h[2],h[3],h[4],h[5])}return o.call(this,l,this),l.restore(),this}drawHitFromCache(t=0){const n=this._getCanvasCache(),r=this._getCachedSceneCanvas(),a=n.hit,i=a.getContext(),l=a.getWidth(),o=a.getHeight();i.clear(),i.drawImage(r._canvas,0,0,l,o);try{const c=i.getImageData(0,0,l,o),d=c.data,u=d.length,h=yn._hexToRgb(this.colorKey);for(let p=0;pt?(d[p]=h.r,d[p+1]=h.g,d[p+2]=h.b,d[p+3]=255):d[p+3]=0;i.putImageData(c,0,0)}catch(c){yn.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return Vgt(t,this)}setPointerCapture(t){Hgt(t,this)}releaseCapture(t){gz(t)}};Qr.prototype._fillFunc=S0s;Qr.prototype._strokeFunc=C0s;Qr.prototype._fillFuncHit=T0s;Qr.prototype._strokeFuncHit=E0s;Qr.prototype._centroid=!1;Qr.prototype.nodeType="Shape";Wu(Qr);Qr.prototype.eventListeners={};Qr.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",A0s);Qr.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",M0s);Qr.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",I0s);Qr.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",P0s);Qr.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",L0s);Ps.addGetterSetter(Qr,"stroke",void 0,Ugt());Ps.addGetterSetter(Qr,"strokeWidth",2,oa());Ps.addGetterSetter(Qr,"fillAfterStrokeEnabled",!1);Ps.addGetterSetter(Qr,"hitStrokeWidth","auto",RIe());Ps.addGetterSetter(Qr,"strokeHitEnabled",!0,Ob());Ps.addGetterSetter(Qr,"perfectDrawEnabled",!0,Ob());Ps.addGetterSetter(Qr,"shadowForStrokeEnabled",!0,Ob());Ps.addGetterSetter(Qr,"lineJoin");Ps.addGetterSetter(Qr,"lineCap");Ps.addGetterSetter(Qr,"miterLimit");Ps.addGetterSetter(Qr,"sceneFunc");Ps.addGetterSetter(Qr,"hitFunc");Ps.addGetterSetter(Qr,"dash");Ps.addGetterSetter(Qr,"dashOffset",0,oa());Ps.addGetterSetter(Qr,"shadowColor",void 0,ZM());Ps.addGetterSetter(Qr,"shadowBlur",0,oa());Ps.addGetterSetter(Qr,"shadowOpacity",1,oa());Ps.addComponentsGetterSetter(Qr,"shadowOffset",["x","y"]);Ps.addGetterSetter(Qr,"shadowOffsetX",0,oa());Ps.addGetterSetter(Qr,"shadowOffsetY",0,oa());Ps.addGetterSetter(Qr,"fillPatternImage");Ps.addGetterSetter(Qr,"fill",void 0,Ugt());Ps.addGetterSetter(Qr,"fillPatternX",0,oa());Ps.addGetterSetter(Qr,"fillPatternY",0,oa());Ps.addGetterSetter(Qr,"fillLinearGradientColorStops");Ps.addGetterSetter(Qr,"strokeLinearGradientColorStops");Ps.addGetterSetter(Qr,"fillRadialGradientStartRadius",0);Ps.addGetterSetter(Qr,"fillRadialGradientEndRadius",0);Ps.addGetterSetter(Qr,"fillRadialGradientColorStops");Ps.addGetterSetter(Qr,"fillPatternRepeat","repeat");Ps.addGetterSetter(Qr,"fillEnabled",!0);Ps.addGetterSetter(Qr,"strokeEnabled",!0);Ps.addGetterSetter(Qr,"shadowEnabled",!0);Ps.addGetterSetter(Qr,"dashEnabled",!0);Ps.addGetterSetter(Qr,"strokeScaleEnabled",!0);Ps.addGetterSetter(Qr,"fillPriority","color");Ps.addComponentsGetterSetter(Qr,"fillPatternOffset",["x","y"]);Ps.addGetterSetter(Qr,"fillPatternOffsetX",0,oa());Ps.addGetterSetter(Qr,"fillPatternOffsetY",0,oa());Ps.addComponentsGetterSetter(Qr,"fillPatternScale",["x","y"]);Ps.addGetterSetter(Qr,"fillPatternScaleX",1,oa());Ps.addGetterSetter(Qr,"fillPatternScaleY",1,oa());Ps.addComponentsGetterSetter(Qr,"fillLinearGradientStartPoint",["x","y"]);Ps.addComponentsGetterSetter(Qr,"strokeLinearGradientStartPoint",["x","y"]);Ps.addGetterSetter(Qr,"fillLinearGradientStartPointX",0);Ps.addGetterSetter(Qr,"strokeLinearGradientStartPointX",0);Ps.addGetterSetter(Qr,"fillLinearGradientStartPointY",0);Ps.addGetterSetter(Qr,"strokeLinearGradientStartPointY",0);Ps.addComponentsGetterSetter(Qr,"fillLinearGradientEndPoint",["x","y"]);Ps.addComponentsGetterSetter(Qr,"strokeLinearGradientEndPoint",["x","y"]);Ps.addGetterSetter(Qr,"fillLinearGradientEndPointX",0);Ps.addGetterSetter(Qr,"strokeLinearGradientEndPointX",0);Ps.addGetterSetter(Qr,"fillLinearGradientEndPointY",0);Ps.addGetterSetter(Qr,"strokeLinearGradientEndPointY",0);Ps.addComponentsGetterSetter(Qr,"fillRadialGradientStartPoint",["x","y"]);Ps.addGetterSetter(Qr,"fillRadialGradientStartPointX",0);Ps.addGetterSetter(Qr,"fillRadialGradientStartPointY",0);Ps.addComponentsGetterSetter(Qr,"fillRadialGradientEndPoint",["x","y"]);Ps.addGetterSetter(Qr,"fillRadialGradientEndPointX",0);Ps.addGetterSetter(Qr,"fillRadialGradientEndPointY",0);Ps.addGetterSetter(Qr,"fillPatternRotation",0);Ps.addGetterSetter(Qr,"fillRule",void 0,ZM());Ps.backCompat(Qr,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const D0s="beforeDraw",R0s="draw",o0t=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],O0s=o0t.length;let QM=class extends py{constructor(t){super(t),this.canvas=new xS,this.hitCanvas=new DIe({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(t){return this.getContext().clear(t),this.getHitCanvas().getContext().clear(t),this}setZIndex(t){super.setZIndex(t);const n=this.getStage();return n&&n.content&&(n.content.removeChild(this.getNativeCanvasElement()),t{this.draw(),this._waitingForDraw=!1})),this}getIntersection(t){if(!this.isListening()||!this.isVisible())return null;let n=1,r=!1;for(;;){for(let a=0;a0)return{antialiased:!0};return{}}drawScene(t,n,r){const a=this.getLayer(),i=t||a&&a.getCanvas();return this._fire(D0s,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),py.prototype.drawScene.call(this,i,n,r),this._fire(R0s,{node:this}),this}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),py.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){yn.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return yn.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const t=this.parent;!!this.hitCanvas._canvas.parentNode?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}destroy(){return yn.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};QM.prototype.nodeType="Layer";Wu(QM);Ps.addGetterSetter(QM,"imageSmoothingEnabled",!0);Ps.addGetterSetter(QM,"clearBeforeDraw",!0);Ps.addGetterSetter(QM,"hitGraphEnabled",!0,Ob());class FIe extends QM{constructor(t){super(t),this.listening(!1),yn.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}FIe.prototype.nodeType="FastLayer";Wu(FIe);let O8=class extends py{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&yn.throw("You may only add groups and shapes to groups.")}};O8.prototype.nodeType="Group";Wu(O8);const L2e=function(){return tA.performance&&tA.performance.now?function(){return tA.performance.now()}:function(){return new Date().getTime()}}();class Sv{constructor(t,n){this.id=Sv.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:L2e(),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=cHe,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=dHe,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===cHe?this.setTime(t):this.state===dHe&&this.setTime(this.duration-t)}pause(){this.state=z0s,this.fire("onPause")}getTimer(){return new Date().getTime()}}class gd{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||bz.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=B0s++;const d=r.getLayer()||(r instanceof xa.Stage?r.getLayers():null);d||yn.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new Sv(function(){n.tween.onEnterFrame()},d),this.tween=new $0s(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),gd.attrs[a]||(gd.attrs[a]={}),gd.attrs[a][this._id]||(gd.attrs[a][this._id]={}),gd.tweens[a]||(gd.tweens[a]={});for(c in t)F0s[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=gd.tweens[a][t];u&&delete gd.attrs[a][u][t];let h=r.getAttr(t);if(yn._isArray(n))if(i=[],l=Math.max(n.length,h.length),t==="points"&&n.length!==h.length&&(n.length>h.length?(c=h,h=yn._prepareArrayForTween(h,n,r.closed())):(o=n,n=yn._prepareArrayForTween(n,h,r.closed()))),t.indexOf("fill")===0)for(let p=0;p{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,n=gd.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=gd.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=gd.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in r)delete gd.tweens[t][a];delete gd.attrs[t][n],gd.tweens[t]&&(Object.keys(gd.tweens[t]).length===0&&delete gd.tweens[t],Object.keys(gd.attrs[t]).length===0&&delete gd.attrs[t])}}gd.attrs={};gd.tweens={};wa.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new gd(s).play()};const bz={BackEaseIn(s,t,n,r){return n*(s/=r)*s*((1.70158+1)*s-1.70158)+t},BackEaseOut(s,t,n,r){return n*((s=s/r-1)*s*((1.70158+1)*s+1.70158)+1)+t},BackEaseInOut(s,t,n,r){let a=1.70158;return(s/=r/2)<1?n/2*(s*s*(((a*=1.525)+1)*s-a))+t:n/2*((s-=2)*s*(((a*=1.525)+1)*s+a)+2)+t},ElasticEaseIn(s,t,n,r,a,i){let l=0;return s===0?t:(s/=r)===1?t+n:(i||(i=r*.3),!a||a0?t:n),u=l*n,h=o*(o>0?t:n),p=c*(c>0?n:t);return{x:d,y:r?-1*p:h,width:u-d,height:p-h}}}CN.prototype._centroid=!0;CN.prototype.className="Arc";CN.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Wu(CN);Ps.addGetterSetter(CN,"innerRadius",0,oa());Ps.addGetterSetter(CN,"outerRadius",0,oa());Ps.addGetterSetter(CN,"angle",0,oa());Ps.addGetterSetter(CN,"clockwise",!1,Ob());function f3e(s,t,n,r,a,i,l){const o=Math.sqrt(Math.pow(n-s,2)+Math.pow(r-t,2)),c=Math.sqrt(Math.pow(a-n,2)+Math.pow(i-r,2)),d=l*o/(o+c),u=l*c/(o+c),h=n-d*(a-s),p=r-d*(i-t),f=n+u*(a-s),g=r+u*(i-t);return[h,p,f,g]}function hHe(s,t){const n=s.length,r=[];for(let a=2;a=0){const c=Math.sqrt(o);n.push((-i+c)/(2*a)),n.push((-i-c)/(2*a))}}}return n.filter(r=>r>0&&r<1).flatMap(r=>t.map(a=>{const i=1-r;return i*i*i*a[0]+3*i*i*r*a[1]+3*i*r*r*a[2]+r*r*r*a[3]}))}let TN=class extends Qr{constructor(t){super(t),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(t){const n=this.points(),r=n.length,a=this.tension(),i=this.closed(),l=this.bezier();if(!r)return;let o=0;if(t.beginPath(),t.moveTo(n[0],n[1]),a!==0&&r>4){const c=this.getTensionPoints(),d=c.length;for(o=i?0:4,i||t.quadraticCurveTo(c[0],c[1],c[2],c[3]);o{let r,a;const l=n/2;r=0;for(let o=0;o<20;o++)a=l*q0s[20][o]+l,r+=V0s[20][o]*G0s(s,t,a);return l*r},pHe=(s,t,n)=>{n===void 0&&(n=1);const r=s[0]-2*s[1]+s[2],a=t[0]-2*t[1]+t[2],i=2*s[1]-2*s[0],l=2*t[1]-2*t[0],o=4*(r*r+a*a),c=4*(r*i+a*l),d=i*i+l*l;if(o===0)return n*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(t[2]-t[0],2));const u=c/(2*o),h=d/o,p=n+u,f=h-u*u,g=p*p+f>0?Math.sqrt(p*p+f):0,b=u*u+f>0?Math.sqrt(u*u+f):0,v=u+Math.sqrt(u*u+f)!==0?f*Math.log(Math.abs((p+g)/(u+b))):0;return Math.sqrt(o)/2*(p*g-u*b+v)};function G0s(s,t,n){const r=x3e(1,n,s),a=x3e(1,n,t),i=r*r+a*a;return Math.sqrt(i)}const x3e=(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+=H0s[r][l]*Math.pow(1-t,r-l)*Math.pow(t,l)*n[l];return i}else{a=new Array(r);for(let l=0;l{let r=1,a=s/t,i=(s-n(a))/t,l=0;for(;r>.001;){const o=n(a+i),c=Math.abs(s-o)/t;if(c500)break}return a};let Cv=class Tg extends Qr{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=Tg.parsePathData(this.data()),this.pathLength=Tg.getPathLength(this.dataArray)}_sceneFunc(t){const n=this.dataArray;t.beginPath();let r=!1;for(let a=0;au?d:u,v=d>u?1:d/u,j=d>u?u/d:1;t.translate(o,c),t.rotate(f),t.scale(v,j),t.arc(0,0,b,h,h+p,1-g),t.scale(1/v,1/j),t.rotate(-f),t.translate(-o,-c);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(c){if(c.command==="A"){const d=c.points[4],u=c.points[5],h=c.points[4]+u;let p=Math.PI/180;if(Math.abs(d-h)h;f-=p){const g=Tg.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],f,0);t.push(g.x,g.y)}else for(let f=d+p;fn[a].pathLength;)t-=n[a].pathLength,++a;if(a===i)return r=n[a-1].points.slice(-2),{x:r[0],y:r[1]};if(t<.01)return n[a].command==="M"?(r=n[a].points.slice(0,2),{x:r[0],y:r[1]}):{x:n[a].start.x,y:n[a].start.y};const l=n[a],o=l.points;switch(l.command){case"L":return Tg.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return Tg.getPointOnCubicBezier(fHe(t,Tg.getPathLength(n),b=>mHe([l.start.x,o[0],o[2],o[4]],[l.start.y,o[1],o[3],o[5]],b)),l.start.x,l.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return Tg.getPointOnQuadraticBezier(fHe(t,Tg.getPathLength(n),b=>pHe([l.start.x,o[0],o[2]],[l.start.y,o[1],o[3]],b)),l.start.x,l.start.y,o[0],o[1],o[2],o[3]);case"A":const c=o[0],d=o[1],u=o[2],h=o[3],p=o[5],f=o[6];let g=o[4];return g+=p*t/l.pathLength,Tg.getPointOnEllipticalArc(c,d,u,h,g,f)}return null}static getPointOnLine(t,n,r,a,i,l,o){l=l??n,o=o??r;const c=this.getLineLength(n,r,a,i);if(c<1e-10)return{x:n,y:r};if(a===n)return{x:l,y:o+(i>r?t:-t)};const d=(i-r)/(a-n),u=Math.sqrt(t*t/(1+d*d))*(a=0&&(b+=2,b>=7&&(b-=7));continue}if(b>=0){if(b===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(_)){g.push(parseInt(_[0],10)),g.push(parseInt(_[1],10)),g.push(parseFloat(_.slice(2))),b+=3,b>=7&&(b-=7);continue}if(_==="11"||_==="10"||_==="01"){g.push(parseInt(_[0],10)),g.push(parseInt(_[1],10)),b+=2,b>=7&&(b-=7);continue}if(_==="0"||_==="1"){g.push(parseInt(_,10)),b+=1,b>=7&&(b-=7);continue}}else if(b===4){if(/^[01]\d+(?:\.\d+)?$/.test(_)){g.push(parseInt(_[0],10)),g.push(parseFloat(_.slice(1))),b+=2,b>=7&&(b-=7);continue}if(_==="0"||_==="1"){g.push(parseInt(_,10)),b+=1,b>=7&&(b-=7);continue}}const S=parseFloat(_);isNaN(S)?g.push(0):g.push(S),b+=1,b>=7&&(b-=7)}else{const S=parseFloat(_);isNaN(S)?g.push(0):g.push(S)}}for(;g.length>0&&!isNaN(g[0]);){let v="",j=[];const _=o,S=c;let A,T,D,L,M,F,z,V,W,K;switch(f){case"l":o+=g.shift(),c+=g.shift(),v="L",j.push(o,c);break;case"L":o=g.shift(),c=g.shift(),j.push(o,c);break;case"m":const Y=g.shift(),ee=g.shift();if(o+=Y,c+=ee,v="M",i.length>2&&i[i.length-1].command==="z"){for(let ne=i.length-2;ne>=0;ne--)if(i[ne].command==="M"){o=i[ne].points[0]+Y,c=i[ne].points[1]+ee;break}}j.push(o,c),f="l";break;case"M":o=g.shift(),c=g.shift(),v="M",j.push(o,c),f="L";break;case"h":o+=g.shift(),v="L",j.push(o,c);break;case"H":o=g.shift(),v="L",j.push(o,c);break;case"v":c+=g.shift(),v="L",j.push(o,c);break;case"V":c=g.shift(),v="L",j.push(o,c);break;case"C":j.push(g.shift(),g.shift(),g.shift(),g.shift()),o=g.shift(),c=g.shift(),j.push(o,c);break;case"c":j.push(o+g.shift(),c+g.shift(),o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),v="C",j.push(o,c);break;case"S":T=o,D=c,A=i[i.length-1],A.command==="C"&&(T=o+(o-A.points[2]),D=c+(c-A.points[3])),j.push(T,D,g.shift(),g.shift()),o=g.shift(),c=g.shift(),v="C",j.push(o,c);break;case"s":T=o,D=c,A=i[i.length-1],A.command==="C"&&(T=o+(o-A.points[2]),D=c+(c-A.points[3])),j.push(T,D,o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),v="C",j.push(o,c);break;case"Q":j.push(g.shift(),g.shift()),o=g.shift(),c=g.shift(),j.push(o,c);break;case"q":j.push(o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),v="Q",j.push(o,c);break;case"T":T=o,D=c,A=i[i.length-1],A.command==="Q"&&(T=o+(o-A.points[0]),D=c+(c-A.points[1])),o=g.shift(),c=g.shift(),v="Q",j.push(T,D,o,c);break;case"t":T=o,D=c,A=i[i.length-1],A.command==="Q"&&(T=o+(o-A.points[0]),D=c+(c-A.points[1])),o+=g.shift(),c+=g.shift(),v="Q",j.push(T,D,o,c);break;case"A":L=g.shift(),M=g.shift(),F=g.shift(),z=g.shift(),V=g.shift(),W=o,K=c,o=g.shift(),c=g.shift(),v="A",j=this.convertEndpointToCenterParameterization(W,K,o,c,z,V,L,M,F);break;case"a":L=g.shift(),M=g.shift(),F=g.shift(),z=g.shift(),V=g.shift(),W=o,K=c,o+=g.shift(),c+=g.shift(),v="A",j=this.convertEndpointToCenterParameterization(W,K,o,c,z,V,L,M,F);break}i.push({command:v||f,points:j,start:{x:_,y:S},pathLength:this.calcLength(_,S,v||f,j)})}(f==="z"||f==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,n,r,a){let i,l,o,c;const d=Tg;switch(r){case"L":return d.getLineLength(t,n,a[0],a[1]);case"C":return mHe([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return pHe([t,a[0],a[2]],[n,a[1],a[3]],1);case"A":i=0;const u=a[4],h=a[5],p=a[4]+h;let f=Math.PI/180;if(Math.abs(u-p)p;c-=f)o=d.getPointOnEllipticalArc(a[0],a[1],a[2],a[3],c,0),i+=d.getLineLength(l.x,l.y,o.x,o.y),l=o;else for(c=u+f;c1&&(o*=Math.sqrt(f),c*=Math.sqrt(f));let g=Math.sqrt((o*o*(c*c)-o*o*(p*p)-c*c*(h*h))/(o*o*(p*p)+c*c*(h*h)));i===l&&(g*=-1),isNaN(g)&&(g=0);const b=g*o*p/c,v=g*-c*h/o,j=(t+r)/2+Math.cos(u)*b-Math.sin(u)*v,_=(n+a)/2+Math.sin(u)*b+Math.cos(u)*v,S=function(z){return Math.sqrt(z[0]*z[0]+z[1]*z[1])},A=function(z,V){return(z[0]*V[0]+z[1]*V[1])/(S(z)*S(V))},T=function(z,V){return(z[0]*V[1]=1&&(F=0),l===0&&F>0&&(F=F-2*Math.PI),l===1&&F<0&&(F=F+2*Math.PI),[j,_,o,c,D,F,u,l]}};Cv.prototype.className="Path";Cv.prototype._attrsAffectingSize=["data"];Wu(Cv);Ps.addGetterSetter(Cv,"data");class XM extends TN{_sceneFunc(t){super._sceneFunc(t);const n=Math.PI*2,r=this.points();let a=r;const i=this.tension()!==0&&r.length>4;i&&(a=this.getTensionPoints());const l=this.pointerLength(),o=r.length;let c,d;if(i){const p=[a[a.length-4],a[a.length-3],a[a.length-2],a[a.length-1],r[o-2],r[o-1]],f=Cv.calcLength(a[a.length-4],a[a.length-3],"C",p),g=Cv.getPointOnQuadraticBezier(Math.min(1,1-l/f),p[0],p[1],p[2],p[3],p[4],p[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}}}XM.prototype.className="Arrow";Wu(XM);Ps.addGetterSetter(XM,"pointerLength",10,oa());Ps.addGetterSetter(XM,"pointerWidth",10,oa());Ps.addGetterSetter(XM,"pointerAtBeginning",!1);Ps.addGetterSetter(XM,"pointerAtEnding",!0);class sR extends Qr{_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)}}sR.prototype._centroid=!0;sR.prototype.className="Circle";sR.prototype._attrsAffectingSize=["radius"];Wu(sR);Ps.addGetterSetter(sR,"radius",0,oa());class iC extends Qr{_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)}}iC.prototype.className="Ellipse";iC.prototype._centroid=!0;iC.prototype._attrsAffectingSize=["radiusX","radiusY"];Wu(iC);Ps.addComponentsGetterSetter(iC,"radius",["x","y"]);Ps.addGetterSetter(iC,"radiusX",0,oa());Ps.addGetterSetter(iC,"radiusY",0,oa());let Fb=class l0t extends Qr{constructor(t){super(t),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",n=>{this._removeImageLoad(n.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.complete||t&&t.readyState===4||t&&t.addEventListener&&t.addEventListener("load",this._loadListener)}_removeImageLoad(t){t&&t.removeEventListener&&t.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const t=!!this.cornerRadius(),n=this.hasShadow();return t&&n?!0:super._useBufferCanvas(!0)}_sceneFunc(t){const n=this.getWidth(),r=this.getHeight(),a=this.cornerRadius(),i=this.attrs.image;let l;if(i){const o=this.attrs.cropWidth,c=this.attrs.cropHeight;o&&c?l=[i,this.cropX(),this.cropY(),o,c,0,0,n,r]:l=[i,0,0,n,r]}(this.hasFill()||this.hasStroke()||a)&&(t.beginPath(),a?yn.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)),i&&(a&&t.clip(),t.drawImage.apply(t,l))}_hitFunc(t){const n=this.width(),r=this.height(),a=this.cornerRadius();t.beginPath(),a?yn.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,n,r;return(r=(t=this.attrs.width)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.width)!==null&&r!==void 0?r:0}getHeight(){var t,n,r;return(r=(t=this.attrs.height)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.height)!==null&&r!==void 0?r:0}static fromURL(t,n,r=null){const a=yn.createImageElement();a.onload=function(){const i=new l0t({image:a});n(i)},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};Fb.prototype.className="Image";Fb.prototype._attrsAffectingSize=["image"];Wu(Fb);Ps.addGetterSetter(Fb,"cornerRadius",0,bve(4));Ps.addGetterSetter(Fb,"image");Ps.addComponentsGetterSetter(Fb,"crop",["x","y","width","height"]);Ps.addGetterSetter(Fb,"cropX",0,oa());Ps.addGetterSetter(Fb,"cropY",0,oa());Ps.addGetterSetter(Fb,"cropWidth",0,oa());Ps.addGetterSetter(Fb,"cropHeight",0,oa());const c0t=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],W0s="Change.konva",K0s="none",g3e="up",y3e="right",v3e="down",b3e="left",Y0s=c0t.length;let zIe=class extends O8{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)}}oC.prototype.className="RegularPolygon";oC.prototype._centroid=!0;oC.prototype._attrsAffectingSize=["radius"];Wu(oC);Ps.addGetterSetter(oC,"radius",0,oa());Ps.addGetterSetter(oC,"sides",0,oa());Ps.addGetterSetter(oC,"cornerRadius",0,bve(4));const xHe=Math.PI*2;let e6=class extends Qr{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,xHe,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),xHe,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)}};e6.prototype.className="Ring";e6.prototype._centroid=!0;e6.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Wu(e6);Ps.addGetterSetter(e6,"innerRadius",0,oa());Ps.addGetterSetter(e6,"outerRadius",0,oa());class Jw extends Qr{constructor(t){super(t),this._updated=!0,this.anim=new Sv(()=>{const n=this._updated;return this._updated=!1,n}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+0],c=i[a+1],d=i[a+2],u=i[a+3],h=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,d,u),t.closePath(),t.fillStrokeShape(this)),h)if(l){const p=l[n],f=r*2;t.drawImage(h,o,c,d,u,p[f+0],p[f+1],d,u)}else t.drawImage(h,o,c,d,u,0,0,d,u)}_hitFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+2],c=i[a+3];if(t.beginPath(),l){const d=l[n],u=r*2;t.rect(d[u+0],d[u+1],o,c)}else t.rect(0,0,o,c);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const t=this;this.interval=setInterval(function(){t._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const t=this.frameIndex(),n=this.animation(),r=this.animations(),a=r[n],i=a.length/4;t{if(new RegExp("\\p{Emoji}","u").test(n)){const i=a[r+1];i&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(i)?(t.push(n+i),a[r+1]=""):t.push(n)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(n+(a[r+1]||""))?t.push(n+a[r+1]):r>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(n)?t[t.length-1]+=n:n&&t.push(n);return t},[])}const MI="auto",Z0s="center",d0t="inherit",NF="justify",Q0s="Change.konva",u0t="2d",gHe="-",h0t="left",X0s="text",J0s="Text",eys="top",tys="bottom",yHe="middle",m0t="normal",sys="px ",qH=" ",nys="right",vHe="rtl",rys="word",ays="char",bHe="none",D2e="…",p0t=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],iys=p0t.length;let kF=null;function oys(){if(kF!==null)return kF;kF=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(u0t);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){kF=!0;break}}}catch{}return kF}function lys(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 VH;function R2e(){return VH||(VH=yn.createCanvasElement().getContext(u0t),VH)}function cys(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function dys(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function uys(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let Nd=class extends Qr{constructor(t){super(uys(t)),this._partialTextX=0,this._partialTextY=0;for(let n=0;nye+Gk(_e.text).length,0),ie=oe+de;b({char:pe,index:ie,x:M,y:D+F,lineIndex:T,column:oe,isLastInLine:K,width:this.measureSize(pe).width,context:t})}t.fillStrokeShape(this),b&&t.restore(),M+=this.measureSize(pe).width+g}}else g!==0&&t.setAttr("letterSpacing",`${g}px`),this._partialTextX=M,this._partialTextY=D+F,this._partialText=V,t.fillStrokeShape(this);if(A){t.save(),t.beginPath();const ee=xa.legacyTextRendering?0:-Math.round(o/4),ne=Y;t.moveTo(ne,D+F+ee);const oe=p===NF&&!K?f-l*2:W;t.lineTo(ne+Math.round(oe),D+F+ee),t.lineWidth=o/15;const pe=this._getLinearGradient();t.strokeStyle=pe||v,t.stroke(),t.restore()}t.restore(),i>1&&(D+=c)}}_hitFunc(t){const n=this.getWidth(),r=this.getHeight();t.beginPath(),t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}setText(t){const n=yn._isString(t)?t:t==null?"":t+"";return this._setAttr(X0s,n),this}getWidth(){return this.attrs.width===MI||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===MI||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return yn.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var n,r,a,i,l,o,c,d,u,h,p;let f=R2e(),g=this.fontSize(),b;f.save(),f.font=this._getContextFont(),b=f.measureText(t),f.restore();const v=g/100;return{actualBoundingBoxAscent:(n=b.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*v,actualBoundingBoxDescent:(r=b.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=b.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*v,actualBoundingBoxRight:(i=b.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*v,alphabeticBaseline:(l=b.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=b.emHeightAscent)!==null&&o!==void 0?o:100*v,emHeightDescent:(c=b.emHeightDescent)!==null&&c!==void 0?c:-20*v,fontBoundingBoxAscent:(d=b.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*v,fontBoundingBoxDescent:(u=b.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*v,hangingBaseline:(h=b.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*v,ideographicBaseline:(p=b.ideographicBaseline)!==null&&p!==void 0?p:-21*v,width:b.width,height:g}}_getContextFont(){return this.fontStyle()+qH+this.fontVariant()+qH+(this.fontSize()+sys)+lys(this.fontFamily())}_addTextLine(t){this.align()===NF&&(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 R2e().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!==MI&&i!==void 0,c=l!==MI&&l!==void 0,d=this.padding(),u=i-d*2,h=l-d*2,p=0,f=this.wrap(),g=f!==bHe,b=f!==ays&&g,v=this.ellipsis();this.textArr=[],R2e().font=this._getContextFont();const j=v?this._getTextWidth(D2e):0;for(let _=0,S=t.length;_u)for(;A.length>0;){let D=0,L=Gk(A).length,M="",F=0;for(;D>>1,V=Gk(A),W=V.slice(0,z+1).join(""),K=this._getTextWidth(W);(v&&c&&p+a>h?K+j:K)<=u?(D=z+1,M=W,F=K):L=z}if(M){if(b){const W=Gk(A),K=Gk(M),Y=W[K.length],ee=Y===qH||Y===gHe;let ne;if(ee&&F<=u)ne=K.length;else{const oe=K.lastIndexOf(qH),pe=K.lastIndexOf(gHe);ne=Math.max(oe,pe)+1}ne>0&&(D=ne,M=W.slice(0,D).join(""),F=this._getTextWidth(M))}if(M=M.trimRight(),this._addTextLine(M),r=Math.max(r,F),p+=a,this._shouldHandleEllipsis(p)){this._tryToAddEllipsisToLastLine();break}if(A=Gk(A).slice(D).join("").trimLeft(),A.length>0&&(T=this._getTextWidth(A),T<=u)){this._addTextLine(A),p+=a,r=Math.max(r,T);break}}else break}else this._addTextLine(A),p+=a,r=Math.max(r,T),this._shouldHandleEllipsis(p)&&_h)break}this.textHeight=n,this.textWidth=r}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==MI&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==bHe)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==MI&&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+D2e)n?null:Cv.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=Cv.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();const n=this.textDecoration(),r=this.fill(),a=this.fontSize(),i=this.glyphInfo,l=n.indexOf("underline")!==-1,o=n.indexOf("line-through")!==-1;l&&t.beginPath();for(let c=0;c=1){const r=n[0].p0;t.moveTo(r.x,r.y)}for(let r=0;rthis.pathLength&&j-this.pathLength<=d?this.pathLength:j);if(!_)return;const S=Cv.getLineLength(g.x,g.y,_.x,_.y);let A=0;if(c)try{A=c(n[f-1].char,b)*this.fontSize()}catch{A=0}g.x+=A,_.x+=A,this.textWidth+=A;const T=Cv.getPointOnLine(A+S/2,g.x,g.y,_.x,_.y),D=Math.atan2(_.y-g.y,_.x-g.x);this.glyphInfo.push({transposeX:T.x,transposeY:T.y,text:t[f],rotation:D,p0:g,p1:_,width:S}),p+=v}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const t=[];this.glyphInfo.forEach(function(d){t.push(d.p0.x),t.push(d.p0.y),t.push(d.p1.x),t.push(d.p1.y)});let n=t[0]||0,r=t[0]||0,a=t[1]||0,i=t[1]||0,l,o;for(let d=0;ds+`.${y0t}`).join(" "),_He="nodesRect",pys=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],fys={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},xys="ontouchstart"in xa._global;function gys(s,t,n){if(s==="rotater")return n;t+=yn.degToRad(fys[s]||0);const r=(yn.radToDeg(t)%360+360)%360;return yn._inRange(r,315+22.5,360)||yn._inRange(r,0,22.5)?"ns-resize":yn._inRange(r,45-22.5,45+22.5)?"nesw-resize":yn._inRange(r,90-22.5,90+22.5)?"ew-resize":yn._inRange(r,135-22.5,135+22.5)?"nwse-resize":yn._inRange(r,180-22.5,180+22.5)?"ns-resize":yn._inRange(r,225-22.5,225+22.5)?"nesw-resize":yn._inRange(r,270-22.5,270+22.5)?"ew-resize":yn._inRange(r,315-22.5,315+22.5)?"nwse-resize":(yn.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const Cxe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],wHe=1e8;function yys(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 v0t(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 vys(s,t){const n=yys(s);return v0t(s,t,n)}function bys(s,t,n){let r=t;for(let a=0;aa.isAncestorOf(this)?(yn.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=t=n,t.length===1&&this.useSingleNodeRotation()?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(a=>{const i=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(a._attrsAffectingSize.length){const l=a._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");a.on(l,i)}a.on(pys.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(_He),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(_He,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=(xa.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 v0t(u,-xa.getAngle(n),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-wHe,y:-wHe,width:0,height:0,rotation:0};const n=[];this.nodes().map(d=>{const u=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),h=[{x:u.x,y:u.y},{x:u.x+u.width,y:u.y},{x:u.x+u.width,y:u.y+u.height},{x:u.x,y:u.y+u.height}],p=d.getAbsoluteTransform();h.forEach(function(f){const g=p.point(f);n.push(g)})});const r=new J0;r.rotate(-xa.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:xa.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(),Cxe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new SU({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:xys?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=xa.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=gys(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 Qr({name:"back",width:0,height:0,sceneFunc(n,r){const a=r.getParent(),i=a.padding(),l=r.width(),o=r.height();if(n.beginPath(),n.rect(-i,-i,l+i*2,o+i*2),a.rotateEnabled()&&a.rotateLineVisible()){const c=a.rotateAnchorAngle(),d=a.rotateAnchorOffset(),u=yn.degToRad(c),h=Math.sin(u),p=-Math.cos(u),f=l/2,g=o/2;let b=1/0;p<0?b=Math.min(b,-g/p):p>0&&(b=Math.min(b,(o-g)/p)),h<0?b=Math.min(b,-f/h):h>0&&(b=Math.min(b,(l-f)/h));const v=f+h*b,j=g+p*b,_=yn._sign(o),S=v+h*d*_,A=j+p*d*_;n.moveTo(v,j),n.lineTo(S,A)}n.fillStrokeShape(r)},hitFunc:(n,r)=>{if(!this.shouldOverdrawWholeArea())return;const a=this.padding();n.beginPath(),n.rect(-a,-a,r.width()+a*2,r.height()+a*2),n.fillStrokeShape(r)}});this.add(t),this._proxyDrag(t),t.on("dragstart",n=>{n.cancelBubble=!0}),t.on("dragmove",n=>{n.cancelBubble=!0}),t.on("dragend",n=>{n.cancelBubble=!0}),this.on("dragmove",n=>{this.update()})}_handleMouseDown(t){if(this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const n=this._getNodeRect(),r=n.width,a=n.height,i=Math.sqrt(Math.pow(r,2)+Math.pow(a,2));this.sin=Math.abs(a/i),this.cos=Math.abs(r/i),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const l=t.target.getAbsolutePosition(),o=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-l.x,y:o.y-l.y},_3e++,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 S=xa.getAngle(this.rotateAnchorAngle());let A=Math.atan2(-r,n)+Math.PI/2-S;_.height<0&&(A-=Math.PI);const D=xa.getAngle(this.rotation())+A,L=xa.getAngle(this.rotationSnapTolerance()),F=bys(this.rotationSnaps(),D,L)-_.rotation,z=vys(_,F);this._fitNodesInto(z,t);return}const h=this.shiftBehavior();let p;h==="inverted"?p=this.keepRatio()&&!t.shiftKey:h==="none"?p=this.keepRatio():p=this.keepRatio()||t.shiftKey;let f=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(p){const _=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(_.x-i.x(),2)+Math.pow(_.y-i.y(),2));const S=this.findOne(".top-left").x()>_.x?-1:1,A=this.findOne(".top-left").y()>_.y?-1:1;n=a*this.cos*S,r=a*this.sin*A,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(p){const _=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(i.x()-_.x,2)+Math.pow(_.y-i.y(),2));const S=this.findOne(".top-right").x()<_.x?-1:1,A=this.findOne(".top-right").y()>_.y?-1:1;n=a*this.cos*S,r=a*this.sin*A,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(p){const _=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(_.x-i.x(),2)+Math.pow(i.y()-_.y,2));const S=_.x{var i;a._fire("transformend",{evt:t,target:a}),(i=a.getLayer())===null||i===void 0||i.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,n){const r=this._getNodeRect(),a=1;if(yn._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(yn._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new J0;if(i.rotate(xa.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const p=i.point({x:-this.padding()*2,y:0});t.x+=p.x,t.y+=p.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const p=i.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const p=i.point({x:0,y:-this.padding()*2});t.x+=p.x,t.y+=p.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.height+=this.padding()*2}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const p=i.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.height+=this.padding()*2}if(this.boundBoxFunc()){const p=this.boundBoxFunc()(r,t);p?t=p:yn.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new J0;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/l,r.height/l);const c=new J0,d=t.width/l,u=t.height/l;this.flipEnabled()===!1?(c.translate(t.x,t.y),c.rotate(t.rotation),c.translate(t.width<0?t.width:0,t.height<0?t.height:0),c.scale(Math.abs(d),Math.abs(u))):(c.translate(t.x,t.y),c.rotate(t.rotation),c.scale(d,u));const h=c.multiply(o.invert());this._nodes.forEach(p=>{var f;if(!p.getStage())return;const g=p.getParent().getAbsoluteTransform(),b=p.getTransform().copy();b.translate(p.offsetX(),p.offsetY());const v=new J0;v.multiply(g.copy().invert()).multiply(h).multiply(g).multiply(b);const j=v.decompose();p.setAttrs(j),(f=p.getLayer())===null||f===void 0||f.batchDraw()}),this.rotation(yn._getRotation(t.rotation)),this._nodes.forEach(p=>{this._fire("transform",{evt:n,target:p}),p._fire("transform",{evt:n,target:p})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,n){this.findOne(t).setAttrs(n)}update(){var t;const n=this._getNodeRect();this.rotation(yn._getRotation(n.rotation));const r=n.width,a=n.height,i=this.enabledAnchors(),l=this.resizeEnabled(),o=this.padding(),c=this.anchorSize(),d=this.find("._anchor");d.forEach(D=>{D.setAttrs({width:c,height:c,offsetX:c/2,offsetY:c/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:c/2+o,offsetY:c/2+o,visible:l&&i.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:r/2,y:0,offsetY:c/2+o,visible:l&&i.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:r,y:0,offsetX:c/2-o,offsetY:c/2+o,visible:l&&i.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:a/2,offsetX:c/2+o,visible:l&&i.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:r,y:a/2,offsetX:c/2-o,visible:l&&i.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:a,offsetX:c/2+o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:r/2,y:a,offsetY:c/2-o,visible:l&&i.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:r,y:a,offsetX:c/2-o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-right")>=0});const u=this.rotateAnchorAngle(),h=this.rotateAnchorOffset(),p=yn.degToRad(u),f=Math.sin(p),g=-Math.cos(p),b=r/2,v=a/2;let j=1/0;g<0?j=Math.min(j,-v/g):g>0&&(j=Math.min(j,(a-v)/g)),f<0?j=Math.min(j,-b/f):f>0&&(j=Math.min(j,(r-b)/f));const _=b+f*j,S=v+g*j,A=yn._sign(a);this._batchChangeChild(".rotater",{x:_+f*h*A,y:S+g*h*A-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(D=>D.draggable()),x:0,y:0});const T=this.anchorStyleFunc();T&&d.forEach(D=>{T(D)}),(t=this.getLayer())===null||t===void 0||t.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),O8.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(yn.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return wa.prototype.toObject.call(this)}clone(t){return wa.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};Nl.isTransforming=()=>_3e>0;function _ys(s){return s instanceof Array||yn.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){Cxe.indexOf(t)===-1&&yn.warn("Unknown anchor name: "+t+". Available names are: "+Cxe.join(", "))}),s||[]}Nl.prototype.className="Transformer";Wu(Nl);Ps.addGetterSetter(Nl,"enabledAnchors",Cxe,_ys);Ps.addGetterSetter(Nl,"flipEnabled",!0,Ob());Ps.addGetterSetter(Nl,"resizeEnabled",!0);Ps.addGetterSetter(Nl,"anchorSize",10,oa());Ps.addGetterSetter(Nl,"rotateEnabled",!0);Ps.addGetterSetter(Nl,"rotateLineVisible",!0);Ps.addGetterSetter(Nl,"rotationSnaps",[]);Ps.addGetterSetter(Nl,"rotateAnchorOffset",50,oa());Ps.addGetterSetter(Nl,"rotateAnchorAngle",0,oa());Ps.addGetterSetter(Nl,"rotateAnchorCursor","crosshair");Ps.addGetterSetter(Nl,"rotationSnapTolerance",5,oa());Ps.addGetterSetter(Nl,"borderEnabled",!0);Ps.addGetterSetter(Nl,"anchorStroke","rgb(0, 161, 255)");Ps.addGetterSetter(Nl,"anchorStrokeWidth",1,oa());Ps.addGetterSetter(Nl,"anchorFill","white");Ps.addGetterSetter(Nl,"anchorCornerRadius",0,oa());Ps.addGetterSetter(Nl,"borderStroke","rgb(0, 161, 255)");Ps.addGetterSetter(Nl,"borderStrokeWidth",1,oa());Ps.addGetterSetter(Nl,"borderDash");Ps.addGetterSetter(Nl,"keepRatio",!0);Ps.addGetterSetter(Nl,"shiftBehavior","default");Ps.addGetterSetter(Nl,"centeredScaling",!1);Ps.addGetterSetter(Nl,"ignoreStroke",!1);Ps.addGetterSetter(Nl,"padding",0,oa());Ps.addGetterSetter(Nl,"nodes");Ps.addGetterSetter(Nl,"node");Ps.addGetterSetter(Nl,"boundBoxFunc");Ps.addGetterSetter(Nl,"anchorDragBoundFunc");Ps.addGetterSetter(Nl,"anchorStyleFunc");Ps.addGetterSetter(Nl,"shouldOverdrawWholeArea",!1);Ps.addGetterSetter(Nl,"useSingleNodeRotation",!0);Ps.backCompat(Nl,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class EN extends Qr{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,xa.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)}}EN.prototype.className="Wedge";EN.prototype._centroid=!0;EN.prototype._attrsAffectingSize=["radius"];Wu(EN);Ps.addGetterSetter(EN,"radius",0,oa());Ps.addGetterSetter(EN,"angle",0,oa());Ps.addGetterSetter(EN,"clockwise",!1);Ps.backCompat(EN,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function jHe(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const wys=[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],jys=[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 Nys(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,p,f,g,b,v,j,_,S,A,T,D,L,M;const F=t+t+1,z=r-1,V=a-1,W=t+1,K=W*(W+1)/2,Y=new jHe,ee=wys[t],ne=jys[t];let oe=null,pe=Y,ce=null,de=null;for(let ie=1;ie>ne,L!==0?(L=255/L,n[l]=(c*ee>>ne)*L,n[l+1]=(d*ee>>ne)*L,n[l+2]=(u*ee>>ne)*L):n[l]=n[l+1]=n[l+2]=0,c-=p,d-=f,u-=g,h-=b,p-=ce.r,f-=ce.g,g-=ce.b,b-=ce.a,i=o+((i=ye+t+1)>ne,L>0?(L=255/L,n[i]=(c*ee>>ne)*L,n[i+1]=(d*ee>>ne)*L,n[i+2]=(u*ee>>ne)*L):n[i]=n[i+1]=n[i+2]=0,c-=p,d-=f,u-=g,h-=b,p-=ce.r,f-=ce.g,g-=ce.b,b-=ce.a,i=ie+((i=_e+W)0&&Nys(t,n)};Ps.addGetterSetter(wa,"blurRadius",0,oa(),Ps.afterSetFilter);const Sys=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};Ps.addGetterSetter(wa,"contrast",0,oa(),Ps.afterSetFilter);const Eys=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,p=s.height,f=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),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)),v=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(l=(i=this.embossDirection)===null||i===void 0?void 0:i.call(this))!==null&&l!==void 0?l:"top-left"])!==null&&o!==void 0?o:315,j=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),_=f*10,S=g*255,A=v*Math.PI/180,T=Math.cos(A),D=Math.sin(A),L=128/1020*_,M=new Uint8ClampedArray(u),F=new Float32Array(h*p);for(let Y=0,ee=0;eeY<0?0:Y>255?255:Y;for(let Y=1;Ya&&(a=i),c=t[S+1],co&&(o=c),h=t[S+2],hu&&(u=h);a===r&&(a=255,r=0),o===l&&(o=255,l=0),u===d&&(u=255,d=0);let f,g,b,v,j,_;if(p>0)f=a+p*(255-a),g=r-p*(r-0),b=o+p*(255-o),v=l-p*(l-0),j=u+p*(255-u),_=d-p*(d-0);else{const S=(a+r)*.5;f=a+p*(a-S),g=r+p*(r-S);const A=(o+l)*.5;b=o+p*(o-A),v=l+p*(l-A);const T=(u+d)*.5;j=u+p*(u-T),_=d+p*(d-T)}for(let S=0;Sd?p:d;const f=l,g=i,b=360/g*Math.PI/180;for(let v=0;vd?p:d;const f=l,g=i,b=0;let v,j;for(u=0;ut&&(A=S,T=0,D=-1),a=0;a=0&&f=0&&g=0&&f=0&&g=255*4?255:0}return l}function qys(s,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(r.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&f=0&&g=n))for(let S=b;S=r)continue;const A=(n*S+_)*4;d+=l[A+0],u+=l[A+1],h+=l[A+2],p+=l[A+3],j+=1}d=d/j,u=u/j,h=h/j,p=p/j;for(let _=f;_=n))for(let S=b;S=r)continue;const A=(n*S+_)*4;l[A+0]=d,l[A+1]=u,l[A+2]=h,l[A+3]=p}}};Ps.addGetterSetter(wa,"pixelSize",8,oa(),Ps.afterSetFilter);const Wys=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)});Ps.addGetterSetter(wa,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});Ps.addGetterSetter(wa,"blue",0,$gt,Ps.afterSetFilter);const Yys=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)});Ps.addGetterSetter(wa,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});Ps.addGetterSetter(wa,"blue",0,$gt,Ps.afterSetFilter);Ps.addGetterSetter(wa,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const Zys=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},Xys=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;apn||et[ps]!==yt[pn]){var Kn=` `+et[ps].replace(" at new "," at ");return Q.displayName&&Kn.includes("")&&(Kn=Kn.replace("",Q.displayName)),Kn}while(1<=ps&&0<=pn);break}}}finally{Tr=!1,Error.prepareStackTrace=ke}return(Q=Q?Q.displayName||Q.name:"")?sr(Q):""}var wn=Object.prototype.hasOwnProperty,kr=[],dr=-1;function Jr(Q){return{current:Q}}function jr(Q){0>dr||(Q.current=kr[dr],kr[dr]=null,dr--)}function qn(Q,J){dr++,kr[dr]=Q.current,Q.current=J}var wi={},Oi=Jr(wi),ea=Jr(!1),ya=wi;function Mi(Q,J){var ke=Q.type.contextTypes;if(!ke)return wi;var Ve=Q.stateNode;if(Ve&&Ve.__reactInternalMemoizedUnmaskedChildContext===J)return Ve.__reactInternalMemoizedMaskedChildContext;var et={},yt;for(yt in ke)et[yt]=J[yt];return Ve&&(Q=Q.stateNode,Q.__reactInternalMemoizedUnmaskedChildContext=J,Q.__reactInternalMemoizedMaskedChildContext=et),et}function da(Q){return Q=Q.childContextTypes,Q!=null}function jn(){jr(ea),jr(Oi)}function Aa(Q,J,ke){if(Oi.current!==wi)throw Error(l(168));qn(Oi,J),qn(ea,ke)}function Yi(Q,J,ke){var Ve=Q.stateNode;if(J=J.childContextTypes,typeof Ve.getChildContext!="function")return ke;Ve=Ve.getChildContext();for(var et in Ve)if(!(et in J))throw Error(l(108,M(Q)||"Unknown",et));return i({},ke,Ve)}function Bo(Q){return Q=(Q=Q.stateNode)&&Q.__reactInternalMemoizedMergedChildContext||wi,ya=Oi.current,qn(Oi,Q),qn(ea,ea.current),!0}function rl(Q,J,ke){var Ve=Q.stateNode;if(!Ve)throw Error(l(169));ke?(Q=Yi(Q,J,ya),Ve.__reactInternalMemoizedMergedChildContext=Q,jr(ea),jr(Oi),qn(Oi,Q)):jr(ea),qn(ea,ke)}var po=Math.clz32?Math.clz32:fm,zc=Math.log,Sd=Math.LN2;function fm(Q){return Q>>>=0,Q===0?32:31-(zc(Q)/Sd|0)|0}var Cd=64,Hd=4194304;function uc(Q){switch(Q&-Q){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return Q&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return Q&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return Q}}function Gd(Q,J){var ke=Q.pendingLanes;if(ke===0)return 0;var Ve=0,et=Q.suspendedLanes,yt=Q.pingedLanes,ps=ke&268435455;if(ps!==0){var pn=ps&~et;pn!==0?Ve=uc(pn):(yt&=ps,yt!==0&&(Ve=uc(yt)))}else ps=ke&~et,ps!==0?Ve=uc(ps):yt!==0&&(Ve=uc(yt));if(Ve===0)return 0;if(J!==0&&J!==Ve&&!(J&et)&&(et=Ve&-Ve,yt=J&-J,et>=yt||et===16&&(yt&4194240)!==0))return J;if(Ve&4&&(Ve|=ke&16),J=Q.entangledLanes,J!==0)for(Q=Q.entanglements,J&=Ve;0ke;ke++)J.push(Q);return J}function Ef(Q,J,ke){Q.pendingLanes|=J,J!==536870912&&(Q.suspendedLanes=0,Q.pingedLanes=0),Q=Q.eventTimes,J=31-po(J),Q[J]=ke}function _h(Q,J){var ke=Q.pendingLanes&~J;Q.pendingLanes=J,Q.suspendedLanes=0,Q.pingedLanes=0,Q.expiredLanes&=J,Q.mutableReadLanes&=J,Q.entangledLanes&=J,J=Q.entanglements;var Ve=Q.eventTimes;for(Q=Q.expirationTimes;0>=ps,et-=ps,Zc=1<<32-po(J)+et|ke<ro?(Xd=ai,ai=null):Xd=ai.sibling;var il=Ta(Vn,ai,cn[ro],Oa);if(il===null){ai===null&&(ai=Xd);break}Q&&ai&&il.alternate===null&&J(Vn,ai),Zs=yt(il,Zs,ro),Ui===null?Wa=il:Ui.sibling=il,Ui=il,ai=Xd}if(ro===cn.length)return ke(Vn,ai),va&&Op(Vn,ro),Wa;if(ai===null){for(;roro?(Xd=ai,ai=null):Xd=ai.sibling;var bg=Ta(Vn,ai,il.value,Oa);if(bg===null){ai===null&&(ai=Xd);break}Q&&ai&&bg.alternate===null&&J(Vn,ai),Zs=yt(bg,Zs,ro),Ui===null?Wa=bg:Ui.sibling=bg,Ui=bg,ai=Xd}if(il.done)return ke(Vn,ai),va&&Op(Vn,ro),Wa;if(ai===null){for(;!il.done;ro++,il=cn.next())il=oo(Vn,il.value,Oa),il!==null&&(Zs=yt(il,Zs,ro),Ui===null?Wa=il:Ui.sibling=il,Ui=il);return va&&Op(Vn,ro),Wa}for(ai=Ve(Vn,ai);!il.done;ro++,il=cn.next())il=kc(ai,Vn,ro,il.value,Oa),il!==null&&(Q&&il.alternate!==null&&ai.delete(il.key===null?ro:il.key),Zs=yt(il,Zs,ro),Ui===null?Wa=il:Ui.sibling=il,Ui=il);return Q&&ai.forEach(function(zC){return J(Vn,zC)}),va&&Op(Vn,ro),Wa}function Kp(Vn,Zs,cn,Oa){if(typeof cn=="object"&&cn!==null&&cn.type===u&&cn.key===null&&(cn=cn.props.children),typeof cn=="object"&&cn!==null){switch(cn.$$typeof){case c:e:{for(var Wa=cn.key,Ui=Zs;Ui!==null;){if(Ui.key===Wa){if(Wa=cn.type,Wa===u){if(Ui.tag===7){ke(Vn,Ui.sibling),Zs=et(Ui,cn.props.children),Zs.return=Vn,Vn=Zs;break e}}else if(Ui.elementType===Wa||typeof Wa=="object"&&Wa!==null&&Wa.$$typeof===S&&Wb(Wa)===Ui.type){ke(Vn,Ui.sibling),Zs=et(Ui,cn.props),Zs.ref=yx(Vn,Ui,cn),Zs.return=Vn,Vn=Zs;break e}ke(Vn,Ui);break}else J(Vn,Ui);Ui=Ui.sibling}cn.type===u?(Zs=fs(cn.props.children,Vn.mode,Oa,cn.key),Zs.return=Vn,Vn=Zs):(Oa=Zo(cn.type,cn.key,cn.props,null,Vn.mode,Oa),Oa.ref=yx(Vn,Zs,cn),Oa.return=Vn,Vn=Oa)}return ps(Vn);case d:e:{for(Ui=cn.key;Zs!==null;){if(Zs.key===Ui)if(Zs.tag===4&&Zs.stateNode.containerInfo===cn.containerInfo&&Zs.stateNode.implementation===cn.implementation){ke(Vn,Zs.sibling),Zs=et(Zs,cn.children||[]),Zs.return=Vn,Vn=Zs;break e}else{ke(Vn,Zs);break}else J(Vn,Zs);Zs=Zs.sibling}Zs=qj(cn,Vn.mode,Oa),Zs.return=Vn,Vn=Zs}return ps(Vn);case S:return Ui=cn._init,Kp(Vn,Zs,Ui(cn._payload),Oa)}if(ee(cn))return lo(Vn,Zs,cn,Oa);if(D(cn))return Nh(Vn,Zs,cn,Oa);Oy(Vn,cn)}return typeof cn=="string"&&cn!==""||typeof cn=="number"?(cn=""+cn,Zs!==null&&Zs.tag===6?(ke(Vn,Zs.sibling),Zs=et(Zs,cn),Zs.return=Vn,Vn=Zs):(ke(Vn,Zs),Zs=x_(cn,Vn.mode,Oa),Zs.return=Vn,Vn=Zs),ps(Vn)):ke(Vn,Zs)}return Kp}var Ol=Qu(!0),x6=Qu(!1),Fy=Jr(null),Kb=null,vx=null,bx=null;function dj(){bx=vx=Kb=null}function Yb(Q,J,ke){Fe?(qn(Fy,J._currentValue),J._currentValue=ke):(qn(Fy,J._currentValue2),J._currentValue2=ke)}function Wd(Q){var J=Fy.current;jr(Fy),Fe?Q._currentValue=J:Q._currentValue2=J}function rp(Q,J,ke){for(;Q!==null;){var Ve=Q.alternate;if((Q.childLanes&J)!==J?(Q.childLanes|=J,Ve!==null&&(Ve.childLanes|=J)):Ve!==null&&(Ve.childLanes&J)!==J&&(Ve.childLanes|=J),Q===ke)break;Q=Q.return}}function Kd(Q,J){Kb=Q,bx=vx=null,Q=Q.dependencies,Q!==null&&Q.firstContext!==null&&(Q.lanes&J&&(wm=!0),Q.firstContext=null)}function Fp(Q){var J=Fe?Q._currentValue:Q._currentValue2;if(bx!==Q)if(Q={context:Q,memoizedValue:J,next:null},vx===null){if(Kb===null)throw Error(l(308));vx=Q,Kb.dependencies={lanes:0,firstContext:Q}}else vx=vx.next=Q;return J}var Pf=null;function Ml(Q){Pf===null?Pf=[Q]:Pf.push(Q)}function na(Q,J,ke,Ve){var et=J.interleaved;return et===null?(ke.next=ke,Ml(J)):(ke.next=et.next,et.next=ke),J.interleaved=ke,rr(Q,Ve)}function rr(Q,J){Q.lanes|=J;var ke=Q.alternate;for(ke!==null&&(ke.lanes|=J),ke=Q,Q=Q.return;Q!==null;)Q.childLanes|=J,ke=Q.alternate,ke!==null&&(ke.childLanes|=J),ke=Q,Q=Q.return;return ke.tag===3?ke.stateNode:null}var vl=!1;function la(Q){Q.updateQueue={baseState:Q.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ap(Q,J){Q=Q.updateQueue,J.updateQueue===Q&&(J.updateQueue={baseState:Q.baseState,firstBaseUpdate:Q.firstBaseUpdate,lastBaseUpdate:Q.lastBaseUpdate,shared:Q.shared,effects:Q.effects})}function vm(Q,J){return{eventTime:Q,lane:J,tag:0,payload:null,callback:null,next:null}}function Fr(Q,J,ke){var Ve=Q.updateQueue;if(Ve===null)return null;if(Ve=Ve.shared,xo&2){var et=Ve.pending;return et===null?J.next=J:(J.next=et.next,et.next=J),Ve.pending=J,rr(Q,ke)}return et=Ve.interleaved,et===null?(J.next=J,Ml(Ve)):(J.next=et.next,et.next=J),Ve.interleaved=J,rr(Q,ke)}function zy(Q,J,ke){if(J=J.updateQueue,J!==null&&(J=J.shared,(ke&4194240)!==0)){var Ve=J.lanes;Ve&=Q.pendingLanes,ke|=Ve,J.lanes=ke,px(Q,ke)}}function uj(Q,J){var ke=Q.updateQueue,Ve=Q.alternate;if(Ve!==null&&(Ve=Ve.updateQueue,ke===Ve)){var et=null,yt=null;if(ke=ke.firstBaseUpdate,ke!==null){do{var ps={eventTime:ke.eventTime,lane:ke.lane,tag:ke.tag,payload:ke.payload,callback:ke.callback,next:null};yt===null?et=yt=ps:yt=yt.next=ps,ke=ke.next}while(ke!==null);yt===null?et=yt=J:yt=yt.next=J}else et=yt=J;ke={baseState:Ve.baseState,firstBaseUpdate:et,lastBaseUpdate:yt,shared:Ve.shared,effects:Ve.effects},Q.updateQueue=ke;return}Q=ke.lastBaseUpdate,Q===null?ke.firstBaseUpdate=J:Q.next=J,ke.lastBaseUpdate=J}function o1(Q,J,ke,Ve){var et=Q.updateQueue;vl=!1;var yt=et.firstBaseUpdate,ps=et.lastBaseUpdate,pn=et.shared.pending;if(pn!==null){et.shared.pending=null;var Kn=pn,qr=Kn.next;Kn.next=null,ps===null?yt=qr:ps.next=qr,ps=Kn;var Va=Q.alternate;Va!==null&&(Va=Va.updateQueue,pn=Va.lastBaseUpdate,pn!==ps&&(pn===null?Va.firstBaseUpdate=qr:pn.next=qr,Va.lastBaseUpdate=Kn))}if(yt!==null){var oo=et.baseState;ps=0,Va=qr=Kn=null,pn=yt;do{var Ta=pn.lane,kc=pn.eventTime;if((Ve&Ta)===Ta){Va!==null&&(Va=Va.next={eventTime:kc,lane:0,tag:pn.tag,payload:pn.payload,callback:pn.callback,next:null});e:{var lo=Q,Nh=pn;switch(Ta=J,kc=ke,Nh.tag){case 1:if(lo=Nh.payload,typeof lo=="function"){oo=lo.call(kc,oo,Ta);break e}oo=lo;break e;case 3:lo.flags=lo.flags&-65537|128;case 0:if(lo=Nh.payload,Ta=typeof lo=="function"?lo.call(kc,oo,Ta):lo,Ta==null)break e;oo=i({},oo,Ta);break e;case 2:vl=!0}}pn.callback!==null&&pn.lane!==0&&(Q.flags|=64,Ta=et.effects,Ta===null?et.effects=[pn]:Ta.push(pn))}else kc={eventTime:kc,lane:Ta,tag:pn.tag,payload:pn.payload,callback:pn.callback,next:null},Va===null?(qr=Va=kc,Kn=oo):Va=Va.next=kc,ps|=Ta;if(pn=pn.next,pn===null){if(pn=et.shared.pending,pn===null)break;Ta=pn,pn=Ta.next,Ta.next=null,et.lastBaseUpdate=Ta,et.shared.pending=null}}while(!0);if(Va===null&&(Kn=oo),et.baseState=Kn,et.firstBaseUpdate=qr,et.lastBaseUpdate=Va,J=et.shared.interleaved,J!==null){et=J;do ps|=et.lane,et=et.next;while(et!==J)}else yt===null&&(et.shared.lanes=0);N0|=ps,Q.lanes=ps,Q.memoizedState=oo}}function Zb(Q,J,ke){if(Q=J.effects,J.effects=null,Q!==null)for(J=0;Jke?ke:4,Q(!0);var Ve=gC.transition;gC.transition={};try{Q(!1),J()}finally{fo=ke,gC.transition=Ve}}function _C(){return Qc().memoizedState}function wC(Q,J,ke){var Ve=yg(Q);if(ke={lane:Ve,action:ke,hasEagerState:!1,eagerState:null,next:null},jC(Q))g6(J,ke);else if(ke=na(Q,J,ke,Ve),ke!==null){var et=jh();dp(ke,Q,Ve,et),dl(ke,J,Ve)}}function UR(Q,J,ke){var Ve=yg(Q),et={lane:Ve,action:ke,hasEagerState:!1,eagerState:null,next:null};if(jC(Q))g6(J,et);else{var yt=Q.alternate;if(Q.lanes===0&&(yt===null||yt.lanes===0)&&(yt=J.lastRenderedReducer,yt!==null))try{var ps=J.lastRenderedState,pn=yt(ps,ke);if(et.hasEagerState=!0,et.eagerState=pn,Jm(pn,ps)){var Kn=J.interleaved;Kn===null?(et.next=et,Ml(J)):(et.next=Kn.next,Kn.next=et),J.interleaved=et;return}}catch{}finally{}ke=na(Q,J,et,Ve),ke!==null&&(et=jh(),dp(ke,Q,Ve,et),dl(ke,J,Ve))}}function jC(Q){var J=Q.alternate;return Q===Wl||J!==null&&J===Wl}function g6(Q,J){Rf=Qb=!0;var ke=Q.pending;ke===null?J.next=J:(J.next=ke.next,ke.next=J),Q.pending=J}function dl(Q,J,ke){if(ke&4194240){var Ve=J.lanes;Ve&=Q.pendingLanes,ke|=Ve,J.lanes=ke,px(Q,ke)}}var vj={readContext:Fp,useCallback:qh,useContext:qh,useEffect:qh,useImperativeHandle:qh,useInsertionEffect:qh,useLayoutEffect:qh,useMemo:qh,useReducer:qh,useRef:qh,useState:qh,useDebugValue:qh,useDeferredValue:qh,useTransition:qh,useMutableSource:qh,useSyncExternalStore:qh,useId:qh,unstable_isNewReconciler:!1},qR={readContext:Fp,useCallback:function(Q,J){return Of().memoizedState=[Q,J===void 0?null:J],Q},useContext:Fp,useEffect:$y,useImperativeHandle:function(Q,J,ke){return ke=ke!=null?ke.concat([Q]):null,gj(4194308,4,e_.bind(null,J,Q),ke)},useLayoutEffect:function(Q,J){return gj(4194308,4,Q,J)},useInsertionEffect:function(Q,J){return gj(4,2,Q,J)},useMemo:function(Q,J){var ke=Of();return J=J===void 0?null:J,Q=Q(),ke.memoizedState=[Q,J],Q},useReducer:function(Q,J,ke){var Ve=Of();return J=ke!==void 0?ke(J):J,Ve.memoizedState=Ve.baseState=J,Q={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Q,lastRenderedState:J},Ve.queue=Q,Q=Q.dispatch=wC.bind(null,Wl,Q),[Ve.memoizedState,Q]},useRef:function(Q){var J=Of();return Q={current:Q},J.memoizedState=Q},useState:op,useDebugValue:yC,useDeferredValue:function(Q){return Of().memoizedState=Q},useTransition:function(){var Q=op(!1),J=Q[0];return Q=gi.bind(null,Q[1]),Of().memoizedState=Q,[J,Q]},useMutableSource:function(){},useSyncExternalStore:function(Q,J,ke){var Ve=Wl,et=Of();if(va){if(ke===void 0)throw Error(l(407));ke=ke()}else{if(ke=J(),hc===null)throw Error(l(349));p0&30||FN(Ve,J,ke)}et.memoizedState=ke;var yt={value:ke,getSnapshot:J};return et.queue=yt,$y(h1.bind(null,Ve,yt,Q),[Q]),Ve.flags|=2048,f0(9,u1.bind(null,Ve,yt,ke,J),void 0,null),ke},useId:function(){var Q=Of(),J=hc.identifierPrefix;if(va){var ke=np,Ve=Zc;ke=(Ve&~(1<<32-po(Ve)-1)).toString(32)+ke,J=":"+J+"R"+ke,ke=mj++,0zf&&(J.flags|=128,Ve=!0,a_(et,!1),J.lanes=4194304)}else{if(!Ve)if(Q=l1(yt),Q!==null){if(J.flags|=128,Ve=!0,Q=Q.updateQueue,Q!==null&&(J.updateQueue=Q,J.flags|=4),a_(et,!0),et.tail===null&&et.tailMode==="hidden"&&!yt.alternate&&!va)return cd(J),null}else 2*al()-et.renderingStartTime>zf&&ke!==1073741824&&(J.flags|=128,Ve=!0,a_(et,!1),J.lanes=4194304);et.isBackwards?(yt.sibling=J.child,J.child=yt):(Q=et.last,Q!==null?Q.sibling=yt:J.child=yt,et.last=yt)}return et.tail!==null?(J=et.tail,et.rendering=J,et.tail=J.sibling,et.renderingStartTime=al(),J.sibling=null,Q=ec.current,qn(ec,Ve?Q&1|2:Q&1),J):(cd(J),null);case 22:case 23:return Bj(),ke=J.memoizedState!==null,Q!==null&&Q.memoizedState!==null!==ke&&(J.flags|=8192),ke&&J.mode&1?Hh&1073741824&&(cd(J),qe&&J.subtreeFlags&6&&(J.flags|=8192)):cd(J),null;case 24:return null;case 25:return null}throw Error(l(156,J.tag))}function GN(Q,J){switch(zn(J),J.tag){case 1:return da(J.type)&&jn(),Q=J.flags,Q&65536?(J.flags=Q&-65537|128,J):null;case 3:return zp(),jr(ea),jr(Oi),Bp(),Q=J.flags,Q&65536&&!(Q&128)?(J.flags=Q&-65537|128,J):null;case 5:return LN(J),null;case 13:if(jr(ec),Q=J.memoizedState,Q!==null&&Q.dehydrated!==null){if(J.alternate===null)throw Error(l(340));Ii()}return Q=J.flags,Q&65536?(J.flags=Q&-65537|128,J):null;case 19:return jr(ec),null;case 4:return zp(),null;case 10:return Wd(J.type._context),null;case 22:case 23:return Bj(),null;case 24:return null;default:return null}}var WN=!1,wh=!1,HR=typeof WeakSet=="function"?WeakSet:Set,qa=null;function y0(Q,J){var ke=Q.ref;if(ke!==null)if(typeof ke=="function")try{ke(null)}catch(Ve){Ra(Q,J,Ve)}else ke.current=null}function i_(Q,J,ke){try{ke()}catch(Ve){Ra(Q,J,Ve)}}var EC=!1;function o_(Q,J){for(ce(Q.containerInfo),qa=J;qa!==null;)if(Q=qa,J=Q.child,(Q.subtreeFlags&1028)!==0&&J!==null)J.return=Q,qa=J;else for(;qa!==null;){Q=qa;try{var ke=Q.alternate;if(Q.flags&1024)switch(Q.tag){case 0:case 11:case 15:break;case 1:if(ke!==null){var Ve=ke.memoizedProps,et=ke.memoizedState,yt=Q.stateNode,ps=yt.getSnapshotBeforeUpdate(Q.elementType===Q.type?Ve:Ff(Q.type,Ve),et);yt.__reactInternalSnapshotBeforeUpdate=ps}break;case 3:qe&&Us(Q.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(pn){Ra(Q,Q.return,pn)}if(J=Q.sibling,J!==null){J.return=Q.return,qa=J;break}qa=Q.return}return ke=EC,EC=!1,ke}function l_(Q,J,ke){var Ve=J.updateQueue;if(Ve=Ve!==null?Ve.lastEffect:null,Ve!==null){var et=Ve=Ve.next;do{if((et.tag&Q)===Q){var yt=et.destroy;et.destroy=void 0,yt!==void 0&&i_(J,ke,yt)}et=et.next}while(et!==Ve)}}function Aj(Q,J){if(J=J.updateQueue,J=J!==null?J.lastEffect:null,J!==null){var ke=J=J.next;do{if((ke.tag&Q)===Q){var Ve=ke.create;ke.destroy=Ve()}ke=ke.next}while(ke!==J)}}function w1(Q){var J=Q.ref;if(J!==null){var ke=Q.stateNode;switch(Q.tag){case 5:Q=ne(ke);break;default:Q=ke}typeof J=="function"?J(Q):J.current=Q}}function Mj(Q){var J=Q.alternate;J!==null&&(Q.alternate=null,Mj(J)),Q.child=null,Q.deletions=null,Q.sibling=null,Q.tag===5&&(J=Q.stateNode,J!==null&&He(J)),Q.stateNode=null,Q.return=null,Q.dependencies=null,Q.memoizedProps=null,Q.memoizedState=null,Q.pendingProps=null,Q.stateNode=null,Q.updateQueue=null}function v0(Q){return Q.tag===5||Q.tag===3||Q.tag===4}function Ij(Q){e:for(;;){for(;Q.sibling===null;){if(Q.return===null||v0(Q.return))return null;Q=Q.return}for(Q.sibling.return=Q.return,Q=Q.sibling;Q.tag!==5&&Q.tag!==6&&Q.tag!==18;){if(Q.flags&2||Q.child===null||Q.tag===4)continue e;Q.child.return=Q,Q=Q.child}if(!(Q.flags&2))return Q.stateNode}}function c_(Q,J,ke){var Ve=Q.tag;if(Ve===5||Ve===6)Q=Q.stateNode,J?$t(ke,Q,J):ns(ke,Q);else if(Ve!==4&&(Q=Q.child,Q!==null))for(c_(Q,J,ke),Q=Q.sibling;Q!==null;)c_(Q,J,ke),Q=Q.sibling}function KN(Q,J,ke){var Ve=Q.tag;if(Ve===5||Ve===6)Q=Q.stateNode,J?St(ke,Q,J):Qt(ke,Q);else if(Ve!==4&&(Q=Q.child,Q!==null))for(KN(Q,J,ke),Q=Q.sibling;Q!==null;)KN(Q,J,ke),Q=Q.sibling}var Uc=null,jm=!1;function qp(Q,J,ke){for(ke=ke.child;ke!==null;)YN(Q,J,ke),ke=ke.sibling}function YN(Q,J,ke){if(Xa&&typeof Xa.onCommitFiberUnmount=="function")try{Xa.onCommitFiberUnmount(Af,ke)}catch{}switch(ke.tag){case 5:wh||y0(ke,J);case 6:if(qe){var Ve=Uc,et=jm;Uc=null,qp(Q,J,ke),Uc=Ve,jm=et,Uc!==null&&(jm?Ut(Uc,ke.stateNode):ht(Uc,ke.stateNode))}else qp(Q,J,ke);break;case 18:qe&&Uc!==null&&(jm?ln(Uc,ke.stateNode):Ns(Uc,ke.stateNode));break;case 4:qe?(Ve=Uc,et=jm,Uc=ke.stateNode.containerInfo,jm=!0,qp(Q,J,ke),Uc=Ve,jm=et):(ve&&(Ve=ke.stateNode.containerInfo,et=Jn(Ve),Gn(Ve,et)),qp(Q,J,ke));break;case 0:case 11:case 14:case 15:if(!wh&&(Ve=ke.updateQueue,Ve!==null&&(Ve=Ve.lastEffect,Ve!==null))){et=Ve=Ve.next;do{var yt=et,ps=yt.destroy;yt=yt.tag,ps!==void 0&&(yt&2||yt&4)&&i_(ke,J,ps),et=et.next}while(et!==Ve)}qp(Q,J,ke);break;case 1:if(!wh&&(y0(ke,J),Ve=ke.stateNode,typeof Ve.componentWillUnmount=="function"))try{Ve.props=ke.memoizedProps,Ve.state=ke.memoizedState,Ve.componentWillUnmount()}catch(pn){Ra(ke,J,pn)}qp(Q,J,ke);break;case 21:qp(Q,J,ke);break;case 22:ke.mode&1?(wh=(Ve=wh)||ke.memoizedState!==null,qp(Q,J,ke),wh=Ve):qp(Q,J,ke);break;default:qp(Q,J,ke)}}function ZN(Q){var J=Q.updateQueue;if(J!==null){Q.updateQueue=null;var ke=Q.stateNode;ke===null&&(ke=Q.stateNode=new HR),J.forEach(function(Ve){var et=f_.bind(null,Q,Ve);ke.has(Ve)||(ke.add(Ve),Ve.then(et,et))})}}function cp(Q,J){var ke=J.deletions;if(ke!==null)for(var Ve=0;Ve";case j1:return":has("+(Vp(Q)||"")+")";case Wy:return'[role="'+Q.value+'"]';case b0:return'"'+Q.value+'"';case jx:return'[data-testname="'+Q.value+'"]';default:throw Error(l(365))}}function XN(Q,J){var ke=[];Q=[Q,0];for(var Ve=0;Veet&&(et=ps),Ve&=~yt}if(Ve=et,Ve=al()-Ve,Ve=(120>Ve?120:480>Ve?480:1080>Ve?1080:1920>Ve?1920:3e3>Ve?3e3:4320>Ve?4320:1960*Dj(Ve/1960))-Ve,10Q?16:Q,gg===null)var Ve=!1;else{if(Q=gg,gg=null,h_=0,xo&6)throw Error(l(331));var et=xo;for(xo|=4,qa=Q.current;qa!==null;){var yt=qa,ps=yt.child;if(qa.flags&16){var pn=yt.deletions;if(pn!==null){for(var Kn=0;Knal()-u_?vg(Q,0):N1|=ke),Wh(Q,J)}function $j(Q,J){J===0&&(Q.mode&1?(J=Hd,Hd<<=1,!(Hd&130023424)&&(Hd=4194304)):J=1);var ke=jh();Q=rr(Q,J),Q!==null&&(Ef(Q,J,ke),Wh(Q,ke))}function sk(Q){var J=Q.memoizedState,ke=0;J!==null&&(ke=J.retryLane),$j(Q,ke)}function f_(Q,J){var ke=0;switch(Q.tag){case 13:var Ve=Q.stateNode,et=Q.memoizedState;et!==null&&(ke=et.retryLane);break;case 19:Ve=Q.stateNode;break;default:throw Error(l(314))}Ve!==null&&Ve.delete(J),$j(Q,ke)}var nk;nk=function(Q,J,ke){if(Q!==null)if(Q.memoizedProps!==J.pendingProps||ea.current)wm=!0;else{if(!(Q.lanes&ke)&&!(J.flags&128))return wm=!1,Tj(Q,J,ke);wm=!!(Q.flags&131072)}else wm=!1,va&&J.flags&1048576&&Lt(J,Gb,J.index);switch(J.lanes=0,J.tag){case 2:var Ve=J.type;b1(Q,J),Q=J.pendingProps;var et=Mi(J,Oi.current);Kd(J,ke),et=pj(null,J,Ve,Q,et,ke);var yt=Xb();return J.flags|=1,typeof et=="object"&&et!==null&&typeof et.render=="function"&&et.$$typeof===void 0?(J.tag=1,J.memoizedState=null,J.updateQueue=null,da(Ve)?(yt=!0,Bo(J)):yt=!1,J.memoizedState=et.state!==null&&et.state!==void 0?et.state:null,la(J),et.updater=f1,J.stateNode=et,et._reactInternals=J,Vy(J,Ve,Q,ke),J=Sj(null,J,Ve,!0,yt,ke)):(J.tag=0,va&&yt&&hn(J),Vh(null,J,et,ke),J=J.child),J;case 16:Ve=J.elementType;e:{switch(b1(Q,J),Q=J.pendingProps,et=Ve._init,Ve=et(Ve._payload),J.type=Ve,et=J.tag=Nn(Ve),Q=Ff(Ve,Q),et){case 0:J=SC(null,J,Ve,Q,ke);break e;case 1:J=VN(null,J,Ve,Q,ke);break e;case 11:J=NC(null,J,Ve,Q,ke);break e;case 14:J=g1(null,J,Ve,Ff(Ve.type,Q),ke);break e}throw Error(l(306,Ve,""))}return J;case 0:return Ve=J.type,et=J.pendingProps,et=J.elementType===Ve?et:Ff(Ve,et),SC(Q,J,Ve,et,ke);case 1:return Ve=J.type,et=J.pendingProps,et=J.elementType===Ve?et:Ff(Ve,et),VN(Q,J,Ve,et,ke);case 3:e:{if(t_(J),Q===null)throw Error(l(387));Ve=J.pendingProps,yt=J.memoizedState,et=yt.element,ap(Q,J),o1(J,Ve,null,ke);var ps=J.memoizedState;if(Ve=ps.element,Je&&yt.isDehydrated)if(yt={element:Ve,isDehydrated:!1,cache:ps.cache,pendingSuspenseBoundaries:ps.pendingSuspenseBoundaries,transitions:ps.transitions},J.updateQueue.baseState=yt,J.memoizedState=yt,J.flags&256){et=_m(Error(l(423)),J),J=y1(Q,J,Ve,ke,et);break e}else if(Ve!==et){et=_m(Error(l(424)),J),J=y1(Q,J,Ve,ke,et);break e}else for(Je&&(Wn=Oe(J.stateNode.containerInfo),Or=J,va=!0,oi=null,Ja=!1),ke=x6(J,null,Ve,ke),J.child=ke;ke;)ke.flags=ke.flags&-3|4096,ke=ke.sibling;else{if(Ii(),Ve===et){J=Up(Q,J,ke);break e}Vh(Q,J,Ve,ke)}J=J.child}return J;case 5:return hj(J),Q===null&&Zu(J),Ve=J.type,et=J.pendingProps,yt=Q!==null?Q.memoizedProps:null,ps=et.children,Te(Ve,et)?ps=null:yt!==null&&Te(Ve,yt)&&(J.flags|=32),b6(Q,J),Vh(Q,J,ps,ke),J.child;case 6:return Q===null&&Zu(J),null;case 13:return _6(Q,J,ke);case 4:return $c(J,J.stateNode.containerInfo),Ve=J.pendingProps,Q===null?J.child=Ol(J,null,Ve,ke):Vh(Q,J,Ve,ke),J.child;case 11:return Ve=J.type,et=J.pendingProps,et=J.elementType===Ve?et:Ff(Ve,et),NC(Q,J,Ve,et,ke);case 7:return Vh(Q,J,J.pendingProps,ke),J.child;case 8:return Vh(Q,J,J.pendingProps.children,ke),J.child;case 12:return Vh(Q,J,J.pendingProps.children,ke),J.child;case 10:e:{if(Ve=J.type._context,et=J.pendingProps,yt=J.memoizedProps,ps=et.value,Yb(J,Ve,ps),yt!==null)if(Jm(yt.value,ps)){if(yt.children===et.children&&!ea.current){J=Up(Q,J,ke);break e}}else for(yt=J.child,yt!==null&&(yt.return=J);yt!==null;){var pn=yt.dependencies;if(pn!==null){ps=yt.child;for(var Kn=pn.firstContext;Kn!==null;){if(Kn.context===Ve){if(yt.tag===1){Kn=vm(-1,ke&-ke),Kn.tag=2;var qr=yt.updateQueue;if(qr!==null){qr=qr.shared;var Va=qr.pending;Va===null?Kn.next=Kn:(Kn.next=Va.next,Va.next=Kn),qr.pending=Kn}}yt.lanes|=ke,Kn=yt.alternate,Kn!==null&&(Kn.lanes|=ke),rp(yt.return,ke,J),pn.lanes|=ke;break}Kn=Kn.next}}else if(yt.tag===10)ps=yt.type===J.type?null:yt.child;else if(yt.tag===18){if(ps=yt.return,ps===null)throw Error(l(341));ps.lanes|=ke,pn=ps.alternate,pn!==null&&(pn.lanes|=ke),rp(ps,ke,J),ps=yt.sibling}else ps=yt.child;if(ps!==null)ps.return=yt;else for(ps=yt;ps!==null;){if(ps===J){ps=null;break}if(yt=ps.sibling,yt!==null){yt.return=ps.return,ps=yt;break}ps=ps.return}yt=ps}Vh(Q,J,et.children,ke),J=J.child}return J;case 9:return et=J.type,Ve=J.pendingProps.children,Kd(J,ke),et=Fp(et),Ve=Ve(et),J.flags|=1,Vh(Q,J,Ve,ke),J.child;case 14:return Ve=J.type,et=Ff(Ve,J.pendingProps),et=Ff(Ve.type,et),g1(Q,J,Ve,et,ke);case 15:return kC(Q,J,J.type,J.pendingProps,ke);case 17:return Ve=J.type,et=J.pendingProps,et=J.elementType===Ve?et:Ff(Ve,et),b1(Q,J),J.tag=1,da(Ve)?(Q=!0,Bo(J)):Q=!1,Kd(J,ke),Uy(J,Ve,et),Vy(J,Ve,et,ke),Sj(null,J,Ve,!0,Q,ke);case 19:return n_(Q,J,ke);case 22:return v6(Q,J,ke)}throw Error(l(156,J.tag))};function rk(Q,J){return gm(Q,J)}function S1(Q,J,ke,Ve){this.tag=Q,this.key=ke,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=J,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=Ve,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Qd(Q,J,ke,Ve){return new S1(Q,J,ke,Ve)}function kn(Q){return Q=Q.prototype,!(!Q||!Q.isReactComponent)}function Nn(Q){if(typeof Q=="function")return kn(Q)?1:0;if(Q!=null){if(Q=Q.$$typeof,Q===b)return 11;if(Q===_)return 14}return 2}function Wp(Q,J){var ke=Q.alternate;return ke===null?(ke=Qd(Q.tag,J,Q.key,Q.mode),ke.elementType=Q.elementType,ke.type=Q.type,ke.stateNode=Q.stateNode,ke.alternate=Q,Q.alternate=ke):(ke.pendingProps=J,ke.type=Q.type,ke.flags=0,ke.subtreeFlags=0,ke.deletions=null),ke.flags=Q.flags&14680064,ke.childLanes=Q.childLanes,ke.lanes=Q.lanes,ke.child=Q.child,ke.memoizedProps=Q.memoizedProps,ke.memoizedState=Q.memoizedState,ke.updateQueue=Q.updateQueue,J=Q.dependencies,ke.dependencies=J===null?null:{lanes:J.lanes,firstContext:J.firstContext},ke.sibling=Q.sibling,ke.index=Q.index,ke.ref=Q.ref,ke}function Zo(Q,J,ke,Ve,et,yt){var ps=2;if(Ve=Q,typeof Q=="function")kn(Q)&&(ps=1);else if(typeof Q=="string")ps=5;else e:switch(Q){case u:return fs(ke.children,et,yt,J);case h:ps=8,et|=8;break;case p:return Q=Qd(12,ke,J,et|2),Q.elementType=p,Q.lanes=yt,Q;case v:return Q=Qd(13,ke,J,et),Q.elementType=v,Q.lanes=yt,Q;case j:return Q=Qd(19,ke,J,et),Q.elementType=j,Q.lanes=yt,Q;case A:return Uj(ke,et,yt,J);default:if(typeof Q=="object"&&Q!==null)switch(Q.$$typeof){case f:ps=10;break e;case g:ps=9;break e;case b:ps=11;break e;case _:ps=14;break e;case S:ps=16,Ve=null;break e}throw Error(l(130,Q==null?Q:typeof Q,""))}return J=Qd(ps,ke,J,et),J.elementType=Q,J.type=Ve,J.lanes=yt,J}function fs(Q,J,ke,Ve){return Q=Qd(7,Q,Ve,J),Q.lanes=ke,Q}function Uj(Q,J,ke,Ve){return Q=Qd(22,Q,Ve,J),Q.elementType=A,Q.lanes=ke,Q.stateNode={isHidden:!1},Q}function x_(Q,J,ke){return Q=Qd(6,Q,null,J),Q.lanes=ke,Q}function qj(Q,J,ke){return J=Qd(4,Q.children!==null?Q.children:[],Q.key,J),J.lanes=ke,J.stateNode={containerInfo:Q.containerInfo,pendingChildren:null,implementation:Q.implementation},J}function ak(Q,J,ke,Ve,et){this.tag=J,this.containerInfo=Q,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Ie,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Py(0),this.expirationTimes=Py(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Py(0),this.identifierPrefix=Ve,this.onRecoverableError=et,Je&&(this.mutableSourceEagerHydrationData=null)}function RC(Q,J,ke,Ve,et,yt,ps,pn,Kn){return Q=new ak(Q,J,ke,pn,Kn),J===1?(J=1,yt===!0&&(J|=8)):J=0,yt=Qd(3,null,null,J),Q.current=yt,yt.stateNode=Q,yt.memoizedState={element:Ve,isDehydrated:ke,cache:null,transitions:null,pendingSuspenseBoundaries:null},la(yt),Q}function OC(Q){if(!Q)return wi;Q=Q._reactInternals;e:{if(F(Q)!==Q||Q.tag!==1)throw Error(l(170));var J=Q;do{switch(J.tag){case 3:J=J.stateNode.context;break e;case 1:if(da(J.type)){J=J.stateNode.__reactInternalMemoizedMergedChildContext;break e}}J=J.return}while(J!==null);throw Error(l(171))}if(Q.tag===1){var ke=Q.type;if(da(ke))return Yi(Q,ke,J)}return J}function C1(Q){var J=Q._reactInternals;if(J===void 0)throw typeof Q.render=="function"?Error(l(188)):(Q=Object.keys(Q).join(","),Error(l(268,Q)));return Q=W(J),Q===null?null:Q.stateNode}function FC(Q,J){if(Q=Q.memoizedState,Q!==null&&Q.dehydrated!==null){var ke=Q.retryLane;Q.retryLane=ke!==0&&ke=qr&&yt>=oo&&et<=Va&&ps<=Ta){Q.splice(J,1);break}else if(Ve!==qr||ke.width!==Kn.width||Taps){if(!(yt!==oo||ke.height!==Kn.height||Vaet)){qr>Ve&&(Kn.width+=qr-Ve,Kn.x=Ve),Vayt&&(Kn.height+=oo-yt,Kn.y=yt),Take&&(ke=ps)),ps ")+` No matching component was found for: `)+Q.join(" > ")}return null},n.getPublicRootInstance=function(Q){if(Q=Q.current,!Q.child)return null;switch(Q.child.tag){case 5:return ne(Q.child.stateNode);default:return Q.child.stateNode}},n.injectIntoDevTools=function(Q){if(Q={bundleType:Q.bundleType,version:Q.version,rendererPackageName:Q.rendererPackageName,rendererConfig:Q.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:A6,findFiberByHostInstance:Q.findFiberByHostInstance||ok,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")Q=!1;else{var J=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(J.isDisabled||!J.supportsFiber)Q=!0;else{try{Af=J.inject(Q),Xa=J}catch{}Q=!!J.checkDCE}}return Q},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(Q,J,ke,Ve){if(!Ke)throw Error(l(363));Q=JN(Q,J);var et=kt(Q,ke,Ve).disconnect;return{disconnect:function(){et()}}},n.registerMutableSourceForHydration=function(Q,J){var ke=J._getVersion;ke=ke(J._source),Q.mutableSourceEagerHydrationData==null?Q.mutableSourceEagerHydrationData=[J,ke]:Q.mutableSourceEagerHydrationData.push(J,ke)},n.runWithPriority=function(Q,J){var ke=fo;try{return fo=Q,J()}finally{fo=ke}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(Q,J,ke,Ve){var et=J.current,yt=jh(),ps=yg(et);return ke=OC(ke),J.context===null?J.context=ke:J.pendingContext=ke,J=vm(yt,ps),J.payload={element:Q},Ve=Ve===void 0?null:Ve,Ve!==null&&(J.callback=Ve),Q=Fr(et,J,ps),Q!==null&&(dp(Q,et,ps,yt),zy(Q,et,ps)),ps},n};b0t.exports=Jys;var evs=b0t.exports;const tvs=jl(evs);var _0t={exports:{}},t6={};/** * @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. */t6.ConcurrentRoot=1;t6.ContinuousEventPriority=4;t6.DefaultEventPriority=16;t6.DiscreteEventPriority=1;t6.IdleEventPriority=536870912;t6.LegacyRoot=0;_0t.exports=t6;var w0t=_0t.exports;const NHe={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let kHe=!1,SHe=!1;const BIe=".react-konva-event",svs=`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 `,nvs=`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 `,rvs={};function wve(s,t,n=rvs){if(!kHe&&"zIndex"in t&&(console.warn(nvs),kHe=!0),!SHe&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(svs),SHe=!0)}for(var i in n)if(!NHe[i]){var l=i.slice(0,2)==="on",o=n[i]!==t[i];if(l&&o){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),s.off(c,n[i])}var d=!t.hasOwnProperty(i);d&&s.setAttr(i,void 0)}var u=t._useStrictMode,h={},p=!1;const f={};for(var i in t)if(!NHe[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]&&(f[c]=t[i])}!l&&(t[i]!==n[i]||u&&t[i]!==s.getAttr(i))&&(p=!0,h[i]=t[i])}p&&(s.setAttrs(h),cC(s));for(var c in f)s.on(c+BIe,f[c])}function cC(s){if(!xa.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const j0t={},avs={};EM.Node.prototype._applyProps=wve;function ivs(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),cC(s)}function ovs(s,t,n){let r=EM[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=EM.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 wve(c,i),c}function lvs(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function cvs(s,t,n){return!1}function dvs(s){return s}function uvs(){return null}function hvs(){return null}function mvs(s,t,n,r){return avs}function pvs(){}function fvs(s){}function xvs(s,t){return!1}function gvs(){return j0t}function yvs(){return j0t}const vvs=setTimeout,bvs=clearTimeout,_vs=-1;function wvs(s,t){return!1}const jvs=!1,Nvs=!0,kvs=!0;function Svs(s,t){t.parent===s?t.moveToTop():s.add(t),cC(s)}function Cvs(s,t){t.parent===s?t.moveToTop():s.add(t),cC(s)}function N0t(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),cC(s)}function Tvs(s,t,n){N0t(s,t,n)}function Evs(s,t){t.destroy(),t.off(BIe),cC(s)}function Avs(s,t){t.destroy(),t.off(BIe),cC(s)}function Mvs(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function Ivs(s,t,n){}function Pvs(s,t,n,r,a){wve(s,a,r)}function Lvs(s){s.hide(),cC(s)}function Dvs(s){}function Rvs(s,t){(t.visible==null||t.visible)&&s.show()}function Ovs(s,t){}function Fvs(s){}function zvs(){}const Bvs=()=>w0t.DefaultEventPriority,$vs=Object.freeze(Object.defineProperty({__proto__:null,appendChild:Svs,appendChildToContainer:Cvs,appendInitialChild:ivs,cancelTimeout:bvs,clearContainer:Fvs,commitMount:Ivs,commitTextUpdate:Mvs,commitUpdate:Pvs,createInstance:ovs,createTextInstance:lvs,detachDeletedInstance:zvs,finalizeInitialChildren:cvs,getChildHostContext:yvs,getCurrentEventPriority:Bvs,getPublicInstance:dvs,getRootHostContext:gvs,hideInstance:Lvs,hideTextInstance:Dvs,idlePriority:R7.unstable_IdlePriority,insertBefore:N0t,insertInContainerBefore:Tvs,isPrimaryRenderer:jvs,noTimeout:_vs,now:R7.unstable_now,prepareForCommit:uvs,preparePortalMount:hvs,prepareUpdate:mvs,removeChild:Evs,removeChildFromContainer:Avs,resetAfterCommit:pvs,resetTextContent:fvs,run:R7.unstable_runWithPriority,scheduleTimeout:vvs,shouldDeprioritizeSubtree:xvs,shouldSetTextContent:wvs,supportsMutation:kvs,unhideInstance:Rvs,unhideTextInstance:Ovs,warnsIfNotActing:Nvs},Symbol.toStringTag,{value:"Module"}));var Uvs=Object.defineProperty,qvs=Object.defineProperties,Vvs=Object.getOwnPropertyDescriptors,CHe=Object.getOwnPropertySymbols,Hvs=Object.prototype.hasOwnProperty,Gvs=Object.prototype.propertyIsEnumerable,THe=(s,t,n)=>t in s?Uvs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,EHe=(s,t)=>{for(var n in t||(t={}))Hvs.call(t,n)&&THe(s,n,t[n]);if(CHe)for(var n of CHe(t))Gvs.call(t,n)&&THe(s,n,t[n]);return s},Wvs=(s,t)=>qvs(s,Vvs(t)),AHe,MHe;typeof window<"u"&&((AHe=window.document)!=null&&AHe.createElement||((MHe=window.navigator)==null?void 0:MHe.product)==="ReactNative")?N.useLayoutEffect:N.useEffect;function k0t(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=k0t(r,t,n);if(a)return a;r=r.sibling}}function S0t(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const IHe=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=IHe;return}return IHe.apply(this,arguments)};const $Ie=S0t(N.createContext(null));class C0t extends N.Component{render(){return N.createElement($Ie.Provider,{value:this._reactInternals},this.props.children)}}function Kvs(){const s=N.useContext($Ie);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=N.useId();return N.useMemo(()=>{for(const r of[s,s==null?void 0:s.alternate]){if(!r)continue;const a=k0t(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 Yvs(){const s=Kvs(),[t]=N.useState(()=>new Map);t.clear();let n=s;for(;n;){if(n.type&&typeof n.type=="object"){const a=n.type._context===void 0&&n.type.Provider===n.type?n.type:n.type._context;a&&a!==$Ie&&!t.has(a)&&t.set(a,N.useContext(S0t(a)))}n=n.return}return t}function Zvs(){const s=Yvs();return N.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>N.createElement(t,null,N.createElement(n.Provider,Wvs(EHe({},r),{value:s.get(n)}))),t=>N.createElement(C0t,EHe({},t))),[s])}function Qvs(s){const t=Nt.useRef({});return Nt.useLayoutEffect(()=>{t.current=s}),Nt.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const Xvs=s=>{const t=Nt.useRef(null),n=Nt.useRef(null),r=Nt.useRef(null),a=Qvs(s),i=Zvs(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Nt.useLayoutEffect(()=>(n.current=new EM.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=C7.createContainer(n.current,w0t.LegacyRoot,!1,null),C7.updateContainer(Nt.createElement(i,{},s.children),r.current),()=>{EM.isBrowser&&(l(null),C7.updateContainer(null,r.current,null),n.current.destroy())}),[]),Nt.useLayoutEffect(()=>{l(n.current),wve(n.current,s,a),C7.updateContainer(Nt.createElement(i,{},s.children),r.current,null)}),Nt.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})},Jvs="Layer",RS="Group",O_="Rect",DP="Image",II="Text",vgn="Transformer",C7=tvs($vs);C7.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Nt.version,rendererPackageName:"react-konva"});const e1s=Nt.forwardRef((s,t)=>Nt.createElement(C0t,{},Nt.createElement(Xvs,{...s,forwardedRef:t})));function t1s({imageUrl:s,preset:t,barStyleId:n,overrides:r,maxDisplayWidth:a=720,stageRef:i}){const l=N.useRef(null),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(null),f=(t==null?void 0:t.headshot_url)??"",g=(t==null?void 0:t.brokerage_logo_url)??"";N.useEffect(()=>{if(!s){c(null);return}const K=new window.Image;K.crossOrigin="anonymous",K.onload=()=>c(K),K.onerror=()=>c(null),K.src=s},[s]),N.useEffect(()=>{if(!f){u(null);return}const K=new window.Image;K.crossOrigin="anonymous",K.onload=()=>u(K),K.onerror=()=>u(null),K.src=f},[f]),N.useEffect(()=>{if(!g){p(null);return}const K=new window.Image;K.crossOrigin="anonymous",K.onload=()=>p(K),K.onerror=()=>p(null),K.src=g},[g]);const b=Sgs(n),v=(o==null?void 0:o.naturalWidth)??1080,j=(o==null?void 0:o.naturalHeight)??1080,_=N.useMemo(()=>Math.min(1,a/v),[v,a]),S=v*_,A=j*_,T=(r==null?void 0:r.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",D=(r==null?void 0:r.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",L=(r==null?void 0:r.display_name)??(t==null?void 0:t.display_name)??"",M=(r==null?void 0:r.phone)??(t==null?void 0:t.phone)??"",F=(r==null?void 0:r.email)??(t==null?void 0:t.email)??"",z=(r==null?void 0:r.tagline)??(t==null?void 0:t.tagline)??"",V=new Set((r==null?void 0:r.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),W=K=>b.fields.includes(K)&&!V.has(K);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(e1s,{ref:K=>{l.current=K,i&&(i.current=K)},width:S,height:A,scaleX:_,scaleY:_,children:e.jsxs(Jvs,{children:[o&&e.jsx(DP,{image:o,width:v,height:j,listening:!1}),!o&&e.jsx(O_,{x:0,y:0,width:v,height:j,fill:"#e2e8f0"}),e.jsx(s1s,{style:b,canvasW:v,canvasH:j,brandColor:T,accentColor:D,name:L,phone:M,email:F,tagline:z,headshot:d,logo:h,hidden:V,has:W})]})})})}function s1s({style:s,canvasW:t,canvasH:n,brandColor:r,accentColor:a,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h}){const p=n*s.heightRatio,f=p*.18,g=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":Cgs(r),b=g==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const v=s.position==="bottom"?n-p:0;return e.jsxs(RS,{children:[e.jsx(O_,{x:0,y:v,width:t,height:p,fill:r}),e.jsx(O_,{x:0,y:s.position==="bottom"?v:p-4,width:t,height:4,fill:a}),e.jsx(GH,{x:f,y:v+f,width:t-f*2,height:p-f*2,textColor:g,subTextColor:b,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="corner-br"){const v=t*.42,j=p,_=t-v-n*.025,S=n-j-n*.025;return e.jsxs(RS,{children:[e.jsx(O_,{x:_,y:S,width:v,height:j,fill:r,cornerRadius:j*.12,opacity:.92}),e.jsx(O_,{x:_,y:S+j-4,width:v,height:4,fill:a,cornerRadius:2}),e.jsx(GH,{x:_+f,y:S+f,width:v-f*2,height:j-f*2,textColor:g,subTextColor:b,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="side-right"){const v=Math.max(t*.22,Math.min(t*.3,260)),j=v*.12;return e.jsxs(RS,{children:[e.jsx(O_,{x:t-v,y:0,width:v,height:n,fill:r}),e.jsx(O_,{x:t-v,y:0,width:4,height:n,fill:a}),e.jsx(GH,{x:t-v+j,y:n*.08,width:v-j*2,height:n*.84,textColor:g,subTextColor:b,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot,vertical:!0,railWidth:v})]})}return s.position==="letterbox"?e.jsxs(RS,{children:[e.jsx(O_,{x:0,y:0,width:t,height:p,fill:"#0a0a0a"}),e.jsx(O_,{x:0,y:n-p,width:t,height:p,fill:"#0a0a0a"}),e.jsx(O_,{x:0,y:n-p,width:t,height:3,fill:a}),e.jsx(GH,{x:f,y:n-p+f,width:t-f*2,height:p-f*2,textColor:"#ffffff",subTextColor:"rgba(255,255,255,0.75)",name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot}),u&&h("logo")&&e.jsx(DP,{image:u,x:t-f-p*.7,y:f,height:p-f*2,width:p*.7})]}):null}function GH({x:s,y:t,width:n,height:r,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:u,logo:h,has:p,circular:f,vertical:g,railWidth:b}){if(g){const K=b??n,Y=Math.min(n,K*.7),ee=Math.max(14,K*.13),ne=Math.max(11,K*.085),oe=K*.08,pe=K*.35;let ce=t;const de=ce;ce+=Y+oe;const ie=ce,ye=l.length>12?2:1;ce+=ee*1.15*ye+oe*.5;const _e=ce;p("phone")&&o&&(ce+=ne*1.3+oe*.4);const Me=ce;p("email")&&c&&(ce+=ne*1.3+oe*.4);const Te=ce+oe*.5;return e.jsxs(RS,{children:[p("headshot")&&u&&e.jsx(RS,{clipFunc:f?Ce=>{Ce.beginPath(),Ce.arc(s+n/2,de+Y/2,Y/2,0,Math.PI*2),Ce.closePath()}:void 0,children:e.jsx(DP,{image:u,x:s+(n-Y)/2,y:de,width:Y,height:Y})}),p("name")&&l&&e.jsx(II,{text:l,x:s,y:ie,width:n,align:"center",fontSize:ee,fontStyle:"bold",fill:a}),p("phone")&&o&&e.jsx(II,{text:o,x:s,y:_e,width:n,align:"center",fontSize:ne,fill:i}),p("email")&&c&&e.jsx(II,{text:c,x:s,y:Me,width:n,align:"center",fontSize:ne,fill:i,ellipsis:!0,wrap:"none"}),p("logo")&&h&&e.jsx(DP,{image:h,x:s,y:Te,width:n,height:pe})]})}const v=r*.95,j=u&&p("headshot")?s+v+r*.18:s,_=n-(j-s)-(h&&p("logo")?r*1.6:0),S=Math.max(20,r*.34),A=Math.max(13,r*.22),T=r*.06,D=p("tagline")&&d?1:0,L=p("phone")&&o?1:0,M=p("email")&&c?1:0,F=1+D+(L||M?1:0),z=F*S+(F-1)*T;let W=t+(r-z)/2;return e.jsxs(RS,{children:[p("headshot")&&u&&e.jsx(RS,{clipFunc:f?K=>{K.beginPath(),K.arc(s+v/2,t+v/2,v/2,0,Math.PI*2),K.closePath()}:void 0,children:e.jsx(DP,{image:u,x:s,y:t+(r-v)/2,width:v,height:v})}),p("name")&&l&&e.jsx(II,{text:l,x:j,y:W,width:_,fontSize:S,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(W+=S+T,null),p("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(II,{text:d,x:j,y:W,width:_,fontSize:A*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(W+=A*1.1+T,null)]}),L||M?e.jsx(II,{text:[o,c].filter(Boolean).join(" • "),x:j,y:W,width:_,fontSize:A,fill:i,ellipsis:!0,wrap:"none"}):null,p("logo")&&h&&e.jsx(DP,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function n1s(){const{data:s}=kU(),t=(s==null?void 0:s.find(W=>W.is_default))??(s==null?void 0:s[0])??null,[n,r]=N.useState(void 0),a=(s==null?void 0:s.find(W=>W.id===n))??t,[i,l]=N.useState([]),[o,c]=N.useState(0),[d,u]=N.useState("minimal-stripe"),[h,p]=N.useState({}),[f,g]=N.useState(!1),b=N.useRef(null),[v,j]=N.useState(780),_=N.useRef(null),S=W=>{if(_.current&&(_.current.disconnect(),_.current=null),!W)return;const K=()=>{const ee=W.clientWidth;ee>0&&j(Math.min(780,ee-16))};K();const Y=new ResizeObserver(K);Y.observe(W),_.current=Y};N.useEffect(()=>()=>{var W;(W=_.current)==null||W.disconnect()},[]);const A=N.useRef(null),T=W=>{if(!W)return;const K=[];Array.from(W).forEach(Y=>{Y.type.startsWith("image/")&&K.push({id:crypto.randomUUID(),url:URL.createObjectURL(Y),file:Y,name:Y.name})}),l(Y=>[...Y,...K])},D=W=>{l(K=>{const Y=K.find(ee=>ee.id===W);return Y&&URL.revokeObjectURL(Y.url),K.filter(ee=>ee.id!==W)}),c(0)},L=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),M=W=>{var pe;const[K,Y]=W.split(","),ee=((pe=K.match(/:(.*?);/))==null?void 0:pe[1])??"image/jpeg",ne=atob(Y),oe=new Uint8Array(ne.length);for(let ce=0;ce{var W;if(A.current){g(!0);try{const K=A.current,Y=K.toDataURL({pixelRatio:1/(K.scaleX()||1),mimeType:"image/jpeg",quality:.95}),ne=`${((W=i[o])==null?void 0:W.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,oe=M(Y),pe=URL.createObjectURL(oe);if(L)window.open(pe,"_blank")||(window.location.href=pe),ae.success('Long-press the image and tap "Save to Photos"');else{const ce=document.createElement("a");ce.href=pe,ce.download=ne,document.body.appendChild(ce),ce.click(),ce.remove(),ae.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(pe),6e4)}catch(K){ae.error(K.message||"Export failed")}finally{g(!1)}}},z=async()=>{if(i.length){g(!0);try{const W=new Bgt,K=i.length,Y=o;for(let oe=0;oesetTimeout(ye,600)),!A.current)continue;const pe=A.current,de=pe.toDataURL({pixelRatio:1/(pe.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],ie=i[oe].name.replace(/\.[^.]+$/,"")||`image-${oe+1}`;W.file(`${ie}-branded.jpg`,de,{base64:!0})}c(Y);const ee=await W.generateAsync({type:"blob"}),ne=document.createElement("a");ne.href=URL.createObjectURL(ee),ne.download=`branded-images-${Date.now()}.zip`,ne.click(),URL.revokeObjectURL(ne.href),ae.success(`${K} images exported`)}catch(W){ae.error(W.message||"Batch export failed")}finally{g(!1)}}},V=i[o];return e.jsx(Cs,{title:"Branding Bar Studio",children:e.jsxs("div",{className:"container max-w-7xl py-4 md:py-6 space-y-4 px-3 md:px-6",children:[e.jsx(Yo,{children:e.jsx("title",{children:"Branding Bar Studio | Marketing Studio"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Ln,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Wr,{className:"h-3 w-3"})," Marketing Studio"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Branding Bar Studio"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Drop in any image, get a branded export. No AI credits used."})]}),e.jsx(B,{variant:"outline",asChild:!0,className:"w-full sm:w-auto",children:e.jsxs(Ln,{to:"/marketing-studio/brand-kit",children:[e.jsx(xl,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(fe,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Ae,{className:"py-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Create your brand kit first"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We'll pre-fill it from your profile so you can be exporting in seconds."})]}),e.jsx(B,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(Ln,{to:"/marketing-studio/brand-kit",children:"Set up brand"})})]})}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_360px]",children:[e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsx(fe,{className:"overflow-hidden",children:e.jsxs(Ae,{className:"p-4",children:[V?e.jsx("div",{ref:S,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(t1s,{imageUrl:V.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:v,stageRef:A})}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-12 text-center space-y-3 cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>{var W;return(W=b.current)==null?void 0:W.click()},onDragOver:W=>W.preventDefault(),onDrop:W=>{W.preventDefault(),T(W.dataTransfer.files)},children:[e.jsx(nl,{className:"h-12 w-12 mx-auto text-muted-foreground/60"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Drop images here or click to browse"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add up to 50 photos at once. We'll batch-brand them all."})]}),e.jsxs(B,{type:"button",children:[e.jsx(Sa,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:b,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:W=>T(W.target.files)})]})}),i.length>0&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ae,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((W,K)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(K),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${K===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:W.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>D(W.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(Fn,{className:"h-3 w-3"})})]},W.id)),e.jsx("button",{onClick:()=>{var W;return(W=b.current)==null?void 0:W.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(As,{className:"h-5 w-5 text-muted-foreground"})})]})})}),i.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[e.jsx(B,{variant:"outline",onClick:()=>{i.forEach(W=>URL.revokeObjectURL(W.url)),l([])},children:"Clear all"}),e.jsxs(B,{onClick:F,disabled:f||!V,children:[f?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Da,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs(B,{onClick:z,disabled:f,children:[f?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Da,{className:"h-4 w-4 mr-1"}),"Download all (",i.length,") as ZIP"]})]})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-base",children:"Brand preset"})}),e.jsx(Ae,{children:e.jsxs(us,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Choose preset"})}),e.jsx(ds,{children:s==null?void 0:s.map(W=>e.jsxs(Ze,{value:W.id,children:[W.name," ",W.is_default?"(default)":""]},W.id))})]})})]}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-base",children:"Bar style"})}),e.jsx(Ae,{children:e.jsx(Tgs,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-base",children:"Tweak this design"})}),e.jsx(Ae,{children:e.jsxs($r,{defaultValue:"text",children:[e.jsxs(Ur,{className:"grid grid-cols-2 w-full",children:[e.jsx(Zt,{value:"text",children:"Text"}),e.jsx(Zt,{value:"colors",children:"Colors"})]}),e.jsxs(ls,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Display name"}),e.jsx(ge,{value:h.display_name??(a==null?void 0:a.display_name)??"",onChange:W=>p({...h,display_name:W.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ge,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:W=>p({...h,phone:W.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ge,{value:h.email??(a==null?void 0:a.email)??"",onChange:W=>p({...h,email:W.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Tagline"}),e.jsx(ge,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:W=>p({...h,tagline:W.target.value})})]})]}),e.jsxs(ls,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(se,{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:W=>p({...h,brand_color:W.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(ge,{value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:W=>p({...h,brand_color:W.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{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:W=>p({...h,accent_color:W.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(ge,{value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:W=>p({...h,accent_color:W.target.value})})]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>p({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function r1s(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 a1s=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function _4(s){const t=[];for(let n=0,r=s.length;nM0||s.height>M0)&&(s.width>M0&&s.height>M0?s.width>s.height?(s.height*=M0/s.width,s.width=M0):(s.width*=M0/s.height,s.height=M0):s.width>M0?(s.height*=M0/s.width,s.width=M0):(s.width*=M0/s.height,s.height=M0))}function Exe(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 d1s(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function u1s(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),d1s(a)}const Zg=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||Zg(n,t)};function h1s(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function m1s(s,t){return T0t(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function p1s(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?h1s(n):m1s(n,r);return document.createTextNode(`${a}{${i}}`)}function PHe(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=a1s();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(p1s(l,n,a,r)),t.appendChild(o)}function f1s(s,t,n){PHe(s,t,":before",n),PHe(s,t,":after",n)}const LHe="application/font-woff",DHe="image/jpeg",x1s={woff:LHe,woff2:LHe,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:DHe,jpeg:DHe,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function g1s(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function UIe(s){const t=g1s(s).toLowerCase();return x1s[t]||""}function y1s(s){return s.split(/,/)[1]}function w3e(s){return s.search(/^(data:)/)!==-1}function v1s(s,t){return`data:${t};base64,${s}`}async function A0t(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 F2e={};function b1s(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 qIe(s,t,n){const r=b1s(s,t,n.includeQueryParams);if(F2e[r]!=null)return F2e[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await A0t(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),y1s(o)));a=v1s(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 F2e[r]=a,a}async function _1s(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):Exe(t)}async function w1s(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 Exe(o)}const n=s.poster,r=UIe(n),a=await qIe(n,r,t);return Exe(a)}async function j1s(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await jve(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function N1s(s,t){return Zg(s,HTMLCanvasElement)?_1s(s):Zg(s,HTMLVideoElement)?w1s(s,t):Zg(s,HTMLIFrameElement)?j1s(s,t):s.cloneNode(M0t(s))}const k1s=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",M0t=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function S1s(s,t,n){var r,a;if(M0t(t))return t;let i=[];return k1s(s)&&s.assignedNodes?i=_4(s.assignedNodes()):Zg(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=_4(s.contentDocument.body.childNodes):i=_4(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||Zg(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>jve(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function C1s(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):T0t(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`),Zg(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 T1s(s,t){Zg(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),Zg(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function E1s(s,t){if(Zg(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function A1s(s,t,n){return Zg(t,Element)&&(C1s(s,t,n),f1s(s,t,n),T1s(s,t),E1s(s,t)),t}async function M1s(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;iN1s(r,t)).then(r=>S1s(s,r,t)).then(r=>A1s(s,r,t)).then(r=>M1s(r,t))}const I0t=/url\((['"]?)([^'"]+?)\1\)/g,I1s=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,P1s=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function L1s(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function D1s(s){const t=[];return s.replace(I0t,(n,r,a)=>(t.push(a),n)),t.filter(n=>!w3e(n))}async function R1s(s,t,n,r,a){try{const i=n?r1s(t,n):t,l=UIe(t);let o;return a||(o=await qIe(i,l,r)),s.replace(L1s(t),`$1${o}$3`)}catch{}return s}function O1s(s,{preferredFontFormat:t}){return t?s.replace(P1s,n=>{for(;;){const[r,,a]=I1s.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function P0t(s){return s.search(I0t)!==-1}async function L0t(s,t,n){if(!P0t(s))return s;const r=O1s(s,n);return D1s(r).reduce((i,l)=>i.then(o=>R1s(o,l,t,n)),Promise.resolve(r))}async function LI(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await L0t(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function F1s(s,t){await LI("background",s,t)||await LI("background-image",s,t),await LI("mask",s,t)||await LI("-webkit-mask",s,t)||await LI("mask-image",s,t)||await LI("-webkit-mask-image",s,t)}async function z1s(s,t){const n=Zg(s,HTMLImageElement);if(!(n&&!w3e(s.src))&&!(Zg(s,SVGImageElement)&&!w3e(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await qIe(r,UIe(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 B1s(s,t){const r=_4(s.childNodes).map(a=>D0t(a,t));await Promise.all(r).then(()=>s)}async function D0t(s,t){Zg(s,Element)&&(await F1s(s,t),await z1s(s,t),await B1s(s,t))}function $1s(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 RHe={};async function OHe(s){let t=RHe[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},RHe[s]=t,t}async function FHe(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),A0t(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function zHe(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 U1s(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{_4(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=OHe(c).then(u=>FHe(u,t)).then(u=>zHe(u).forEach(h=>{try{a.insertRule(h,h.startsWith("@import")?o+=1:a.cssRules.length)}catch(p){console.error("Error inserting rule from remote css",{rule:h,error:p})}})).catch(u=>{console.error("Error loading remote css",u.toString())});r.push(d)}})}catch(i){const l=s.find(o=>o.href==null)||document.styleSheets[0];a.href!=null&&r.push(OHe(a.href).then(o=>FHe(o,t)).then(o=>zHe(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{_4(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function q1s(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>P0t(t.style.getPropertyValue("src")))}async function V1s(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=_4(s.ownerDocument.styleSheets),r=await U1s(n,t);return q1s(r)}function R0t(s){return s.trim().replace(/["']/g,"")}function H1s(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(R0t(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function G1s(s,t){const n=await V1s(s,t),r=H1s(s);return(await Promise.all(n.filter(i=>r.has(R0t(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return L0t(i.cssText,l,t)}))).join(` `)}async function W1s(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await G1s(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 K1s(s,t={}){const{width:n,height:r}=E0t(s,t),a=await jve(s,t,!0);return await W1s(a,t),await D0t(a,t),$1s(a,t),await u1s(a,n,r)}async function Y1s(s,t={}){const{width:n,height:r}=E0t(s,t),a=await K1s(s,t),i=await Exe(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||l1s(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||c1s(l),l.style.width=`${d}`,l.style.height=`${u}`,t.backgroundColor&&(o.fillStyle=t.backgroundColor,o.fillRect(0,0,l.width,l.height)),o.drawImage(i,0,0,l.width,l.height),l}async function VIe(s,t={}){return(await Y1s(s,t)).toDataURL()}const F8=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),Nve={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},OS={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},Z1s=({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})]})]}),HIe=Nt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=Nve[t],u=[s.bedrooms?`${s.bedrooms} Bed`:null,s.bathrooms?`${s.bathrooms} Bath`:null,s.sqft?`${s.sqft.toLocaleString()} Sq Ft`:null].filter(Boolean).join(" • ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"linear-gradient(180deg, rgba(10,10,30,0.3) 0%, rgba(10,10,30,0.85) 100%)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",justifyContent:"space-between",padding:l.w*.06},children:[e.jsx("div",{children:e.jsx("div",{style:{display:"inline-block",background:"linear-gradient(135deg, #C9A84C, #E8D48B)",color:"#1A1A2E",padding:`${l.w*.012}px ${l.w*.035}px`,fontSize:l.w*.032,fontWeight:700,letterSpacing:"0.25em",textTransform:"uppercase"},children:d})}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:l.w*.07,fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,textShadow:"0 2px 12px rgba(0,0,0,0.5)"},children:F8(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",F8(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(Z1s,{branding:r,dim:l})]})]})]})});HIe.displayName="LuxuryDarkTemplate";const Q1s=({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})]})]}),GIe=Nt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var f;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(f=s.photos)==null?void 0:f[a],d=Nve[t],u=n==="instagram-story",h=n==="facebook-post",p=t==="just-sold"?"#7C3AED":t==="open-house"?"#2563EB":t==="price-drop"?"#DC2626":"#059669";return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Helvetica Neue', Arial, sans-serif",color:"#1A1A1A",background:"#FFFFFF",display:"flex",flexDirection:h?"row":"column"},children:[e.jsxs("div",{style:{width:h?"55%":"100%",height:h?"100%":u?"50%":"52%",position:"relative",overflow:"hidden",flexShrink:0},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",top:l.w*.04,left:0,background:p,color:"#FFFFFF",padding:`${l.w*.012}px ${l.w*.04}px`,fontSize:l.w*.026,fontWeight:800,letterSpacing:"0.15em"},children:d})]}),e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05},children:[e.jsx("div",{style:{fontSize:l.w*(h?.055:.065),fontWeight:800,lineHeight:1.1,color:p,marginBottom:l.w*.012},children:F8(s.price)}),e.jsx("div",{style:{fontSize:l.w*.026,fontWeight:600,marginBottom:l.w*.006},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.02,color:"#6B7280",marginBottom:l.w*.02},children:[s.city,", ",s.state," ",s.zip]}),e.jsxs("div",{style:{display:"flex",gap:l.w*.03,marginBottom:l.w*.02},children:[s.bedrooms>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.bedrooms}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Beds"})]}),s.bathrooms>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.bathrooms}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Baths"})]}),s.sqft>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.sqft.toLocaleString()}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Sq Ft"})]})]}),t==="open-house"&&e.jsx("div",{style:{background:`${p}10`,border:`2px solid ${p}`,borderRadius:l.w*.01,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,color:p,display:"inline-block",marginBottom:l.w*.015},children:"SAT & SUN • 1–4 PM"}),e.jsx(Q1s,{branding:r,dim:l,accentColor:p})]})]})});GIe.displayName="ModernCleanTemplate";const X1s=({branding:s,dim:t})=>!(s!=null&&s.enabled)||!s.agentName?null:e.jsxs("div",{style:{marginTop:t.w*.025,display:"flex",alignItems:"center",gap:t.w*.02},children:[s.agentPhotoUrl&&e.jsx("img",{src:s.agentPhotoUrl,alt:"",crossOrigin:"anonymous",style:{width:t.w*.12,height:t.w*.12,borderRadius:"50%",objectFit:"cover",border:"3px solid rgba(255,255,255,0.5)"}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:t.w*.035,fontWeight:900},children:s.agentName}),s.brokerage&&e.jsx("div",{style:{fontSize:t.w*.024,opacity:.8,marginTop:t.w*.004,fontFamily:"'Helvetica Neue', sans-serif",fontWeight:400},children:s.brokerage})]})]}),WIe=Nt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var p;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(p=s.photos)==null?void 0:p[a],d=Nve[t],u={"just-listed":"linear-gradient(135deg, #059669, #10B981)","just-sold":"linear-gradient(135deg, #7C3AED, #A855F7)","open-house":"linear-gradient(135deg, #2563EB, #3B82F6)","price-drop":"linear-gradient(135deg, #DC2626, #F43F5E)"},h=[s.bedrooms?`${s.bedrooms} BD`:null,s.bathrooms?`${s.bathrooms} BA`:null,s.sqft?`${s.sqft.toLocaleString()} SF`:null].filter(Boolean).join(" | ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Arial Black', 'Helvetica Neue', sans-serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.4)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",padding:l.w*.05},children:[e.jsx("div",{style:{background:u[t],padding:`${l.w*.025}px ${l.w*.04}px`,fontSize:l.w*.055,fontWeight:900,letterSpacing:"0.08em",alignSelf:"flex-start",borderRadius:l.w*.01,boxShadow:"0 8px 32px rgba(0,0,0,0.3)",transform:"rotate(-2deg)",marginBottom:l.w*.03},children:d}),e.jsx("div",{style:{flex:1}}),e.jsxs("div",{style:{background:"rgba(0,0,0,0.65)",backdropFilter:"blur(10px)",borderRadius:l.w*.015,padding:l.w*.04},children:[e.jsx("div",{style:{fontSize:l.w*.08,fontWeight:900,lineHeight:1,marginBottom:l.w*.01},children:F8(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(X1s,{branding:r,dim:l})]})]})]})});WIe.displayName="BoldColorfulTemplate";const J1s=({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})]})]}),KIe=Nt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=Nve[t],u=n==="instagram-story";return e.jsx("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#1A1A1A",background:"#F5F0EB"},children:e.jsxs("div",{style:{display:"flex",flexDirection:u?"column":"row",height:"100%"},children:[e.jsxs("div",{style:{width:u?"100%":"42%",height:u?"40%":"100%",display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05,order:u?2:1},children:[e.jsx("div",{style:{fontSize:l.w*.016,letterSpacing:"0.3em",textTransform:"uppercase",color:"#8B7355",borderBottom:"2px solid #8B7355",paddingBottom:l.w*.01,marginBottom:l.w*.025,display:"inline-block",alignSelf:"flex-start"},children:d}),e.jsx("div",{style:{fontSize:l.w*(u?.06:.055),fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,fontStyle:"italic"},children:F8(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",F8(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(J1s,{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"}})]})]})})});KIe.displayName="EditorialTemplate";const ebs=[{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:"📉"}],BHe=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(mu,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(mu,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(Oh,{className:"h-4 w-4"})}],tbs=[{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:"📰"}],$He={"luxury-dark":HIe,"modern-clean":GIe,"bold-colorful":WIe,editorial:KIe},z2e=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function sbs(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;oDe.is_default))??(s==null?void 0:s[0])??null,[n,r]=N.useState(void 0),a=(s==null?void 0:s.find(De=>De.id===n))??t,i=fa(),[l,o]=N.useState("mine"),[c,d]=N.useState(""),[u,h]=N.useState("address"),[p,f]=N.useState(!1),[g,b]=N.useState([]),[v,j]=N.useState(null),[_,S]=N.useState(0),[A,T]=N.useState("just-listed"),[D,L]=N.useState(["instagram-square"]),[M,F]=N.useState("luxury-dark"),[z,V]=N.useState(!0),[W,K]=N.useState(!1),[Y,ee]=N.useState([]),[ne,oe]=N.useState("search"),pe=N.useRef({}),{data:ce=[],isLoading:de}=lt({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:De,error:Ie}=await q.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Ie)throw Ie;return(De||[]).map(Fe=>{const qe=(Fe.listing_photos||[]).slice().sort((Je,we)=>(we.is_primary?1:0)-(Je.is_primary?1:0)||(Je.sort_order??0)-(we.sort_order??0)).map(Je=>Je.photo_url).filter(Boolean),ve=String(Fe.status||"");return{mlsNumber:Fe.id,address:Fe.property_address||"",city:Fe.city||"",state:Fe.state||"",zip:"",price:Number(Fe.price||0),status:ve,bedrooms:Number(Fe.bedrooms||0),bathrooms:Number(Fe.bathrooms||0),sqft:Number(Fe.square_footage||0),lotSize:"",yearBuilt:Fe.year_built??null,propertyType:Fe.property_type||"",description:Fe.description||"",photos:qe,listDate:Fe.created_at,soldDate:ve.toLowerCase().includes("sold")?Fe.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),ie=N.useMemo(()=>!z||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[z,a]),ye=async()=>{if(c.trim()){f(!0),b([]);try{const{data:De,error:Ie}=await q.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Ie)throw Ie;if(De!=null&&De.error)throw new Error(De.error);b((De==null?void 0:De.listings)||[]),((De==null?void 0:De.listings)||[]).length===0&&ae.info("No listings found. Try a different search.")}catch(De){ae.error(De.message||"Search failed")}finally{f(!1)}}},_e=De=>{var Ie;j(De),S(0),oe("customize"),De.soldDate||(Ie=De.status)!=null&&Ie.toLowerCase().includes("sold")?T("just-sold"):T("just-listed")},Me=De=>L(Ie=>Ie.includes(De)?Ie.filter(Fe=>Fe!==De):[...Ie,De]),Te=v?{listing:v,postType:A,format:"instagram-square",branding:ie,selectedPhotoIndex:_}:null,Ce=N.useCallback(async()=>{if(!(!v||D.length===0)){K(!0),ee([]),oe("generate");try{await new Promise(Ie=>setTimeout(Ie,600));const De=[];for(const Ie of D){const Fe=`${M}-${Ie}`,qe=pe.current[Fe];if(!qe)continue;const ve=OS[Ie],Je=await VIe(qe,{width:ve.width,height:ve.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});De.push({format:Ie,url:Je})}ee(De),ae.success(`Generated ${De.length} design${De.length>1?"s":""}!`)}catch(De){ae.error(De.message||"Generation failed")}finally{K(!1)}}},[v,D,M]),Ee=(De,Ie)=>{const Fe=`${((v==null?void 0:v.address)||"listing").replace(/\s+/g,"-")}-${A}-${Ie}.png`;try{const qe=sbs(De),ve=URL.createObjectURL(qe);if(nbs)window.open(ve,"_blank"),ae.message("Long-press the image to save to Photos");else{const Je=document.createElement("a");Je.href=ve,Je.download=Fe,document.body.appendChild(Je),Je.click(),document.body.removeChild(Je)}setTimeout(()=>URL.revokeObjectURL(ve),6e4)}catch{const qe=document.createElement("a");qe.href=De,qe.download=Fe,qe.click()}};return N.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(Cs,{title:"Listing Templates",children:e.jsxs("div",{className:"container max-w-6xl py-4 md:py-8 px-3 md:px-6 space-y-5",children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"Listing Templates | Marketing Studio"}),e.jsx("meta",{name:"description",content:"Just Listed, Just Sold, Open House and Price Drop templates pulled directly from your MLS."})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(Ln,{to:"/marketing-studio",children:[e.jsx(Wr,{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(ze,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," Listing Templates"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight",children:"Just Listed. Just Stunning."}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl mt-1",children:"Search any MLS listing and get pixel-perfect, on-brand graphics for Instagram, Stories and Facebook in one click."})]}),s&&s.length>0&&e.jsxs("div",{className:"min-w-0 sm:min-w-[220px]",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Default"})}),e.jsx(ds,{children:s.map(De=>e.jsxs(Ze,{value:De.id,children:[De.name,De.is_default?" (default)":""]},De.id))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs sm:text-sm overflow-x-auto -mx-1 px-1 pb-1",children:[e.jsxs("button",{onClick:()=>oe("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ne==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(_r,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>v&&oe("customize"),disabled:!v,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ne==="customize"?"bg-primary text-primary-foreground":v?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(un,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ne==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Da,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),ne==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx($r,{value:l,onValueChange:De=>o(De),children:e.jsxs(Ur,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(Zt,{value:"mine",children:[e.jsx(zr,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(_r,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:de?e.jsx(fe,{children:e.jsx(Ae,{className:"py-12 flex items-center justify-center",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):ce.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-10 text-center space-y-2",children:[e.jsx(zr,{className:"h-10 w-10 mx-auto text-muted-foreground/40"}),e.jsx("p",{className:"text-sm font-medium",children:"No listings yet"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-sm mx-auto",children:"Add a listing to your Listing Exchange first, and it'll show up here ready to brand."}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(Ln,{to:"/mission-control/listings",children:"Go to Listings"})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[ce.length," listing",ce.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:ce.map((De,Ie)=>{var Fe;return e.jsx(fe,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>_e(De),children:e.jsx(Ae,{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:(Fe=De.photos)!=null&&Fe[0]?e.jsx("img",{src:De.photos[0],alt:De.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(zr,{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:De.price>0?z2e(De.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:De.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[De.city,De.state?`, ${De.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[De.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(G2,{className:"h-3 w-3"})," ",De.bedrooms]}),De.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Tp,{className:"h-3 w-3"})," ",De.bathrooms]}),De.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(OA,{className:"h-3 w-3"})," ",De.sqft.toLocaleString()]})]}),De.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(ze,{variant:"outline",className:"text-[10px]",children:De.status})})]})]})})},De.mlsNumber||Ie)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(_r,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(Hn,{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(Ae,{className:"space-y-3",children:[e.jsx($r,{value:u,onValueChange:De=>h(De),children:e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"address",children:[e.jsx(Ca,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(mh,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(ge,{value:c,onChange:De=>d(De.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:De=>De.key==="Enter"&&ye()}),e.jsxs(B,{onClick:ye,disabled:p||!c.trim(),className:"sm:w-auto w-full",children:[p?e.jsx(ss,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(_r,{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((De,Ie)=>{var Fe;return e.jsx(fe,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>_e(De),children:e.jsx(Ae,{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:(Fe=De.photos)!=null&&Fe[0]?e.jsx("img",{src:De.photos[0],alt:De.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(zr,{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:z2e(De.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:De.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[De.city,", ",De.state," ",De.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[De.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(G2,{className:"h-3 w-3"})," ",De.bedrooms]}),De.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Tp,{className:"h-3 w-3"})," ",De.bathrooms]}),De.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(OA,{className:"h-3 w-3"})," ",De.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[De.mlsNumber&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:De.mlsNumber}),De.status&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:De.status})]})]})]})})},De.mlsNumber||Ie)})})]})]})]}),ne==="customize"&&v&&Te&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(fe,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(Pt,{className:"text-base",children:"Selected listing"})}),e.jsxs(Ae,{className:"space-y-3",children:[v.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:v.photos[_],alt:"",className:"w-full h-full object-cover"})}),v.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>S(De=>Math.max(0,De-1)),disabled:_===0,children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[_+1," of ",v.photos.length]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>S(De=>Math.min(v.photos.length-1,De+1)),disabled:_===v.photos.length-1,children:e.jsx(ga,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:z2e(v.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.city,", ",v.state," ",v.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[v.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),v.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),v.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{oe("search"),j(null)},children:[e.jsx(Fh,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(fe,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2 text-base",children:[e.jsx(un,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(Hn,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Ae,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(xl,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:tbs.map(De=>e.jsxs("button",{onClick:()=>F(De.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${M===De.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:De.preview}),e.jsx("span",{className:"text-sm font-medium",children:De.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:De.description})]},De.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:ebs.map(De=>e.jsxs("button",{onClick:()=>T(De.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${A===De.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:De.icon})," ",e.jsx("span",{className:"truncate",children:De.label})]},De.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:BHe.map(De=>e.jsxs("button",{onClick:()=>Me(De.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${D.includes(De.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[De.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:De.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:De.dimensions})]})]},De.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Xi,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(vn,{checked:z,onCheckedChange:V})]}),z&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(Ln,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),z&&a&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[a.headshot_url&&e.jsx("img",{src:a.headshot_url,alt:"",className:"w-10 h-10 rounded-full object-cover border"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:a.display_name||"Unnamed agent"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.tagline||a.email||""})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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*(OS[D[0]||"instagram-square"].height/OS[D[0]||"instagram-square"].width)},children:(()=>{const De=$He[M],Ie=D[0]||"instagram-square";return e.jsx(De,{...Te,format:Ie})})()})})]}),e.jsx(B,{onClick:Ce,disabled:D.length===0||W,size:"lg",className:"w-full gap-2",children:W?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-5 w-5"})," Generate ",D.length," design",D.length>1?"s":""]})})]})]})]}),ne==="generate"&&e.jsxs("div",{className:"space-y-4",children:[W&&e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(ss,{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."})]})}),Y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Your designs"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>oe("customize"),children:[e.jsx(Fh,{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:Y.map((De,Ie)=>{const Fe=BHe.find(qe=>qe.value===De.format);return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:De.url,alt:"",className:"w-full rounded"})}),e.jsxs(Ae,{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:[Fe==null?void 0:Fe.icon,e.jsx("span",{className:"text-sm font-medium",children:Fe==null?void 0:Fe.label})]}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Fe==null?void 0:Fe.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>Ee(De.url,De.format),children:[e.jsx(Da,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ie)})})]})]}),ne==="generate"&&v&&Te&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:D.map(De=>{const Ie=$He[M],Fe=OS[De];return e.jsx("div",{style:{width:Fe.width,height:Fe.height},children:e.jsx(Ie,{ref:qe=>{pe.current[`${M}-${De}`]=qe},...Te,format:De})},`${M}-${De}`)})})]})})}var O0t="Toggle",YIe=N.forwardRef((s,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:a,...i}=s,[l,o]=mm({prop:n,onChange:a,defaultProp:r??!1,caller:O0t});return e.jsx(sa.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:wr(s.onClick,()=>{s.disabled||o(!l)})})});YIe.displayName=O0t;var F0t=YIe,dC="ToggleGroup",[z0t,bgn]=gu(dC,[K4]),B0t=K4(),ZIe=Nt.forwardRef((s,t)=>{const{type:n,...r}=s;if(n==="single"){const a=r;return e.jsx(abs,{...a,ref:t})}if(n==="multiple"){const a=r;return e.jsx(ibs,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${dC}\``)});ZIe.displayName=dC;var[$0t,U0t]=z0t(dC),abs=Nt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=mm({prop:n,defaultProp:r??"",onChange:a,caller:dC});return e.jsx($0t,{scope:s.__scopeToggleGroup,type:"single",value:Nt.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:Nt.useCallback(()=>o(""),[o]),children:e.jsx(q0t,{...i,ref:t})})}),ibs=Nt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=mm({prop:n,defaultProp:r??[],onChange:a,caller:dC}),c=Nt.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Nt.useCallback(u=>o((h=[])=>h.filter(p=>p!==u)),[o]);return e.jsx($0t,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(q0t,{...i,ref:t})})});ZIe.displayName=dC;var[obs,lbs]=z0t(dC),q0t=Nt.forwardRef((s,t)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=B0t(n),u=kN(l),h={role:"group",dir:u,...c};return e.jsx(obs,{scope:n,rovingFocus:a,disabled:r,children:a?e.jsx(Q0e,{asChild:!0,...d,orientation:i,dir:u,loop:o,children:e.jsx(sa.div,{...h,ref:t})}):e.jsx(sa.div,{...h,ref:t})})}),Axe="ToggleGroupItem",V0t=Nt.forwardRef((s,t)=>{const n=U0t(Axe,s.__scopeToggleGroup),r=lbs(Axe,s.__scopeToggleGroup),a=B0t(s.__scopeToggleGroup),i=n.value.includes(s.value),l=r.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=Nt.useRef(null);return r.rovingFocus?e.jsx(X0e,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(UHe,{...o,ref:t})}):e.jsx(UHe,{...o,ref:t})});V0t.displayName=Axe;var UHe=Nt.forwardRef((s,t)=>{const{__scopeToggleGroup:n,value:r,...a}=s,i=U0t(Axe,n),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(YIe,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(r):i.onItemDeactivate(r)}})}),H0t=ZIe,G0t=V0t;const W0t=qM("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"}}),cbs=N.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(F0t,{ref:a,className:Et(W0t({variant:t,size:n,className:s})),...r}));cbs.displayName=F0t.displayName;const K0t=N.createContext({size:"default",variant:"default"}),$L=N.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(H0t,{ref:i,className:Et("flex items-center justify-center gap-1",s),...a,children:e.jsx(K0t.Provider,{value:{variant:t,size:n},children:r})}));$L.displayName=H0t.displayName;const XA=N.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=N.useContext(K0t);return e.jsx(G0t,{ref:i,className:Et(W0t({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});XA.displayName=G0t.displayName;const dbs=[{id:"meet",label:"Meet Your Agent",icon:Xi,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:yb,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:vo,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:bw,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:qd,description:"Personal philosophy, mantra, or rallying call."}],B2e={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"}},ubs=[{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."}],qHe={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 hbs(){const{data:s}=bgs(),{data:t}=kU(),[n,r]=N.useState(void 0),a=N.useMemo(()=>(t==null?void 0:t.find(g=>g.id===n))??s??null,[t,n,s]),[i,l]=N.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...qHe.meet}),o=g=>l(b=>({...b,...g})),c=g=>l(b=>({...b,template:g,...qHe[g]})),d=N.useRef(null),[u,h]=N.useState(!1),p=async()=>{if(!d.current)return;h(!0);const g=d.current,b=g.style.transform;try{g.style.transform="none",await new Promise(_=>requestAnimationFrame(()=>_(null)));const v=await VIe(g,{cacheBust:!0,pixelRatio:2,width:g.offsetWidth,height:g.offsetHeight,backgroundColor:"#ffffff"}),j=document.createElement("a");j.href=v,j.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(j),j.click(),j.remove(),ae.success("Downloaded to your device")}catch(v){ae.error((v==null?void 0:v.message)||"Export failed")}finally{g.style.transform=b,h(!1)}},f=B2e[i.aspect];return e.jsx(Cs,{title:"Personal Branding",children:e.jsxs("div",{className:"container max-w-7xl py-6 md:py-8 space-y-6 px-4",children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"Personal Branding | Marketing Studio"}),e.jsx("meta",{name:"description",content:"Editorial-grade personal branding graphics — meet your agent, testimonials, milestones, and pro tips."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Ln,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Wr,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," New"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Personal Branding"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl",children:"Five editorial-grade templates, four distinct aesthetics. Pick one, drop in your story, export in seconds."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs(Ln,{to:"/marketing-studio/brand-kit",children:[e.jsx(xl,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs(B,{onClick:p,disabled:u,children:[e.jsx(Da,{className:"h-4 w-4 mr-1"})," ",u?"Exporting…":"Download"]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[380px_1fr] gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:dbs.map(g=>{const b=g.icon,v=i.template===g.id;return e.jsxs("button",{onClick:()=>c(g.id),className:`text-left rounded-lg border p-3 transition-all ${v?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[e.jsx(b,{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(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx($L,{type:"single",value:i.style,onValueChange:g=>g&&o({style:g}),className:"grid grid-cols-2 gap-1",children:ubs.map(g=>e.jsx(XA,{value:g.id,className:"text-xs h-9",children:g.label},g.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx($L,{type:"single",value:i.aspect,onValueChange:g=>g&&o({aspect:g}),className:"grid grid-cols-3 gap-1",children:Object.keys(B2e).map(g=>e.jsx(XA,{value:g,className:"text-xs h-9",children:B2e[g].label},g))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(us,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Choose preset"})}),e.jsx(ds,{children:t.map(g=>e.jsx(Ze,{value:g.id,children:g.name},g.id))})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 space-y-3",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Ts,{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(se,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(ge,{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(se,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Ts,{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(se,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Rating"}),e.jsx($L,{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(XA,{value:String(g),className:"text-xs h-9",children:[g,"★"]},g))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(ge,{id:"badge",value:i.badgeText,onChange:g=>o({badgeText:g.target.value})})]})]})})]}),e.jsx(mbs,{aspect:f,canvasRef:d,children:e.jsx(pbs,{form:i,preset:a,width:f.w,height:f.h})})]})]})})}function mbs({aspect:s,canvasRef:t,children:n}){const r=N.useRef(null),[a,i]=N.useState(.5);return N.useEffect(()=>{const l=r.current;if(!l)return;const o=()=>{const d=l.clientWidth-32;i(Math.min(1,d/s.w))};o();const c=new ResizeObserver(o);return c.observe(l),()=>c.disconnect()},[s.w]),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{ref:r,className:"rounded-xl bg-muted/40 p-4 md:p-6 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:s.w*a,height:s.h*a,position:"relative"},className:"shadow-2xl",children:e.jsx("div",{ref:t,style:{width:s.w,height:s.h,transform:`scale(${a})`,transformOrigin:"top left",position:"absolute",top:0,left:0},children:n})})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:["Preview scaled. Export is ",s.w,"×",s.h,"px @ 2× retina."]})]})}function pbs({form:s,preset:t,width:n,height:r}){const a=(t==null?void 0:t.brand_color)||"#0F172A",i=(t==null?void 0:t.accent_color)||"#D4AF37",l=t==null?void 0:t.headshot_url,o=t==null?void 0:t.brokerage_logo_url,c=(t==null?void 0:t.display_name)||"Your Name",d=(t==null?void 0:t.phone)||"",u=(t==null?void 0:t.email)||"",h=(t==null?void 0:t.tagline)||"",p=(t==null?void 0:t.website_url)||"",f={form:s,brandColor:a,accentColor:i,headshot:l,logo:o,name:c,phone:d,email:u,tagline:h,website:p,width:n,height:r};return s.style==="editorial"?e.jsx(fbs,{...f}):s.style==="bold"?e.jsx(xbs,{...f}):s.style==="luxury"?e.jsx(ybs,{...f}):e.jsx(gbs,{...f})}function Y0t({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 kve({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(ua,{size:28,fill:r1.5;return e.jsxs("div",{style:{width:h,height:p,background:"#FAF7F2",position:"relative",fontFamily:"Georgia, serif",color:"#1a1a1a",overflow:"hidden"},children:[e.jsxs("div",{style:{position:"absolute",top:64,left:64,right:64,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:14,letterSpacing:"0.3em",color:n},children:t.badgeText}),e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:12,letterSpacing:"0.2em",color:"#888"},children:["EST. ",new Date().getFullYear()]})]}),e.jsx("div",{style:{position:"absolute",top:100,left:64,right:64,height:1,background:"#1a1a1a",opacity:.15}}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:140,left:64,width:h-128,height:f?700:480,overflow:"hidden",borderRadius:4},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"grayscale(0.15)"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:220,textAlign:t.template==="quote"?"center":"left"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:120,lineHeight:.7,color:r,fontFamily:"Georgia, serif"},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?76:92,lineHeight:1.05,fontWeight:400,margin:0,letterSpacing:"-0.02em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:22,marginTop:16,color:"#555",fontStyle:"italic"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:22,lineHeight:1.5,color:"#333",marginTop:28,maxWidth:820},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(kve,{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(Y0t,{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 xbs(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%, ${vbs(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(kve,{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(Y0t,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function gbs(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(kve,{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 ybs(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(kve,{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 vbs(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 bbs=()=>{const{swagId:s}=_i(),{user:t}=gs(),{toast:n}=Ua(),r=Gt(),{trackEngagement:a}=QD(),[i,l]=N.useState(""),{data:o,isLoading:c}=lt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:j,error:_}=await q.from("social_swag").select("*").eq("id",s).single();if(_)throw _;const{data:S}=await q.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...j,links:S||[]}},enabled:!!s});N.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=lt({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:j,error:_}=await q.from("social_swag_likes").select("*").eq("swag_id",s);if(_)throw _;return j},enabled:!!s}),{data:u=[]}=lt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:j,error:_}=await q.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(_)throw _;const S=[...new Set(j.map(D=>D.user_id))],{data:A}=await q.from("profiles").select("id, name").in("id",S),T=new Map((A==null?void 0:A.map(D=>[D.id,D.name]))||[]);return j.map(D=>({...D,user_name:T.get(D.user_id)||"Unknown User"}))},enabled:!!s}),h=gt({mutationFn:async j=>{const{error:_}=await q.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:j});if(_)throw _},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:j=>{n({title:"Error adding comment",description:j.message,variant:"destructive"})}}),p=gt({mutationFn:async j=>{const{error:_}=await q.from("social_swag_comments").delete().eq("id",j);if(_)throw _},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),f=gt({mutationFn:async()=>{const j=d.find(_=>_.user_id===(t==null?void 0:t.id));if(j){const{error:_}=await q.from("social_swag_likes").delete().eq("id",j.id);if(_)throw _}else{const{error:_}=await q.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(j=>j.user_id===(t==null?void 0:t.id)),b=j=>j.split(" ").map(_=>_[0]).join("").toUpperCase().slice(0,2),v=j=>{j.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx(Cs,{title:"Social Swag",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):o?e.jsx(Cs,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Ln,{to:"/social-swag",children:[e.jsx(Wr,{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(tR,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(B,{variant:g?"default":"outline",className:"gap-2 w-fit",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx(Hm,{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(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(tl,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(j=>e.jsxs(B,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{a("social_swag",o.id,o.title,"click_canva"),window.open(j.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:j.title}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground"})]},j.id))})]})}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ql,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:v,className:"flex gap-2",children:[e.jsx(Ts,{placeholder:"Add a comment...",value:i,onChange:j=>l(j.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||h.isPending,children:e.jsx(cr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:u.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):u.map(j=>e.jsx(fe,{children:e.jsx(Ae,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(aa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(ia,{className:"text-sm",children:b(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:Go(new Date(j.created_at),{addSuffix:!0})}),j.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(j.id),children:e.jsx(bn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.content})]})]})})},j.id))})]})]})}):e.jsx(Cs,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(tl,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Item not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This item may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(Ln,{to:"/social-swag",children:"Back to Social Swag"})})]})})},_bs=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=N.useState(!0),[o,c]=N.useState(!0),[d,u]=N.useState(!0),h=p=>p.split(" ").map(f=>f[0]).join("").toUpperCase().slice(0,2);return e.jsx("aside",{className:"w-64 shrink-0 hidden lg:block relative z-0",children:e.jsx("div",{className:"sticky top-4 space-y-4 max-h-[calc(100vh-8rem)] overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"space-y-2 pr-4",children:[e.jsxs(B,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(JS,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(uy,{open:i,onOpenChange:l,children:[e.jsx(hy,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider",children:"Categories"}),i?e.jsx(io,{className:"h-4 w-4"}):e.jsx(ga,{className:"h-4 w-4"})]})}),e.jsx(my,{className:"space-y-1 pl-2",children:s.map(p=>e.jsxs(B,{variant:n===p.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(p.id),children:[e.jsx("span",{className:"mr-2",children:p.icon||"📂"}),e.jsx("span",{className:"truncate",children:p.name})]},p.id))})]}),t.length>0&&e.jsxs(uy,{open:o,onOpenChange:c,children:[e.jsx(hy,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Rc,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(io,{className:"h-4 w-4"}):e.jsx(ga,{className:"h-4 w-4"})]})}),e.jsx(my,{className:"space-y-1 pl-2",children:t.map(p=>e.jsxs(B,{variant:n===`group:${p.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(`group:${p.id}`),children:[e.jsx("span",{className:"mr-2",children:p.icon||"🔒"}),e.jsx("span",{className:"truncate",children:p.name})]},p.id))})]}),e.jsxs(uy,{open:d,onOpenChange:u,children:[e.jsx(hy,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(_n,{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(io,{className:"h-4 w-4"}):e.jsx(ga,{className:"h-4 w-4"})]})}),e.jsx(my,{className:"pl-2 space-y-1",children:a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2 px-2",children:"No one else online right now"}):a.map(p=>e.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-2 rounded-md hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(aa,{className:"h-7 w-7",children:[e.jsx(ri,{src:p.avatarUrl}),e.jsx(ia,{className:"text-xs",children:h(p.name)})]}),e.jsx(dm,{className:"h-2.5 w-2.5 fill-green-500 text-green-500 absolute -bottom-0.5 -right-0.5"})]}),e.jsx("span",{className:"text-sm truncate",children:p.name})]},p.id))})]})]})})})},wbs=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=N.useState(!1),o=d=>d.split(" ").map(u=>u[0]).join("").toUpperCase().slice(0,2),c=()=>{if(n==="all")return"All Posts";if(n.startsWith("group:")){const u=n.replace("group:",""),h=t.find(p=>p.id===u);return h?`🔒 ${h.name}`:"Private Group"}const d=s.find(u=>u.id===n);return d?`${d.icon||"📂"} ${d.name}`:"Category"};return e.jsxs("div",{className:"lg:hidden flex items-center gap-2 mb-4",children:[e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(io,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(cc,{className:"w-56 bg-background border",children:[e.jsxs(Xr,{onClick:()=>r("all"),children:[e.jsx(JS,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(Qg,{}),e.jsx(I4,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(Xr,{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(Qg,{}),e.jsxs(I4,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Rc,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(Xr,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(ug,{open:i,onOpenChange:l,children:[e.jsx(oU,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(_n,{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(ox,{children:[e.jsx(r0,{children:e.jsxs(a0,{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(mi,{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(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:d.avatarUrl}),e.jsx(ia,{children:o(d.name)})]}),e.jsx(dm,{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 $2e,Sve="HoverCard",[Z0t,_gn]=gu(Sve,[Ww]),Cve=Ww(),[jbs,QIe]=Z0t(Sve),Q0t=s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=Cve(t),d=N.useRef(0),u=N.useRef(0),h=N.useRef(!1),p=N.useRef(!1),[f,g]=mm({prop:r,defaultProp:a??!1,onChange:i,caller:Sve}),b=N.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>g(!0),l)},[l,g]),v=N.useCallback(()=>{clearTimeout(d.current),!h.current&&!p.current&&(u.current=window.setTimeout(()=>g(!1),o))},[o,g]),j=N.useCallback(()=>g(!1),[g]);return N.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(jbs,{scope:t,open:f,onOpenChange:g,onOpen:b,onClose:v,onDismiss:j,hasSelectionRef:h,isPointerDownOnContentRef:p,children:e.jsx(V$,{...c,children:n})})};Q0t.displayName=Sve;var X0t="HoverCardTrigger",J0t=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=QIe(X0t,n),i=Cve(n);return e.jsx(RD,{asChild:!0,...i,children:e.jsx(sa.a,{"data-state":a.open?"open":"closed",...r,ref:t,onPointerEnter:wr(s.onPointerEnter,Ixe(a.onOpen)),onPointerLeave:wr(s.onPointerLeave,Ixe(a.onClose)),onFocus:wr(s.onFocus,a.onOpen),onBlur:wr(s.onBlur,a.onClose),onTouchStart:wr(s.onTouchStart,l=>l.preventDefault())})})});J0t.displayName=X0t;var Nbs="HoverCardPortal",[wgn,kbs]=Z0t(Nbs,{forceMount:void 0}),Mxe="HoverCardContent",eyt=N.forwardRef((s,t)=>{const n=kbs(Mxe,s.__scopeHoverCard),{forceMount:r=n.forceMount,...a}=s,i=QIe(Mxe,s.__scopeHoverCard);return e.jsx(Bh,{present:r||i.open,children:e.jsx(Sbs,{"data-state":i.open?"open":"closed",...a,onPointerEnter:wr(s.onPointerEnter,Ixe(i.onOpen)),onPointerLeave:wr(s.onPointerLeave,Ixe(i.onClose)),ref:t})})});eyt.displayName=Mxe;var Sbs=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=QIe(Mxe,n),d=Cve(n),u=N.useRef(null),h=Ti(t,u),[p,f]=N.useState(!1);return N.useEffect(()=>{if(p){const g=document.body;return $2e=g.style.userSelect||g.style.webkitUserSelect,g.style.userSelect="none",g.style.webkitUserSelect="none",()=>{g.style.userSelect=$2e,g.style.webkitUserSelect=$2e}}},[p]),N.useEffect(()=>{if(u.current){const g=()=>{f(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var v;((v=document.getSelection())==null?void 0:v.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",g),()=>{document.removeEventListener("pointerup",g),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),N.useEffect(()=>{u.current&&Ebs(u.current).forEach(b=>b.setAttribute("tabindex","-1"))}),e.jsx(G4,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:wr(i,g=>{g.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(H$,{...d,...o,onPointerDown:wr(o.onPointerDown,g=>{g.currentTarget.contains(g.target)&&f(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...o.style,userSelect:p?"text":void 0,WebkitUserSelect:p?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),Cbs="HoverCardArrow",Tbs=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=Cve(n);return e.jsx(G$,{...a,...r,ref:t})});Tbs.displayName=Cbs;function Ixe(s){return t=>t.pointerType==="touch"?void 0:s()}function Ebs(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;n.nextNode();)t.push(n.currentNode);return t}var Abs=Q0t,Mbs=J0t,tyt=eyt;const Ibs=Abs,Pbs=Mbs,syt=N.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(tyt,{ref:a,align:t,sideOffset:n,className:Et("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}));syt.displayName=tyt.displayName;const Lbs=[{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"}],Dbs=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),nyt=({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(Ibs,{openDelay:200,closeDelay:100,children:[e.jsx(Pbs,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(syt,{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=Lbs.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(aa,{className:"h-6 w-6",children:[e.jsx(ri,{src:l.user_avatar||void 0}),e.jsx(ia,{className:"text-[10px]",children:Dbs(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 Rbs({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=N.useState(t),[l,o]=N.useState(!1);N.useEffect(()=>{n&&(i(t),o(!1))},[n,t]);const c=()=>{i(p=>p>0?p-1:s.length-1),o(!1)},d=()=>{i(p=>p{n&&(p.key==="ArrowLeft"&&c(),p.key==="ArrowRight"&&d(),p.key==="Escape"&&r(!1))},[n,s.length]);N.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(bs,{open:n,onOpenChange:r,children:e.jsxs(vs,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"absolute top-2 right-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>r(!1),children:e.jsx(Fn,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12",onClick:c,children:e.jsx(fl,{className:"h-8 w-8"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12",onClick:d,children:e.jsx(ga,{className:"h-8 w-8"})})]}),s.length>1&&e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-50 text-white text-sm bg-black/50 px-3 py-1 rounded-full",children:[a+1," / ",s.length]}),(h==null?void 0:h.type)==="image"&&e.jsx(B,{variant:"ghost",size:"icon",className:"absolute top-2 left-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>o(!l),children:l?e.jsx(CL,{className:"h-5 w-5"}):e.jsx(h4,{className:"h-5 w-5"})}),e.jsx("div",{className:Et("flex items-center justify-center w-full h-full min-h-[50vh] p-4",l?"cursor-zoom-out overflow-auto":"cursor-zoom-in"),onClick:()=>(h==null?void 0:h.type)==="image"&&o(!l),children:(h==null?void 0:h.type)==="video"?e.jsx("video",{src:h.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-[85vh] object-contain",onClick:p=>p.stopPropagation()}):e.jsx("img",{src:h==null?void 0:h.url,alt:"",className:Et("object-contain transition-transform duration-200",l?"max-w-none max-h-none scale-150":"max-w-full max-h-[85vh]")})}),s.length>1&&e.jsx("div",{className:"absolute bottom-12 left-1/2 -translate-x-1/2 z-50 flex gap-2 bg-black/50 p-2 rounded-lg max-w-[90vw] overflow-x-auto",children:s.map((p,f)=>e.jsx("button",{onClick:()=>{i(f),o(!1)},className:Et("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===f?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:p.type==="video"?e.jsx("video",{src:p.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:p.url,alt:"",className:"w-full h-full object-cover"})},f))})]})})}const WH=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],Obs=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=Gt(),[a,i]=N.useState(!1),l=t.find(h=>h.user_id===n),o=gt({mutationFn:async h=>{l?l.reaction_type===h?await q.from("community_comment_reactions").delete().eq("id",l.id):await q.from("community_comment_reactions").update({reaction_type:h}).eq("id",l.id):await q.from("community_comment_reactions").insert({comment_id:s,user_id:n,reaction_type:h})},onSuccess:()=>{r.invalidateQueries({queryKey:["community-posts"]}),i(!1)}}),c={};return t.forEach(h=>{c[h.reaction_type]=(c[h.reaction_type]||0)+1}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&e.jsx(nyt,{reactions:t,children:e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("div",{className:"flex -space-x-0.5",children:Object.keys(c).slice(0,2).map(h=>{var p;return e.jsx("span",{className:"text-sm",children:(p=WH.find(f=>f.type===h))==null?void 0:p.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(Wo,{open:a,onOpenChange:i,children:[e.jsx(Ko,{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=WH.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=WH.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yi,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(zo,{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:WH.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 XIe({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(Ln,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:Et("font-medium hover:underline",u?"text-white bg-[#2a4c64] px-1.5 py-0.5 rounded":"text-primary"),onClick:h=>h.stopPropagation(),children:u?c:`@${c}`},`mention-${l++}`))}else if(i[4]){const o=i[4],c=o.replace(/[.,;:!?)]+$/,""),d=o.slice(c.length);let u;try{const h=new URL(c);u=h.hostname+(h.pathname!=="/"?h.pathname.slice(0,20)+(h.pathname.length>20?"...":""):"")}catch{u=c.length>40?c.slice(0,40)+"...":c}r.push(e.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all",onClick:h=>h.stopPropagation(),children:u},`url-${l++}`)),d&&r.push(d)}a=i.index+i[0].length}return ae.jsx(N.Fragment,{children:o},c))})}function Pxe({value:s,onChange:t,placeholder:n="What's on your mind? Use @ to mention someone",className:r,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const u=N.useRef(null),h=N.useRef(null),[p,f]=N.useState(!1),[g,b]=N.useState("user"),[v,j]=N.useState(""),[_,S]=N.useState(null),[A,T]=N.useState(0),[D,L]=N.useState({top:0,left:0,width:0}),M=N.useRef(new Map),F=N.useRef(new Map),z=ye=>{if(c==="plain"){const Ce=[];return M.current.forEach((De,Ie)=>{ye.includes(`@${Ie}`)&&Ce.push(De)}),[...new Set(Ce)]}const _e=/@\[([^\]]+)\]\(([^)]+)\)/g,Me=[];let Te;for(;(Te=_e.exec(ye))!==null;)Me.push(Te[2]);return[...new Set(Me)]},V=ye=>{if(c==="plain"){const Ce=[];return F.current.forEach((De,Ie)=>{ye.includes(`#${Ie}`)&&Ce.push(De)}),[...new Set(Ce)]}const _e=/#\[([^\]]+)\]\(([^)]+)\)/g,Me=[];let Te;for(;(Te=_e.exec(ye))!==null;)Me.push(Te[2]);return[...new Set(Me)]};N.useEffect(()=>{if(i){const ye=z(s);i(ye)}if(l){const ye=V(s);l(ye)}},[s,i,l,c]);const{data:W=[],isLoading:K}=lt({queryKey:["mention-users",v],queryFn:async()=>{const ye=q.from("profiles").select("id, name").limit(8),_e=v.length>=1?ye.ilike("name",`%${v}%`):ye.order("name"),{data:Me,error:Te}=await _e;if(Te)throw Te;const Ce=Me.map(De=>De.id),Ee=await Jht(Ce);return Me.map(De=>({id:De.id,name:De.name||"Unknown",avatar_url:Ee.get(De.id)}))},enabled:p&&g==="user",staleTime:3e4}),{data:Y=[],isLoading:ee}=lt({queryKey:["mention-templates",v],queryFn:async()=>{let ye=q.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);v.length>=1&&(ye=ye.ilike("name",`%${v}%`));const{data:_e,error:Me}=await ye;if(Me)throw Me;return _e||[]},enabled:p&&g==="template"&&d,staleTime:3e4}),ne=g==="user"?K:ee,oe=g==="user"?W:Y,pe=ye=>ye.split(" ").map(_e=>_e[0]).join("").toUpperCase().slice(0,2),ce=ye=>{const _e=ye.target.value,Me=ye.target.selectionStart;t(_e);const Te=_e.substring(0,Me),Ce=Te.lastIndexOf("@"),Ee=d?Te.lastIndexOf("#"):-1;let De=-1,Ie="user";if(Ce>Ee?(De=Ce,Ie="user"):Ee>Ce&&d&&(De=Ee,Ie="template"),De!==-1){const Fe=Te.substring(De+1),qe=Fe.includes(" "),ve=Fe.includes(` `);if(!qe&&!ve&&Fe.length<=30){S(De),j(Fe),b(Ie),f(!0),T(0);return}}f(!1),S(null)},de=ye=>{if(_===null)return;const _e=s.substring(0,_),Me=s.substring(_+v.length+1),Te=g==="user"?"@":"#",Ce=c==="plain"?`${Te}${ye.name} `:`${Te}[${ye.name}](${ye.id}) `;c==="plain"&&(g==="user"?M.current.set(ye.name,ye.id):F.current.set(ye.name,ye.id));const Ee=_e+Ce+Me;t(Ee),f(!1),S(null),j(""),setTimeout(()=>{if(u.current){const De=_e.length+Ce.length;u.current.focus(),u.current.setSelectionRange(De,De)}},0)},ie=ye=>{if(!(!p||oe.length===0))switch(ye.key){case"ArrowDown":ye.preventDefault(),T(_e=>(_e+1)%oe.length);break;case"ArrowUp":ye.preventDefault(),T(_e=>(_e-1+oe.length)%oe.length);break;case"Enter":oe[A]&&(ye.preventDefault(),de(oe[A]));break;case"Escape":ye.preventDefault(),f(!1);break;case"Tab":oe[A]&&(ye.preventDefault(),de(oe[A]));break}};return N.useEffect(()=>{const ye=_e=>{h.current&&!h.current.contains(_e.target)&&u.current&&!u.current.contains(_e.target)&&f(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[]),N.useEffect(()=>{if(!p)return;const ye=()=>{const _e=u.current;if(!_e)return;const Me=_e.getBoundingClientRect();L({top:Me.bottom+4,left:Me.left,width:Me.width})};return ye(),window.addEventListener("resize",ye),window.addEventListener("scroll",ye,!0),()=>{window.removeEventListener("resize",ye),window.removeEventListener("scroll",ye,!0)}},[p,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ts,{ref:u,value:s,onChange:ce,onKeyDown:ye=>{ie(ye),ye.defaultPrevented||o==null||o(ye)},placeholder:n,className:Et("resize-none",r),style:{minHeight:a}}),p&&Gx.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:D.top,left:D.left,width:D.width,maxWidth:"320px"},children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30",children:g==="user"?"👤 Mention a person":"📋 Link a template"}),ne?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):oe.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:v.length<1?`Type to search ${g==="user"?"people":"templates"}...`:`No ${g==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:oe.map((ye,_e)=>e.jsx("li",{className:Et("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",_e===A?"bg-accent":"hover:bg-accent/50"),onClick:()=>de(ye),onMouseEnter:()=>T(_e),children:g==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(aa,{className:"h-6 w-6",children:[e.jsx(ri,{src:ye.avatar_url}),e.jsx(ia,{className:"text-xs",children:pe(ye.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:ye.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:ye.preview_image_url?e.jsx("img",{src:ye.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(xl,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:ye.name})]})},ye.id))})]}),document.body)]})}function Fbs(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const VHe=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function ryt({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=Gt(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState([]),g=gt({mutationFn:async({content:_,parentCommentId:S})=>{const{data:A,error:T}=await q.from("community_comments").insert({post_id:t,user_id:n,content:_,parent_comment_id:S}).select("id").single();if(T)throw T;const D=p;if(D.length>0&&A){const L=D.filter(M=>M!==n).map(M=>({comment_id:A.id,mentioned_user_id:M,mentioned_by_user_id:n}));L.length>0&&await q.from("community_comment_mentions").insert(L)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),f([]),d(!1)}}),b=gt({mutationFn:async _=>{const{error:S}=await q.from("community_comments").delete().eq("id",_);if(S)throw S},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),v=()=>{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(aa,{className:"h-8 w-8 shrink-0",children:[e.jsx(ri,{src:s.user_avatar||void 0}),e.jsx(ia,{className:"text-xs",children:VHe(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(XIe,{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:Go(new Date(s.created_at),{addSuffix:!0})}),e.jsx(Obs,{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(N9,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===n||i)&&e.jsx("button",{onClick:()=>b.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(aa,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(ri,{src:r||void 0}),e.jsx(ia,{className:"text-xs",children:VHe((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(Pxe,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:h,onMentionsChange:f,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:v,disabled:!u.trim()||g.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(cr,{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(ryt,{comment:_,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},_.id))})]})}const KH=[{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"}],zbs=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=gs(),{avatarUrl:a}=Xht(s==null?void 0:s.id),{onlineUsers:i}=_it(),{toast:l}=Ua(),o=Gt(),c=N.useRef(null),[d,u]=N.useState("all"),[h,p]=N.useState(""),[f,g]=N.useState(""),[b,v]=N.useState(""),[j,_]=N.useState([]),[S,A]=N.useState([]),[T,D]=N.useState(""),[L,M]=N.useState(!1),[F,z]=N.useState(null),[V,W]=N.useState(""),[K,Y]=N.useState(new Set),[ee,ne]=N.useState({}),[oe,pe]=N.useState({}),[ce,de]=N.useState([]),[ie,ye]=N.useState([]),[_e,Me]=N.useState({open:!1,images:[],index:0});N.useEffect(()=>{if(d.startsWith("group:")){const kt=d.replace("group:","");v(kt),g("")}else d!=="all"?(g(d),v("")):(g(""),v(""))},[d]);const{data:Te=[]}=lt({queryKey:["community-categories"],queryFn:async()=>{const{data:kt,error:Qt}=await q.from("community_categories").select("*").order("sort_order");if(Qt)throw Qt;return kt}}),{data:Ce=[]}=lt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:kt,error:Qt}=await q.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(Qt)throw Qt;return kt}}),Ee=20,{data:De,isLoading:Ie,hasNextPage:Fe,fetchNextPage:qe,isFetchingNextPage:ve}=yLt({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:kt})=>{var Qe;const Qt=kt*Ee,ns=Qt+Ee;let $s=q.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(Qt,ns);if(d.startsWith("group:")){const ct=d.replace("group:","");$s=$s.eq("private_group_id",ct)}else d==="all"||($s=$s.eq("category_id",d).is("private_group_id",null));const{data:Ds,error:Dt}=await $s;if(Dt)throw Dt;const St=((Ds==null?void 0:Ds.length)||0)>Ee,$t=(Ds||[]).slice(0,Ee);if($t.length===0)return{posts:[],hasMore:!1,nextPage:kt+1};const ht=$t.map(ct=>ct.id),Ut=[...new Set($t.filter(ct=>ct.category_id).map(ct=>ct.category_id))].filter(Boolean),[Es,Xt,Ys,Ss,Bs]=await Promise.all([Ut.length?q.from("community_categories").select("*").in("id",Ut):Promise.resolve({data:[]}),q.from("community_post_media").select("*").in("post_id",ht).order("sort_order"),q.from("community_reactions").select("*").in("post_id",ht),q.from("community_comments").select("*").in("post_id",ht).order("created_at",{ascending:!0}),q.from("community_post_resources").select("*").in("post_id",ht)]),Us=Es==null?void 0:Es.data,sn=Xt==null?void 0:Xt.data,Jn=Ys==null?void 0:Ys.data,fn=Ss==null?void 0:Ss.data,Sn=Bs==null?void 0:Bs.data,Gn=(fn||[]).map(ct=>ct.id),[Hr,pi]=await Promise.all([Gn.length?q.from("community_comment_reactions").select("*").in("comment_id",Gn):Promise.resolve({data:[]}),(()=>{const ct=(Sn||[]).filter(vt=>vt.resource_type==="template").map(vt=>vt.resource_id);return ct.length===0?Promise.resolve({data:[]}):q.from("canva_templates").select("id, name, preview_image_url").in("id",ct)})()]),Ms=(Hr==null?void 0:Hr.data)||[],bi=(pi==null?void 0:pi.data)||[],Rr=new Map(bi.map(ct=>[ct.id,{name:ct.name,preview_image_url:ct.preview_image_url}])),er=Array.from(new Set([...$t.map(ct=>ct.user_id),...(Jn||[]).map(ct=>ct.user_id),...(fn||[]).map(ct=>ct.user_id),...Ms.map(ct=>ct.user_id)])),[lr,Fs]=await Promise.all([er.length?q.from("profiles").select("id, name").in("id",er):Promise.resolve({data:[]}),Jht(er)]),$n=new Map(((Qe=lr==null?void 0:lr.data)==null?void 0:Qe.map(ct=>[ct.id,ct.name]))||[]),Cr=new Map((Us||[]).map(ct=>[ct.id,ct])),ts=ct=>{const vt=new Map,It=[];return ct.forEach(qt=>{vt.set(qt.id,{...qt,user_name:$n.get(qt.user_id)||"Unknown User",user_avatar:Fs.get(qt.user_id),reactions:Ms.filter(xs=>xs.comment_id===qt.id).map(xs=>({...xs,user_name:$n.get(xs.user_id)||"Unknown User",user_avatar:Fs.get(xs.user_id)})),replies:[]})}),ct.forEach(qt=>{const xs=vt.get(qt.id);if(qt.parent_comment_id&&vt.has(qt.parent_comment_id)){const as=vt.get(qt.parent_comment_id);as.replies=as.replies||[],as.replies.push(xs)}else It.push(xs)}),It};return{posts:$t.map(ct=>{const vt=(Sn||[]).filter(It=>It.post_id===ct.id).map(It=>{let qt="",xs=null;if(It.resource_type==="template"){const as=Rr.get(It.resource_id);qt=(as==null?void 0:as.name)||"Unknown Template",xs=(as==null?void 0:as.preview_image_url)||null}return{id:It.id,resource_type:It.resource_type,resource_id:It.resource_id,resource_name:qt,resource_preview_url:xs}});return{...ct,user_name:$n.get(ct.user_id)||"Unknown User",user_avatar:Fs.get(ct.user_id),category:ct.category_id?Cr.get(ct.category_id):null,media:(sn||[]).filter(It=>It.post_id===ct.id),reactions:((Jn||[]).filter(It=>It.post_id===ct.id)||[]).map(It=>({...It,user_name:$n.get(It.user_id)||"Unknown User",user_avatar:Fs.get(It.user_id)})),comments:ts((fn||[]).filter(It=>It.post_id===ct.id)),resources:vt}}),hasMore:St,nextPage:kt+1}},getNextPageParam:kt=>kt.hasMore?kt.nextPage:void 0}),Je=N.useMemo(()=>(De==null?void 0:De.pages.flatMap(kt=>kt.posts))??[],[De]),we=gt({mutationFn:async()=>{M(!0);const{data:kt,error:Qt}=await q.from("community_posts").insert({user_id:s.id,category_id:b?null:f||null,private_group_id:b||null,content:h,link_url:T||null}).select().single();if(Qt)throw Qt;for(let $s=0;$s0){const $s=ce.filter(Ds=>Ds!==s.id).map(Ds=>({post_id:kt.id,mentioned_user_id:Ds,mentioned_by_user_id:s.id}));$s.length>0&&await q.from("community_post_mentions").insert($s)}const ns=Fbs(h);if(ns.length>0){const $s=ns.map(Ds=>({post_id:kt.id,resource_type:"template",resource_id:Ds}));await q.from("community_post_resources").insert($s)}return kt},onSuccess:async kt=>{var Qt;o.invalidateQueries({queryKey:["community-posts"]}),p(""),de([]),ye([]),g(""),v(""),_([]),A([]),D(""),l({title:"Post created!"});try{const ns=((Qt=s==null?void 0:s.user_metadata)==null?void 0:Qt.name)||"Someone",$s=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),Ds=$s.length>50?$s.substring(0,50)+"...":$s;await q.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${ns}: ${Ds}`,url:"/community"}})}catch(ns){console.error("Failed to send push notification:",ns)}},onError:kt=>{l({title:"Error creating post",description:kt.message,variant:"destructive"})},onSettled:()=>M(!1)}),it=gt({mutationFn:async({postId:kt,content:Qt})=>{const{error:ns}=await q.from("community_posts").update({content:Qt}).eq("id",kt);if(ns)throw ns},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),z(null),W(""),l({title:"Post updated!"})}}),Ne=gt({mutationFn:async kt=>{const{error:Qt}=await q.from("community_posts").delete().eq("id",kt);if(Qt)throw Qt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),He=gt({mutationFn:async({postId:kt,isPinned:Qt})=>{const{error:ns}=await q.from("community_posts").update({is_pinned:!Qt,pinned_at:Qt?null:new Date().toISOString(),pinned_by:Qt?null:s==null?void 0:s.id}).eq("id",kt);if(ns)throw ns},onSuccess:(kt,{isPinned:Qt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:Qt?"Post unpinned":"Post pinned to top"})}}),$e=gt({mutationFn:async({postId:kt,reactionType:Qt})=>{var $s;const ns=($s=Je.find(Ds=>Ds.id===kt))==null?void 0:$s.reactions.find(Ds=>Ds.user_id===(s==null?void 0:s.id));ns?ns.reaction_type===Qt?await q.from("community_reactions").delete().eq("id",ns.id):await q.from("community_reactions").update({reaction_type:Qt}).eq("id",ns.id):await q.from("community_reactions").insert({post_id:kt,user_id:s.id,reaction_type:Qt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ye=gt({mutationFn:async({postId:kt,content:Qt})=>{const{data:ns,error:$s}=await q.from("community_comments").insert({post_id:kt,user_id:s.id,content:Qt}).select("id").single();if($s)throw $s;const Ds=oe[kt]||[];if(Ds.length>0&&ns){const Dt=Ds.filter(St=>St!==s.id).map(St=>({comment_id:ns.id,mentioned_user_id:St,mentioned_by_user_id:s.id}));Dt.length>0&&await q.from("community_comment_mentions").insert(Dt)}},onSuccess:(kt,{postId:Qt})=>{o.invalidateQueries({queryKey:["community-posts"]}),ne(ns=>({...ns,[Qt]:""})),pe(ns=>({...ns,[Qt]:[]}))}});gt({mutationFn:async kt=>{const{error:Qt}=await q.from("community_comments").delete().eq("id",kt);if(Qt)throw Qt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const Ke=kt=>{const Qt=Array.from(kt.target.files||[]);if(Qt.length+j.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}_(ns=>[...ns,...Qt]),Qt.forEach(ns=>{const $s=new FileReader;$s.onloadend=()=>{A(Ds=>[...Ds,$s.result])},$s.readAsDataURL(ns)})},rt=kt=>{_(Qt=>Qt.filter((ns,$s)=>$s!==kt)),A(Qt=>Qt.filter((ns,$s)=>$s!==kt))},tt=kt=>kt.split(" ").map(Qt=>Qt[0]).join("").toUpperCase().slice(0,2),at=kt=>{const Qt={};return kt.forEach(ns=>{Qt[ns.reaction_type]=(Qt[ns.reaction_type]||0)+1}),Qt},Ge=kt=>{var Qt;return(Qt=kt.find(ns=>ns.user_id===(s==null?void 0:s.id)))==null?void 0:Qt.reaction_type},dt=kt=>kt.reduce((Qt,ns)=>Qt+1+(ns.replies?dt(ns.replies):0),0),Bt=kt=>{if(r)return!0;if(!t||!kt.private_group_id)return!1;const Qt=Ce.find(ns=>ns.id===kt.private_group_id);return Qt!=null&&Qt.brokerage_id?n.some(ns=>ns.id===Qt.brokerage_id):!1};return e.jsx(Cs,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(_bs,{categories:Te,privateGroups:Ce,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-2xl mx-auto lg:mx-0 space-y-6",children:[e.jsxs("div",{className:"px-1",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-foreground",children:"Community"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Connect and share with fellow agents"})]}),e.jsx(wbs,{categories:Te,privateGroups:Ce,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:a||void 0}),e.jsx(ia,{children:s!=null&&s.email?tt(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(Pxe,{placeholder:r?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:h,onChange:p,onMentionsChange:de,onTemplatesChange:ye,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),S.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:S.map((kt,Qt)=>{var ns;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(ns=j[Qt])!=null&&ns.type.startsWith("video/")?e.jsx("video",{src:kt,className:"w-full h-full object-cover"}):e.jsx("img",{src:kt,alt:"",className:"w-full h-full object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>rt(Qt),children:e.jsx(Fn,{className:"h-3 w-3"})})]},Qt)})}),T&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ge,{value:T,onChange:kt=>D(kt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>D(""),children:e.jsx(Fn,{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:Ke,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var kt;return(kt=c.current)==null?void 0:kt.click()},children:[e.jsx(nl,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var kt;return(kt=c.current)==null?void 0:kt.click()},children:[e.jsx(vr,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>D("https://"),children:[e.jsx(tl,{className:"h-4 w-4 mr-1"}),"Link"]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end",children:[Ce.length>0?e.jsxs(us,{value:b||f||"none",onValueChange:kt=>{kt==="none"?(g(""),v("")):kt.startsWith("group:")?(v(kt.replace("group:","")),g("")):(g(kt),v(""))},children:[e.jsx(cs,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(hs,{placeholder:"Select..."})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No category"}),Te.map(kt=>e.jsxs(Ze,{value:kt.id,children:[kt.icon," ",kt.name]},kt.id)),Ce.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 py-1 text-xs font-semibold text-muted-foreground border-t mt-1 pt-1",children:"🔒 Private Groups"}),Ce.map(kt=>e.jsxs(Ze,{value:`group:${kt.id}`,children:[kt.icon||"🔒"," ",kt.name]},kt.id))]})]})]}):e.jsxs(us,{value:f,onValueChange:g,children:[e.jsx(cs,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(hs,{placeholder:"Category"})}),e.jsx(ds,{children:Te.map(kt=>e.jsxs(Ze,{value:kt.id,children:[kt.icon," ",kt.name]},kt.id))})]}),e.jsxs(B,{size:"sm",onClick:()=>we.mutate(),disabled:!h.trim()||L,children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Ie?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((kt,Qt)=>e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ws,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ws,{className:"h-4 w-32"}),e.jsx(Ws,{className:"h-4 w-full"}),e.jsx(Ws,{className:"h-4 w-3/4"})]})]})})},Qt))}):Je.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx(Ql,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No posts yet"}),e.jsx("p",{className:"text-muted-foreground",children:"Be the first to start a conversation!"})]})}):e.jsxs("div",{className:"space-y-4",children:[Je.map(kt=>{var Qt,ns,$s,Ds;return e.jsx(fe,{children:e.jsxs(Ae,{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(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:kt.user_avatar||void 0}),e.jsx(ia,{children:tt(kt.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:kt.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:Go(new Date(kt.created_at),{addSuffix:!0})}),kt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[kt.category.icon," ",kt.category.name]})]})]})]})]}),(kt.user_id===(s==null?void 0:s.id)||Bt(kt))&&e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Xf,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[Bt(kt)&&kt.private_group_id&&e.jsx(Xr,{onClick:()=>He.mutate({postId:kt.id,isPinned:kt.is_pinned}),children:kt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(b9,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(o4,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),kt.user_id===(s==null?void 0:s.id)&&e.jsxs(Xr,{onClick:()=>{z(kt),W(kt.content)},children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Xr,{className:"text-destructive",onClick:()=>Ne.mutate(kt.id),children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),kt.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),kt.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(o4,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(XIe,{content:kt.content})}),kt.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${kt.media.length===1?"grid-cols-1":kt.media.length===2?"grid-cols-2":kt.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:kt.media.slice(0,4).map((Dt,St)=>{const $t=St===3&&kt.media.length>4,ht=kt.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${kt.media.length===1?"max-h-[500px]":kt.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>Me({open:!0,images:kt.media.map(Ut=>({url:Ut.media_url,type:Ut.media_type==="video"?"video":"image"})),index:St}),children:[Dt.media_type==="video"?e.jsx("video",{src:Dt.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:Dt.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"})})})}),$t&&e.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center",children:e.jsxs("span",{className:"text-white text-2xl font-bold",children:["+",ht]})})]},Dt.id)})}),kt.link_url&&e.jsxs("a",{href:kt.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[kt.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:kt.link_image,alt:kt.link_title||"Link preview",className:"w-full h-full object-cover",onError:Dt=>{Dt.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:kt.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:kt.link_title}),kt.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:kt.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(kt.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(tl,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:kt.link_url})]})})]}),kt.reactions.length>0&&e.jsx(nyt,{reactions:kt.reactions,children:e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:[e.jsx("div",{className:"flex -space-x-1",children:Object.entries(at(kt.reactions)).slice(0,3).map(([Dt])=>{var St;return e.jsx("span",{className:"text-base",children:(St=KH.find($t=>$t.type===Dt))==null?void 0:St.emoji},Dt)})}),e.jsx("span",{children:kt.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",children:[Ge(kt.reactions)?e.jsx("span",{className:"mr-1",children:(Qt=KH.find(Dt=>Dt.type===Ge(kt.reactions)))==null?void 0:Qt.emoji}):e.jsx(Hm,{className:"h-4 w-4 mr-1"}),Ge(kt.reactions)?(ns=KH.find(Dt=>Dt.type===Ge(kt.reactions)))==null?void 0:ns.label:"Like"]})}),e.jsx(zo,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:KH.map(Dt=>e.jsx("button",{onClick:()=>$e.mutate({postId:kt.id,reactionType:Dt.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:Dt.label,children:Dt.emoji},Dt.type))})})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>Y(Dt=>{const St=new Set(Dt);return St.has(kt.id)?St.delete(kt.id):St.add(kt.id),St}),children:[e.jsx(Ql,{className:"h-4 w-4 mr-1"}),(()=>{const Dt=dt(kt.comments);return Dt>0?`Comment (${Dt})`:"Comment"})()]})]}),K.has(kt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[kt.comments.map(Dt=>e.jsx(ryt,{comment:Dt,postId:kt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:Bt(kt)},Dt.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:a||void 0}),e.jsx(ia,{className:"text-xs",children:tt((($s=s.email)==null?void 0:$s.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(Pxe,{placeholder:"Write a comment... (use @ to mention)",value:ee[kt.id]||"",onChange:Dt=>ne(St=>({...St,[kt.id]:Dt})),onMentionsChange:Dt=>pe(St=>({...St,[kt.id]:Dt})),mentionFormat:"plain",onKeyDown:Dt=>{var St;Dt.defaultPrevented||Dt.key==="Enter"&&!Dt.shiftKey&&((St=ee[kt.id])!=null&&St.trim())&&(Dt.preventDefault(),Ye.mutate({postId:kt.id,content:ee[kt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var Dt;(Dt=ee[kt.id])!=null&&Dt.trim()&&Ye.mutate({postId:kt.id,content:ee[kt.id]})},disabled:!((Ds=ee[kt.id])!=null&&Ds.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(cr,{className:"h-4 w-4"})})]})]})]})]})},kt.id)}),Fe&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(B,{variant:"outline",onClick:()=>qe(),disabled:ve,children:ve?"Loading…":"Load more posts"})})]}),e.jsx(bs,{open:!!F,onOpenChange:()=>z(null),children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Edit Post"})}),e.jsx(Ts,{value:V,onChange:kt=>W(kt.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>z(null),children:"Cancel"}),e.jsx(B,{onClick:()=>{F&&it.mutate({postId:F.id,content:V})},disabled:!V.trim(),children:"Save Changes"})]})]})}),e.jsx(Rbs,{images:_e.images,initialIndex:_e.index,open:_e.open,onOpenChange:kt=>Me(Qt=>({...Qt,open:kt}))})]})]})})},Bbs=50*1024*1024;function ayt({value:s,onChange:t,disabled:n}){const{user:r}=gs(),a=N.useRef(null),[i,l]=N.useState(!1),o=async d=>{if(!d||!r)return;const u=[];l(!0);try{for(const h of Array.from(d)){if(!h.type.startsWith("image/")&&!h.type.startsWith("video/")){ae.error(`${h.name}: only images and videos allowed`);continue}if(h.size>Bbs){ae.error(`${h.name}: must be under 50MB`);continue}const p=h.name.split(".").pop()||"bin",f=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${p}`,{error:g}=await q.storage.from("support-attachments").upload(f,h,{contentType:h.type,upsert:!1});if(g){ae.error(`${h.name}: ${g.message}`);continue}u.push({path:f,type:h.type,name:h.name,size:h.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((h,p)=>p!==d)),await q.storage.from("support-attachments").remove([u.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(a9,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(K2,{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(Fn,{className:"h-3 w-3"})})]},d.path))}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var d;return(d=a.current)==null?void 0:d.click()},disabled:n||i,className:"gap-1.5",children:[i?e.jsx(ss,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(r4,{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 iyt({attachments:s}){const[t,n]=N.useState({}),[r,a]=N.useState(!0);return N.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await q.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,u)=>{d.signedUrl&&(c[l[u]]=d.signedUrl)}),n(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?r?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(ss,{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 DI={open:{label:"Open",icon:gr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ql,color:"bg-blue-500"},resolved:{label:"Resolved",icon:zi,color:"bg-green-500"},closed:{label:"Closed",icon:Gc,color:"bg-muted-foreground"}},HHe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function $bs(){const{user:s}=gs(),t=Gt(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState([]),{data:c=[],isLoading:d}=lt({queryKey:["support-tickets"],queryFn:async()=>{const{data:f,error:g}=await q.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(g)throw g;return f},enabled:!!s}),{data:u=[]}=lt({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:f,error:g}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(g)throw g;return f},enabled:!!n}),h=gt({mutationFn:async({content:f,attachments:g})=>{if(!n||!s)throw new Error("Missing data");const{error:b}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:f,is_admin_reply:!1,attachments:g});if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ae.success("Reply sent!")},onError:()=>{ae.error("Failed to send reply")}}),p=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const f=DI[n.status].icon;return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(Wr,{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(ze,{variant:"secondary",children:HHe[n.category]}),e.jsxs(ze,{className:DI[n.status].color,children:[e.jsx(f,{className:"h-3 w-3 mr-1"}),DI[n.status].label]})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Hn,{children:["Created on ",ks(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Ae,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ae,{children:[e.jsx(mi,{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 b;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":((b=g.profiles)==null?void 0:b.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ks(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(iyt,{attachments:g.attachments})]},g.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(cl,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ts,{placeholder:"Type your reply...",value:a,onChange:g=>i(g.target.value),className:"min-h-[80px]"}),e.jsx(B,{onClick:p,disabled:!a.trim()&&l.length===0||h.isPending,className:"self-end",children:e.jsx(cr,{className:"h-4 w-4"})})]}),e.jsx(ayt,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Ae,{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(Y_,{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(vCe,{trigger:e.jsxs(B,{size:"lg",className:"gap-2",children:[e.jsx(As,{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(Pr,{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(vCe,{trigger:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"New Ticket"]})})]}),d?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):c.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"text-center py-12",children:[e.jsx(Ql,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't submitted any support tickets. Use the button above to get started!"})]})}):e.jsx("div",{className:"space-y-3",children:c.map(f=>{const g=DI[f.status].icon;return e.jsx(fe,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(f),children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:f.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ze,{variant:"outline",className:"text-xs",children:HHe[f.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ks(new Date(f.created_at),"MMM d, yyyy")})]})]}),e.jsxs(ze,{className:DI[f.status].color,children:[e.jsx(g,{className:"h-3 w-3 mr-1"}),DI[f.status].label]})]})})},f.id)})})]})})}function Ubs({open:s,onOpenChange:t}){return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(ws,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(yr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(_s,{children:"Schedule Agent Onboarding"}),e.jsx(Qn,{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 qbs({open:s,onOpenChange:t}){const{brokerageId:n}=gs(),[r,a]=N.useState(""),[i,l]=N.useState([]),[o,c]=N.useState(!1),{data:d,isLoading:u}=lt({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:b,error:v}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(v)throw v;return b},enabled:s&&!!n}),h=d==null?void 0:d.filter(b=>b.name.toLowerCase().includes(r.toLowerCase())||b.email.toLowerCase().includes(r.toLowerCase())),p=b=>{l(v=>v.includes(b)?v.filter(j=>j!==b):[...v,b])},f=async()=>{if(i.length===0){ae.error("Please select at least one agent");return}c(!0);try{const{data:b,error:v}=await q.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(v)throw v;ae.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(b){console.error("Error sending onboarding link:",b),ae.error(b.message||"Failed to send onboarding link")}finally{c(!1)}},g=b=>{b||(l([]),a("")),t(b)};return e.jsx(bs,{open:s,onOpenChange:g,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{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(cr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(_s,{children:"Send Onboarding Link"}),e.jsx(Qn,{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(_r,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search agents...",value:r,onChange:b=>a(b.target.value),className:"pl-10"})]}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ss,{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(_n,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(mi,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:h==null?void 0:h.map(b=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>p(b.id),children:[e.jsx(hi,{checked:i.includes(b.id),onCheckedChange:()=>p(b.id)}),e.jsx(aa,{className:"h-8 w-8",children:e.jsx(ia,{className:"text-xs",children:b.name.split(" ").map(v=>v[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:b.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:b.email})]})]},b.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx(B,{onClick:f,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function Vbs(){const[s,t]=N.useState(!1),[n,r]=N.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"mb-8",children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(_n,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Pt,{children:"Agent Onboarding"}),e.jsx(Hn,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Ae,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs(B,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs(B,{variant:"outline",onClick:()=>r(!0),className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(Ubs,{open:s,onOpenChange:t}),e.jsx(qbs,{open:n,onOpenChange:r})]})}function Hbs({open:s,onOpenChange:t}){return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(ws,{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(nx,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(_s,{children:"Schedule Launch Meeting"}),e.jsx(Qn,{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 Gbs(){const[s,t]=N.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"mb-8",children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(nx,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Pt,{children:"Launch or ReLaunch Meeting"}),e.jsx(Hn,{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(Ae,{children:e.jsxs(B,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(nx,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(Hbs,{open:s,onOpenChange:t})]})}function Wbs(){const s=In(),[t,n]=N.useState(""),[r,a]=N.useState(null),{data:i,isLoading:l}=lt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:b,error:v}=await q.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(v)throw v;return b}}),{data:o}=lt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:b,error:v}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(v)throw v;return b}}),{data:c}=lt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:b,error:v}=await q.from("brokerage_resource_pdfs").select("resource_id");if(v)throw v;return b}}),{data:d}=lt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:b,error:v}=await q.from("brokerage_resource_videos").select("resource_id");if(v)throw v;return b}}),{data:u}=lt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:b,error:v}=await q.from("brokerage_resource_links").select("resource_id");if(v)throw v;return b}}),h=i==null?void 0:i.filter(b=>{var _;const v=b.title.toLowerCase().includes(t.toLowerCase())||((_=b.description)==null?void 0:_.toLowerCase().includes(t.toLowerCase())),j=!r||b.category_id===r;return v&&j}),p=o==null?void 0:o.filter(b=>i==null?void 0:i.some(v=>v.category_id===b.id)),f=b=>{const v=(c==null?void 0:c.filter(S=>S.resource_id===b).length)||0,j=(d==null?void 0:d.filter(S=>S.resource_id===b).length)||0,_=(u==null?void 0:u.filter(S=>S.resource_id===b).length)||0;return{pdfCount:v,videoCount:j,linkCount:_}},g=b=>{s(`/brokerage-resources/${b}`)};return e.jsx(Cs,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vbs,{}),e.jsx(Gbs,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search resources...",value:t,onChange:b=>n(b.target.value),className:"pl-10"})]}),p&&p.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ze,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),p.map(b=>e.jsx(ze,{variant:r===b.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(b.id),children:b.name},b.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((b,v)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-40 w-full"}),e.jsx(Mt,{children:e.jsx(Ws,{className:"h-5 w-3/4"})}),e.jsxs(Ae,{children:[e.jsx(Ws,{className:"h-4 w-full mb-2"}),e.jsx(Ws,{className:"h-4 w-2/3"})]})]},v))}):(h==null?void 0:h.length)===0?e.jsxs(fe,{className:"p-12 text-center",children:[e.jsx(Vm,{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(b=>{const{pdfCount:v,videoCount:j,linkCount:_}=f(b.id),S=o==null?void 0:o.find(A=>A.id===b.category_id);return e.jsxs(fe,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>g(b.id),children:[b.preview_image_url?e.jsx("img",{src:b.preview_image_url,alt:b.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(Vm,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(Pt,{className:"text-lg line-clamp-1",children:b.title}),S&&e.jsx(ze,{variant:"secondary",className:"shrink-0 text-xs",children:S.name})]})}),e.jsxs(Ae,{children:[b.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:b.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nr,{className:"h-4 w-4"}),v]}),j>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vr,{className:"h-4 w-4"}),j]}),_>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tl,{className:"h-4 w-4"}),_]})]})]})]},b.id)})})]})})}const Kbs=()=>{const{resourceId:s}=_i(),{data:t,isLoading:n}=lt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await q.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await q.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await q.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await q.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),r=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return n?e.jsx(Cs,{title:"Brokerage Resources",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):t?e.jsx(Cs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Ln,{to:"/brokerage-resources",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Back to Resources"]})}),t.preview_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:t.preview_image_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),t.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:t.description}})]}),t.videos&&t.videos.length>0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(vr,{className:"h-4 w-4"}),"Videos (",t.videos.length,")"]}),e.jsx("div",{className:"space-y-4",children:t.videos.map(a=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:a.title}),e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:a.video_url,className:"absolute top-0 left-0 w-full h-full rounded-lg border",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})]},a.id))})]})}),t.pdfs&&t.pdfs.length>0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Nr,{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(Nr,{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(Da,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(tr,{className:"h-4 w-4"}),"Canva Templates (",t.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:t.links.map(a=>e.jsxs("a",{href:a.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(tr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(Cs,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Vm,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(Ln,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function Ybs(){const{onlineUsers:s,totalOnline:t}=_it();return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(_n,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(ze,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(dm,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Ae,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No other users online right now"}):e.jsx(mi,{className:"h-[300px] pr-4",children:e.jsx("div",{className:"space-y-3",children:s.map(n=>{var r;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(aa,{className:"h-9 w-9",children:[e.jsx(ri,{src:n.avatarUrl,alt:n.name}),e.jsx(ia,{className:"text-xs",children:(r=n.name)==null?void 0:r.split(" ").map(a=>a[0]).join("").slice(0,2).toUpperCase()})]}),e.jsx("span",{className:"absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full bg-green-500 ring-2 ring-background"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:n.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Online ",Go(new Date(n.onlineSince),{addSuffix:!1})]})]})]},n.id)})})})})]})}const GHe={users:{label:"Users & Access",sections:[{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:_n,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:O9,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:ff,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:t9,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:mh,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:Hl,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:_n,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:wc,path:"/admin/prospector",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"Recruiting",description:"Manage agent recruit pipeline and outreach",icon:Fo,path:"/admin/recruiting",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Coaching",description:"Promote coaches and manage agent coaching assignments",icon:vo,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:xl,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:_d,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:_d,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:wb,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:un,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:un,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:iy,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:iy,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:Tl,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:wf,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:Vm,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:Vm,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:Hs,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:qd,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:t4,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:xv,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:Hs,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:qd,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:W2,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:ww,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:Bi,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:vo,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:El,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:_n,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:qd,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:Ci,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:oL,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:bw,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:ua,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:Hs,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:yo,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:$u,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:oy,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:_d,path:"/admin/lms",color:"bg-gradient-to-br from-primary/20 to-primary/10 text-primary"}]},"agent-os":{label:"Agent OS",sections:[{title:"Agent OS Control Center",description:"Manage InnerCircle feature: relationship types, action types, scripts, plans & feature flags",icon:yi,path:"/admin/agent-os",color:"bg-gradient-to-br from-rose-500/20 to-pink-500/10 text-rose-600"},{title:"Listing Exchange",description:"Approve, feature, and moderate community listings",icon:zr,path:"/admin/listing-exchange",color:"bg-gradient-to-br from-blue-500/20 to-sky-500/10 text-blue-600"},{title:"Listing Leads",description:"View all leads from the public listings site with property & agent assignment",icon:Fo,path:"/admin/listing-leads",color:"bg-gradient-to-br from-teal-500/20 to-emerald-500/10 text-teal-600"},{title:"Public Site Leads",description:"Alerts signups, exit-intent captures & saved-home leads from listings.relevelup.com",icon:Fo,path:"/admin/public-site-leads",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Presentation Analytics",description:"Track agent presentation usage, views, and leads",icon:oy,path:"/admin/presentation-analytics",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"},{title:"Guest Book Analytics",description:"Track open house sign-in usage, visitors, and lead generation",icon:$u,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:nl,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:Hs,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:XS,path:"/admin/beta/homereel",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"}]},"lead-sites":{label:"Lead Sites",sections:[{title:"All Sites",description:"Overview of all agent websites with status and quick actions",icon:lc,path:"/admin/lead-sites",color:"bg-gradient-to-br from-sky-500/20 to-blue-500/10 text-sky-600"},{title:"MLS Feeds",description:"Manage MLS data feed connections, API keys, and coverage areas",icon:s9,path:"/admin/mls-feeds",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Lead Analytics",description:"Cross-site lead capture stats, conversions, and top-performing sites",icon:mo,path:"/admin/lead-site-analytics",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Website Interests",description:"Track interest form submissions from TheLocalMove.com",icon:Nr,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:Nr,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:Zl,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function WHe(){const s=In();return console.log("[AdminDashboard] render"),e.jsx(Cs,{title:"Admin Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Admin Dashboard"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage all aspects of your platform"})]}),e.jsx("div",{className:"w-full lg:w-80",children:e.jsx(Ybs,{})})]}),e.jsxs($r,{defaultValue:"users",className:"w-full",children:[e.jsx(Ur,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(GHe).map(([t,n])=>e.jsx(Zt,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(GHe).map(([t,n])=>e.jsx(ls,{value:t,className:"mt-6",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:n.sections.map(r=>e.jsxs(fe,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(Mt,{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(Pt,{className:"text-base",children:r.title})]}),e.jsx(Ae,{className:"pt-0",children:e.jsx(Hn,{className:"text-sm",children:r.description})})]},r.path))})},t))]})]})})}const Zbs=()=>{const{isAdmin:s}=gs(),t=In(),[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(!1),[c,d]=N.useState(null);N.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:b,error:v}=await q.from("app_tiles").select("*").order("name");if(v)throw v;r(b||[])}catch(b){console.error("Error loading apps:",b),ae.error("Failed to load apps")}finally{i(!1)}},h=async b=>{b.preventDefault();const v=new FormData(b.currentTarget),j={name:v.get("name"),description:v.get("description"),icon:v.get("icon"),app_id:v.get("app_id"),target_url:v.get("target_url"),required_tags:v.get("required_tags").split(",").map(_=>_.trim()).filter(Boolean)};try{if(c){const{error:_}=await q.from("app_tiles").update(j).eq("id",c.id);if(_)throw _;ae.success("App updated successfully")}else{const{error:_}=await q.from("app_tiles").insert([j]);if(_)throw _;ae.success("App created successfully")}o(!1),d(null),u()}catch(_){console.error("Error saving app:",_),ae.error("Failed to save app")}},p=async b=>{if(confirm("Are you sure you want to delete this app?"))try{const{error:v}=await q.from("app_tiles").delete().eq("id",b);if(v)throw v;ae.success("App deleted successfully"),u()}catch(v){console.error("Error deleting app:",v),ae.error("Failed to delete app")}},f=b=>{d(b),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(B,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(Wr,{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(bs,{open:l,onOpenChange:o,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{onClick:g,children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:c?"Edit App":"Create New App"}),e.jsx(Qn,{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(se,{htmlFor:"name",children:"App Name"}),e.jsx(ge,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"app_id",children:"App ID"}),e.jsx(ge,{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(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{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(se,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(ge,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"target_url",children:"Target URL"}),e.jsx(ge,{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(se,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(ge,{id:"required_tags",name:"required_tags",defaultValue:c==null?void 0:c.required_tags.join(", "),placeholder:"levelup-member, agent-connect"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Application Tiles"}),e.jsx(Hn,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Ae,{children:n.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsxs(B,{onClick:g,children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Icon"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"App ID"}),e.jsx(Ct,{children:"Target URL"}),e.jsx(Ct,{children:"Tags"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:n.map(b=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"text-2xl",children:b.icon}),e.jsx(ut,{className:"font-medium",children:b.name}),e.jsx(ut,{className:"font-mono text-sm",children:b.app_id}),e.jsx(ut,{className:"text-sm text-muted-foreground max-w-xs truncate",children:b.target_url}),e.jsx(ut,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:b.required_tags.map(v=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:v},v))})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>f(b),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(b.id),children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},b.id))})]})})]})})]})};function Vd({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ln,{to:"/admin",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(Wr,{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 KHe=({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(ze,{variant:"destructive",className:Et("gap-1",t),children:[e.jsx(Dl,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(ze,{variant:"destructive",className:Et("gap-1",t),children:[e.jsx(gr,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(ze,{className:Et("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(gr,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(ze,{variant:"secondary",className:Et("gap-1",t),children:[e.jsx(gr,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},oyt=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=Ua(),l=N.useRef(null),[o,c]=N.useState([]),[d,u]=N.useState(""),[h,p]=N.useState(!1),[f,g]=N.useState("upload"),[b,v]=N.useState(null),j=()=>{c([]),u(""),g("upload"),v(null),l.current&&(l.current.value="")},_=()=>{j(),t(!1)},S=M=>{const F=M.split(` `).map(Y=>Y.trim()).filter(Y=>Y);if(F.length===0)return[];const z=F[0].toLowerCase(),W=z.includes("first")||z.includes("last")||z.includes("email")||z.includes("name")||z.includes("phone")||z.includes("sms")||z.includes("consent")?F.slice(1):F,K=[];for(const Y of W){const ne=(Y.includes(" ")?Y.split(" "):Y.split(",")).map(oe=>oe.trim().replace(/^["']|["']$/g,""));if(ne.length>=2){let oe="",pe="",ce="",de="",ie;if(ne.length===2){const Me=ne[0].split(" ");oe=Me[0]||"",pe=Me.slice(1).join(" ")||"",ce=ne[1]}else if(ne.length===3)oe=ne[0],pe=ne[1],ce=ne[2];else if(ne.length===4)oe=ne[0],pe=ne[1],ce=ne[2],de=ne[3];else if(ne.length>=5){oe=ne[0],pe=ne[1],ce=ne[2],de=ne[3];const Me=ne[4].toLowerCase();ie=Me==="true"||Me==="yes"||Me==="1"||Me==="y"}const _e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ce);K.push({firstName:oe.trim(),lastName:pe.trim(),email:ce.trim().toLowerCase(),phone:de.trim()||void 0,smsConsent:ie,isValid:_e&&oe.trim().length>0,error:_e?oe.trim()?void 0:"Missing name":"Invalid email"})}}return K},A=M=>{var V;const F=(V=M.target.files)==null?void 0:V[0];if(!F)return;const z=new FileReader;z.onload=W=>{var ee;const K=(ee=W.target)==null?void 0:ee.result,Y=S(K);if(Y.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(Y),g("preview")},z.readAsText(F)},T=async()=>{const M=o.filter(z=>z.isValid);if(M.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const F=r||d||null;p(!0);try{const{data:{session:z}}=await q.auth.getSession(),V=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z==null?void 0:z.access_token}`},body:JSON.stringify({users:M.map(K=>({firstName:K.firstName,lastName:K.lastName,email:K.email,phone:K.phone,smsConsent:K.smsConsent})),brokerageId:F})}),W=await V.json();if(!V.ok)throw new Error(W.error||"Failed to import users");v(W),g("result"),W.created>0&&a(),i({title:"Import Complete",description:`${W.created} user(s) created successfully.${W.failed>0?` ${W.failed} failed.`:""}`})}catch(z){console.error("Import error:",z),i({title:"Import Failed",description:z.message||"Failed to import users",variant:"destructive"})}finally{p(!1)}},D=o.filter(M=>M.isValid).length,L=o.filter(M=>!M.isValid).length;return e.jsx(bs,{open:s,onOpenChange:_,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(yw,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Qn,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),f==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:A,className:"hidden"}),e.jsx(Sa,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(B,{onClick:()=>{var M;return(M=l.current)==null?void 0:M.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Expected CSV Format:"}),e.jsxs("code",{className:"text-xs block bg-background p-2 rounded",children:["First Name, Last Name, Email, Phone, SMS Consent",e.jsx("br",{}),"John, Doe, john@example.com, 555-123-4567, yes",e.jsx("br",{}),"Jane, Smith, jane@example.com, 555-987-6543, true"]}),e.jsx("p",{className:"text-muted-foreground mt-2 text-xs",children:"Phone and SMS Consent columns are optional. SMS Consent accepts: yes/no, true/false, 1/0, y/n."})]})]}),f==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!r&&n&&n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Assign to Brokerage (optional)"}),e.jsxs(us,{value:d||"none",onValueChange:M=>u(M==="none"?"":M),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select a brokerage..."})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No brokerage"}),n.map(M=>e.jsx(Ze,{value:M.id,children:M.name},M.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(xr,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[D," valid"]})]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Gi,{className:"h-4 w-4"}),e.jsxs("span",{children:[L," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{className:"bg-muted/30",children:[e.jsx(Ct,{children:"First Name"}),e.jsx(Ct,{children:"Last Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Phone"}),e.jsx(Ct,{children:"SMS"}),e.jsx(Ct,{children:"Status"})]})}),e.jsx(pa,{children:o.slice(0,100).map((M,F)=>e.jsxs(Gs,{children:[e.jsx(ut,{children:M.firstName}),e.jsx(ut,{children:M.lastName}),e.jsx(ut,{children:M.email}),e.jsx(ut,{className:"text-muted-foreground",children:M.phone||"-"}),e.jsx(ut,{className:"text-muted-foreground",children:M.smsConsent===!0?"✓":M.smsConsent===!1?"✗":"-"}),e.jsx(ut,{children:M.isValid?e.jsx(ze,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(ze,{variant:"destructive",children:M.error||"Invalid"})})]},F))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),f==="result"&&b&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(xr,{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:[b.created," agent(s) created and invited"]}),b.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[b.failed," failed to create"]})]}),b.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:[b.errors.slice(0,10).map((M,F)=>e.jsxs("li",{children:["• ",M]},F)),b.errors.length>10&&e.jsxs("li",{children:["...and ",b.errors.length-10," more"]})]})]})]}),e.jsxs(Xn,{children:[f==="upload"&&e.jsx(B,{variant:"outline",onClick:_,children:"Cancel"}),f==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:j,children:"Back"}),e.jsx(B,{onClick:T,disabled:h||D===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${D} Agent${D!==1?"s":""}`})]}),f==="result"&&e.jsx(B,{onClick:_,children:"Done"})]})]})})};function Pc({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Ct,{className:Et("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(Bu,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(om,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(sm,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function CU(s=null,t=null){const[n,r]=N.useState(s),[a,i]=N.useState(t),l=N.useCallback(c=>{n===c?a==="asc"?i("desc"):a==="desc"?(r(null),i(null)):i("asc"):(r(c),i("asc"))},[n,a]),o=N.useCallback((c,d)=>{if(!n||!a||!d[n])return c;const u=d[n];return[...c].sort((h,p)=>{const f=u(h),g=u(p);if(f==null&&g==null)return 0;if(f==null)return 1;if(g==null)return-1;let b;return typeof f=="string"&&typeof g=="string"?b=f.localeCompare(g,void 0,{sensitivity:"base"}):b=f-g,a==="asc"?b:-b})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const Qbs=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:ua},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:vo},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:uh}];function lyt({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=N.useState("custom"),[l,o]=N.useState(""),[c,d]=N.useState(""),u=X7t(),h=f=>{i(f.type),o(f.title),d(f.message)},p=async f=>{if(f.preventDefault(),!l.trim()){Dr({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}),Dr({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{Dr({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(uh,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(Qn,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(se,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Qbs.map((f,g)=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(f),className:"text-xs",children:[e.jsx(f.icon,{className:"h-3 w-3 mr-1"}),f.title]},g))})]}),e.jsxs("form",{onSubmit:p,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(us,{value:a,onValueChange:f=>i(f),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4"})," Custom"]})}),e.jsx(Ze,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(Ze,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(Ze,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zl,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ge,{id:"title",value:l,onChange:f=>o(f.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Ts,{id:"message",value:c,onChange:f=>d(f.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:u.isPending,children:[e.jsx(uh,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const U2e={points_earned:{label:"Points Earned",icon:vo,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:zr,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:Zl,color:"bg-green-500"},custom:{label:"Custom",icon:un,color:"bg-purple-500"}};function Xbs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),{data:l=[],isLoading:o}=lt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:h}=await q.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(h)throw h;const p=[...new Set([...u.map(b=>b.user_id),...u.map(b=>b.created_by).filter(Boolean)])],{data:f}=await q.from("profiles").select("id, name, email").in("id",p),g=new Map((f==null?void 0:f.map(b=>[b.id,b]))||[]);return u.map(b=>{var v,j,_;return{...b,user_name:((v=g.get(b.user_id))==null?void 0:v.name)||"Unknown",user_email:((j=g.get(b.user_id))==null?void 0:j.email)||"",creator_name:b.created_by?((_=g.get(b.created_by))==null?void 0:_.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var g,b;const h=((g=u.user_name)==null?void 0:g.toLowerCase().includes(s.toLowerCase()))||((b=u.user_email)==null?void 0:b.toLowerCase().includes(s.toLowerCase()))||u.title.toLowerCase().includes(s.toLowerCase()),p=n==="all"||u.celebration_type===n,f=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return h&&p&&f}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(U2e).reduce((u,h)=>(u[h]=l.filter(p=>p.celebration_type===h).length,u),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(uh,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Hn,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Ae,{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(_r,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"Filter by type"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),Object.entries(U2e).map(([u,h])=>e.jsx(Ze,{value:u,children:h.label},u))]})]}),e.jsxs(us,{value:a,onValueChange:i,children:[e.jsx(cs,{className:"w-[140px]",children:e.jsx(hs,{placeholder:"Status"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Status"}),e.jsx(Ze,{value:"seen",children:"Seen"}),e.jsx(Ze,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Points"}),e.jsx(Ct,{children:"Created By"}),e.jsx(Ct,{children:"Created"}),e.jsx(Ct,{children:"Status"})]})}),e.jsx(pa,{children:c.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=U2e[u.celebration_type],p=h.icon;return e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(p,{className:"h-3 w-3"}),h.label]})}),e.jsx(ut,{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(ut,{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(ut,{children:u.points_amount?e.jsxs(ze,{variant:"secondary",children:["+",u.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:u.creator_name})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:ks(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(ut,{children:u.seen_at?e.jsx(ze,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(ze,{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 Jbs=()=>{const{user:s}=gs(),{toast:t}=Ua(),[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(!1),[c,d]=N.useState("all"),[u,h]=N.useState("all"),[p,f]=N.useState("new"),[g,b]=N.useState(new Set),v=N.useCallback(async()=>{try{i(!0);const{data:K,error:Y}=await q.from("profiles").select("id, name, email, phone, is_trial, trial_started_at, trial_expires_at, subscription_status, subscription_end_date, converted_from_trial_at, created_at, last_login").or("is_trial.eq.true,subscription_status.eq.trialing,converted_from_trial_at.not.is.null");if(Y)throw Y;const{data:ee,error:ne}=await q.from("trial_email_exports").select("user_id");if(ne)throw ne;const oe=new Set((ee||[]).map(ce=>ce.user_id)),pe=(K||[]).map(ce=>({...ce,converted_from_trial_at:ce.converted_from_trial_at??null,already_exported:oe.has(ce.id)}));pe.sort((ce,de)=>new Date(de.created_at).getTime()-new Date(ce.created_at).getTime()),r(pe)}catch(K){console.error("Error loading trial users:",K),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);N.useEffect(()=>{v()},[v]);const j=K=>K.trial_started_at?"ghl":"stripe",_=K=>K.trial_expires_at?K.trial_expires_at:K.subscription_end_date?K.subscription_end_date:null,S=K=>K.converted_from_trial_at!==null,A=K=>{if(S(K))return!1;const Y=_(K);return Y?new Date(Y).getTime()<=Date.now():!1},T=n.filter(K=>!(c!=="all"&&j(K)!==c||u==="active"&&(A(K)||S(K))||u==="expired"&&!A(K)||u==="converted"&&!S(K)||p==="new"&&K.already_exported||p==="exported"&&!K.already_exported)),D=()=>{g.size===T.length?b(new Set):b(new Set(T.map(K=>K.id)))},L=K=>{const Y=new Set(g);Y.has(K)?Y.delete(K):Y.add(K),b(Y)},M=async()=>{if(g.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const K=n.filter(ie=>g.has(ie.id)),Y="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",ee=K.map(ie=>{const ye=(ie.name||"").split(" "),_e=ye[0]||"",Me=ye.slice(1).join(" ")||"",Te=j(ie)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",Ce=S(ie)?"Converted":A(ie)?"Expired":"Active",Ee=ie.created_at?new Date(ie.created_at).toLocaleDateString():"",De=_(ie)?new Date(_(ie)).toLocaleDateString():"";return`"${_e}","${Me}","${ie.email}","${ie.phone||""}","${Te}","${Ce}","${Ee}","${De}"`}),ne=[Y,...ee].join(` `),oe=new Blob([ne],{type:"text/csv"}),pe=URL.createObjectURL(oe),ce=document.createElement("a");ce.href=pe,ce.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ce.click(),URL.revokeObjectURL(pe);const de=K.filter(ie=>!ie.already_exported).map(ie=>({user_id:ie.id,exported_by:s.id}));if(de.length>0){const{error:ie}=await q.from("trial_email_exports").upsert(de,{onConflict:"user_id"});ie&&console.error("Error marking exports:",ie)}t({title:"Export complete",description:`Downloaded ${K.length} trial user(s). ${de.length} newly marked as exported.`}),b(new Set),v()}catch(K){console.error("Export error:",K),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},F=n.filter(K=>!K.already_exported).length,z=n.filter(K=>K.already_exported).length,V=n.filter(K=>S(K)).length,W=n.filter(K=>!A(K)&&!S(K)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-4",children:[e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Hn,{children:"Total"}),e.jsx(Pt,{className:"text-2xl",children:n.length})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Hn,{children:"New (Not Exported)"}),e.jsx(Pt,{className:"text-2xl text-green-600",children:F})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Hn,{children:"Active Trials"}),e.jsx(Pt,{className:"text-2xl",children:W})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Hn,{children:"Converted 🎉"}),e.jsx(Pt,{className:"text-2xl text-primary",children:V})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Hn,{children:"Already Exported"}),e.jsx(Pt,{className:"text-2xl text-muted-foreground",children:z})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(us,{value:p,onValueChange:K=>f(K),children:[e.jsx(cs,{className:"w-[160px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Users"}),e.jsx(Ze,{value:"new",children:"New Only"}),e.jsx(Ze,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(us,{value:c,onValueChange:K=>d(K),children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Trial Types"}),e.jsx(Ze,{value:"stripe",children:"Credit Card Trial"}),e.jsx(Ze,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(us,{value:u,onValueChange:K=>h(K),children:[e.jsx(cs,{className:"w-[160px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),e.jsx(Ze,{value:"active",children:"Active Trial"}),e.jsx(Ze,{value:"expired",children:"Expired"}),e.jsx(Ze,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(B,{onClick:M,disabled:l||g.size===0,children:[l?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Export Selected (",g.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Ct,{className:"w-[40px]",children:e.jsx(hi,{checked:T.length>0&&g.size===T.length,onCheckedChange:D})}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Trial Type"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Signup Date"}),e.jsx(Ct,{children:"Last Login"}),e.jsx(Ct,{children:"Expires / Renews"}),e.jsx(Ct,{children:"Exported"})]})}),e.jsx(pa,{children:T.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):T.map(K=>{const Y=j(K),ee=S(K),ne=A(K),oe=_(K);return e.jsxs(Gs,{className:`hover:bg-muted/30 ${ee?"bg-primary/5":""}`,children:[e.jsx(ut,{children:e.jsx(hi,{checked:g.has(K.id),onCheckedChange:()=>L(K.id)})}),e.jsx(ut,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[K.name,ee&&e.jsx(mo,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(ut,{className:"text-muted-foreground",children:K.email}),e.jsx(ut,{children:Y==="stripe"?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(ff,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Hs,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(ut,{children:ee?e.jsxs(ze,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(mo,{className:"h-3 w-3"}),"Converted"]}):ne?e.jsx(ze,{variant:"destructive",children:"Expired"}):e.jsx(ze,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(ut,{className:"text-sm",children:K.created_at?new Date(K.created_at).toLocaleDateString():"—"}),e.jsx(ut,{className:"text-sm",children:K.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(K.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(K.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(ut,{className:"text-sm",children:ee&&oe?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(oe).toLocaleDateString()]}):oe?new Date(oe).toLocaleDateString():"—"}),e.jsx(ut,{children:K.already_exported?e.jsx(xr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ze,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},K.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",T.length," of ",n.length," trial users · ",V," converted to paid"]})]})},e_s=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,t_s=()=>{const[s,t]=N.useState([]),[n,r]=N.useState(!0);N.useEffect(()=>{(async()=>{const{data:l,error:o}=await q.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){ae.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[ks(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(e_s).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(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(bn,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Pt,{className:"text-lg",children:"User Deletion History"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Ae,{children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Date"}),e.jsx(Ct,{children:"User"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Brokerage"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Deleted By"})]})}),e.jsx(pa,{children:s.map(i=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"whitespace-nowrap text-sm",children:ks(new Date(i.created_at),"MMM d, yyyy h:mm a")}),e.jsx(ut,{className:"font-medium",children:i.deleted_user_name||"—"}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:i.deleted_user_email||"—"}),e.jsx(ut,{children:i.brokerage_name||"—"}),e.jsx(ut,{children:e.jsx(ze,{variant:i.deletion_type==="deleted"?"destructive":"secondary",children:i.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(ut,{className:"text-sm",children:i.deleted_by_name||i.deleted_by_email||"—"})]},i.id))})]})})]})},s6=s=>{const{user:t}=gs(),n=Gt(),r=lt({queryKey:["teams",s],queryFn:async()=>{let h=q.from("teams").select("*").order("created_at",{ascending:!1});s&&(h=h.eq("brokerage_id",s));const{data:p,error:f}=await h;if(f)throw f;return p||[]},enabled:!!t}),a=h=>lt({queryKey:["team-members",h],queryFn:async()=>{const{data:p,error:f}=await q.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(f)throw f;const g=(p||[]).map(j=>j.user_id),{data:b}=await q.from("profiles").select("id, name, email, avatar_url").in("id",g),v=new Map((b||[]).map(j=>[j.id,j]));return(p||[]).map(j=>({...j,profile:v.get(j.user_id)||null}))},enabled:!!h}),i=gt({mutationFn:async h=>{const p={name:h.name,created_by:t.id,description:h.description,contact_visibility:h.contact_visibility,lead_pond_enabled:h.lead_pond_enabled,shared_assets_enabled:h.shared_assets_enabled};h.brokerage_id&&(p.brokerage_id=h.brokerage_id);const{data:f,error:g}=await q.from("teams").insert(p).select().single();if(g)throw g;return f},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team created!")},onError:h=>{ae.error("Failed to create team: "+h.message)}}),l=gt({mutationFn:async({id:h,...p})=>{const{data:f,error:g}=await q.from("teams").update(p).eq("id",h).select().single();if(g)throw g;return f},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team updated")},onError:h=>{ae.error("Failed to update team: "+h.message)}}),o=gt({mutationFn:async h=>{const{error:p}=await q.from("teams").delete().eq("id",h);if(p)throw p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team deleted")},onError:h=>{ae.error("Failed to delete team: "+h.message)}}),c=gt({mutationFn:async h=>{const{data:p,error:f}=await q.from("team_members").insert({team_id:h.team_id,user_id:h.user_id,role:h.role||"team_member"}).select().single();if(f)throw f.message.includes("duplicate")||f.message.includes("unique")?new Error("This agent is already on a team. They must be removed from their current team first."):f;return p},onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["team-members",p.team_id]}),ae.success("Member added to team")},onError:h=>{ae.error(h.message)}}),d=gt({mutationFn:async h=>{const{error:p}=await q.from("team_members").delete().eq("id",h.member_id);if(p)throw p},onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["team-members",p.team_id]}),ae.success("Member removed from team")},onError:h=>{ae.error("Failed to remove member: "+h.message)}}),u=gt({mutationFn:async h=>{const{error:p}=await q.from("team_members").update({role:h.role}).eq("id",h.member_id);if(p)throw p},onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["team-members",p.team_id]}),ae.success("Member role updated")},onError:h=>{ae.error("Failed to update role: "+h.message)}});return{teams:r.data||[],isLoading:r.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:u,useTeamMembers:a}},s_s=()=>{const{user:s}=gs();return lt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_contacts",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},cyt=s=>{const{user:t}=gs(),n=Gt(),r=lt({queryKey:["lead-pond",s],queryFn:async()=>{const{data:o,error:c}=await q.from("team_lead_pond").select("*").eq("team_id",s).order("created_at",{ascending:!1});if(c)throw c;if(!o||o.length===0)return[];const d=o.map(j=>j.contact_id),u=[...new Set(o.map(j=>j.added_by))],h=o.filter(j=>j.claimed_by).map(j=>j.claimed_by),p=[...new Set([...u,...h])],[f,g]=await Promise.all([q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",d),q.from("profiles").select("id, name, avatar_url").in("id",p)]),b=new Map((f.data||[]).map(j=>[j.id,j])),v=new Map((g.data||[]).map(j=>[j.id,j]));return o.map(j=>({...j,status:j.claimed_by?"claimed":"available",contact:b.get(j.contact_id)||null,contributor:v.get(j.added_by)||null,claimer:j.claimed_by&&v.get(j.claimed_by)||null}))},enabled:!!s&&!!t}),a=gt({mutationFn:async o=>{const{data:c,error:d}=await q.rpc("add_to_lead_pond",{_contact_id:o.contact_id,_team_id:o.team_id,_notes:o.notes||null});if(d)throw d;return c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Contact added to Lead Pond")},onError:o=>{ae.error(o.message)}}),i=gt({mutationFn:async o=>{const{error:c}=await q.rpc("claim_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Lead claimed!")},onError:o=>{ae.error(o.message)}}),l=gt({mutationFn:async o=>{const{error:c}=await q.rpc("return_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Lead returned to pond")},onError:o=>{ae.error(o.message)}});return{leadPondItems:r.data||[],isLoading:r.isLoading,addToLeadPond:a,claimLead:i,returnLead:l}},n_s=()=>{const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["team-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ae.success("Contact transferred successfully")},onError:t=>{ae.error(t.message||"Failed to transfer contact")}})};function dyt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var T;const{user:i}=gs(),{data:l}=Xv(),{useTeamMembers:o}=s6(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=n_s(),[u,h]=N.useState(null),[p,f]=N.useState(""),[g,b]=N.useState(!1),v=c.filter(D=>D.user_id!==(i==null?void 0:i.id)),j=async()=>{if(u){b(!0);try{for(const D of n)await d.mutateAsync({contactId:D,toUserId:u,notes:p||void 0});t(!1),h(null),f(""),a==null||a()}catch{}finally{b(!1)}}},_=v.find(D=>D.user_id===u),S=n.length>1,A=r.length>0?S?`${r.length} contacts`:r[0]:S?`${n.length} contacts`:"this contact";return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(pw,{className:"h-5 w-5"}),"Transfer ",A]}),e.jsxs(Qn,{children:["Select a team member to transfer ",S?"these contacts":"this contact"," to. The contact will be removed from the current owner's CRM and added to the selected member's."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium mb-2 block",children:"Transfer to:"}),e.jsx("div",{className:"space-y-1 max-h-[240px] overflow-y-auto",children:v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):v.map(D=>{var L,M,F;return e.jsxs("button",{onClick:()=>h(D.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===D.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:((L=D.profile)==null?void 0:L.avatar_url)||""}),e.jsx(ia,{className:"text-xs",children:(((M=D.profile)==null?void 0:M.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((F=D.profile)==null?void 0:F.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:D.role.replace("_"," ")})]})]},D.user_id)})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Ts,{id:"transfer-notes",value:p,onChange:D=>f(D.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:j,disabled:!u||g,children:[g?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pw,{className:"h-4 w-4 mr-2"}),"Transfer",_?` to ${(T=_.profile)==null?void 0:T.name}`:""]})]})]})})}const JIe=()=>{const s=In(),{data:t,isLoading:n}=s_s(),{data:r}=Xv(),[a,i]=N.useState(""),[l,o]=N.useState("all"),[c,d]=N.useState(null),[u,h]=N.useState(""),p=(r==null?void 0:r.role)==="team_leader",f=N.useMemo(()=>{if(!t)return[];const b=new Map;return t.forEach(v=>{b.has(v.owner_user_id)||b.set(v.owner_user_id,{id:v.owner_user_id,name:v.owner_name||"Unknown",avatar:v.owner_avatar_url})}),Array.from(b.values())},[t]),g=N.useMemo(()=>{if(!t)return[];let b=t;if(l!=="all"&&(b=b.filter(v=>v.owner_user_id===l)),a.trim()){const v=a.toLowerCase();b=b.filter(j=>{var _,S,A;return(j.first_name+" "+(j.last_name||"")).toLowerCase().includes(v)||((_=j.email)==null?void 0:_.toLowerCase().includes(v))||((S=j.phone)==null?void 0:S.includes(v))||((A=j.owner_name)==null?void 0:A.toLowerCase().includes(v))})}return b},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-10 w-full"}),e.jsx(Ws,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(_n,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Team Contacts"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team contact sharing is not enabled, or you're not on a team. Ask your manager about contact visibility settings."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(fe,{children:e.jsx(Ae,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:b=>i(b.target.value),className:"pl-9"})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(cs,{className:"w-[200px]",children:e.jsx(hs,{placeholder:"Filter by agent"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Team Members"}),f.map(b=>e.jsx(Ze,{value:b.id,children:b.name},b.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," contact",g.length!==1?"s":""," from ",f.length," teammate",f.length!==1?"s":""]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0 overflow-x-auto",children:e.jsxs(ha,{className:"min-w-[800px]",children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Contact Info"}),e.jsx(Ct,{children:"Address"}),e.jsx(Ct,{children:"Lead Source"}),e.jsx(Ct,{children:"Date Added"}),p&&e.jsx(Ct,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(pa,{children:g.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:p?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):g.map(b=>e.jsxs(Gs,{className:`hover:bg-accent/50 ${p?"cursor-pointer":""}`,onClick:p?()=>s(`/mission-control/contacts/${b.id}`):void 0,children:[e.jsx(ut,{className:"font-medium",children:e.jsxs("span",{className:p?"hover:text-primary hover:underline transition-colors":"",children:[b.first_name," ",b.last_name||""]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(aa,{className:"h-6 w-6",children:[e.jsx(ri,{src:b.owner_avatar_url||""}),e.jsx(ia,{className:"text-[10px]",children:(b.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:b.owner_name||"Unknown"})]})}),e.jsx(ut,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[b.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Hs,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:b.email})]}),b.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Pr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:b.phone})]}),!b.email&&!b.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(ut,{children:b.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Ca,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:b.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(ut,{children:b.lead_source?e.jsx(ze,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:b.lead_source}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:ks(new Date(b.created_at),"MMM d, yyyy")})}),p&&e.jsx(ut,{children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:v=>{v.stopPropagation(),d(b.id),h(`${b.first_name} ${b.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(pw,{className:"h-4 w-4"})})})]},b.id))})]})})}),e.jsx(dyt,{open:!!c,onOpenChange:b=>{b||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},ePe=({teamId:s})=>{const{user:t}=gs(),{leadPondItems:n,isLoading:r,claimLead:a,returnLead:i}=cyt(s);if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",n.length,"loading:",r),r)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(c=>e.jsx(Ws,{className:"h-20 w-full"},c))});if(n.length===0)return e.jsx(fe,{children:e.jsxs(Ae,{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."})]})});const l=n.filter(c=>c.status==="available"),o=n.filter(c=>c.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",l.length,")"]}),l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads available right now."}):e.jsx("div",{className:"space-y-2",children:l.map(c=>{var d,u,h,p,f,g,b;return e.jsx(fe,{children:e.jsxs(Ae,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((u=c.contact)==null?void 0:u.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 mt-1",children:[((h=c.contact)==null?void 0:h.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Hs,{className:"h-3 w-3"})," ",c.contact.email]}),((p=c.contact)==null?void 0:p.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Pr,{className:"h-3 w-3"})," ",c.contact.phone]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs(aa,{className:"h-4 w-4",children:[e.jsx(ri,{src:((f=c.contributor)==null?void 0:f.avatar_url)||""}),e.jsx(ia,{className:"text-[8px]",children:(((g=c.contributor)==null?void 0:g.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((b=c.contributor)==null?void 0:b.name)||"Unknown"]})]})]}),e.jsxs(B,{size:"sm",onClick:()=>a.mutate(c.id),disabled:a.isPending,children:[e.jsx(l9,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},c.id)})})]}),o.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Claimed (",o.length,")"]}),e.jsx("div",{className:"space-y-2",children:o.map(c=>{var d,u,h;return e.jsx(fe,{className:"opacity-75",children:e.jsxs(Ae,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((u=c.contact)==null?void 0:u.last_name)||""]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(ze,{variant:"secondary",className:"text-xs",children:["Claimed by ",((h=c.claimer)==null?void 0:h.name)||"Unknown"]})})]}),c.claimed_by===(t==null?void 0:t.id)&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>i.mutate(c.id),disabled:i.isPending,children:[e.jsx(Fh,{className:"mr-1 h-3 w-3"}),"Return"]})]})},c.id)})})]})]})},uyt=({teamId:s})=>{const{useTeamMembers:t}=s6(),{data:n=[]}=t(s),r=n.map(f=>f.user_id),a=new Map(n.map(f=>[f.user_id,f.profile])),{data:i=[],isLoading:l}=lt({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await q.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",r).neq("status","archived").order("created_at",{ascending:!1});if(g)throw g;return f||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=lt({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await q.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",r).order("event_date",{ascending:!1});if(g)throw g;return f||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=lt({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await q.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",r).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(g)throw g;return f||[]},enabled:r.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(Ws,{className:"h-20 w-full"},f))});const p=f=>{const g=a.get(f);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(fe,{children:e.jsxs(Ae,{className:"flex items-center gap-3 p-4",children:[e.jsx(oy,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:i.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Presentations"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"flex items-center gap-3 p-4",children:[e.jsx(zr,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:o.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Guest Books"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"flex items-center gap-3 p-4",children:[e.jsx(vr,{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($r,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Zt,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Zt,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(ls,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(q2e,{icon:e.jsx(oy,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(f=>{const g=p(f.owner_user_id);return e.jsx(fe,{children:e.jsxs(Ae,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(aa,{className:"h-8 w-8 shrink-0",children:[e.jsx(ri,{src:g.avatar}),e.jsx(ia,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",ks(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(ze,{variant:f.status==="published"?"default":"secondary",className:"text-xs capitalize",children:f.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ir,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})}),e.jsx(ls,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(q2e,{icon:e.jsx(zr,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(f=>{const g=p(f.agent_id);return e.jsx(fe,{children:e.jsxs(Ae,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(aa,{className:"h-8 w-8 shrink-0",children:[e.jsx(ri,{src:g.avatar}),e.jsx(ia,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",ks(new Date(f.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[f.is_active?e.jsx(ze,{className:"text-xs",children:"Active"}):e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(_n,{className:"h-3 w-3"}),f.visitor_count||0]})]})]})},f.id)})}),e.jsx(ls,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(q2e,{icon:e.jsx(vr,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(f=>{const g=p(f.owner_user_id);return e.jsx(fe,{children:e.jsxs(Ae,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(aa,{className:"h-8 w-8 shrink-0",children:[e.jsx(ri,{src:g.avatar}),e.jsx(ia,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.title||f.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",ks(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(ze,{variant:"secondary",className:"text-xs capitalize",children:f.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ir,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})})]})]})},q2e=({icon:s,label:t})=>e.jsx(fe,{children:e.jsxs(Ae,{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})]})}),hyt=({team:s,brokerageAgents:t,onBack:n,onUpdate:r,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var L,M;const{useTeamMembers:u}=s6(),{data:h=[],isLoading:p}=u(s.id),[f,g]=N.useState(!1),[b,v]=N.useState(""),[j,_]=N.useState("team_member"),{data:S}=lt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:F}=await q.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),z=new Map;return(F||[]).forEach(V=>{var W;z.set(V.user_id,((W=V.teams)==null?void 0:W.name)||"another team")}),z}}),A=new Set(h.map(F=>F.user_id)),T=t.filter(F=>!A.has(F.id)),D=async()=>{b&&(await a(b,j),v(""),_("team_member"),g(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(B,{variant:"ghost",onClick:n,className:"mb-2",children:"← Back to Teams"}),e.jsxs($r,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"members",children:"Members"}),e.jsxs(Zt,{value:"contacts",children:[e.jsx(CA,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Zt,{value:"lead-pond",children:[e.jsx(pb,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Zt,{value:"shared-assets",children:[e.jsx(yf,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(ls,{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(bs,{open:f,onOpenChange:g,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Fo,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add Team Member"}),e.jsxs(Qn,{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(se,{children:"Agent"}),e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[b&&(((L=T.find(F=>F.id===b))==null?void 0:L.name)||((M=T.find(F=>F.id===b))==null?void 0:M.email))||"Select an agent",e.jsx(Hg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(zo,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search agents..."}),e.jsxs(e0,{children:[e.jsx(t0,{children:"No agents found."}),e.jsx(s0,{children:T.map(F=>{const z=S==null?void 0:S.get(F.id);return e.jsxs(ex,{value:F.name||F.email||F.id,disabled:!!z,onSelect:()=>v(F.id),children:[e.jsx(Lr,{className:Et("mr-2 h-4 w-4",b===F.id?"opacity-100":"opacity-0")}),F.name||F.email,z&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(on ",z,")"]})]},F.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Role"}),e.jsxs(us,{value:j,onValueChange:_,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"team_leader",children:"Team Leader"}),e.jsx(Ze,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx(B,{onClick:D,disabled:!b||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),p?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(F=>e.jsx(Ws,{className:"h-16 w-full"},F))}):h.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(_n,{className:"h-10 w-10 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No members yet. Add agents to this team."})]})}):e.jsx("div",{className:"space-y-2",children:h.map(F=>{var z,V,W,K,Y;return e.jsx(fe,{children:e.jsxs(Ae,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:((z=F.profile)==null?void 0:z.avatar_url)||""}),e.jsx(ia,{children:(((V=F.profile)==null?void 0:V.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((W=F.profile)==null?void 0:W.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(K=F.profile)==null?void 0:K.email})]}),F.role==="team_leader"?e.jsxs(ze,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(xf,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(ze,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(us,{value:F.role,onValueChange:ee=>l(F.id,ee),children:[e.jsx(cs,{className:"w-[140px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"team_leader",children:"Team Leader"}),e.jsx(Ze,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx($9,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove Member?"}),e.jsxs(Mo,{children:["Remove ",((Y=F.profile)==null?void 0:Y.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>i(F.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},F.id)})})]}),e.jsx(ls,{value:"contacts",className:"space-y-4",children:e.jsx(JIe,{})}),s.lead_pond_enabled&&e.jsx(ls,{value:"lead-pond",className:"space-y-4",children:e.jsx(ePe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(ls,{value:"shared-assets",className:"space-y-4",children:e.jsx(uyt,{teamId:s.id})}),e.jsxs(ls,{value:"settings",className:"space-y-4",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{className:"text-lg",children:"Team Settings"}),e.jsx(Hn,{children:"Configure how this team operates."})]}),e.jsxs(Ae,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Team Name"}),e.jsx(ge,{defaultValue:s.name,onBlur:F=>{F.target.value!==s.name&&r({name:F.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{defaultValue:s.description||"",onBlur:F=>{F.target.value!==(s.description||"")&&r({description:F.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact Visibility"}),e.jsxs(us,{defaultValue:s.contact_visibility,onValueChange:F=>r({contact_visibility:F}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(Ze,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(Ze,{value:"full_team",children:"Full Team — All team members can see shared contacts"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls whether team leaders and members can view each other's contacts."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(vn,{checked:s.lead_pond_enabled,onCheckedChange:F=>r({lead_pond_enabled:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(vn,{checked:s.shared_assets_enabled,onCheckedChange:F=>r({shared_assets_enabled:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(vn,{checked:s.shared_videos_enabled??!1,onCheckedChange:F=>r({shared_videos_enabled:F})})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsxs(B,{variant:"destructive",size:"sm",children:[e.jsx(bn,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Team?"}),e.jsxs(Mo,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},myt=({open:s,onOpenChange:t,onCreateTeam:n,isCreating:r,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=N.useState(1),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,b]=N.useState(""),[v,j]=N.useState(""),[_,S]=N.useState([]),A=()=>{d(1),h(""),f(""),b(""),j(""),S([])},T=F=>{F||A(),t(F)},D=async()=>{const F=g&&g!=="none"?g:o||null;await n({name:u.trim(),description:p.trim()||void 0,brokerage_id:F,leaderId:v||void 0,memberIds:_.length>0?_:void 0}),A()},L=F=>{F!==v&&S(z=>z.includes(F)?z.filter(V=>V!==F):[...z,F])},M=a.filter(F=>F.id!==v);return e.jsx(bs,{open:s,onOpenChange:T,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Qn,{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:Et("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Et("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(se,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(ge,{id:"team-name",value:u,onChange:F=>h(F.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"team-desc",children:"Description"}),e.jsx(Ts,{id:"team-desc",value:p,onChange:F=>f(F.target.value),placeholder:"What is this team focused on?",rows:3})]}),i&&l&&l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brokerage"}),e.jsxs(us,{value:g,onValueChange:b,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"No brokerage (independent team)"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No brokerage (independent)"}),l.map(F=>e.jsx(Ze,{value:F.id,children:F.name},F.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-1.5",children:[e.jsx(xf,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(us,{value:v,onValueChange:F=>{j(F),S(z=>z.filter(V=>V!==F))},children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select a team leader (optional)"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No leader for now"}),a.map(F=>e.jsx(Ze,{value:F.id,children:F.name||F.email||"Unknown"},F.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-1.5",children:[e.jsx(Fo,{className:"h-3.5 w-3.5"}),"Initial Members",_.length>0&&e.jsxs(ze,{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:M.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(_n,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):M.map(F=>{const z=_.includes(F.id);return e.jsxs("button",{type:"button",className:Et("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",z&&"bg-primary/5"),onClick:()=>L(F.id),children:[e.jsxs(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:F.avatar_url||""}),e.jsx(ia,{className:"text-xs",children:(F.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:F.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:F.email})]}),e.jsx("div",{className:Et("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",z?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:z&&e.jsx(Lr,{className:"h-3 w-3"})})]},F.id)})})]})]})}),e.jsx(Xn,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(za,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>d(1),children:[e.jsx(Wr,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(B,{onClick:D,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},r_s=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=s6(),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(""),{data:g}=lt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:T,error:D}=await q.from("brokerages").select("id, name").order("name");if(D)throw D;return T||[]}}),{data:b}=lt({queryKey:["admin-team-member-info",s.map(T=>T.id).join(",")],queryFn:async()=>{var F;if(s.length===0)return{};const{data:T}=await q.from("team_members").select("team_id, user_id, role").in("team_id",s.map(z=>z.id));if(!T)return{};const D=T.filter(z=>z.role==="team_leader").map(z=>z.user_id);let L={};if(D.length>0){const{data:z}=await q.from("profiles").select("id, name").in("id",D);z&&(L=Object.fromEntries(z.map(V=>[V.id,{name:V.name}])))}const M={};for(const z of s){const V=T.filter(K=>K.team_id===z.id),W=V.find(K=>K.role==="team_leader");M[z.id]={count:V.length,leaderName:W&&((F=L[W.user_id])==null?void 0:F.name)||null}}return M},enabled:s.length>0}),v=(u==null?void 0:u.brokerage_id)||null,{data:j}=lt({queryKey:["brokerage-agents-for-teams",v],queryFn:async()=>{let T=q.from("profiles").select("id, name, email, avatar_url").order("name");v&&(T=T.eq("brokerage_id",v));const{data:D,error:L}=await T;if(L)throw L;return D||[]},enabled:!!u}),_=Object.fromEntries((g||[]).map(T=>[T.id,T.name])),S=async T=>{const D=await n.mutateAsync({name:T.name,brokerage_id:T.brokerage_id||null,description:T.description});if(T.leaderId&&T.leaderId!=="none"&&await i.mutateAsync({team_id:D.id,user_id:T.leaderId,role:"team_leader"}),T.memberIds)for(const L of T.memberIds)await i.mutateAsync({team_id:D.id,user_id:L,role:"team_member"});d(!1)};if(u)return e.jsx(hyt,{team:u,brokerageAgents:j||[],onBack:()=>h(null),onUpdate:T=>r.mutateAsync({id:u.id,...T}).then(D=>h(D)),onAddMember:(T,D)=>i.mutateAsync({team_id:u.id,user_id:T,role:D}),onRemoveMember:T=>l.mutateAsync({team_id:u.id,member_id:T}),onUpdateRole:(T,D)=>o.mutateAsync({team_id:u.id,member_id:T,role:D}),onDeleteTeam:()=>{a.mutate(u.id),h(null)},isUpdating:r.isPending,isAddingMember:i.isPending});const A=s.filter(T=>T.name.toLowerCase().includes(p.toLowerCase())||(T.description||"").toLowerCase().includes(p.toLowerCase()));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search teams...",value:p,onChange:T=>f(T.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[A.length," of ",s.length," teams"]})]}),e.jsxs(B,{size:"sm",onClick:()=>d(!0),children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(myt,{open:c,onOpenChange:d,onCreateTeam:S,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:g,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Ct,{className:"font-semibold",children:"Team Name"}),e.jsx(Ct,{className:"font-semibold",children:"Brokerage"}),e.jsx(Ct,{className:"font-semibold",children:"Leader"}),e.jsx(Ct,{className:"font-semibold",children:"Members"}),e.jsx(Ct,{className:"font-semibold",children:"Visibility"}),e.jsx(Ct,{className:"w-[100px]"})]})}),e.jsx(pa,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(T=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-32"})}),e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-24"})}),e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-28"})}),e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-12"})}),e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-16"})})]},T))}):A.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:p?"No teams match your search":"No teams found. Create one to get started."})}):A.map(T=>{const D=b==null?void 0:b[T.id];return e.jsxs(Gs,{className:"hover:bg-muted/30",children:[e.jsxs(ut,{children:[e.jsx("button",{onClick:()=>h(T),className:"text-primary hover:underline font-medium",children:T.name}),T.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:T.description})]}),e.jsx(ut,{children:T.brokerage_id?e.jsx("span",{className:"text-sm",children:_[T.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(ut,{children:D!=null&&D.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(xf,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),D.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(ut,{children:e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[e.jsx(_n,{className:"h-3 w-3 mr-1"}),(D==null?void 0:D.count)??0]})}),e.jsx(ut,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(hh,{className:"h-3 w-3"}),T.contact_visibility.replace("_"," ")]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>h(T),title:"Edit team",children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete team "${T.name}"? This cannot be undone.`)&&a.mutate(T.id)},title:"Delete team",children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})})]},T.id)})})]})})]})};function YHe(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 a_s({open:s,onOpenChange:t,recipients:n}){const{toast:r}=Ua(),[a,i]=N.useState([]),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,b]=N.useState(!1),[v,j]=N.useState(!1),_=N.useMemo(()=>a.find(D=>D.id===c)||null,[a,c]);N.useEffect(()=>{s&&(o(!0),(async()=>{const D=new Date().toISOString(),{data:L,error:M}=await q.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",D).order("event_date",{ascending:!0}).limit(50);M?r({title:"Could not load events",description:M.message,variant:"destructive"}):i(L||[]),o(!1)})())},[s,r]);const S=N.useMemo(()=>n.filter(D=>D.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(D.email)),[n]),A=()=>{if(!_){r({title:"Pick an event first",variant:"destructive"});return}if(S.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}j(!0)},T=async()=>{if(_){j(!1),b(!0);try{const{data:{session:D}}=await q.auth.getSession(),L=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D==null?void 0:D.access_token}`},body:JSON.stringify({event_id:_.id,recipients:S.map(V=>({email:V.email,name:V.name,user_id:V.id})),custom_subject:u.trim()||void 0,custom_intro:p.trim()||void 0})}),M=await L.json().catch(()=>({}));if(!L.ok)throw new Error((M==null?void 0:M.error)||"Failed to send event invite");const F=(M==null?void 0:M.sent)??0,z=(M==null?void 0:M.failed)??0;r({title:"Invites sent",description:`Sent: ${F}${z?` · Failed: ${z}`:""}`}),t(!1),f(""),h(""),d("")}catch(D){const L=D instanceof Error?D.message:"Send failed";r({title:"Send failed",description:L,variant:"destructive"})}finally{b(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Qn,{children:["Send a beautiful event invitation to ",S.length," selected member",S.length===1?"":"s",".",n.length!==S.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[n.length-S.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{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(ss,{className:"h-4 w-4 animate-spin"})," Loading upcoming events..."]}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No upcoming events found. Create an event first."}):e.jsxs(us,{value:c,onValueChange:d,children:[e.jsx(cs,{id:"event-select",children:e.jsx(hs,{placeholder:"Pick an upcoming event..."})}),e.jsx(ds,{children:a.map(D=>e.jsx(Ze,{value:D.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:D.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[YHe(D.event_date),!D.is_published&&" · (Draft)"]})]})},D.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(yr,{className:"h-4 w-4 text-primary"}),_.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:YHe(_.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(se,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(ge,{id:"subject",placeholder:_?`You're invited: ${_.title}`:"You're invited to...",value:u,onChange:D=>h(D.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the default."})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(Ts,{id:"intro",placeholder:"Add a custom intro message... e.g. 'As a new member, we'd love to have you at our weekly onboarding event!'",value:p,onChange:D=>f(D.target.value),rows:4}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"This appears at the top of the email. Leave blank for a friendly default."})]}),e.jsxs("div",{className:"rounded-lg border p-3 bg-muted/20",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:["RECIPIENTS (",S.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[S.slice(0,30).map(D=>e.jsx(ze,{variant:"secondary",className:"text-xs font-normal",children:D.name||D.email},D.id)),S.length>30&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:["+",S.length-30," more"]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsx(B,{onClick:A,disabled:g||!c||S.length===0,children:g?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send to ",S.length]})})]})]})}),e.jsx(Oo,{open:v,onOpenChange:j,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Send event invite?"}),e.jsx(Mo,{children:_?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:[S.length," member",S.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsxs(jo,{onClick:T,children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const i_s=()=>{const s=In(),{user:t,isAdmin:n}=gs(),{startImpersonation:r,isLoading:a}=K0e(),{toast:i}=Ua(),[l,o]=N.useState([]),[c,d]=N.useState([]),[u,h]=N.useState([]),[p,f]=N.useState({}),[g,b]=N.useState(!0);N.useState({});const[v,j]=N.useState(!1),[_,S]=N.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[A,T]=N.useState(!1),[D,L]=N.useState(""),[M,F]=N.useState(1),[z,V]=N.useState(50),[W,K]=N.useState("all"),[Y,ee]=N.useState("all"),[ne,oe]=N.useState("all"),[pe,ce]=N.useState("all"),[de,ie]=N.useState("all"),[ye,_e]=N.useState(!1),[Me,Te]=N.useState(!1),[Ce,Ee]=N.useState(!1),[De,Ie]=N.useState(null),[Fe,qe]=N.useState(null),[ve,Je]=N.useState(!1),[we,it]=N.useState({name:"",email:"",brokerage_id:"",phone:""}),[Ne,He]=N.useState(null),[$e,Ye]=N.useState(!1),[Ke,rt]=N.useState(""),[tt,at]=N.useState(!1),[Ge,dt]=N.useState(!1),[Bt,kt]=N.useState(null),[Qt,ns]=N.useState(""),[$s,Ds]=N.useState(!1),[Dt,St]=N.useState(!1),[$t,ht]=N.useState(null),[Ut,Es]=N.useState(!1),[Xt,Ys]=N.useState(!1),[Ss,Bs]=N.useState(null),[Us,sn]=N.useState(""),[Jn,fn]=N.useState(!1),[Sn,Gn]=N.useState({email:"",name:"",password:"",phone:""}),[Hr,pi]=N.useState(!1),[Ms,bi]=N.useState(!1),[Rr,er]=N.useState(""),[lr,Fs]=N.useState(!1),[$n,Cr]=N.useState(!1),[ts,Oe]=N.useState(""),[Qe,ct]=N.useState(new Set),[vt,It]=N.useState(!1),[qt,xs]=N.useState(!1),[as,Ns]=N.useState(null),[ln,Ks]=N.useState(!1),[Un,br]=N.useState(null),[Ar,sr]=N.useState([]),[Tr,Ot]=N.useState([]),[wn,kr]=N.useState(!1),[dr,Jr]=N.useState({});N.useEffect(()=>{!t||!n||(qn(),wi())},[t,n]);const jr=async()=>{try{const{data:Lt,error:hn}=await q.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(hn)throw hn;const zn={};for(const Or of Lt??[])zn[Or.brokerage_id]||(zn[Or.brokerage_id]=[]),zn[Or.brokerage_id].push(Or.user_id);f(zn)}catch(Lt){console.error("Error loading brokerage manager assignments:",Lt)}},qn=async()=>{try{b(!0);const{data:Lt,error:hn}=await q.functions.invoke("get-user-details");if(hn)throw hn;const zn=Lt.users||[];o(zn),h(Lt.brokerages||[]),await jr();const Or=zn.filter(Wn=>Wn.roles.includes("assistant"));if(Or.length>0){const Wn=Or.map(Ja=>Ja.id),{data:va}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Wn);if(va&&va.length>0){const Ja=[...new Set(va.map(Ed=>Ed.agent_id))],{data:oi}=await q.from("profiles").select("id, name, email").in("id",Ja),Br={};for(const Ed of va){const ym=oi==null?void 0:oi.find(Zu=>Zu.id===Ed.agent_id);ym&&(Br[Ed.assistant_id]={agent_name:ym.name||"",agent_email:ym.email||""})}Jr(Br)}}}catch(Lt){console.error("Error loading members:",Lt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{b(!1)}},wi=async()=>{try{const{data:Lt,error:hn}=await q.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(hn)throw hn;d(Lt||[])}catch(Lt){console.error("Error loading apps:",Lt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},Oi=async Lt=>{if(!we.name.trim()||!we.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(we.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:zn}=await q.from("profiles").update({name:we.name.trim(),email:we.email.trim(),brokerage_id:we.brokerage_id||null,phone:we.phone.trim()||null}).eq("id",Lt);if(zn)throw zn;i({title:"Success",description:"Member details updated successfully"}),Ie(null),qn()}catch(zn){console.error("Error updating member:",zn),i({title:"Error",description:zn.message||"Failed to update member",variant:"destructive"})}},ea=async Lt=>{try{const{data:{session:hn}}=await q.auth.getSession(),zn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${hn==null?void 0:hn.access_token}`},body:JSON.stringify({userId:Lt})}),Or=await zn.json();if(!zn.ok)throw new Error(Or.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(hn){console.error("Error resending welcome email:",hn),i({title:"Error",description:hn.message||"Failed to resend welcome email",variant:"destructive"})}},ya=async(Lt,hn)=>{try{const{error:zn}=await q.functions.invoke("send-password-reset",{body:{email:Lt,redirectTo:window.location.origin}});if(zn)throw zn;i({title:"Password Reset Sent",description:`Password reset email sent to ${hn}`})}catch(zn){console.error("Error sending password reset:",zn),i({title:"Error",description:zn.message||"Failed to send password reset email",variant:"destructive"})}},Mi=async(Lt,hn)=>{if(confirm(`Are you sure you want to delete ${hn}? This action cannot be undone.`))try{const{data:{session:zn}}=await q.auth.getSession(),Or=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({userId:Lt})}),Wn=await Or.json();if(!Or.ok)throw new Error(Wn.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),qn()}catch(zn){console.error("Error deleting user:",zn),i({title:"Error",description:zn.message||"Failed to delete user",variant:"destructive"})}},da=async()=>{if(!_.email||!_.name||!_.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(_.role==="brokerage_manager"&&!_.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}j(!0);try{const{data:{session:Lt}}=await q.auth.getSession(),hn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Lt==null?void 0:Lt.access_token}`},body:JSON.stringify(_)}),zn=await hn.json();if(!hn.ok)throw new Error(zn.error||"Failed to create user");if(_.role&&_.role!=="user"&&zn.userId){const Or=_.role==="brokerage_manager"?_.brokerage_id:void 0;await jn(zn.userId,_.role,"add",Or)}i({title:"Success",description:`User ${_.email} created successfully`}),S({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),T(!1),qn()}catch(Lt){console.error("Error creating user:",Lt),i({title:"Error",description:Lt.message||"Failed to create user",variant:"destructive"})}finally{j(!1)}},jn=async(Lt,hn,zn,Or)=>{try{const{data:{session:Wn}}=await q.auth.getSession(),va={userId:Lt,role:hn,action:zn};if(hn==="brokerage_manager"){if(!Or){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}va.brokerageId=Or}const Ja=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wn==null?void 0:Wn.access_token}`},body:JSON.stringify(va)}),oi=await Ja.json();if(!Ja.ok)throw new Error(oi.error||"Failed to manage user role");i({title:"Success",description:`Role ${zn==="add"?"added":"removed"} successfully`}),qn()}catch(Wn){console.error("Error managing user role:",Wn),i({title:"Error",description:Wn.message||"Failed to manage user role",variant:"destructive"})}},Aa=(Lt,hn)=>hn.length===0?!0:hn.some(zn=>Lt.includes(zn)),Yi=async(Lt,hn,zn)=>{const Or=`${Lt}-${hn.id}`;He(Or);try{if(zn){const Wn=l.find(Ja=>Ja.id===Lt),va=hn.required_tags.filter(Ja=>Wn==null?void 0:Wn.tags.includes(Ja));for(const Ja of va){const{error:oi}=await q.from("user_tags").delete().eq("user_id",Lt).eq("tag",Ja);if(oi)throw oi}i({title:"Access Removed",description:`Removed access to ${hn.name}`})}else if(hn.required_tags.length>0){const{error:Wn}=await q.from("user_tags").insert({user_id:Lt,tag:hn.required_tags[0]});if(Wn)throw Wn;i({title:"Access Granted",description:`Granted access to ${hn.name}`})}await qn()}catch(Wn){console.error("Error toggling access:",Wn),i({title:"Error",description:Wn.message||"Failed to update access",variant:"destructive"})}finally{He(null)}},Bo=async()=>{const Lt=Ke.trim();if(!Lt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Lt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(zn=>zn.name.toLowerCase()===Lt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}at(!0);try{const{error:zn}=await q.from("brokerages").insert({name:Lt});if(zn)throw zn;i({title:"Success",description:`Brokerage "${Lt}" created successfully`}),rt(""),Ye(!1),qn()}catch(zn){console.error("Error creating brokerage:",zn),i({title:"Error",description:zn.message||"Failed to create brokerage",variant:"destructive"})}finally{at(!1)}},rl=Lt=>{kt(Lt),ns(Lt.name),dt(!0)},po=()=>{kt(null),ns(""),dt(!1)},zc=async()=>{if(!Bt)return;const Lt=Qt.trim();if(!Lt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Lt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}Ds(!0);try{const{error:hn}=await q.from("brokerages").update({name:Lt}).eq("id",Bt.id);if(hn)throw hn;i({title:"Success",description:"Brokerage updated successfully"}),po(),qn()}catch(hn){console.error("Error updating brokerage:",hn),i({title:"Error",description:hn.message||"Failed to update brokerage",variant:"destructive"})}finally{Ds(!1)}},Sd=async(Lt,hn)=>{var zn;if(!hn||typeof hn!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const Or={userId:Lt,role:"brokerage_manager",action:"add",brokerageId:hn};console.debug("[assignManagerToBrokerage] payload",Or);const{data:{session:Wn}}=await q.auth.getSession(),va=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wn==null?void 0:Wn.access_token}`},body:JSON.stringify(Or)}),Ja=await va.json();if(!va.ok&&!((zn=Ja.error)!=null&&zn.includes("duplicate")))throw new Error(Ja.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await qn()}catch(Or){console.error("Error assigning manager:",Or),i({title:"Error",description:Or.message||"Failed to assign manager",variant:"destructive"})}},fm=Lt=>{ht(Lt),St(!0)},Cd=async()=>{if($t){Es(!0);try{const Lt=l.filter(Or=>Or.brokerage_id===$t.id),{data:{session:hn}}=await q.auth.getSession();for(const Or of Lt){const Wn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${hn==null?void 0:hn.access_token}`},body:JSON.stringify({userId:Or.id})});if(!Wn.ok){const va=await Wn.json();console.error(`Failed to delete user ${Or.email}:`,va.error)}}const{error:zn}=await q.from("brokerages").delete().eq("id",$t.id);if(zn)throw zn;i({title:"Success",description:`Brokerage "${$t.name}" and ${Lt.length} member(s) deleted`}),St(!1),ht(null),qn()}catch(Lt){console.error("Error deleting brokerage:",Lt),i({title:"Error",description:Lt.message||"Failed to delete brokerage",variant:"destructive"})}finally{Es(!1)}}},Hd=Lt=>{Bs(Lt),sn(""),Ys(!0)},uc=()=>{Bs(null),sn(""),Ys(!1)},Gd=async Lt=>{try{const{error:hn}=await q.from("profiles").update({brokerage_id:null}).eq("id",Lt);if(hn)throw hn;i({title:"Success",description:"User removed from brokerage"}),qn()}catch(hn){console.error("Error removing user from brokerage:",hn),i({title:"Error",description:hn.message||"Failed to remove user",variant:"destructive"})}},i1=async(Lt,hn)=>{try{const{error:zn}=await q.from("profiles").update({brokerage_id:hn}).eq("id",Lt);if(zn)throw zn;i({title:"Success",description:"User added to brokerage"}),qn()}catch(zn){console.error("Error adding user to brokerage:",zn),i({title:"Error",description:zn.message||"Failed to add user",variant:"destructive"})}},lj=async()=>{if(!Ss||!Sn.email||!Sn.name||!Sn.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}pi(!0);try{const{data:{session:Lt}}=await q.auth.getSession(),hn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Lt==null?void 0:Lt.access_token}`},body:JSON.stringify({...Sn,brokerage_id:Ss.id,role:"user"})}),zn=await hn.json();if(!hn.ok)throw new Error(zn.error||"Failed to create agent");i({title:"Success",description:`Agent ${Sn.email} created successfully`}),Gn({email:"",name:"",password:"",phone:""}),fn(!1),qn()}catch(Lt){console.error("Error creating agent:",Lt),i({title:"Error",description:Lt.message||"Failed to create agent",variant:"destructive"})}finally{pi(!1)}},xm=Lt=>l.filter(hn=>hn.brokerage_id===Lt),Iy=Lt=>{const hn=xm(Lt);if(!Us)return hn;const zn=Us.toLowerCase();return hn.filter(Or=>Or.name.toLowerCase().includes(zn)||Or.email.toLowerCase().includes(zn))},Py=Lt=>l.filter(hn=>hn.brokerage_id!==Lt),Ef=l.filter(Lt=>{var zn;if(D){const Or=D.toLowerCase();if(!(Lt.name.toLowerCase().includes(Or)||Lt.email.toLowerCase().includes(Or)||((zn=Lt.brokerage_name)==null?void 0:zn.toLowerCase().includes(Or))))return!1}if(W==="claimed"&&!Lt.claimed||W==="unclaimed"&&Lt.claimed||Y!=="all"&&!Lt.roles.includes(Y))return!1;const hn=Lt.is_trial||Lt.subscription_status==="trialing";if(ne==="trial"&&!hn||ne==="non-trial"&&hn||pe==="none"&&Lt.brokerage_id||pe!=="all"&&pe!=="none"&&Lt.brokerage_id!==pe)return!1;if(de!=="all"){if(!Lt.created_at)return!1;const Or=parseInt(de,10),Wn=Date.now()-Or*24*60*60*1e3;if(new Date(Lt.created_at).getTime(){var hn;return((hn=Lt.name)==null?void 0:hn.toLowerCase())||""},brokerage:Lt=>{var hn;return((hn=Lt.brokerage_name)==null?void 0:hn.toLowerCase())||""},status:Lt=>Lt.claimed?"active":"pending",role:Lt=>Lt.roles[0]||"",last_login:Lt=>Lt.last_sign_in_at?new Date(Lt.last_sign_in_at).getTime():null,created_at:Lt=>Lt.created_at?new Date(Lt.created_at).getTime():null}),$h=gm.length,fx=z===0,Yu=fx?1:Math.ceil($h/z),al=fx?0:(M-1)*z,u0=fx?$h:al+z,vu=gm.slice(al,u0),h0=Lt=>{L(Lt),F(1)},cj=Lt=>{V(Lt),F(1)},Af=(Lt,hn)=>{Lt(hn),F(1)},Xa=async(Lt,hn)=>{Te(!0);try{const zn=l.find(Ja=>Ja.id===Lt);if(!zn)return;const Or=zn.trial_expires_at?new Date(zn.trial_expires_at):new Date,Wn=new Date(Or.getTime()+hn*24*60*60*1e3),{error:va}=await q.from("profiles").update({trial_expires_at:Wn.toISOString()}).eq("id",Lt);if(va)throw va;i({title:"Trial Extended",description:`Trial extended by ${hn} days`}),qn()}catch(zn){console.error("Error extending trial:",zn),i({title:"Error",description:zn.message||"Failed to extend trial",variant:"destructive"})}finally{Te(!1)}},Ly=async Lt=>{Ee(!0);try{const{error:hn}=await q.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Lt);if(hn)throw hn;i({title:"Account Converted",description:"User has been converted to a full account"}),qn(),hg()}catch(hn){console.error("Error converting trial:",hn),i({title:"Error",description:hn.message||"Failed to convert account",variant:"destructive"})}finally{Ee(!1)}},[Dy,Jm]=N.useState(!1),ep=async(Lt,hn)=>{if(confirm(`Revert this user to a ${hn}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){Jm(!0);try{const zn=new Date,Or=new Date(zn.getTime()+hn*24*60*60*1e3),{error:Wn}=await q.from("profiles").update({is_trial:!0,trial_started_at:zn.toISOString(),trial_expires_at:Or.toISOString(),trial_claimed_at:zn.toISOString(),is_grandfathered:!1,subscription_status:"none",subscription_end_date:null,subscription_product_id:null,subscription_price_id:null,converted_from_trial_at:null}).eq("id",Lt);if(Wn)throw Wn;i({title:"Reverted to Trial",description:`User is now on a ${hn}-day free trial.`}),qn()}catch(zn){console.error("Error reverting to trial:",zn),i({title:"Error",description:zn.message||"Failed to revert to trial",variant:"destructive"})}finally{Jm(!1)}}},Dp=async Lt=>{kr(!0);try{const{data:hn}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",Lt);if(hn&&hn.length>0){const Or=hn.map(va=>va.assistant_id),{data:Wn}=await q.from("profiles").select("id, name, email").in("id",Or);sr(hn.map(va=>{const Ja=Wn==null?void 0:Wn.find(oi=>oi.id===va.assistant_id);return{id:va.id,assistant_id:va.assistant_id,assistant_name:(Ja==null?void 0:Ja.name)||"Unknown",assistant_email:(Ja==null?void 0:Ja.email)||"",permissions:va.permissions||{}}}))}else sr([]);const{data:zn}=await q.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",Lt);if(zn&&zn.length>0){const Or=zn.map(va=>va.agent_id),{data:Wn}=await q.from("profiles").select("id, name, email").in("id",Or);Ot(zn.map(va=>{const Ja=Wn==null?void 0:Wn.find(oi=>oi.id===va.agent_id);return{id:va.id,agent_id:va.agent_id,agent_name:(Ja==null?void 0:Ja.name)||"Unknown",agent_email:(Ja==null?void 0:Ja.email)||"",permissions:va.permissions||{}}}))}else Ot([])}catch(hn){console.error("Error loading assistant data:",hn)}finally{kr(!1)}},xx=Lt=>{qe(Lt),it({name:Lt.name,email:Lt.email,brokerage_id:Lt.brokerage_id||"",phone:Lt.phone||""}),Je(!0),Dp(Lt.id)},hg=()=>{qe(null),Je(!1),it({name:"",email:"",brokerage_id:"",phone:""})},Hb=async()=>{Fe&&(await Oi(Fe.id),hg())},Rp=Lt=>{ct(hn=>{const zn=new Set(hn);return zn.has(Lt)?zn.delete(Lt):zn.add(Lt),zn})},tp=()=>{if(Qe.size===vu.length&&vu.every(Lt=>Qe.has(Lt.id))){const Lt=new Set(Qe);vu.forEach(hn=>Lt.delete(hn.id)),ct(Lt)}else{const Lt=new Set(Qe);vu.forEach(hn=>Lt.add(hn.id)),ct(Lt)}},Mf=()=>{ct(new Set)},Ry=async()=>{if(Qe.size===0)return;It(!0);let Lt=0,hn=0;try{const{data:{session:zn}}=await q.auth.getSession();for(const Or of Qe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({userId:Or})})).ok?Lt++:hn++}catch{hn++}i({title:"Bulk Email Complete",description:`Sent ${Lt} emails${hn>0?`, ${hn} failed`:""}`}),Mf()}catch(zn){i({title:"Error",description:zn.message||"Failed to send emails",variant:"destructive"})}finally{It(!1)}},Gb=async()=>{if(Qe.size===0)return;It(!0);let Lt=0,hn=0;try{const{data:{session:zn}}=await q.auth.getSession();for(const Or of Qe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({userId:Or})})).ok?Lt++:hn++}catch{hn++}i({title:"Bulk Password Reset Complete",description:`Sent ${Lt} reset emails${hn>0?`, ${hn} failed`:""}`}),Mf()}catch(zn){i({title:"Error",description:zn.message||"Failed to send password reset emails",variant:"destructive"})}finally{It(!1)}},Td=async()=>{if(Qe.size===0)return;const Lt=l.filter(Wn=>Qe.has(Wn.id)).map(Wn=>Wn.name).slice(0,5).join(", "),hn=Qe.size>5?` and ${Qe.size-5} more`:"";if(!confirm(`Are you sure you want to delete ${Qe.size} users (${Lt}${hn})? This action cannot be undone.`))return;It(!0);let zn=0,Or=0;try{const{data:{session:Wn}}=await q.auth.getSession();for(const va of Qe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wn==null?void 0:Wn.access_token}`},body:JSON.stringify({userId:va})})).ok?zn++:Or++}catch{Or++}i({title:"Bulk Delete Complete",description:`Deleted ${zn} users${Or>0?`, ${Or} failed`:""}`}),Mf(),qn()}catch(Wn){i({title:"Error",description:Wn.message||"Failed to delete users",variant:"destructive"})}finally{It(!1)}},Bc=async()=>{xs(!0);try{const{data:{session:Lt}}=await q.auth.getSession(),hn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Lt==null?void 0:Lt.access_token}`}});if(!hn.ok){const Or=await hn.json();throw new Error(Or.error||"Failed to sync phones")}const zn=await hn.json();i({title:"Phone Sync Complete",description:`Pulled ${zn.summary.pulledFromGHL} from GHL, pushed ${zn.summary.pushedToGHL} to GHL, ${zn.summary.alreadySynced} already synced`}),qn()}catch(Lt){i({title:"Error",description:Lt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{xs(!1)}},sp=async(Lt,hn)=>{Ns(Lt);try{const{data:{session:zn}}=await q.auth.getSession(),{data:Or}=await q.from("profiles").select("phone").eq("id",Lt).single(),Wn=(Or==null?void 0:Or.phone)||"",va=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({email:hn,action:"update",phone:Wn||void 0})});if(!va.ok){const oi=await va.json();throw new Error(oi.error||"Failed to sync with GHL")}const Ja=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(hn)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Wn?`Phone ${Wn} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),qn()}catch(zn){i({title:"Error",description:zn.message||"Failed to sync phone",variant:"destructive"})}finally{Ns(null)}},Zc=async Lt=>{await r(Lt)},np=()=>{if(Qe.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const Lt=l.filter(oi=>Qe.has(oi.id)),hn=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],zn=Lt.map(oi=>[oi.name,oi.email,oi.phone||"",oi.brokerage_name||"",oi.roles.join("; "),oi.claimed?"Claimed":"Unclaimed",new Date(oi.created_at).toLocaleDateString()]),Or=[hn.join(","),...zn.map(oi=>oi.map(Br=>`"${(Br||"").replace(/"/g,'""')}"`).join(","))].join(` `),Wn=new Blob([Or],{type:"text/csv"}),va=URL.createObjectURL(Wn),Ja=document.createElement("a");Ja.href=va,Ja.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Ja.click(),URL.revokeObjectURL(va),i({title:"Export complete",description:`Exported ${Lt.length} member(s)`})},Op=()=>{if(Ef.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const Lt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],hn=Ef.map(oi=>[oi.name,oi.email,oi.phone||"",oi.brokerage_name||"",oi.roles.join("; "),oi.claimed?"Claimed":"Unclaimed",oi.created_at?new Date(oi.created_at).toLocaleDateString():""]),zn=[Lt.join(","),...hn.map(oi=>oi.map(Br=>`"${(Br||"").replace(/"/g,'""')}"`).join(","))].join(` `),Or=new Blob([zn],{type:"text/csv"}),Wn=URL.createObjectURL(Or),va=document.createElement("a"),Ja=de!=="all"?`-last-${de}days`:"";va.href=Wn,va.download=`members-export${Ja}-${new Date().toISOString().split("T")[0]}.csv`,va.click(),URL.revokeObjectURL(Wn),i({title:"Export complete",description:`Exported ${Ef.length} member(s)`})};return g?e.jsx(Cs,{title:"Members",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(Cs,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Member Management",description:"Manage users, roles, and permissions",children:e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>s("/admin/unassigned-members"),className:"gap-2",children:[e.jsx(Dl,{className:"h-4 w-4 text-amber-500"}),"Unassigned Members"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:Bc,disabled:qt,children:[qt?e.jsx(ss,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Pr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:qt?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:qt?"Syncing...":"Sync GHL"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>bi(!0),children:[e.jsx(yw,{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(bs,{open:A,onOpenChange:T,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Fo,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Add Member"}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create New User"}),e.jsx(Qn,{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(se,{htmlFor:"name",children:"Name"}),e.jsx(ge,{id:"name",placeholder:"John Doe",value:_.name,onChange:Lt=>S({..._,name:Lt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ge,{id:"email",type:"email",placeholder:"john@example.com",value:_.email,onChange:Lt=>S({..._,email:Lt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"password",children:"Password"}),e.jsx(ge,{id:"password",type:"password",placeholder:"Min 6 characters",value:_.password,onChange:Lt=>S({..._,password:Lt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(ge,{id:"phone",type:"tel",placeholder:"555-123-4567",value:_.phone,onChange:Lt=>S({..._,phone:Lt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"brokerage",children:["Brokerage",_.role==="brokerage_manager"?" (required)":""]}),e.jsxs(us,{value:_.brokerage_id||"none",onValueChange:Lt=>S({..._,brokerage_id:Lt==="none"?"":Lt}),children:[e.jsx(cs,{id:"brokerage",children:e.jsx(hs,{placeholder:_.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"None"}),u.map(Lt=>e.jsx(Ze,{value:Lt.id,children:Lt.name},Lt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"role",children:"Role"}),e.jsxs(us,{value:_.role,onValueChange:Lt=>S({..._,role:Lt}),children:[e.jsx(cs,{id:"role",children:e.jsx(hs,{placeholder:"Select role"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"user",children:"User"}),e.jsx(Ze,{value:"moderator",children:"Moderator"}),e.jsx(Ze,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(Ze,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(us,{value:_.trial_days||"none",onValueChange:Lt=>S({..._,trial_days:Lt==="none"?"":Lt}),children:[e.jsx(cs,{id:"trial_days",children:e.jsx(hs,{placeholder:"No trial (full access)"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No trial (full access)"}),e.jsx(Ze,{value:"7",children:"7-day trial"}),e.jsx(Ze,{value:"30",children:"30-day trial"}),e.jsx(Ze,{value:"60",children:"60-day trial"}),e.jsx(Ze,{value:"90",children:"90-day trial"}),e.jsx(Ze,{value:"365",children:"1-year trial"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Trial accounts don't require a credit card. Access expires after the trial period."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx(B,{onClick:da,disabled:v,children:v?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs($r,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"members",children:"Members"}),e.jsx(Zt,{value:"brokerages",children:"Brokerages"}),e.jsx(Zt,{value:"teams",children:"Teams"}),e.jsx(Zt,{value:"trials",children:"Trial Users"}),e.jsx(Zt,{value:"access",children:"Access Matrix"}),e.jsx(Zt,{value:"celebrations",children:"Celebrations"}),e.jsx(Zt,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(ls,{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(_r,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search members...",value:D,onChange:Lt=>h0(Lt.target.value),className:"pl-10 h-9"})]}),e.jsxs(us,{value:W,onValueChange:Lt=>Af(K,Lt),children:[e.jsx(cs,{className:"w-[130px] h-9",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Status"}),e.jsx(Ze,{value:"claimed",children:"Active"}),e.jsx(Ze,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(us,{value:Y,onValueChange:Lt=>Af(ee,Lt),children:[e.jsx(cs,{className:"w-[130px] h-9",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Roles"}),e.jsx(Ze,{value:"admin",children:"Admin"}),e.jsx(Ze,{value:"brokerage_manager",children:"Manager"}),e.jsx(Ze,{value:"assistant",children:"Assistant"}),e.jsx(Ze,{value:"user",children:"User"})]})]}),e.jsxs(us,{value:ne,onValueChange:Lt=>Af(oe,Lt),children:[e.jsx(cs,{className:"w-[130px] h-9",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Users"}),e.jsx(Ze,{value:"trial",children:"Trial Only"}),e.jsx(Ze,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(us,{value:pe,onValueChange:Lt=>Af(ce,Lt),children:[e.jsx(cs,{className:"w-[150px] h-9",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Brokerages"}),e.jsx(Ze,{value:"none",children:"No Brokerage"}),u.map(Lt=>e.jsx(Ze,{value:Lt.id,children:Lt.name},Lt.id))]})]}),e.jsxs(us,{value:de,onValueChange:Lt=>Af(ie,Lt),children:[e.jsx(cs,{className:"w-[150px] h-9",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"Any Join Date"}),e.jsx(Ze,{value:"30",children:"Joined Last 30 Days"}),e.jsx(Ze,{value:"60",children:"Joined Last 60 Days"}),e.jsx(Ze,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-9",onClick:Op,title:"Export currently filtered members to CSV",children:[e.jsx(Da,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(D||W!=="all"||Y!=="all"||ne!=="all"||pe!=="all"||de!=="all")&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{L(""),K("all"),ee("all"),oe("all"),ce("all"),ie("all"),F(1)},children:[e.jsx(Fn,{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:fx?`Showing all ${$h} members`:`Showing ${al+1}-${Math.min(u0,$h)} of ${$h} members`}),e.jsxs(us,{value:z.toString(),onValueChange:Lt=>cj(Number(Lt)),children:[e.jsx(cs,{className:"h-9 w-[110px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"50",children:"50 / page"}),e.jsx(Ze,{value:"100",children:"100 / page"}),e.jsx(Ze,{value:"250",children:"250 / page"}),e.jsx(Ze,{value:"0",children:"All"})]})]})]})]}),Qe.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[vu.length>0&&vu.every(Lt=>Qe.has(Lt.id))&&gm.length>Qe.size&&e.jsxs("div",{className:"flex items-center justify-between gap-2 px-1 text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["All ",Qe.size," on this page are selected."]}),e.jsxs(B,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>ct(new Set(gm.map(Lt=>Lt.id))),children:["Select all ",gm.length," filtered members"]})]}),gm.length>0&&Qe.size===gm.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",gm.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(A2,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[Qe.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:Ry,disabled:vt,children:[vt?e.jsx(ss,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Hs,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Resend Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:Gb,disabled:vt,children:[vt?e.jsx(ss,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Gg,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Password Reset"}),e.jsx("span",{className:"sm:hidden",children:"Reset"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>_e(!0),disabled:vt,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(mb,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Send Event Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:np,children:[e.jsx(Da,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Export"}),e.jsx("span",{className:"sm:hidden",children:"CSV"})]}),e.jsxs(B,{size:"sm",variant:"destructive",onClick:Td,disabled:vt,children:[vt?e.jsx(ss,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(bn,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Delete"}),e.jsx("span",{className:"sm:hidden",children:"Del"})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:Mf,disabled:vt,children:e.jsx(Fn,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Ct,{className:"w-[50px]",children:e.jsx(hi,{checked:vu.length>0&&vu.every(Lt=>Qe.has(Lt.id)),onCheckedChange:tp,"aria-label":"Select all on page"})}),e.jsx(Pc,{sortKey:"name",currentSortKey:_h,currentDirection:px,onSort:fo,children:"Name"}),e.jsx(Pc,{sortKey:"brokerage",currentSortKey:_h,currentDirection:px,onSort:fo,children:"Brokerage"}),e.jsx(Pc,{sortKey:"status",currentSortKey:_h,currentDirection:px,onSort:fo,children:"Status"}),e.jsx(Pc,{sortKey:"role",currentSortKey:_h,currentDirection:px,onSort:fo,children:"Role"}),e.jsx(Pc,{sortKey:"last_login",currentSortKey:_h,currentDirection:px,onSort:fo,children:"Last Login"}),e.jsx(Pc,{sortKey:"created_at",currentSortKey:_h,currentDirection:px,onSort:fo,children:"Member Since"}),e.jsx(Ct,{className:"w-[100px]"})]})}),e.jsx(pa,{children:vu.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):vu.map(Lt=>e.jsxs(Gs,{className:`hover:bg-muted/30 ${Qe.has(Lt.id)?"bg-primary/5":""}`,children:[e.jsx(ut,{children:e.jsx(hi,{checked:Qe.has(Lt.id),onCheckedChange:()=>Rp(Lt.id),"aria-label":`Select ${Lt.name}`})}),e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>xx(Lt),className:"text-primary hover:underline font-medium text-left",children:Lt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Lt.email})]})}),e.jsx(ut,{className:"text-muted-foreground",children:Lt.brokerage_name||"—"}),e.jsx(ut,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const hn=Lt.trial_expires_at||Lt.subscription_end_date;if((Lt.is_trial||Lt.subscription_status==="trialing")&&hn){const Or=Math.ceil((new Date(hn).getTime()-Date.now())/864e5),Wn=Or<=0,va=Or<=3;return e.jsx(ze,{variant:"outline",className:Et("w-fit",Wn?"border-destructive text-destructive":va?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Wn?"Trial Expired":`Trial · ${Or}d left`})}return e.jsx(ze,{variant:Lt.claimed?"default":"secondary",className:Lt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Lt.claimed?"Active":"Pending"})})()})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex flex-col",children:[Lt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:Lt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),Lt.roles.includes("assistant")&&dr[Lt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",dr[Lt.id].agent_name||dr[Lt.id].agent_email]})]})}),e.jsx(ut,{className:"text-muted-foreground",children:Lt.last_sign_in_at?new Date(Lt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(ut,{className:"text-muted-foreground",children:Lt.created_at?new Date(Lt.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{br(Lt),Ks(!0)},title:"Send celebration",children:e.jsx(uh,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>xx(Lt),title:"Edit member",children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>sp(Lt.id,Lt.email),disabled:as===Lt.id,title:"Sync phone with GHL",children:as===Lt.id?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(Pr,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ea(Lt.id),title:"Resend welcome email",children:e.jsx(Hs,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ya(Lt.email,Lt.name),title:"Send password reset",children:e.jsx(PA,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Zc(Lt.id),disabled:a||Lt.id===(t==null?void 0:t.id),title:Lt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Lt.name}`,children:a?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(LA,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Mi(Lt.id,Lt.name),title:"Delete user",children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},Lt.id))})]})}),Yu>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 ",M," of ",Yu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>F(1),disabled:M===1,children:"First"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Lt=>Math.max(1,Lt-1)),disabled:M===1,children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,Yu)},(Lt,hn)=>{let zn;return Yu<=5||M<=3?zn=hn+1:M>=Yu-2?zn=Yu-4+hn:zn=M-2+hn,e.jsx(B,{variant:M===zn?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>F(zn),children:zn},zn)})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Lt=>Math.min(Yu,Lt+1)),disabled:M===Yu,children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>F(Yu),disabled:M===Yu,children:"Last"})]})]})]}),e.jsx(bs,{open:ve,onOpenChange:Je,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Member"}),e.jsx(Qn,{children:"Update member details, roles, and app access"})]}),Fe&&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(se,{htmlFor:"edit-name",children:"Name"}),e.jsx(ge,{id:"edit-name",value:we.name,onChange:Lt=>it({...we,name:Lt.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-email",children:"Email"}),e.jsx(ge,{id:"edit-email",type:"email",value:we.email,onChange:Lt=>it({...we,email:Lt.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(se,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(ge,{id:"edit-phone",type:"tel",value:we.phone,onChange:Lt=>it({...we,phone:Lt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(us,{value:we.brokerage_id||"none",onValueChange:Lt=>it({...we,brokerage_id:Lt==="none"?"":Lt}),children:[e.jsx(cs,{id:"edit-brokerage",children:e.jsx(hs,{placeholder:"Select brokerage"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"None"}),u.map(Lt=>e.jsx(Ze,{value:Lt.id,children:Lt.name},Lt.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:[Fe.roles.map(Lt=>e.jsxs(ze,{variant:"default",className:"gap-1",children:[e.jsx(hh,{className:"h-3 w-3"}),Lt,Lt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>jn(Fe.id,Lt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(Fn,{className:"h-3 w-3"})})]},Lt)),Fe.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(us,{onValueChange:Lt=>jn(Fe.id,Lt,"add"),children:[e.jsx(cs,{className:"w-[200px]",children:e.jsx(hs,{placeholder:"Add role..."})}),e.jsxs(ds,{children:[!Fe.roles.includes("admin")&&e.jsx(Ze,{value:"admin",children:"Admin"}),!Fe.roles.includes("user")&&e.jsx(Ze,{value:"user",children:"User"})]})]}),!Fe.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"})]}),(Ar.length>0||Tr.length>0||Fe.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(_n,{className:"h-4 w-4"}),"Assistant Relationships"]}),wn?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ss,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[Ar.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:"}),Ar.map(Lt=>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:Lt.assistant_name}),e.jsx(ze,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Lt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Lt.permissions).filter(([,hn])=>hn).map(([hn])=>e.jsx(ze,{variant:"secondary",className:"text-[10px] capitalize",children:hn},hn))})]},Lt.id))]}),Tr.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:"}),Tr.map(Lt=>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:Lt.agent_name}),e.jsx(ze,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Lt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Lt.permissions).filter(([,hn])=>hn).map(([hn])=>e.jsx(ze,{variant:"secondary",className:"text-[10px] capitalize",children:hn},hn))})]},Lt.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(Lt=>{const hn=Aa(Fe.tags,Lt.required_tags),zn=`${Fe.id}-${Lt.id}`,Or=Ne===zn,Wn=Lt.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:Lt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:Lt.name}),Wn&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:Or?e.jsx(ss,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Wn?e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(vn,{checked:hn,onCheckedChange:()=>Yi(Fe.id,Lt,hn)})})]},Lt.id)})})]}),(Fe.is_trial||Fe.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(gr,{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:[Fe.trial_expires_at&&e.jsx(KHe,{expiresAt:Fe.trial_expires_at}),!Fe.trial_expires_at&&Fe.subscription_status==="trialing"&&Fe.subscription_end_date&&e.jsx(KHe,{expiresAt:Fe.subscription_end_date})]}),(Fe.trial_expires_at||Fe.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Fe.trial_expires_at||Fe.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Xa(Fe.id,7),disabled:Me,children:[e.jsx(Fg,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Xa(Fe.id,14),disabled:Me,children:[e.jsx(Fg,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Xa(Fe.id,30),disabled:Me,children:[e.jsx(Fg,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(B,{size:"sm",variant:"default",onClick:()=>Ly(Fe.id),disabled:Ce,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(_b,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Fe.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Fe.trial_started_at).toLocaleDateString(),Fe.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Fe.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Fe.is_trial||Fe.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(gr,{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(Lt=>e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>ep(Fe.id,Lt),disabled:Dy,children:[e.jsx(Fg,{className:"h-4 w-4 mr-1"}),Lt,"-day trial"]},Lt))})]})]}),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:[Fe.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Fe.email_confirmed_at).toLocaleString()]}),Fe.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Fe.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Fe.created_at).toLocaleString()]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:hg,children:"Cancel"}),e.jsx(B,{onClick:Hb,children:"Save Changes"})]})]})}),e.jsxs(ls,{value:"access",children:[c.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx(B,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Member Access Matrix"}),e.jsx(Hn,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search agents by name or email...",value:D,onChange:Lt=>{L(Lt.target.value),F(1)},className:"pl-9"})]})]}),e.jsxs(Ae,{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(Lt=>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:Lt.icon}),e.jsx("span",{className:"text-sm",children:Lt.name})]})},Lt.id))]})}),e.jsxs("tbody",{children:[vu.map(Lt=>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:Lt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Lt.email})]})}),c.map(hn=>{const zn=Aa(Lt.tags,hn.required_tags),Or=`${Lt.id}-${hn.id}`,Wn=Ne===Or;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Wn?e.jsx(ss,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(vn,{checked:zn,onCheckedChange:()=>Yi(Lt.id,hn,zn),disabled:hn.required_tags.length===0})})},hn.id)})]},Lt.id)),vu.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"})})]})]})}),Yu>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 ",al+1,"-",Math.min(u0,$h)," of ",$h," • Page ",M," of ",Yu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Lt=>Math.max(1,Lt-1)),disabled:M===1,children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Lt=>Math.min(Yu,Lt+1)),disabled:M===Yu,children:e.jsx(ga,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(B,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(ls,{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(_r,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search brokerages...",value:Rr,onChange:Lt=>er(Lt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(Lt=>Lt.name.toLowerCase().includes(Rr.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{const Lt=[];for(const Ja of u){const oi=p[Ja.id]??[];for(const Br of oi){const Ed=l.find(ym=>ym.id===Br);if(Ed){const ym=(Ed.name||"").trim().split(/\s+/),Zu=ym[0]||"",mg=ym.slice(1).join(" ")||"";Lt.push({firstName:Zu,lastName:mg,email:Ed.email,brokerageName:Ja.name})}}}if(Lt.length===0){i({title:"No managers found to export"});return}const zn=[["First Name","Last Name","Email","Brokerage Name"].join(","),...Lt.map(Ja=>[Ja.firstName,Ja.lastName,Ja.email,Ja.brokerageName].map(oi=>`"${(oi||"").replace(/"/g,'""')}"`).join(","))].join(` `),Or=new Blob([zn],{type:"text/csv"}),Wn=URL.createObjectURL(Or),va=document.createElement("a");va.href=Wn,va.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,va.click(),URL.revokeObjectURL(Wn),i({title:`Exported ${Lt.length} managers`})},children:[e.jsx(Da,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(bs,{open:$e,onOpenChange:Ye,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create New Brokerage"}),e.jsx(Qn,{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(se,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(ge,{id:"brokerage-name",placeholder:"Enter brokerage name",value:Ke,onChange:Lt=>rt(Lt.target.value),maxLength:100})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ye(!1),children:"Cancel"}),e.jsx(B,{onClick:Bo,disabled:tt,children:tt?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Ct,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Ct,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Ct,{className:"font-semibold",children:"Agents"}),e.jsx(Ct,{className:"w-[150px]"})]})}),e.jsx(pa,{children:(()=>{const Lt=u.filter(hn=>hn.name.toLowerCase().includes(Rr.toLowerCase()));return Lt.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:Rr?"No brokerages match your search":"No brokerages found"})}):Lt.map(hn=>{const zn=l.filter(Ja=>Ja.brokerage_id===hn.id),Wn=(p[hn.id]??[]).map(Ja=>l.find(oi=>oi.id===Ja)).filter(Boolean),va=zn.length;return e.jsxs(Gs,{className:"hover:bg-muted/30",children:[e.jsx(ut,{children:e.jsx("button",{onClick:()=>rl(hn),className:"text-primary hover:underline font-medium",children:hn.name})}),e.jsx(ut,{children:Wn.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Wn.map(Ja=>e.jsx(ze,{variant:"secondary",className:"text-xs",children:Ja.name},Ja.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(ut,{children:[va," member",va!==1?"s":""]}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"h-8",onClick:()=>Hd(hn),children:[e.jsx(_n,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>rl(hn),title:"Edit brokerage",children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>fm(hn),title:"Delete brokerage",children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},hn.id)})})()})]})}),e.jsx(bs,{open:Ge,onOpenChange:dt,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Brokerage"}),e.jsx(Qn,{children:"Update brokerage details and manage managers"})]}),Bt&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(ge,{id:"edit-brokerage-name",value:Qt,onChange:Lt=>ns(Lt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{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 hn=(p[Bt.id]??[]).map(zn=>l.find(Or=>Or.id===zn)).filter(Boolean);return hn.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):hn.map(zn=>e.jsxs(ze,{variant:"default",className:"gap-1",children:[e.jsx(hh,{className:"h-3 w-3"}),zn.name,e.jsx("button",{onClick:()=>jn(zn.id,"brokerage_manager","remove",Bt.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(Fn,{className:"h-3 w-3"})})]},zn.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(Wo,{open:lr,onOpenChange:Fs,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":lr,className:"w-full justify-between",children:["Search for a member...",e.jsx(_r,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(zo,{className:"w-full p-0",align:"start",children:e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search by name or email..."}),e.jsxs(e0,{className:"max-h-[200px]",children:[e.jsx(t0,{children:"No members found."}),e.jsx(s0,{children:(()=>{const Lt=new Set(p[Bt.id]??[]);return l.filter(hn=>!Lt.has(hn.id)&&(n||hn.brokerage_id===Bt.id)).map(hn=>e.jsxs(ex,{value:`${hn.name} ${hn.email}`,onSelect:()=>{Sd(hn.id,Bt.id),Fs(!1)},children:[hn.name," (",hn.email,")"]},hn.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(Lt=>Lt.brokerage_id===Bt.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(Lt=>Lt.brokerage_id===Bt.id).map(Lt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:Lt.name}),Lt.roles.includes("brokerage_manager")&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Manager"})]},Lt.id))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:po,children:"Cancel"}),e.jsx(B,{onClick:zc,disabled:$s,children:$s?"Saving...":"Save Changes"})]})]})}),e.jsx(bs,{open:Dt,onOpenChange:St,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Qn,{children:['Are you sure you want to delete "',$t==null?void 0:$t.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 "',$t==null?void 0:$t.name,'"']}),e.jsxs("li",{children:["All ",l.filter(Lt=>Lt.brokerage_id===($t==null?void 0:$t.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>St(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Cd,disabled:Ut,children:Ut?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(bs,{open:Xt,onOpenChange:Ys,children:e.jsxs(vs,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-5 w-5"}),"Manage ",Ss==null?void 0:Ss.name]}),e.jsx(Qn,{children:"Add, remove, or manage users in this brokerage"})]}),Ss&&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(_r,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search members...",value:Us,onChange:Lt=>sn(Lt.target.value),className:"pl-10 h-9"})]}),e.jsxs(bs,{open:Jn,onOpenChange:fn,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Fo,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add New Agent"}),e.jsxs(Qn,{children:["Create a new agent for ",Ss.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-name",children:"Name"}),e.jsx(ge,{id:"agent-name",placeholder:"John Doe",value:Sn.name,onChange:Lt=>Gn({...Sn,name:Lt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-email",children:"Email"}),e.jsx(ge,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Sn.email,onChange:Lt=>Gn({...Sn,email:Lt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-password",children:"Password"}),e.jsx(ge,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Sn.password,onChange:Lt=>Gn({...Sn,password:Lt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(ge,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Sn.phone,onChange:Lt=>Gn({...Sn,phone:Lt.target.value})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>fn(!1),children:"Cancel"}),e.jsx(B,{onClick:lj,disabled:Hr,children:Hr?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(Wo,{open:$n,onOpenChange:Cr,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":$n,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(_r,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(zo,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search users...",value:ts,onValueChange:Oe}),e.jsxs(e0,{children:[e.jsx(t0,{children:"No users found."}),e.jsx(s0,{children:Py(Ss.id).filter(Lt=>ts===""||Lt.name.toLowerCase().includes(ts.toLowerCase())||Lt.email.toLowerCase().includes(ts.toLowerCase())).map(Lt=>e.jsxs(ex,{value:`${Lt.name} ${Lt.email}`,onSelect:()=>{i1(Lt.id,Ss.id),Cr(!1),Oe("")},children:[Lt.name," (",Lt.email,")"]},Lt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Ct,{className:"font-semibold",children:"Name"}),e.jsx(Ct,{className:"font-semibold",children:"Email"}),e.jsx(Ct,{className:"font-semibold",children:"Status"}),e.jsx(Ct,{className:"font-semibold",children:"Role"}),e.jsx(Ct,{className:"w-[120px]"})]})}),e.jsx(pa,{children:Iy(Ss.id).length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:Us?"No matching members found":"No members in this brokerage"})}):Iy(Ss.id).map(Lt=>e.jsxs(Gs,{className:"hover:bg-muted/30",children:[e.jsx(ut,{className:"font-medium",children:Lt.name}),e.jsx(ut,{className:"text-muted-foreground",children:Lt.email}),e.jsx(ut,{children:Lt.claimed?e.jsx(ze,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(ze,{variant:"secondary",children:"Pending"})}),e.jsx(ut,{children:Lt.roles.includes("brokerage_manager")?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(hh,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!Lt.claimed&&e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ea(Lt.id),title:"Resend welcome email",children:e.jsx(Hs,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Gd(Lt.id),title:"Remove from brokerage",children:e.jsx(Fn,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Zc(Lt.id),disabled:a||Lt.id===(t==null?void 0:t.id),title:Lt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Lt.name}`,children:a?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(LA,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Mi(Lt.id,Lt.name),title:"Delete user",children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},Lt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[xm(Ss.id).length," total member",xm(Ss.id).length!==1?"s":""," •",xm(Ss.id).filter(Lt=>Lt.roles.includes("brokerage_manager")).length," manager",xm(Ss.id).filter(Lt=>Lt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(Xn,{children:e.jsx(B,{variant:"outline",onClick:uc,children:"Close"})})]})})]}),e.jsx(ls,{value:"teams",children:e.jsx(r_s,{})}),e.jsx(ls,{value:"trials",children:e.jsx(Jbs,{})}),e.jsx(ls,{value:"celebrations",children:e.jsx(Xbs,{})}),e.jsx(ls,{value:"deletions",children:e.jsx(t_s,{})})]})]}),e.jsx(oyt,{open:Ms,onOpenChange:bi,brokerages:u,onSuccess:qn}),Un&&e.jsx(lyt,{open:ln,onOpenChange:Lt=>{Ks(Lt),Lt||br(null)},userId:Un.id,userName:Un.name}),e.jsx(a_s,{open:ye,onOpenChange:_e,recipients:l.filter(Lt=>Qe.has(Lt.id)).map(Lt=>({id:Lt.id,name:Lt.name,email:Lt.email}))})]})};function o_s(){const{toast:s}=Ua(),t=Gt(),[n,r]=N.useState(""),[a,i]=N.useState(new Set),[l,o]=N.useState({}),[c,d]=N.useState({}),[u,h]=N.useState(""),[p,f]=N.useState(!1),{data:g=[],isLoading:b}=lt({queryKey:["unassigned-members"],queryFn:async()=>{const{data:M,error:F}=await q.from("profiles").select("id, name, email, phone, created_at, subscription_status").is("brokerage_id",null).or("subscription_status.is.null,subscription_status.eq.none").order("created_at",{ascending:!1});if(F)throw F;return M||[]}}),{data:v=[]}=lt({queryKey:["brokerages-all"],queryFn:async()=>{const{data:M,error:F}=await q.from("brokerages").select("id, name").order("name");if(F)throw F;return M||[]}}),j=N.useMemo(()=>{const M=n.toLowerCase().trim();return M?g.filter(F=>(F.name||"").toLowerCase().includes(M)||(F.email||"").toLowerCase().includes(M)||(F.phone||"").toLowerCase().includes(M)):g},[g,n]),_=N.useMemo(()=>{var F;const M=new Map;for(const z of g){const V=(F=(z.email||"").split("@")[1])==null?void 0:F.toLowerCase();V&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes(V)||M.set(V,(M.get(V)||0)+1))}return Array.from(M.entries()).sort((z,V)=>V[1]-z[1]).slice(0,10)},[g]),S=M=>{i(F=>{const z=new Set(F);return z.has(M)?z.delete(M):z.add(M),z})},A=()=>{a.size===j.length?i(new Set):i(new Set(j.map(M=>M.id)))},T=async(M,F)=>{if(F){d(z=>({...z,[M]:!0}));try{const{data:z,error:V}=await q.functions.invoke("assign-brokerage",{body:{userId:M,brokerageId:F}});if(V)throw V;if(z!=null&&z.error)throw new Error(z.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i(W=>{const K=new Set(W);return K.delete(M),K})}catch(z){s({title:"Failed",description:z.message,variant:"destructive"})}finally{d(z=>({...z,[M]:!1}))}}},D=async()=>{if(!u||a.size===0)return;f(!0);let M=0,F=0;for(const z of a)try{const{data:V,error:W}=await q.functions.invoke("assign-brokerage",{body:{userId:z,brokerageId:u}});if(W||V!=null&&V.error)throw new Error((W==null?void 0:W.message)||V.error);M++}catch{F++}f(!1),s({title:`Assigned ${M}${F?`, ${F} failed`:""}`,description:"Bulk assignment complete.",variant:F?"destructive":"default"}),i(new Set),h(""),t.invalidateQueries({queryKey:["unassigned-members"]})},L=(M,F)=>{const z={...l};for(const V of g)(V.email||"").toLowerCase().endsWith(`@${M}`)&&(z[V.id]=F);o(z),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${M}`})};return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Unassigned Members",description:"Members with no brokerage and no active subscription — likely missed brokerage invites."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(_n,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-3xl font-bold",children:g.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4"})," Selected"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-3xl font-bold",children:_.length})})]})]}),_.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Ae,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:_.map(([M,F])=>{const z=v.find(V=>V.name.toLowerCase().replace(/[^a-z0-9]/g,"").includes(M.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:["@",M]}),e.jsx(ze,{variant:"secondary",children:F}),e.jsxs(us,{onValueChange:V=>L(M,V),defaultValue:z==null?void 0:z.id,children:[e.jsx(cs,{className:"h-8 w-[220px]",children:e.jsx(hs,{placeholder:"Apply brokerage…"})}),e.jsx(ds,{children:v.map(V=>e.jsx(Ze,{value:V.id,children:V.name},V.id))})]})]},M)})})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{value:n,onChange:M=>r(M.target.value),placeholder:"Search name, email, phone…",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(us,{value:u,onValueChange:h,children:[e.jsx(cs,{className:"w-[240px]",children:e.jsx(hs,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(ds,{children:v.map(M=>e.jsx(Ze,{value:M.id,children:M.name},M.id))})]}),e.jsxs(B,{onClick:D,disabled:!u||a.size===0||p,children:[p&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(Ae,{children:b?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length===0?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"🎉 No unassigned members."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-10",children:e.jsx(hi,{checked:a.size===j.length&&j.length>0,onCheckedChange:A})}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Signed up"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Assign to brokerage"}),e.jsx(Ct,{className:"w-24"})]})}),e.jsx(pa,{children:j.map(M=>{const F=l[M.id]||"";return e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsx(hi,{checked:a.has(M.id),onCheckedChange:()=>S(M.id)})}),e.jsx(ut,{className:"font-medium",children:M.name||"—"}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:M.email}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Go(new Date(M.created_at),{addSuffix:!0})}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",children:M.subscription_status||"none"})}),e.jsx(ut,{children:e.jsxs(us,{value:F,onValueChange:z=>o(V=>({...V,[M.id]:z})),children:[e.jsx(cs,{className:"h-9 w-[240px]",children:e.jsx(hs,{placeholder:"Pick brokerage…"})}),e.jsx(ds,{children:v.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))})]})}),e.jsx(ut,{children:e.jsx(B,{size:"sm",disabled:!F||c[M.id],onClick:()=>T(M.id,F),children:c[M.id]?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},M.id)})})]})})})]})]})})}const l_s=()=>{const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState("");N.useEffect(()=>{g()},[]);const g=async()=>{const{data:T,error:D}=await q.from("invite_codes").select("*").order("created_at",{ascending:!1});D?(ae.error("Failed to load invite codes"),console.error(D)):t(T||[]),r(!1)},b=async T=>{if(T.preventDefault(),!l.trim()){ae.error("Please enter a code");return}i(!0);const{error:D}=await q.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:p?parseInt(p):null});D?D.code==="23505"?ae.error("This code already exists"):(ae.error("Failed to create invite code"),console.error(D)):(ae.success("Invite code created"),o(""),d(""),h(""),f(""),g()),i(!1)},v=async(T,D)=>{const{error:L}=await q.from("invite_codes").update({is_active:!D}).eq("id",T);L?ae.error("Failed to update code"):t(s.map(M=>M.id===T?{...M,is_active:!D}:M))},j=async T=>{const{error:D}=await q.from("invite_codes").delete().eq("id",T);D?ae.error("Failed to delete code"):(ae.success("Code deleted"),t(s.filter(L=>L.id!==T)))},_="https://dashboard.relevelup.com",S=T=>{const D=`${_}/join?code=${T}`;navigator.clipboard.writeText(D),ae.success("Link copied to clipboard")},A=`${_}/join`;return e.jsx(Cs,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Create New Code"}),e.jsxs(Hn,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:A})]})]}),e.jsx(Ae,{children:e.jsxs("form",{onSubmit:b,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"code",children:"Code"}),e.jsx(ge,{id:"code",placeholder:"WELCOME2024",value:l,onChange:T=>o(T.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(se,{htmlFor:"description",children:"Description (optional)"}),e.jsx(ge,{id:"description",placeholder:"For marketing campaign",value:c,onChange:T=>d(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(ge,{id:"maxUses",type:"number",placeholder:"Unlimited",value:u,onChange:T=>h(T.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(ge,{id:"trialDays",type:"number",placeholder:"None",value:p,onChange:T=>f(T.target.value),className:"w-28"})]}),e.jsxs(B,{type:"submit",disabled:a,children:[a?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(As,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Active Codes"})}),e.jsx(Ae,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ss,{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(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Code"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{children:"Uses"}),e.jsx(Ct,{children:"Trial"}),e.jsx(Ct,{children:"Created"}),e.jsx(Ct,{children:"Active"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(pa,{children:s.map(T=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-mono font-medium",children:T.code}),e.jsx(ut,{className:"text-muted-foreground",children:T.description||"—"}),e.jsxs(ut,{children:[T.uses_count,T.max_uses&&` / ${T.max_uses}`]}),e.jsx(ut,{children:T.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[T.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ut,{className:"text-muted-foreground",children:ks(new Date(T.created_at),"MMM d, yyyy")}),e.jsx(ut,{children:e.jsx(vn,{checked:T.is_active,onCheckedChange:()=>v(T.id,T.is_active)})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>S(T.code),title:"Copy invite link",children:e.jsx(ta,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>j(T.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},T.id))})]})})]})]})})},B2=q;function jgn(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 c_s(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}function Ngn(s,t){const n=`${window.location.origin}/live/${s}`;return t?`${n}?i=${t}`:n}function kgn(){const s=Gt(),t=lt({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await B2.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=gt({mutationFn:async i=>{var d;const{data:l}=await q.auth.getUser(),{data:o,error:c}=await B2.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=gt({mutationFn:async({id:i,...l})=>{const{error:o}=await B2.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=gt({mutationFn:async i=>{const{error:l}=await B2.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 Sgn(s){return lt({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await B2.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function Cgn(s){return lt({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await B2.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function Tgn(s){const t=Gt(),n=lt({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await B2.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=gt({mutationFn:async i=>{const{data:l}=await q.auth.getUser(),o=i.map(u=>{var h;return{event_id:s,code:crypto.randomUUID().replace(/-/g,"").slice(0,12),name:u.name||null,email:u.email||null,phone:u.phone||null,brokerage:u.brokerage||null,created_by:(h=l.user)==null?void 0:h.id}}),{data:c,error:d}=await B2.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=gt({mutationFn:async i=>{const{error:l}=await B2.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 TU=async s=>{try{const{data:t,error:n}=await q.from("push_notification_settings").select("is_enabled").eq("setting_key",s).maybeSingle();return n?(console.error("Error checking notification setting:",n),!0):(t==null?void 0:t.is_enabled)??!0}catch(t){return console.error("Error checking notification setting:",t),!0}},nR=async s=>{try{const{data:t,error:n}=await q.functions.invoke("send-push-notification",{body:s});return n?(console.error("Error sending notification:",n),{success:!1,error:n}):(console.log("Notification sent:",t),{success:!0,data:t})}catch(t){return console.error("Error sending notification:",t),{success:!1,error:t}}},d_s=async(s,t)=>await TU("new_templates")?nR({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}),u_s=async(s,t)=>nR({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),h_s=async(s,t)=>await TU("new_events")?nR({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),m_s=async(s,t)=>await TU("new_toolbox")?nR({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),j3e=async(s,t)=>await TU("new_social_swag")?nR({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}),p_s=async(s,t)=>await TU("new_newsletters")?nR({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),V2e=400;function f_s(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 x_s(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await q.from("profiles").select("id, name, email, event_invite_opt_out").not("email","is",null).neq("email","").eq("event_invite_opt_out",!1).order("created_at",{ascending:!1}).range(t,t+n-1);if(a)throw a;if(!r||r.length===0)break;for(const i of r)i.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i.email)&&s.push({id:i.id,name:i.name||"",email:i.email});if(r.length{if(!s||!n)return;let ne=!1;return(async()=>{h(!0);try{const[oe,pe,ce]=await Promise.all([x_s(),ZHe("event_registrations",n.id),ZHe("event_attendees",n.id)]);if(ne)return;f(oe),b(pe),j(ce)}catch(oe){ne||r({title:"Could not load audience",description:oe instanceof Error?oe.message:"Unknown error",variant:"destructive"})}finally{ne||h(!1)}})(),()=>{ne=!0}},[s,n,r]),N.useEffect(()=>{s||(T(null),d(""),o(""),i("not_registered"))},[s]);const z=N.useMemo(()=>a==="all"?p:a==="not_registered"?p.filter(ne=>!g.has(ne.id)):p.filter(ne=>g.has(ne.id)&&!v.has(ne.id)),[a,p,g,v]),V={all:p.length,not_registered:p.filter(ne=>!g.has(ne.id)).length,registered_never_attended:p.filter(ne=>g.has(ne.id)&&!v.has(ne.id)).length},W=async ne=>{const{data:{session:oe}}=await q.auth.getSession(),pe=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:ne.map(de=>({email:de.email,name:de.name,user_id:de.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0})}),ce=await pe.json().catch(()=>({}));if(!pe.ok)throw new Error((ce==null?void 0:ce.error)||`HTTP ${pe.status}`);return{sent:(ce==null?void 0:ce.sent)??0,failed:(ce==null?void 0:ce.failed)??0}},K=async()=>{var ne;if(n){F(!0);try{const{data:{session:oe}}=await q.auth.getSession(),pe=oe==null?void 0:oe.user;if(!(pe!=null&&pe.email))throw new Error("No signed-in email found");const ce=await W([{id:pe.id,name:((ne=pe.user_metadata)==null?void 0:ne.name)||"",email:pe.email}]);r({title:"Test sent",description:`Sent to ${pe.email} · Sent: ${ce.sent} · Failed: ${ce.failed}`})}catch(oe){r({title:"Test failed",description:oe instanceof Error?oe.message:"Unknown error",variant:"destructive"})}finally{F(!1)}}},Y=async()=>{if(!(!n||z.length===0)){L(!1),S(!0),T({done:0,total:z.length,sent:0,failed:0});try{let ne=0,oe=0;for(let pe=0;pe!_&&t(ne),children:e.jsxs(vs,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(Qn,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(cm,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:f_s(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(se,{className:"flex items-center gap-2",children:[e.jsx(_n,{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(ss,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(db,{value:a,onValueChange:ne=>i(ne),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(Fd,{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:V.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(Fd,{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:V.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(Fd,{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:V.registered_never_attended.toLocaleString()})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"ev-inv-subject",children:"Subject line (optional)"}),e.jsx(ge,{id:"ev-inv-subject",placeholder:n?`You're invited: ${n.title}`:"You're invited to...",value:l,onChange:ne=>o(ne.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(se,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Ts,{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:ne=>d(ne.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."})]}),A&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Sending ",A.done.toLocaleString()," / ",A.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",A.sent.toLocaleString(),A.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",A.failed.toLocaleString()]})]})]}),e.jsx(xi,{value:ee})]})]}),e.jsxs(Xn,{className:"gap-2 sm:gap-2",children:[e.jsx(B,{variant:"outline",onClick:K,disabled:_||M||u,children:M?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsx(B,{onClick:()=>L(!0),disabled:_||u||z.length===0,children:_?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send to ",z.length.toLocaleString()]})})]})]})}),e.jsx(Oo,{open:D,onOpenChange:L,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Send event invite?"}),e.jsxs(Mo,{children:["This will send a branded invite to"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[z.length.toLocaleString()," member",z.length===1?"":"s"]})," ","for"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:['"',n==null?void 0:n.title,'"']}),". This can't be undone."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsxs(jo,{onClick:Y,children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const YH={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 y_s(){const s=In(),t=Gt(),[n,r]=N.useState(!1),[a,i]=N.useState(null),[l,o]=N.useState(YH),[c,d]=N.useState(null),[u,h]=N.useState(null),[p,f]=N.useState(!1),g=N.useRef(null),[b,v]=N.useState(!1),[j,_]=N.useState(null),[S,A]=N.useState(!1),[T,D]=N.useState(null),[L,M]=N.useState(null),[F,z]=N.useState(!0),[V,W]=N.useState(""),[K,Y]=N.useState(!1),[ee,ne]=N.useState(null),{data:oe,isLoading:pe}=lt({queryKey:["admin-events"],queryFn:async()=>{const{data:Ge,error:dt}=await q.from("events").select("*").order("event_date",{ascending:!0});if(dt)throw dt;return Ge}}),{data:ce}=lt({queryKey:["event-registrations-count"],queryFn:async()=>{let Ge=[],dt=0;const Bt=1e3;for(;;){const{data:Qt,error:ns}=await q.from("event_registrations").select("event_id").range(dt,dt+Bt-1);if(ns)throw ns;if(!Qt||Qt.length===0||(Ge=Ge.concat(Qt),Qt.length{kt[Qt.event_id]=(kt[Qt.event_id]||0)+1}),kt}}),{data:de,isLoading:ie}=lt({queryKey:["event-registrations-details",j==null?void 0:j.id],queryFn:async()=>{if(!j)return[];const{data:Ge,error:dt}=await q.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",j.id).order("registered_at",{ascending:!1});if(dt)throw dt;if(!Ge||Ge.length===0)return[];const Bt=Ge.map(ns=>ns.user_id).filter(Boolean);let kt=[];if(Bt.length>0){const{data:ns,error:$s}=await q.from("profiles").select("id, name, email").in("id",Bt);if($s)throw $s;kt=ns||[]}const Qt=new Map((kt==null?void 0:kt.map(ns=>[ns.id,ns]))||[]);return Ge.map(ns=>({...ns,profiles:ns.user_id&&Qt.get(ns.user_id)||null}))},enabled:!!j}),{data:ye,isLoading:_e}=lt({queryKey:["event-attendees-details",j==null?void 0:j.id],queryFn:async()=>{if(!j)return[];const{data:Ge,error:dt}=await q.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",j.id).order("created_at",{ascending:!1});if(dt)throw dt;if(!Ge||Ge.length===0)return[];const Bt=Ge.map(Ds=>Ds.user_id).filter(Boolean);let kt=[];if(Bt.length>0){const{data:Ds,error:Dt}=await q.from("profiles").select("id, name, email").in("id",Bt);if(Dt)throw Dt;kt=Ds||[]}const{data:Qt}=await q.from("agent_points").select("user_id").eq("event_id",j.id),ns=new Set((Qt==null?void 0:Qt.map(Ds=>Ds.user_id))||[]),$s=new Map((kt==null?void 0:kt.map(Ds=>[Ds.id,Ds]))||[]);return Ge.map(Ds=>({...Ds,profiles:Ds.user_id&&$s.get(Ds.user_id)||null,points_awarded:Ds.user_id?ns.has(Ds.user_id):!1}))},enabled:!!j}),Me=Ge=>{_(Ge),v(!0)},Te=gt({mutationFn:async Ge=>{const{data:{session:dt}}=await q.auth.getSession();if(!dt)throw new Error("Not authenticated");const Bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dt.access_token}`},body:JSON.stringify({event_id:Ge})}),kt=await Bt.json();if(!Bt.ok){const Qt=new Error(kt.error||"Failed to sync");throw Qt.scopeError=!!kt.scope_error,Qt.details=kt.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,Qt}return kt},onSuccess:Ge=>{if(t.invalidateQueries({queryKey:["event-registrations-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),Ge!=null&&Ge.scope_error||(Ge==null?void 0:Ge.success)===!1){ae.error("Zoom needs one more authorization step",{description:Ge!=null&&Ge.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.":(Ge==null?void 0:Ge.message)||"Zoom registration sync could not complete.",duration:2e4});return}ae.success(Ge.message)},onError:Ge=>{ae.error("Failed to sync Zoom registrations",{description:Ge.scopeError&&Ge.details||Ge.message,duration:Ge.scopeError?2e4:5e3})}}),Ce=gt({mutationFn:async Ge=>{const{data:{session:dt}}=await q.auth.getSession();if(!dt)throw new Error("Not authenticated");const Bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dt.access_token}`},body:JSON.stringify({event_id:Ge})}),kt=await Bt.json();if(!Bt.ok)throw new Error(kt.error||"Failed to sync attendees");return kt},onSuccess:Ge=>{if(t.invalidateQueries({queryKey:["event-attendees-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ge!=null&&Ge.scope_error||(Ge==null?void 0:Ge.success)===!1){ae.error((Ge==null?void 0:Ge.message)||"Zoom sync failed",{description:Ge!=null&&Ge.scope_error?"Zoom must be re-authorized after adding the missing report scope.":void 0,duration:15e3});return}Ge!=null&&Ge.message?ae.success(Ge.message):ae.success(`Synced ${Ge.synced||0} attendees. ${Ge.points_awarded||0} points awarded!`)},onError:Ge=>{ae.error("Failed to sync attendees: "+Ge.message)}}),Ee=gt({mutationFn:async()=>{const{data:Ge,error:dt}=await q.functions.invoke("zoom-retry-registrations",{body:{}});if(dt)throw dt;return Ge},onSuccess:Ge=>{t.invalidateQueries({queryKey:["event-registrations-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ae.success(`Retry complete: ${(Ge==null?void 0:Ge.successCount)??0} fixed, ${(Ge==null?void 0:Ge.failCount)??0} still failing, ${(Ge==null?void 0:Ge.rateLimitedCount)??0} rate-limited`)},onError:Ge=>{ae.error("Retry failed: "+Ge.message)}}),De=gt({mutationFn:async({eventId:Ge,testMode:dt})=>{const{data:{session:Bt}}=await q.auth.getSession();if(!Bt)throw new Error("Not authenticated");const kt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Bt.access_token}`},body:JSON.stringify({event_id:Ge,test_mode:dt})}),Qt=await kt.json();if(!kt.ok)throw new Error(Qt.error||"Failed to send reminders");return Qt},onSuccess:Ge=>{Ge.test?ae.success(Ge.message||"Test email sent!"):ae.success(Ge.message||`Reminder emails sent to ${Ge.sent} registrants!`)},onError:Ge=>{ae.error("Failed to send reminders: "+Ge.message)}}),{data:Ie}=lt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ge=[],dt=0;const Bt=1e3;for(;;){const{data:kt,error:Qt}=await q.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(dt,dt+Bt-1);if(Qt)throw Qt;if(!kt||kt.length===0||(Ge=[...Ge,...kt],kt.length{const{error:Qt}=await q.from("event_attendees").update({user_id:dt}).eq("id",Ge);if(Qt)throw Qt;if(kt&&Bt){const{error:$s}=await q.from("zoom_email_aliases").upsert({user_id:dt,zoom_email:Bt.toLowerCase()},{onConflict:"zoom_email"});$s&&console.error("Failed to save alias:",$s)}const ns=j==null?void 0:j.id;if(ns){const{data:$s}=await q.from("user_roles").select("id").eq("user_id",dt).eq("role","admin").single();if(!$s){const{data:Ds}=await q.from("agent_points").select("id").eq("user_id",dt).eq("event_id",ns).single();Ds||(await q.rpc("award_attendance_points",{p_user_id:dt,p_event_id:ns,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await q.rpc("check_and_award_badges",{p_user_id:dt}))}}return{userId:dt,zoomEmail:Bt,shouldSaveAlias:kt}},onSuccess:Ge=>{t.invalidateQueries({queryKey:["event-attendees-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let dt="Attendee linked and points awarded!";Ge.shouldSaveAlias&&Ge.zoomEmail&&(dt+=` Email "${Ge.zoomEmail}" will be auto-matched in the future.`),ae.success(dt),A(!1),D(null),M(null),W("")},onError:Ge=>{ae.error("Failed to link attendee: "+Ge.message)}}),qe=Ge=>{D(Ge),M(null),z(!0),W(""),A(!0)},ve=()=>{!T||!L||Fe.mutate({attendeeId:T.id,userId:L,zoomEmail:T.zoom_email,shouldSaveAlias:F})},Je=(Ie==null?void 0:Ie.filter(Ge=>{var Bt,kt;if(!V)return!0;const dt=V.toLowerCase();return((Bt=Ge.name)==null?void 0:Bt.toLowerCase().includes(dt))||((kt=Ge.email)==null?void 0:kt.toLowerCase().includes(dt))}))||[],we=async Ge=>{const dt=Ge.name.split(".").pop(),kt=`${`${crypto.randomUUID()}.${dt}`}`,{error:Qt}=await q.storage.from("event-images").upload(kt,Ge);if(Qt)throw Qt;const{data:{publicUrl:ns}}=q.storage.from("event-images").getPublicUrl(kt);return ns},it=Ge=>{var Bt;const dt=(Bt=Ge.target.files)==null?void 0:Bt[0];if(dt){if(dt.size>5*1024*1024){ae.error("Image must be less than 5MB");return}d(dt),h(URL.createObjectURL(dt))}},Ne=()=>{d(null),h(null),o({...l,image_url:""}),g.current&&(g.current.value="")},He=gt({mutationFn:async Ge=>{f(!0);let dt=Ge.image_url;c&&(dt=await we(c)||"");const Bt=new Date(Ge.event_date),[kt,Qt]=Ge.event_time.split(":");Bt.setHours(parseInt(kt),parseInt(Qt));const ns=[new Date(Bt)];if(Ge.is_recurring&&Ge.recurrence_end_date){let St=new Date(Bt);for(;Ge.recurrence_pattern==="weekly"?St=F2(St,1):Ge.recurrence_pattern==="biweekly"?St=F2(St,2):St=kf(St,1),!(St>Ge.recurrence_end_date);)ns.push(new Date(St))}const $s=ns.map(St=>({title:Ge.title,description:Ge.description||null,image_url:dt||null,video_url:Ge.video_url||null,event_date:St.toISOString(),zoom_link:Ge.zoom_link,zoom_meeting_id:Ge.zoom_meeting_id||null,capacity:Ge.capacity?parseInt(Ge.capacity):null,is_published:Ge.is_published})),{data:Ds,error:Dt}=await q.from("events").insert($s).select();if(Dt)throw Dt;return Ds&&Ds.length>0&&h_s(Ge.title,Ds[0].id),ns.length},onSuccess:Ge=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success(Ge>1?`${Ge} recurring events created successfully`:"Event created successfully"),r(!1),o(YH),d(null),h(null),f(!1)},onError:Ge=>{ae.error("Failed to create event: "+Ge.message),f(!1)}}),$e=gt({mutationFn:async({id:Ge,data:dt})=>{f(!0);let Bt=dt.image_url;c&&(Bt=await we(c)||"");const kt=new Date(dt.event_date),[Qt,ns]=dt.event_time.split(":");kt.setHours(parseInt(Qt),parseInt(ns));const{error:$s}=await q.from("events").update({title:dt.title,description:dt.description||null,image_url:Bt||null,video_url:dt.video_url||null,event_date:kt.toISOString(),zoom_link:dt.zoom_link,zoom_meeting_id:dt.zoom_meeting_id||null,capacity:dt.capacity?parseInt(dt.capacity):null,is_published:dt.is_published}).eq("id",Ge);if($s)throw $s},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success("Event updated successfully"),r(!1),i(null),o(YH),d(null),h(null),f(!1)},onError:Ge=>{ae.error("Failed to update event: "+Ge.message),f(!1)}}),Ye=gt({mutationFn:async Ge=>{const{error:dt}=await q.from("events").delete().eq("id",Ge);if(dt)throw dt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success("Event deleted successfully")},onError:Ge=>{ae.error("Failed to delete event: "+Ge.message)}}),Ke=gt({mutationFn:async Ge=>{var St;const{data:dt}=await q.auth.getUser(),Bt=new Date(Ge.event_date),kt=new Date(Bt.getTime()+60*60*1e3),Qt=c_s(Ge.title),ns=Math.random().toString(36).slice(2,7),$s=`${Qt}-${ns}`,{data:Ds,error:Dt}=await q.from("live_events").insert({slug:$s,title:Ge.title,description:Ge.description||null,hero_image_url:Ge.image_url||null,starts_at:Ge.event_date,ends_at:kt.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:Ge.zoom_meeting_id||null,cta_label:"Join the training",cta_url:Ge.zoom_link||"https://dashboard.relevelup.com/trial",created_by:(St=dt.user)==null?void 0:St.id,agenda:[],offer_bullets:[]}).select().single();if(Dt)throw Dt;return Ds},onSuccess:Ge=>{t.invalidateQueries({queryKey:["live-events"]}),ae.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${Ge.id}`)},onError:Ge=>{ae.error("Failed to clone to LevelUp Live: "+Ge.message)}}),rt=Ge=>{var Bt;const dt=new Date(Ge.event_date);i(Ge),o({title:Ge.title,description:Ge.description||"",image_url:Ge.image_url||"",video_url:Ge.video_url||"",event_date:dt,event_time:ks(dt,"HH:mm"),zoom_link:Ge.zoom_link,zoom_meeting_id:Ge.zoom_meeting_id||"",capacity:((Bt=Ge.capacity)==null?void 0:Bt.toString())||"",is_published:Ge.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),h(Ge.image_url||null),d(null),r(!0)},tt=Ge=>{if(Ge.preventDefault(),!l.event_date){ae.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){ae.error("Please select an end date for recurring events");return}a?$e.mutate({id:a.id,data:l}):He.mutate(l)},at=()=>{r(!1),i(null),o(YH),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(Vd,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(fe,{className:"mb-6",children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Pt,{children:"All Events"}),e.jsxs(bs,{open:n,onOpenChange:Ge=>!Ge&&at(),children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:tt,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ge,{id:"title",value:l.title,onChange:Ge=>o({...l,title:Ge.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Db,{content:l.description,onChange:Ge=>o({...l,description:Ge}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Event Image"}),e.jsx("input",{type:"file",ref:g,accept:"image/*",onChange:it,className:"hidden"}),u?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:u,alt:"Event preview",className:"w-full h-32 object-cover rounded-lg border"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:Ne,children:e.jsx(Fn,{className:"h-4 w-4"})})]}):e.jsxs(B,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var Ge;return(Ge=g.current)==null?void 0:Ge.click()},children:[e.jsx(Sa,{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(se,{children:"Date *"}),e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),l.event_date?ks(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:l.event_date,onSelect:Ge=>o({...l,event_date:Ge}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"time",children:"Time *"}),e.jsx(ge,{id:"time",type:"time",value:l.event_time,onChange:Ge=>o({...l,event_time:Ge.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(ge,{id:"zoom_link",value:l.zoom_link,onChange:Ge=>o({...l,zoom_link:Ge.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(ge,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:Ge=>o({...l,zoom_meeting_id:Ge.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(se,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(ge,{id:"video_url",value:l.video_url,onChange:Ge=>o({...l,video_url:Ge.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(se,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(ge,{id:"capacity",type:"number",value:l.capacity,onChange:Ge=>o({...l,capacity:Ge.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(vL,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(vn,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:Ge=>o({...l,is_recurring:Ge})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Frequency"}),e.jsxs(us,{value:l.recurrence_pattern,onValueChange:Ge=>o({...l,recurrence_pattern:Ge}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"weekly",children:"Weekly"}),e.jsx(Ze,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(Ze,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Repeat Until"}),e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?ks(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:l.recurrence_end_date,onSelect:Ge=>o({...l,recurrence_end_date:Ge}),disabled:Ge=>Ge<(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 Ge=1,dt=new Date(l.event_date);for(;dt=l.recurrence_pattern==="weekly"?F2(dt,1):l.recurrence_pattern==="biweekly"?F2(dt,2):kf(dt,1),!(dt>l.recurrence_end_date);)Ge++;return Ge})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{htmlFor:"is_published",children:"Published"}),e.jsx(vn,{id:"is_published",checked:l.is_published,onCheckedChange:Ge=>o({...l,is_published:Ge})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:at,className:"flex-1",children:"Cancel"}),e.jsx(B,{type:"submit",className:"flex-1",disabled:He.isPending||$e.isPending||p,children:p?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(Ae,{children:pe?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(oe==null?void 0:oe.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const Ge=new Date,dt=[...oe||[]],Bt=dt.filter(Ds=>new Date(Ds.event_date)>=Ge).sort((Ds,Dt)=>new Date(Ds.event_date).getTime()-new Date(Dt.event_date).getTime()),kt=dt.filter(Ds=>new Date(Ds.event_date)new Date(Dt.event_date).getTime()-new Date(Ds.event_date).getTime()),Qt=Bt[0],ns=Ds=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:Ds.title}),e.jsx(ut,{className:"whitespace-nowrap",children:ks(new Date(Ds.event_date),"PPP p")}),e.jsx(ut,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>Me(Ds),children:[e.jsx(_n,{className:"h-4 w-4"}),(ce==null?void 0:ce[Ds.id])||0,Ds.capacity&&` / ${Ds.capacity}`]})}),e.jsx(ut,{children:e.jsx("span",{className:Et("px-2 py-1 rounded-full text-xs font-medium",Ds.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:Ds.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{ne(Ds),Y(!0)},title:"Send invite email to members",children:[e.jsx(cr,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Invite Members"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Ke.mutate(Ds),disabled:Ke.isPending,title:"Clone to LevelUp Live",children:[e.jsx(wf,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"LevelUp Live"})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(Ds.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(tr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>rt(Ds),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this event?")&&Ye.mutate(Ds.id)},children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},Ds.id),$s=(Ds,Dt)=>Ds.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:Dt}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Date & Time"}),e.jsx(Ct,{children:"Registrations"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:Ds.map(ns)})]});return e.jsxs("div",{className:"space-y-6",children:[Qt&&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(gr,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:Qt.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:ks(new Date(Qt.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(ce==null?void 0:ce[Qt.id])||0," registered",Qt.capacity?` of ${Qt.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>{ne(Qt),Y(!0)},children:[e.jsx(cr,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>Me(Qt),children:[e.jsx(_n,{className:"h-4 w-4"}),"Registrations"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Ke.mutate(Qt),disabled:Ke.isPending,children:[e.jsx(wf,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(Qt.zoom_link,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs($r,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"upcoming",className:"gap-2",children:[e.jsx(gr,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:Bt.length})]}),e.jsxs(Zt,{value:"past",className:"gap-2",children:[e.jsx(xr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:kt.length})]})]}),e.jsx(ls,{value:"upcoming",className:"mt-4",children:$s(Bt,"No upcoming events scheduled.")}),e.jsx(ls,{value:"past",className:"mt-4",children:$s(kt,"No past events.")})]})]})})()})]}),e.jsx(g_s,{open:K,onOpenChange:Y,event:ee}),e.jsx(bs,{open:b,onOpenChange:v,children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5"}),j==null?void 0:j.title]}),e.jsx(Qn,{children:"View registrations and attendees for this event"})]}),e.jsxs("div",{className:"flex items-center justify-end mb-4 gap-2 flex-wrap",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>De.mutate({eventId:j.id,testMode:!0}),disabled:De.isPending,children:[e.jsx(Hs,{className:Et("h-4 w-4 mr-2",De.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>De.mutate({eventId:j.id}),disabled:De.isPending||!(de!=null&&de.length),children:[e.jsx(Hs,{className:Et("h-4 w-4 mr-2",De.isPending&&"animate-spin")}),De.isPending?"Sending...":"Send Reminder to All"]}),(j==null?void 0:j.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Te.mutate(j.id),disabled:Te.isPending,children:[e.jsx(Ai,{className:Et("h-4 w-4 mr-2",Te.isPending&&"animate-spin")}),Te.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Ee.mutate(),disabled:Ee.isPending,children:[e.jsx(Ai,{className:Et("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),Ee.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>Ce.mutate(j.id),disabled:Ce.isPending,children:[e.jsx(vo,{className:Et("h-4 w-4 mr-2",Ce.isPending&&"animate-spin")}),Ce.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs($r,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"registrations",className:"gap-2",children:[e.jsx(_n,{className:"h-4 w-4"}),"Registrations (",(de==null?void 0:de.length)||0,")"]}),e.jsxs(Zt,{value:"attendees",className:"gap-2",children:[e.jsx(xr,{className:"h-4 w-4"}),"Attendees (",(ye==null?void 0:ye.length)||0,")"]})]}),e.jsx(ls,{value:"registrations",className:"mt-4",children:ie?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(de==null?void 0:de.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(j==null?void 0:j.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Registered"}),e.jsx(Ct,{children:"Status"})]})}),e.jsx(pa,{children:de==null?void 0:de.map(Ge=>{var Qt,ns;const dt=((Qt=Ge.profiles)==null?void 0:Qt.name)||Ge.zoom_name||"Unknown",Bt=((ns=Ge.profiles)==null?void 0:ns.email)||Ge.zoom_email||null,kt=!Ge.user_id;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[dt,kt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(ut,{children:Bt?e.jsxs("a",{href:`mailto:${Bt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Hs,{className:"h-3 w-3"}),Bt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(ut,{className:"text-muted-foreground text-sm",children:ks(new Date(Ge.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(ut,{children:Ge.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"})})]},Ge.id)})})]})}),e.jsx(ls,{value:"attendees",className:"mt-4",children:_e?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(ye==null?void 0:ye.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(j==null?void 0:j.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Attendees & Award Points" after the event ends to import actual participants from Zoom.'})]}):e.jsxs(e.Fragment,{children:[(ye==null?void 0:ye.filter(Ge=>!Ge.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(Gi,{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 (",ye==null?void 0:ye.filter(Ge=>!Ge.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:ye==null?void 0:ye.filter(Ge=>!Ge.user_id).map(Ge=>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:Ge.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ge.zoom_email||"No email"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>qe(Ge),className:"gap-1",children:[e.jsx(El,{className:"h-3 w-3"}),"Link to Profile"]})]},Ge.id))})]}),e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Duration"}),e.jsx(Ct,{children:"Points"})]})}),e.jsx(pa,{children:ye==null?void 0:ye.filter(Ge=>Ge.user_id).map(Ge=>{var kt,Qt;const dt=((kt=Ge.profiles)==null?void 0:kt.name)||Ge.zoom_name||"Unknown",Bt=((Qt=Ge.profiles)==null?void 0:Qt.email)||Ge.zoom_email||null;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[dt,Ge.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(ut,{children:Bt?e.jsxs("a",{href:`mailto:${Bt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Hs,{className:"h-3 w-3"}),Bt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(ut,{children:Ge.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(gr,{className:"h-3 w-3"}),Ge.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ut,{children:Ge.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(vo,{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"})})]},Ge.id)})})]})]})})]})]})}),e.jsx(bs,{open:S,onOpenChange:A,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(El,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Qn,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),T&&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:T.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:T.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name or email...",value:V,onChange:Ge=>W(Ge.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Je.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No profiles found"}):e.jsx("div",{className:"divide-y",children:Je.slice(0,20).map(Ge=>e.jsxs("button",{type:"button",onClick:()=>M(Ge.id),className:Et("w-full p-3 text-left hover:bg-muted/50 transition-colors",L===Ge.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:Ge.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ge.email})]},Ge.id))})}),T.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(hi,{id:"save-alias",checked:F,onCheckedChange:Ge=>z(Ge)}),e.jsx("label",{htmlFor:"save-alias",className:"text-sm text-muted-foreground cursor-pointer",children:"Remember this email for future auto-matching"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsx(B,{onClick:ve,disabled:!L||Fe.isPending,children:Fe.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const v_s={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 b_s(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState("issues");async function l(){r(!0);let o=q.from("mcp_audit_log").select("id, user_id, tool_name, outcome, error_message, duration_ms, client_id, created_at").order("created_at",{ascending:!1}).limit(200);a==="issues"&&(o=o.in("outcome",["denied","rate_limited","error"]));const{data:c,error:d}=await o;d||t(c??[]),r(!1)}return N.useEffect(()=>{l()},[a]),e.jsx(Cs,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(bL,{className:"h-5 w-5"}),"Recent activity"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:a==="issues"?"default":"outline",size:"sm",onClick:()=>i("issues"),children:"Issues only"}),e.jsx(B,{variant:a==="all"?"default":"outline",size:"sm",onClick:()=>i("all"),children:"All calls"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:l,disabled:n,children:e.jsx(Ai,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Ae,{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(ze,{className:v_s[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 __s({selectedKitIds:s,onChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l=[]}=lt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:h,error:p}=await q.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(p)throw p;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(p=>p!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Oc,{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(ze,{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(Fn,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Wo,{open:a,onOpenChange:i,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Oc,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(zo,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(_r,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ge,{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(Oc,{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 w_s=()=>{const{user:s}=gs(),{toast:t}=Ua(),n=Gt(),[r,a]=yl(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),[h,p]=N.useState(null),[f,g]=N.useState(0),[b,v]=N.useState(!1),[j,_]=N.useState(null),[S,A]=N.useState(""),[T,D]=N.useState([]),[L,M]=N.useState(""),[F,z]=N.useState(""),[V,W]=N.useState(!1),[K,Y]=N.useState(!1),{data:ee=[]}=lt({queryKey:["template-categories"],queryFn:async()=>{const{data:Ne,error:He}=await q.from("template_categories").select("*").order("name");if(He)throw He;return Ne}}),{data:ne=[]}=lt({queryKey:["template-types"],queryFn:async()=>{const{data:Ne,error:He}=await q.from("template_types").select("*").order("name");if(He)throw He;return Ne}}),{data:oe=[],isLoading:pe}=lt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Ne,error:He}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(He)throw He;const{data:$e,error:Ye}=await q.from("template_links").select("*").order("sort_order");if(Ye)throw Ye;const{data:Ke,error:rt}=await q.from("template_guides").select("*").order("sort_order");if(rt)throw rt;return Ne.map(at=>({...at,links:($e==null?void 0:$e.filter(Ge=>Ge.template_id===at.id))||[],guides:(Ke==null?void 0:Ke.filter(Ge=>Ge.template_id===at.id))||[]}))}});N.useEffect(()=>{const Ne=r.get("edit");if(Ne&&oe.length>0){const He=oe.find($e=>$e.id===Ne);He&&(Te(He),a({},{replace:!0}))}},[oe,r]);const ce=gt({mutationFn:async Ne=>{const{data:He,error:$e}=await q.from("template_categories").insert({name:Ne}).select().single();if($e)throw $e;return He},onSuccess:Ne=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:Ne.id}),M(""),W(!1),t({title:"Category added"})},onError:Ne=>{t({title:"Error adding category",description:Ne.message,variant:"destructive"})}}),de=gt({mutationFn:async Ne=>{const{data:He,error:$e}=await q.from("template_types").insert({name:Ne}).select().single();if($e)throw $e;return He},onSuccess:Ne=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:Ne.id}),z(""),Y(!1),t({title:"Type added"})},onError:Ne=>{t({title:"Error adding type",description:Ne.message,variant:"destructive"})}}),ie=gt({mutationFn:async Ne=>{var rt;let He=Ne.existingImageUrl;if(Ne.image){const tt=Ne.image.name.split(".").pop(),at=`${Date.now()}-${Math.random().toString(36).substring(7)}.${tt}`,{error:Ge}=await q.storage.from("template-previews").upload(at,Ne.image);if(Ge)throw Ge;const{data:dt}=q.storage.from("template-previews").getPublicUrl(at);He=dt.publicUrl}const $e={name:Ne.template.name,description:Ne.template.description||null,category_id:Ne.template.category_id||null,type_id:Ne.template.type_id||null,preview_image_url:He,video_url:Ne.videoUrl||null,publish_date:Ne.template.publish_date?new Date(Ne.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let Ye=Ne.templateId;if(Ye){const{error:tt}=await q.from("canva_templates").update($e).eq("id",Ye);if(tt)throw tt;const{error:at}=await q.from("template_links").delete().eq("template_id",Ye);if(at)throw at;const Ge=((rt=Ne.existingGuides)==null?void 0:rt.map(kt=>kt.id).filter(Boolean))||[],dt=Ne.template.guides.map(kt=>kt.id).filter(Boolean),Bt=Ge.filter(kt=>!dt.includes(kt));Bt.length>0&&await q.from("template_guides").delete().in("id",Bt)}else{const{data:tt,error:at}=await q.from("canva_templates").insert($e).select().single();if(at)throw at;Ye=tt.id,d_s(Ne.template.name,tt.id)}const Ke=Ne.template.links.filter(tt=>tt.title.trim()&&tt.canva_share_link.trim());if(Ke.length>0){const tt=Ke.map((Ge,dt)=>({template_id:Ye,title:Ge.title.trim(),canva_share_link:Ge.canva_share_link.trim(),sort_order:dt})),{error:at}=await q.from("template_links").insert(tt);if(at)throw at}for(let tt=0;tt0)){const{error:tt}=await q.from("resource_kit_templates").insert(Ne.linkedKitIds.map(at=>({template_id:Ye,kit_id:at})));if(tt)throw tt}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),Me(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Ne=>{t({title:"Error saving template",description:Ne.message,variant:"destructive"})}}),ye=gt({mutationFn:async Ne=>{const{error:He}=await q.from("canva_templates").delete().eq("id",Ne);if(He)throw He},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Ne=>{t({title:"Error deleting template",description:Ne.message,variant:"destructive"})}}),_e=gt({mutationFn:async({id:Ne,is_featured:He})=>{const{error:$e}=await q.from("canva_templates").update({is_featured:He}).eq("id",Ne);if($e)throw $e},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:Ne=>{t({title:"Error updating featured",description:Ne.message,variant:"destructive"})}}),Me=()=>{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),A(""),c(null),W(!1),Y(!1),M(""),z(""),p(null),g(0),v(!1),D([])},Te=async Ne=>{var $e;c(Ne),u({name:Ne.name,description:Ne.description||"",category_id:Ne.category_id||"",type_id:Ne.type_id||"",publish_date:Ne.publish_date?new Date(Ne.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Ne.links&&Ne.links.length>0?Ne.links.map(Ye=>({id:Ye.id,title:Ye.title,canva_share_link:Ye.canva_share_link,sort_order:Ye.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:(($e=Ne.guides)==null?void 0:$e.map(Ye=>({id:Ye.id,name:Ye.name,file_url:Ye.file_url,file_type:Ye.file_type,file_size:Ye.file_size,sort_order:Ye.sort_order})))||[],video_url:Ne.video_url||""}),A(Ne.preview_image_url||""),p(null);const{data:He}=await q.from("resource_kit_templates").select("kit_id").eq("template_id",Ne.id);D((He||[]).map(Ye=>Ye.kit_id)),l(!0)},Ce=Ne=>{var $e;const He=($e=Ne.target.files)==null?void 0:$e[0];He&&(_(He),A(URL.createObjectURL(He)))},Ee=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},De=Ne=>{if(d.links.length<=1)return;const He=d.links.filter(($e,Ye)=>Ye!==Ne);u({...d,links:He})},Ie=(Ne,He,$e)=>{const Ye=[...d.links];Ye[Ne]={...Ye[Ne],[He]:$e},u({...d,links:Ye})},Fe=Ne=>{const He=Ne.target.files;if(!He)return;const $e=Array.from(He).map((Ye,Ke)=>({name:Ye.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ye.type,file_size:Ye.size,sort_order:d.guides.length+Ke,file:Ye}));u({...d,guides:[...d.guides,...$e]}),Ne.target.value=""},qe=Ne=>{const He=d.guides.filter(($e,Ye)=>Ye!==Ne);u({...d,guides:He})},ve=(Ne,He)=>{const $e=[...d.guides];$e[Ne]={...$e[Ne],name:He},u({...d,guides:$e})},Je=async()=>{if(!h)return null;v(!0),g(0);try{const{data:Ne,error:He}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(He)throw new Error(He.message);const{videoId:$e,libraryId:Ye}=Ne,{data:Ke,error:rt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$e}});if(rt)throw new Error(rt.message);const tt=new XMLHttpRequest;return await new Promise((Ge,dt)=>{tt.upload.addEventListener("progress",Bt=>{if(Bt.lengthComputable){const kt=Math.round(Bt.loaded/Bt.total*100);g(kt)}}),tt.addEventListener("load",()=>{tt.status>=200&&tt.status<300?Ge():dt(new Error(`Upload failed with status ${tt.status}`))}),tt.addEventListener("error",()=>dt(new Error("Upload failed"))),tt.open("PUT",Ke.uploadUrl),tt.setRequestHeader("AccessKey",Ke.apiKey),tt.send(h)}),`https://player.mediadelivery.net/embed/${Ye}/${$e}`}catch(Ne){return console.error("Bunny upload error:",Ne),t({title:"Video upload failed",description:Ne instanceof Error?Ne.message:"Unknown error",variant:"destructive"}),null}finally{v(!1)}},we=Ne=>{var $e;const He=($e=Ne.target.files)==null?void 0:$e[0];He&&p(He),Ne.target.value=""},it=async Ne=>{if(Ne.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(Ye=>Ye.title.trim()&&Ye.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let $e=d.video_url;if(h){const Ye=await Je();if(!Ye)return;$e=Ye}ie.mutate({template:d,image:j,existingImageUrl:(o==null?void 0:o.preview_image_url)||null,templateId:o==null?void 0:o.id,existingGuides:o==null?void 0:o.guides,videoUrl:$e,linkedKitIds:T})};return e.jsx(Cs,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Manage Templates",description:"Create and manage Canva templates"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:oe.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:ee.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.length})})]})]}),e.jsxs(bs,{open:i,onOpenChange:Ne=>{l(Ne),Ne||Me()},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:it,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name *"}),e.jsx(ge,{id:"name",value:d.name,onChange:Ne=>u({...d,name:Ne.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Db,{content:d.description,onChange:Ne=>u({...d,description:Ne}),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(se,{children:"Canva Links *"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Ee,className:"gap-1",children:[e.jsx(As,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Ne,He)=>e.jsxs("div",{className:"flex gap-2 items-start p-3 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ge,{value:Ne.title,onChange:$e=>Ie(He,"title",$e.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(ge,{value:Ne.canva_share_link,onChange:$e=>Ie(He,"canva_share_link",$e.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>De(He),children:e.jsx(Fn,{className:"h-4 w-4"})})]},He))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Category"}),V?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:L,onChange:Ne=>M(Ne.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>L.trim()&&ce.mutate(L.trim()),disabled:ce.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{W(!1),M("")},children:e.jsx(Fn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:d.category_id,onValueChange:Ne=>u({...d,category_id:Ne}),children:[e.jsx(cs,{className:"flex-1",children:e.jsx(hs,{placeholder:"Select category"})}),e.jsx(ds,{children:ee.map(Ne=>e.jsx(Ze,{value:Ne.id,children:Ne.name},Ne.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>W(!0),children:e.jsx(As,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Template Type"}),K?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:F,onChange:Ne=>z(Ne.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>F.trim()&&de.mutate(F.trim()),disabled:de.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{Y(!1),z("")},children:e.jsx(Fn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:d.type_id,onValueChange:Ne=>u({...d,type_id:Ne}),children:[e.jsx(cs,{className:"flex-1",children:e.jsx(hs,{placeholder:"Select type"})}),e.jsx(ds,{children:ne.map(Ne=>e.jsx(Ze,{value:Ne.id,children:Ne.name},Ne.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>Y(!0),children:e.jsx(As,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ge,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ne=>u({...d,publish_date:Ne.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(se,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[S?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:S,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx(B,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{_(null),A("")},children:e.jsx(Fn,{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(nl,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ge,{type:"file",accept:"image/*",onChange:Ce,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Upload a preview image for this template"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{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(vr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({...d,video_url:""}),className:"text-destructive hover:text-destructive",children:"Remove"})]}),e.jsx("div",{className:"aspect-video max-w-md rounded-lg overflow-hidden border",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}):b?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(ss,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",f,"%"]})]}),e.jsx(xi,{value:f,className:"h-2"})]}):h?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(vr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:h.name}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(h.size/1024/1024).toFixed(1)," MB"]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>p(null),children:e.jsx(Fn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(ge,{type:"file",accept:"video/*",onChange:we,className:"hidden"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 p-6 border-2 border-dashed rounded-lg hover:border-primary/50 transition-colors",children:[e.jsx(vr,{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(se,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(ge,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Fe,className:"hidden"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Sa,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Ne,He)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(Nr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(ge,{value:Ne.name,onChange:$e=>ve(He,$e.target.value),placeholder:"Guide name",className:"flex-1"}),Ne.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Ne.file_size/1024).toFixed(0)," KB"]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>qe(He),children:e.jsx(Fn,{className:"h-4 w-4"})})]},Ne.id||He))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No guide files added. Upload PDFs to help agents understand how to use this template."})]}),e.jsx(__s,{selectedKitIds:T,onChange:D}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{l(!1),Me()},children:"Cancel"}),e.jsx(B,{type:"submit",disabled:ie.isPending,children:ie.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:pe?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):oe.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Preview"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Links"}),e.jsx(Ct,{children:"Category"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:oe.map(Ne=>{var He,$e,Ye,Ke,rt;return e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Ne.preview_image_url?e.jsx("img",{src:Ne.preview_image_url,alt:Ne.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(nl,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(ut,{className:"font-medium",children:Ne.name}),e.jsx(ut,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(ze,{variant:"secondary",children:[((He=Ne.links)==null?void 0:He.length)||0," link",((($e=Ne.links)==null?void 0:$e.length)||0)!==1?"s":""]}),(((Ye=Ne.guides)==null?void 0:Ye.length)||0)>0&&e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Nr,{className:"h-3 w-3"}),(Ke=Ne.guides)==null?void 0:Ke.length," guide",(((rt=Ne.guides)==null?void 0:rt.length)||0)!==1?"s":""]})]})}),e.jsx(ut,{children:Ne.category?e.jsx(ze,{variant:"secondary",children:Ne.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ut,{children:Ne.type?e.jsx(ze,{variant:"outline",children:Ne.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ut,{className:"text-muted-foreground",children:new Date(Ne.publish_date).toLocaleDateString()}),e.jsx(ut,{className:"text-center",children:e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Ne.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>_e.mutate({id:Ne.id,is_featured:!Ne.is_featured}),children:e.jsx(ua,{className:`h-4 w-4 ${Ne.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>Te(Ne),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&ye.mutate(Ne.id)},children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},Ne.id)})})]})})})]})})};function pyt({selectedTemplateIds:s,onChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l=[]}=lt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:h,error:p}=await q.from("canva_templates").select("id, name, preview_image_url").order("name");if(p)throw p;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(p=>p!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(s4,{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(ze,{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(Fn,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Wo,{open:a,onOpenChange:i,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(s4,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(zo,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(_r,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ge,{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(s4,{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 j_s=[{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"}],N_s=()=>{const{user:s}=gs(),[t,n]=yl(),{toast:r}=Ua(),a=Gt(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[h,p]=N.useState(null),[f,g]=N.useState(""),[b,v]=N.useState([]),[j,_]=N.useState([]),[S,A]=N.useState([]),[T,D]=N.useState([]),[L,M]=N.useState(""),[F,z]=N.useState(!1),[V,W]=N.useState(null),[K,Y]=N.useState(0),[ee,ne]=N.useState(!1),[oe,pe]=N.useState(null),{data:ce=[]}=lt({queryKey:["academy-categories"],queryFn:async()=>{const{data:Ne,error:He}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(He)throw He;return Ne}}),{data:de=[],isLoading:ie}=lt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Ne,error:He}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(He)throw He;const{data:$e,error:Ye}=await q.from("academy_resources").select("*").order("sort_order");if(Ye)throw Ye;return Ne.map(rt=>({...rt,resources:($e==null?void 0:$e.filter(tt=>tt.video_id===rt.id))||[]}))}});N.useEffect(()=>{const Ne=t.get("edit");if(Ne&&de.length>0){const He=de.find($e=>$e.id===Ne);He&&(Ie(He),n({},{replace:!0}))}},[de,t]);const ye=gt({mutationFn:async Ne=>{const{data:He,error:$e}=await q.from("academy_categories").insert({name:Ne,sort_order:ce.length}).select().single();if($e)throw $e;return He},onSuccess:Ne=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:Ne.id}),M(""),z(!1),r({title:"Category added"})},onError:Ne=>{r({title:"Error adding category",description:Ne.message,variant:"destructive"})}}),_e=gt({mutationFn:async Ne=>{let He=Ne.existingThumbnailUrl;if(Ne.thumbnail){const Ke=Ne.thumbnail.name.split(".").pop(),rt=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${Ke}`,{error:tt}=await q.storage.from("academy-resources").upload(rt,Ne.thumbnail);if(tt)throw tt;const{data:at}=q.storage.from("academy-resources").getPublicUrl(rt);He=at.publicUrl}const $e={title:Ne.video.title,description:Ne.video.description||null,video_url:Ne.video.video_url,video_type:Ne.video.video_type,duration:Ne.video.duration||null,thumbnail_url:He,category_id:Ne.video.category_id||null,publish_date:Ne.video.publish_date?new Date(Ne.video.publish_date).toISOString():new Date().toISOString(),is_published:Ne.video.is_published,created_by:s==null?void 0:s.id};let Ye=Ne.videoId;if(Ye){const{error:Ke}=await q.from("academy_videos").update($e).eq("id",Ye);if(Ke)throw Ke}else{const{data:Ke,error:rt}=await q.from("academy_videos").insert($e).select().single();if(rt)throw rt;Ye=Ke.id,u_s(Ne.video.title,Ke.id)}if(Ne.resourcesToDelete.length>0){const{error:Ke}=await q.from("academy_resources").delete().in("id",Ne.resourcesToDelete);if(Ke)throw Ke}for(let Ke=0;Ke0){const{error:Ke}=await q.from("academy_video_templates").insert(T.map(rt=>({video_id:Ye,template_id:rt})));if(Ke)throw Ke}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),De(),l(!1),r({title:o?"Video updated":"Video created"})},onError:Ne=>{r({title:"Error saving video",description:Ne.message,variant:"destructive"})}}),Me=gt({mutationFn:async Ne=>{const{error:He}=await q.from("academy_videos").delete().eq("id",Ne);if(He)throw He},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:Ne=>{r({title:"Error deleting video",description:Ne.message,variant:"destructive"})}}),Te=gt({mutationFn:async({id:Ne,is_published:He})=>{const{error:$e}=await q.from("academy_videos").update({is_published:He}).eq("id",Ne);if($e)throw $e},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:Ne=>{r({title:"Error updating video",description:Ne.message,variant:"destructive"})}}),Ce=async Ne=>{try{let He=Ne.public_slug||null,$e=!!Ne.is_public;if(!He||!$e){const Ke=(Ne.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!He){let tt=Ke;const{data:at}=await q.from("academy_videos").select("id").eq("public_slug",tt).maybeSingle();at&&at.id!==Ne.id&&(tt=`${Ke}-${Ne.id.slice(0,6)}`),He=tt}const{error:rt}=await q.from("academy_videos").update({public_slug:He,is_public:!0}).eq("id",Ne.id);if(rt)throw rt;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const Ye=`${window.location.origin}/watch/${He}`;await navigator.clipboard.writeText(Ye),r({title:"Public link copied",description:Ye})}catch(He){r({title:"Could not copy link",description:He.message,variant:"destructive"})}},Ee=async Ne=>{if(!confirm("Disable the public teaser link for this video?"))return;const{error:He}=await q.from("academy_videos").update({is_public:!1}).eq("id",Ne.id);if(He){r({title:"Error",description:He.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},De=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),p(null),g(""),v([]),_([]),A([]),c(null),D([]),M(""),W(null),Y(0),ne(!1),pe(null)},Ie=async Ne=>{c(Ne),u({title:Ne.title,description:Ne.description||"",video_url:Ne.video_url,video_type:Ne.video_type,duration:Ne.duration||"",category_id:Ne.category_id||"",publish_date:Ne.publish_date?new Date(Ne.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Ne.is_published}),g(Ne.thumbnail_url||""),_(Ne.resources||[]),v([]),A([]);const{data:He}=await q.from("academy_video_templates").select("template_id").eq("video_id",Ne.id);D((He||[]).map($e=>$e.template_id)),l(!0)},Fe=Ne=>{var $e;const He=($e=Ne.target.files)==null?void 0:$e[0];He&&(p(He),g(URL.createObjectURL(He)))},qe=Ne=>{const He=Ne.target.files;if(He){const $e=Array.from(He).map(Ye=>({file:Ye,title:Ye.name.replace(/\.[^/.]+$/,"")}));v([...b,...$e])}Ne.target.value=""},ve=Ne=>{v(b.filter((He,$e)=>$e!==Ne))},Je=Ne=>{A([...S,Ne]),_(j.filter(He=>He.id!==Ne))},we=async()=>{if(!V)return null;ne(!0),Y(0);try{const{data:Ne,error:He}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||V.name}});if(He)throw new Error(He.message);const{videoId:$e,libraryId:Ye}=Ne;pe($e);const{data:Ke,error:rt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$e}});if(rt)throw new Error(rt.message);const tt=new XMLHttpRequest;return await new Promise((Ge,dt)=>{tt.upload.addEventListener("progress",Bt=>{if(Bt.lengthComputable){const kt=Math.round(Bt.loaded/Bt.total*100);Y(kt)}}),tt.addEventListener("load",()=>{tt.status>=200&&tt.status<300?Ge():dt(new Error(`Upload failed with status ${tt.status}`))}),tt.addEventListener("error",()=>dt(new Error("Upload failed"))),tt.open("PUT",Ke.uploadUrl),tt.setRequestHeader("AccessKey",Ke.apiKey),tt.send(V)}),`https://player.mediadelivery.net/embed/${Ye}/${$e}`}catch(Ne){return console.error("Bunny upload error:",Ne),r({title:"Video upload failed",description:Ne instanceof Error?Ne.message:"Unknown error",variant:"destructive"}),null}finally{ne(!1)}},it=async Ne=>{if(Ne.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let He=d.video_url;if(d.video_type==="bunny_stream"&&V&&!o){const $e=await we();if(!$e)return;He=$e}else if(!d.video_url.trim()&&d.video_type!=="bunny_stream"){r({title:"Please enter a video URL",variant:"destructive"});return}else if(d.video_type==="bunny_stream"&&!V&&!d.video_url&&!o){r({title:"Please select a video file to upload",variant:"destructive"});return}_e.mutate({video:{...d,video_url:He},thumbnail:h,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:b,resourcesToDelete:S})};return e.jsx(Cs,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Manage Academy",description:"Create and manage training videos and resources"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:de.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:de.filter(Ne=>Ne.is_published).length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:de.filter(Ne=>Ne.is_public).length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:de.reduce((Ne,He)=>Ne+(He.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(bs,{open:i,onOpenChange:Ne=>{l(Ne),Ne||De()},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:it,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ge,{id:"title",value:d.title,onChange:Ne=>u({...d,title:Ne.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Db,{content:d.description,onChange:Ne=>u({...d,description:Ne}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video Type"}),e.jsxs(us,{value:d.video_type,onValueChange:Ne=>{u({...d,video_type:Ne,video_url:""}),W(null)},disabled:ee,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:j_s.map(Ne=>e.jsx(Ze,{value:Ne.value,children:Ne.label},Ne.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(se,{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(ge,{type:"file",accept:"video/*",onChange:Ne=>{var $e;const He=($e=Ne.target.files)==null?void 0:$e[0];He&&W(He)},disabled:ee}),V&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(vr,{className:"h-4 w-4"}),V.name," (",(V.size/(1024*1024)).toFixed(1)," MB)"]}),ee&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(xi,{value:K,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[K,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(ge,{id:"video_url",value:d.video_url,onChange:Ne=>u({...d,video_url:Ne.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(se,{htmlFor:"duration",children:"Duration"}),e.jsx(ge,{id:"duration",value:d.duration,onChange:Ne=>u({...d,duration:Ne.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ge,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ne=>u({...d,publish_date:Ne.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Category"}),F?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:L,onChange:Ne=>M(Ne.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>L.trim()&&ye.mutate(L.trim()),disabled:ye.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{z(!1),M("")},children:e.jsx(Fn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:d.category_id,onValueChange:Ne=>u({...d,category_id:Ne}),children:[e.jsx(cs,{className:"flex-1",children:e.jsx(hs,{placeholder:"Select category"})}),e.jsx(ds,{children:ce.map(Ne=>e.jsx(Ze,{value:Ne.id,children:Ne.name},Ne.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>z(!0),children:e.jsx(As,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[f&&e.jsx("img",{src:f,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ge,{type:"file",accept:"image/*",onChange:Fe,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(se,{children:"Resource Files"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(Sa,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:qe,className:"hidden"})]})})]}),(j.length>0||b.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[j.map(Ne=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Ne.title}),e.jsx(ze,{variant:"outline",className:"text-xs",children:Ne.file_type}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>Je(Ne.id),className:"text-destructive hover:text-destructive",children:e.jsx(Fn,{className:"h-4 w-4"})})]},Ne.id)),b.map((Ne,He)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ge,{value:Ne.title,onChange:$e=>{const Ye=[...b];Ye[He].title=$e.target.value,v(Ye)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(ze,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>ve(He),className:"text-destructive hover:text-destructive",children:e.jsx(Fn,{className:"h-4 w-4"})})]},He))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(pyt,{selectedTemplateIds:T,onChange:D}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{id:"is_published",checked:d.is_published,onCheckedChange:Ne=>u({...d,is_published:Ne})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:ee,children:"Cancel"}),e.jsx(B,{type:"submit",disabled:_e.isPending||ee,children:ee?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):_e.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:ie?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):de.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(vr,{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(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Category"}),e.jsx(Ct,{children:"Duration"}),e.jsx(Ct,{children:"Resources"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Public Views"}),e.jsx(Ct,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(pa,{children:de.map(Ne=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ne.thumbnail_url?e.jsx("img",{src:Ne.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(vr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:Ne.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:Ne.video_type.replace("_"," ")})]})]})}),e.jsx(ut,{children:Ne.category?e.jsx(ze,{variant:"outline",children:Ne.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ut,{children:Ne.duration||"-"}),e.jsx(ut,{children:Ne.resources&&Ne.resources.length>0?e.jsxs(ze,{variant:"secondary",children:[Ne.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ut,{children:new Date(Ne.publish_date).toLocaleDateString()}),e.jsx(ut,{children:e.jsx(vn,{checked:Ne.is_published,onCheckedChange:He=>Te.mutate({id:Ne.id,is_published:He})})}),e.jsx(ut,{children:Ne.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(Ne.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",title:Ne.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>Ce(Ne),children:Ne.is_public?e.jsx(ta,{className:"h-4 w-4 text-primary"}):e.jsx(Hl,{className:"h-4 w-4"})}),Ne.is_public&&e.jsx(B,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>Ee(Ne),children:e.jsx(lc,{className:"h-4 w-4 text-emerald-500"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Ie(Ne),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Me.mutate(Ne.id),className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},Ne.id))})]})})})]})})};function k_s(){var _e,Me,Te;const s=Gt(),[t,n]=yl(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=N.useState(null),[h,p]=N.useState(""),[f,g]=N.useState([]),[b,v]=N.useState([]),[j,_]=N.useState([]),[S,A]=N.useState(null),{data:T,isLoading:D}=lt({queryKey:["resource-kits"],queryFn:async()=>{const{data:Ce,error:Ee}=await q.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return Ce}}),{data:L}=lt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:Ce,error:Ee}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return Ce}}),{data:M}=lt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:Ce,error:Ee}=await q.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return Ce}});N.useEffect(()=>{const Ce=t.get("edit");if(Ce&&T&&T.length>0&&L&&M){const Ee=T.find(De=>De.id===Ce);Ee&&(z(Ee),n({},{replace:!0}))}},[T,L,M,t]);const F=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),p(""),g([]),v([]),_([]),l(null)},z=async Ce=>{l(Ce),c({name:Ce.name,description:Ce.description||"",publish_date:Ce.publish_date.split("T")[0],is_published:Ce.is_published}),p(Ce.featured_image_url||"");const Ee=(L==null?void 0:L.filter(Fe=>Fe.kit_id===Ce.id))||[];g(Ee.map(Fe=>({id:Fe.id,name:Fe.name,file_url:Fe.file_url,file_type:Fe.file_type,file_size:Fe.file_size,sort_order:Fe.sort_order})));const De=(M==null?void 0:M.filter(Fe=>Fe.kit_id===Ce.id))||[];v(De.map(Fe=>({id:Fe.id,title:Fe.title,canva_share_link:Fe.canva_share_link,sort_order:Fe.sort_order})));const{data:Ie}=await q.from("resource_kit_templates").select("template_id").eq("kit_id",Ce.id);_((Ie||[]).map(Fe=>Fe.template_id)),a(!0)},V=Ce=>{var De;const Ee=(De=Ce.target.files)==null?void 0:De[0];Ee&&(u(Ee),p(URL.createObjectURL(Ee)))},W=()=>{g([...f,{name:"",file_url:"",sort_order:f.length}])},K=Ce=>{g(f.filter((Ee,De)=>De!==Ce))},Y=(Ce,Ee,De)=>{const Ie=[...f];Ie[Ce]={...Ie[Ce],[Ee]:De},g(Ie)},ee=()=>{v([...b,{title:"",canva_share_link:"",sort_order:b.length}])},ne=Ce=>{v(b.filter((Ee,De)=>De!==Ce))},oe=(Ce,Ee,De)=>{const Ie=[...b];Ie[Ce]={...Ie[Ce],[Ee]:De},v(Ie)},pe=(Ce,Ee)=>{var Ie;const De=(Ie=Ee.target.files)==null?void 0:Ie[0];if(De){const Fe=[...f],qe=De.name.replace(/\.[^/.]+$/,"");Fe[Ce]={...Fe[Ce],file:De,file_type:De.type,file_size:De.size,name:Fe[Ce].name||qe},g(Fe)}},ce=gt({mutationFn:async()=>{let Ce=(i==null?void 0:i.featured_image_url)||null;if(d){const qe=d.name.split(".").pop(),ve=`${Date.now()}.${qe}`,{error:Je}=await q.storage.from("resource-kits").upload(`featured/${ve}`,d);if(Je)throw Je;const{data:we}=q.storage.from("resource-kits").getPublicUrl(`featured/${ve}`);Ce=we.publicUrl}const Ee={name:o.name,description:o.description||null,featured_image_url:Ce,publish_date:o.publish_date,is_published:o.is_published};let De;const Ie=!i,Fe=(i==null?void 0:i.is_published)||!1;if(i){const{error:qe}=await q.from("resource_kits").update(Ee).eq("id",i.id);if(qe)throw qe;De=i.id;const ve=(L==null?void 0:L.filter($e=>$e.kit_id===i.id).map($e=>$e.id))||[],Je=f.filter($e=>$e.id).map($e=>$e.id),we=ve.filter($e=>!Je.includes($e));we.length>0&&await q.from("resource_kit_files").delete().in("id",we);const it=(M==null?void 0:M.filter($e=>$e.kit_id===i.id).map($e=>$e.id))||[],Ne=b.filter($e=>$e.id).map($e=>$e.id),He=it.filter($e=>!Ne.includes($e));He.length>0&&await q.from("resource_kit_links").delete().in("id",He)}else{const{data:qe,error:ve}=await q.from("resource_kits").insert(Ee).select().single();if(ve)throw ve;De=qe.id}for(let qe=0;qe0){const{error:qe}=await q.from("resource_kit_templates").insert(j.map(ve=>({kit_id:De,template_id:ve})));if(qe)throw qe}return{kitId:De,kitName:o.name,isNewKit:Ie,wasPublished:Fe,isPublished:o.is_published}},onSuccess:Ce=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),ae.success(i?"Resource kit updated":"Resource kit created"),Ce.isPublished&&(Ce.isNewKit||!Ce.wasPublished)&&m_s(Ce.kitName,Ce.kitId),a(!1),F()},onError:Ce=>{ae.error("Failed to save resource kit: "+Ce.message)}}),de=gt({mutationFn:async Ce=>{const{error:Ee}=await q.from("resource_kits").delete().eq("id",Ce);if(Ee)throw Ee},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),ae.success("Resource kit deleted")},onError:Ce=>{ae.error("Failed to delete: "+Ce.message)}}),ie=Ce=>{if(Ce.preventDefault(),!o.name){ae.error("Please enter a name");return}ce.mutate()},ye=Ce=>(L==null?void 0:L.filter(Ee=>Ee.kit_id===Ce).length)||0;return e.jsx(Cs,{title:"Toolbox Management",description:"Create and manage resource kits for agents",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:(T==null?void 0:T.length)||0})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:(T==null?void 0:T.filter(Ce=>Ce.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{F(),a(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Files"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:D?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(T==null?void 0:T.length)===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):T==null?void 0:T.map(Ce=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ce.featured_image_url?e.jsx("img",{src:Ce.featured_image_url,alt:Ce.name,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Oc,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ce.name}),Ce.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Ce.description})]})]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),ye(Ce.id)]})}),e.jsx(ut,{children:ks(new Date(Ce.publish_date),"MMM d, yyyy")}),e.jsx(ut,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Ce.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:Ce.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{const Ee=(L==null?void 0:L.filter(Ie=>Ie.kit_id===Ce.id))||[],De=(M==null?void 0:M.filter(Ie=>Ie.kit_id===Ce.id))||[];A({...Ce,files:Ee,links:De})},children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>z(Ce),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource kit?")&&de.mutate(Ce.id)},children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},Ce.id))})]})})}),e.jsx(bs,{open:r,onOpenChange:a,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:ie,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(Oc,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(ge,{type:"file",accept:"image/*",onChange:V})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name *"}),e.jsx(ge,{id:"name",value:o.name,onChange:Ce=>c({...o,name:Ce.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Db,{content:o.description,onChange:Ce=>c({...o,description:Ce}),placeholder:"Brief description of this resource kit",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ge,{id:"publish_date",type:"date",value:o.publish_date,onChange:Ce=>c({...o,publish_date:Ce.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(vn,{checked:o.is_published,onCheckedChange:Ce=>c({...o,is_published:Ce})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to agents":"Hidden from agents"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Resource Files"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:W,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),f.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No files added yet. Click "Add File" to include resources.'}):e.jsx("div",{className:"space-y-3",children:f.map((Ce,Ee)=>e.jsxs("div",{className:"border rounded-md p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("span",{className:"text-sm font-medium",children:["File ",Ee+1]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>K(Ee),children:e.jsx(Fn,{className:"h-4 w-4"})})]}),e.jsx(ge,{placeholder:"File name (e.g., Getting Started Guide)",value:Ce.name,onChange:De=>Y(Ee,"name",De.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{type:"file",onChange:De=>pe(Ee,De),className:"flex-1"}),Ce.file_url&&!Ce.file&&e.jsx("a",{href:Ce.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),Ce.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Ee))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ee,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),b.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:b.map((Ce,Ee)=>e.jsxs("div",{className:"border rounded-md p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("span",{className:"text-sm font-medium",children:["Canva Link ",Ee+1]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>ne(Ee),children:e.jsx(Fn,{className:"h-4 w-4"})})]}),e.jsx(ge,{placeholder:"Link title (e.g., Social Media Post Template)",value:Ce.title,onChange:De=>oe(Ee,"title",De.target.value)}),e.jsx(ge,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:Ce.canva_share_link,onChange:De=>oe(Ee,"canva_share_link",De.target.value)})]},Ee))})]}),e.jsx(pyt,{selectedTemplateIds:j,onChange:_}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:ce.isPending,children:ce.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(bs,{open:!!S,onOpenChange:()=>A(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{children:S==null?void 0:S.name})}),e.jsxs("div",{className:"space-y-4",children:[(S==null?void 0:S.featured_image_url)&&e.jsx("img",{src:S.featured_image_url,alt:S.name,className:"w-full h-48 object-cover rounded-lg"}),(S==null?void 0:S.description)&&e.jsx("p",{className:"text-muted-foreground",children:S.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((_e=S==null?void 0:S.files)==null?void 0:_e.length)||0,")"]}),((Me=S==null?void 0:S.files)==null?void 0:Me.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:(Te=S==null?void 0:S.files)==null?void 0:Te.map(Ce=>e.jsxs("a",{href:Ce.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(Nr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Ce.name})]},Ce.id))})]}),(S==null?void 0:S.links)&&S.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",S.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:S.links.map(Ce=>e.jsxs("a",{href:Ce.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(tl,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Ce.title})]},Ce.id))})]})]})]})})]})})}const S_s=()=>{const{user:s}=gs(),{toast:t}=Ua(),n=Gt(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,u]=N.useState(null),[h,p]=N.useState(""),{data:f=[],isLoading:g}=lt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:M,error:F}=await q.from("social_swag").select("*").order("publish_date",{ascending:!1});if(F)throw F;const{data:z,error:V}=await q.from("social_swag_links").select("*").order("sort_order");if(V)throw V;return M.map(K=>({...K,links:(z==null?void 0:z.filter(Y=>Y.swag_id===K.id))||[]}))}}),b=gt({mutationFn:async M=>{let F=M.existingImageUrl;if(M.image){const ee=M.image.name.split(".").pop(),ne=`${Date.now()}-${Math.random().toString(36).substring(7)}.${ee}`,{error:oe}=await q.storage.from("template-previews").upload(ne,M.image);if(oe)throw oe;const{data:pe}=q.storage.from("template-previews").getPublicUrl(ne);F=pe.publicUrl}const z={title:M.item.title,description:M.item.description||null,preview_image_url:F,publish_date:M.item.publish_date?new Date(M.item.publish_date).toISOString():new Date().toISOString(),is_published:M.item.is_published,created_by:s==null?void 0:s.id};let V=M.itemId;const W=!V,K=(i==null?void 0:i.is_published)||!1;if(V){const{error:ee}=await q.from("social_swag").update(z).eq("id",V);if(ee)throw ee;await q.from("social_swag_links").delete().eq("swag_id",V)}else{const{data:ee,error:ne}=await q.from("social_swag").insert(z).select().single();if(ne)throw ne;V=ee.id}const Y=M.item.links.filter(ee=>ee.title.trim()&&ee.canva_share_link.trim());if(Y.length>0){const ee=Y.map((oe,pe)=>({swag_id:V,title:oe.title.trim(),canva_share_link:oe.canva_share_link.trim(),sort_order:pe})),{error:ne}=await q.from("social_swag_links").insert(ee);if(ne)throw ne}return{itemId:V,itemTitle:M.item.title,isNewItem:W,wasPublished:K,isPublished:M.item.is_published}},onSuccess:M=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),M.isPublished&&(M.isNewItem||!M.wasPublished)&&j3e(M.itemTitle,M.itemId),a(!1),j()},onError:M=>{t({title:"Error saving item",description:M.message,variant:"destructive"})}}),v=gt({mutationFn:async M=>{const{error:F}=await q.from("social_swag").delete().eq("id",M);if(F)throw F},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:M=>{t({title:"Error deleting item",description:M.message,variant:"destructive"})}}),j=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),u(null),p(""),l(null)},_=M=>{l(M),c({title:M.title,description:M.description||"",publish_date:M.publish_date?new Date(M.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:M.is_published,links:M.links&&M.links.length>0?M.links.map(F=>({id:F.id,title:F.title,canva_share_link:F.canva_share_link,sort_order:F.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),p(M.preview_image_url||""),a(!0)},S=M=>{var z;const F=(z=M.target.files)==null?void 0:z[0];F&&(u(F),p(URL.createObjectURL(F)))},A=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},T=M=>{if(o.links.length<=1)return;const F=o.links.filter((z,V)=>V!==M);c({...o,links:F})},D=(M,F,z)=>{const V=[...o.links];V[M]={...V[M],[F]:z},c({...o,links:V})},L=M=>{if(M.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}b.mutate({item:o,image:d,existingImageUrl:(i==null?void 0:i.preview_image_url)||null,itemId:i==null?void 0:i.id})};return e.jsx(Cs,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Manage Social Swag",description:"Create and manage social media content"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(M=>M.is_published).length})})]})]}),e.jsxs(bs,{open:r,onOpenChange:M=>{a(M),M||j()},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:L,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ge,{id:"title",value:o.title,onChange:M=>c({...o,title:M.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Db,{content:o.description,onChange:M=>c({...o,description:M}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ge,{id:"publish_date",type:"date",value:o.publish_date,onChange:M=>c({...o,publish_date:M.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(vn,{id:"is_published",checked:o.is_published,onCheckedChange:M=>c({...o,is_published:M})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),p("")},children:e.jsx(Fn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(nl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(ge,{type:"file",accept:"image/*",onChange:S,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:A,children:[e.jsx(As,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((M,F)=>e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4 pb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Link ",F+1]}),o.links.length>1&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>T(F),children:e.jsx(Fn,{className:"h-3 w-3"})})]}),e.jsx(ge,{placeholder:"Link title (e.g., Instagram Post)",value:M.title,onChange:z=>D(F,"title",z.target.value)}),e.jsx(ge,{placeholder:"Canva share link",value:M.canva_share_link,onChange:z=>D(F,"canva_share_link",z.target.value)})]})},F))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:b.isPending,children:b.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ae,{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"})}):f.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-16",children:"Preview"}),e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Links"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:f.map(M=>{var F;return e.jsxs(Gs,{children:[e.jsx(ut,{children:M.preview_image_url?e.jsx("img",{src:M.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(nl,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(ut,{className:"font-medium",children:M.title}),e.jsxs(ut,{children:[((F=M.links)==null?void 0:F.length)||0," links"]}),e.jsx(ut,{children:new Date(M.publish_date).toLocaleDateString()}),e.jsx(ut,{children:e.jsx(ze,{variant:M.is_published?"default":"secondary",children:M.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${M.id}`,"_blank"),children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>_(M),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this item?")&&v.mutate(M.id)},children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},M.id)})})]})})})]})})};function C_s(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const Tve=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function rR(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function tPe(s){return"nodeType"in s}function o0(s){var t,n;return s?rR(s)?s:tPe(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function sPe(s){const{Document:t}=o0(s);return s instanceof t}function EU(s){return rR(s)?!1:s instanceof o0(s).HTMLElement}function fyt(s){return s instanceof o0(s).SVGElement}function aR(s){return s?rR(s)?s.document:tPe(s)?sPe(s)?s:EU(s)||fyt(s)?s.ownerDocument:document:document:document}const Rw=Tve?N.useLayoutEffect:N.useEffect;function nPe(s){const t=N.useRef(s);return Rw(()=>{t.current=s}),N.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{s.current=setInterval(r,a)},[]),n=N.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,n]}function RB(s,t){t===void 0&&(t=[s]);const n=N.useRef(s);return Rw(()=>{n.current!==s&&(n.current=s)},t),n}function AU(s,t){const n=N.useRef();return N.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function Lxe(s){const t=nPe(s),n=N.useRef(null),r=N.useCallback(a=>{a!==n.current&&(t==null||t(a,n.current)),n.current=a},[]);return[n,r]}function N3e(s){const t=N.useRef();return N.useEffect(()=>{t.current=s},[s]),t.current}let H2e={};function MU(s,t){return N.useMemo(()=>{if(t)return t;const n=H2e[s]==null?0:H2e[s]+1;return H2e[s]=n,s+"-"+n},[s,t])}function xyt(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 UL=xyt(1),OB=xyt(-1);function E_s(s){return"clientX"in s&&"clientY"in s}function rPe(s){if(!s)return!1;const{KeyboardEvent:t}=o0(s.target);return t&&s instanceof t}function A_s(s){if(!s)return!1;const{TouchEvent:t}=o0(s.target);return t&&s instanceof t}function k3e(s){if(A_s(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 E_s(s)?{x:s.clientX,y:s.clientY}:null}const F4=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[F4.Translate.toString(s),F4.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),QHe="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function M_s(s){return s.matches(QHe)?s:s.querySelector(QHe)}const I_s={display:"none"};function P_s(s){let{id:t,value:n}=s;return Nt.createElement("div",{id:t,style:I_s},n)}function L_s(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 Nt.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function D_s(){const[s,t]=N.useState("");return{announce:N.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const gyt=N.createContext(null);function R_s(s){const t=N.useContext(gyt);N.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function O_s(){const[s]=N.useState(()=>new Set),t=N.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[N.useCallback(r=>{let{type:a,event:i}=r;s.forEach(l=>{var o;return(o=l[a])==null?void 0:o.call(l,i)})},[s]),t]}const F_s={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. `},z_s={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 B_s(s){let{announcements:t=z_s,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=F_s}=s;const{announce:i,announcement:l}=D_s(),o=MU("DndLiveRegion"),[c,d]=N.useState(!1);if(N.useEffect(()=>{d(!0)},[]),R_s(N.useMemo(()=>({onDragStart(h){let{active:p}=h;i(t.onDragStart({active:p}))},onDragMove(h){let{active:p,over:f}=h;t.onDragMove&&i(t.onDragMove({active:p,over:f}))},onDragOver(h){let{active:p,over:f}=h;i(t.onDragOver({active:p,over:f}))},onDragEnd(h){let{active:p,over:f}=h;i(t.onDragEnd({active:p,over:f}))},onDragCancel(h){let{active:p,over:f}=h;i(t.onDragCancel({active:p,over:f}))}}),[i,t])),!c)return null;const u=Nt.createElement(Nt.Fragment,null,Nt.createElement(P_s,{id:r,value:a.draggable}),Nt.createElement(L_s,{id:o,announcement:l}));return n?Gx.createPortal(u,n):u}var Lm;(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"})(Lm||(Lm={}));function Dxe(){}function z8(s,t){return N.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function Eve(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const Ib=Object.freeze({x:0,y:0});function yyt(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function vyt(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function $_s(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function XHe(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 byt(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function JHe(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 Ave=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=JHe(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=yyt(JHe(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(vyt)},U_s=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=XHe(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=XHe(c),u=a.reduce((p,f,g)=>p+yyt(d[g],f),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(vyt)};function q_s(s,t){const n=Math.max(t.top,s.top),r=Math.max(t.left,s.left),a=Math.min(t.left+t.width,s.left+s.width),i=Math.min(t.top+t.height,s.top+s.height),l=a-r,o=i-n;if(r{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=[];for(const i of r){const{id:l}=i,o=n.get(l);if(o){const c=q_s(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort($_s)};function H_s(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function _yt(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:Ib}function G_s(s){return function(n){for(var r=arguments.length,a=new Array(r>1?r-1:0),i=1;i({...l,top:l.top+s*o.y,bottom:l.bottom+s*o.y,left:l.left+s*o.x,right:l.right+s*o.x}),{...n})}}const W_s=G_s(1);function K_s(s){if(s.startsWith("matrix3d(")){const t=s.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(s.startsWith("matrix(")){const t=s.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function Y_s(s,t,n){const r=K_s(t);if(!r)return s;const{scaleX:a,scaleY:i,x:l,y:o}=r,c=s.left-l-(1-a)*parseFloat(n),d=s.top-o-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),u=a?s.width/a:s.width,h=i?s.height/i:s.height;return{width:u,height:h,top:d,right:c+u,bottom:d+h,left:c}}const Z_s={ignoreTransform:!1};function iR(s,t){t===void 0&&(t=Z_s);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=o0(s).getComputedStyle(s);d&&(n=Y_s(n,d,u))}const{top:r,left:a,width:i,height:l,bottom:o,right:c}=n;return{top:r,left:a,width:i,height:l,bottom:o,right:c}}function eGe(s){return iR(s,{ignoreTransform:!0})}function Q_s(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function X_s(s,t){return t===void 0&&(t=o0(s).getComputedStyle(s)),t.position==="fixed"}function J_s(s,t){t===void 0&&(t=o0(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 Mve(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(sPe(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!EU(a)||fyt(a)||n.includes(a))return n;const i=o0(s).getComputedStyle(a);return a!==s&&J_s(a,i)&&n.push(a),X_s(a,i)?n:r(a.parentNode)}return s?r(s):n}function wyt(s){const[t]=Mve(s,1);return t??null}function G2e(s){return!Tve||!s?null:rR(s)?s:tPe(s)?sPe(s)||s===aR(s).scrollingElement?window:EU(s)?s:null:null}function jyt(s){return rR(s)?s.scrollX:s.scrollLeft}function Nyt(s){return rR(s)?s.scrollY:s.scrollTop}function S3e(s){return{x:jyt(s),y:Nyt(s)}}var wp;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(wp||(wp={}));function kyt(s){return!Tve||!s?!1:s===document.scrollingElement}function Syt(s){const t={x:0,y:0},n=kyt(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 ews={x:.2,y:.2};function tws(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=ews);const{isTop:d,isBottom:u,isLeft:h,isRight:p}=Syt(s),f={x:0,y:0},g={x:0,y:0},b={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+b.height?(f.y=wp.Backward,g.y=r*Math.abs((t.top+b.height-i)/b.height)):!u&&c>=t.bottom-b.height&&(f.y=wp.Forward,g.y=r*Math.abs((t.bottom-b.height-c)/b.height)),!p&&o>=t.right-b.width?(f.x=wp.Forward,g.x=r*Math.abs((t.right-b.width-o)/b.width)):!h&&l<=t.left+b.width&&(f.x=wp.Backward,g.x=r*Math.abs((t.left+b.width-l)/b.width)),{direction:f,speed:g}}function sws(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 Cyt(s){return s.reduce((t,n)=>UL(t,S3e(n)),Ib)}function nws(s){return s.reduce((t,n)=>t+jyt(n),0)}function rws(s){return s.reduce((t,n)=>t+Nyt(n),0)}function aws(s,t){if(t===void 0&&(t=iR),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);wyt(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const iws=[["x",["left","right"],nws],["y",["top","bottom"],rws]];class aPe{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=Mve(n),a=Cyt(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of iws)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 _z{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 ows(s){const{EventTarget:t}=o0(s);return s instanceof t?s:aR(s)}function W2e(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 _v;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(_v||(_v={}));function tGe(s){s.preventDefault()}function lws(s){s.stopPropagation()}var Cl;(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"})(Cl||(Cl={}));const Tyt={start:[Cl.Space,Cl.Enter],cancel:[Cl.Esc],end:[Cl.Space,Cl.Enter,Cl.Tab]},cws=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case Cl.Right:return{...n,x:n.x+25};case Cl.Left:return{...n,x:n.x-25};case Cl.Down:return{...n,y:n.y+25};case Cl.Up:return{...n,y:n.y-25}}};class Ive{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 _z(aR(n)),this.windowListeners=new _z(o0(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(_v.Resize,this.handleCancel),this.windowListeners.add(_v.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(_v.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&aws(r),n(Ib)}handleKeyDown(t){if(rPe(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=Tyt,coordinateGetter:l=cws,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}:Ib;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const p=OB(h,u),f={x:0,y:0},{scrollableAncestors:g}=r.current;for(const b of g){const v=t.code,{isTop:j,isRight:_,isLeft:S,isBottom:A,maxScroll:T,minScroll:D}=Syt(b),L=sws(b),M={x:Math.min(v===Cl.Right?L.right-L.width/2:L.right,Math.max(v===Cl.Right?L.left:L.left+L.width/2,h.x)),y:Math.min(v===Cl.Down?L.bottom-L.height/2:L.bottom,Math.max(v===Cl.Down?L.top:L.top+L.height/2,h.y))},F=v===Cl.Right&&!_||v===Cl.Left&&!S,z=v===Cl.Down&&!A||v===Cl.Up&&!j;if(F&&M.x!==h.x){const V=b.scrollLeft+p.x,W=v===Cl.Right&&V<=T.x||v===Cl.Left&&V>=D.x;if(W&&!p.y){b.scrollTo({left:V,behavior:o});return}W?f.x=b.scrollLeft-V:f.x=v===Cl.Right?b.scrollLeft-T.x:b.scrollLeft-D.x,f.x&&b.scrollBy({left:-f.x,behavior:o});break}else if(z&&M.y!==h.y){const V=b.scrollTop+p.y,W=v===Cl.Down&&V<=T.y||v===Cl.Up&&V>=D.y;if(W&&!p.x){b.scrollTo({top:V,behavior:o});return}W?f.y=b.scrollTop-V:f.y=v===Cl.Down?b.scrollTop-T.y:b.scrollTop-D.y,f.y&&b.scrollBy({top:-f.y,behavior:o});break}}this.handleMove(t,UL(OB(h,this.referenceCoordinates),f))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Ive.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=Tyt,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 sGe(s){return!!(s&&"distance"in s)}function nGe(s){return!!(s&&"delay"in s)}class iPe{constructor(t,n,r){var a;r===void 0&&(r=ows(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=aR(l),this.documentListeners=new _z(this.document),this.listeners=new _z(r),this.windowListeners=new _z(o0(l)),this.initialCoordinates=(a=k3e(i))!=null?a:Ib,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(_v.Resize,this.handleCancel),this.windowListeners.add(_v.DragStart,tGe),this.windowListeners.add(_v.VisibilityChange,this.handleCancel),this.windowListeners.add(_v.ContextMenu,tGe),this.documentListeners.add(_v.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(nGe(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(sGe(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(_v.Click,lws,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(_v.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=k3e(t))!=null?n:Ib,d=OB(a,c);if(!r&&o){if(sGe(o)){if(o.tolerance!=null&&W2e(d,o.tolerance))return this.handleCancel();if(W2e(d,o.distance))return this.handleStart()}if(nGe(o)&&W2e(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===Cl.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const dws={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class oR extends iPe{constructor(t){const{event:n}=t,r=aR(n.target);super(t,dws,r)}}oR.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 uws={move:{name:"mousemove"},end:{name:"mouseup"}};var C3e;(function(s){s[s.RightClick=2]="RightClick"})(C3e||(C3e={}));class hws extends iPe{constructor(t){super(t,uws,aR(t.event.target))}}hws.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===C3e.RightClick?!1:(r==null||r({event:n}),!0)}}];const K2e={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class mws extends iPe{constructor(t){super(t,K2e)}static setup(){return window.addEventListener(K2e.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(K2e.move.name,t)};function t(){}}}mws.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 wz;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(wz||(wz={}));var Rxe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Rxe||(Rxe={}));function pws(s){let{acceleration:t,activator:n=wz.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=Rxe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:p}=s;const f=xws({delta:h,disabled:!i}),[g,b]=T_s(),v=N.useRef({x:0,y:0}),j=N.useRef({x:0,y:0}),_=N.useMemo(()=>{switch(n){case wz.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case wz.DraggableRect:return a}},[n,a,c]),S=N.useRef(null),A=N.useCallback(()=>{const D=S.current;if(!D)return;const L=v.current.x*j.current.x,M=v.current.y*j.current.y;D.scrollBy(L,M)},[]),T=N.useMemo(()=>o===Rxe.TreeOrder?[...d].reverse():d,[o,d]);N.useEffect(()=>{if(!i||!d.length||!_){b();return}for(const D of T){if((r==null?void 0:r(D))===!1)continue;const L=d.indexOf(D),M=u[L];if(!M)continue;const{direction:F,speed:z}=tws(D,M,_,t,p);for(const V of["x","y"])f[V][F[V]]||(z[V]=0,F[V]=0);if(z.x>0||z.y>0){b(),S.current=D,g(A,l),v.current=z,j.current=F;return}}v.current={x:0,y:0},j.current={x:0,y:0},b()},[t,A,r,b,i,l,JSON.stringify(_),JSON.stringify(f),g,d,T,u,JSON.stringify(p)])}const fws={x:{[wp.Backward]:!1,[wp.Forward]:!1},y:{[wp.Backward]:!1,[wp.Forward]:!1}};function xws(s){let{delta:t,disabled:n}=s;const r=N3e(t);return AU(a=>{if(n||!r||!a)return fws;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[wp.Backward]:a.x[wp.Backward]||i.x===-1,[wp.Forward]:a.x[wp.Forward]||i.x===1},y:{[wp.Backward]:a.y[wp.Backward]||i.y===-1,[wp.Forward]:a.y[wp.Forward]||i.y===1}}},[n,t,r])}function gws(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return AU(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function yws(s,t){return N.useMemo(()=>s.reduce((n,r)=>{const{sensor:a}=r,i=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,r)}));return[...n,...i]},[]),[s,t])}var FB;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(FB||(FB={}));var T3e;(function(s){s.Optimized="optimized"})(T3e||(T3e={}));const rGe=new Map;function vws(s,t){let{dragging:n,dependencies:r,config:a}=t;const[i,l]=N.useState(null),{frequency:o,measure:c,strategy:d}=a,u=N.useRef(s),h=v(),p=RB(h),f=N.useCallback(function(j){j===void 0&&(j=[]),!p.current&&l(_=>_===null?j:_.concat(j.filter(S=>!_.includes(S))))},[p]),g=N.useRef(null),b=AU(j=>{if(h&&!n)return rGe;if(!j||j===rGe||u.current!==s||i!=null){const _=new Map;for(let S of s){if(!S)continue;if(i&&i.length>0&&!i.includes(S.id)&&S.rect.current){_.set(S.id,S.rect.current);continue}const A=S.node.current,T=A?new aPe(c(A),A):null;S.rect.current=T,T&&_.set(S.id,T)}return _}return j},[s,i,n,h,c]);return N.useEffect(()=>{u.current=s},[s]),N.useEffect(()=>{h||f()},[n,h]),N.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),N.useEffect(()=>{h||typeof o!="number"||g.current!==null||(g.current=setTimeout(()=>{f(),g.current=null},o))},[o,h,f,...r]),{droppableRects:b,measureDroppableContainers:f,measuringScheduled:i!=null};function v(){switch(d){case FB.Always:return!1;case FB.BeforeDragging:return n;default:return!n}}}function Eyt(s,t){return AU(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function bws(s,t){return Eyt(s,t)}function _ws(s){let{callback:t,disabled:n}=s;const r=nPe(t),a=N.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return N.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function Pve(s){let{callback:t,disabled:n}=s;const r=nPe(t),a=N.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return N.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function wws(s){return new aPe(iR(s),s)}function aGe(s,t,n){t===void 0&&(t=wws);const[r,a]=N.useState(null);function i(){a(c=>{if(!s)return null;if(s.isConnected===!1){var d;return(d=c??n)!=null?d:null}const u=t(s);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const l=_ws({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=Pve({callback:i});return Rw(()=>{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 jws(s){const t=Eyt(s);return _yt(s,t)}const iGe=[];function Nws(s){const t=N.useRef(s),n=AU(r=>s?r&&r!==iGe&&s&&t.current&&s.parentNode===t.current.parentNode?r:Mve(s):iGe,[s]);return N.useEffect(()=>{t.current=s},[s]),n}function kws(s){const[t,n]=N.useState(null),r=N.useRef(s),a=N.useCallback(i=>{const l=G2e(i.target);l&&n(o=>o?(o.set(l,S3e(l)),new Map(o)):null)},[]);return N.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=G2e(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,S3e(d)]):null}).filter(c=>c!=null);n(o.length?new Map(o):null),r.current=s}return()=>{l(s),l(i)};function l(o){o.forEach(c=>{const d=G2e(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),N.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>UL(i,l),Ib):Cyt(s):Ib,[s,t])}function oGe(s,t){t===void 0&&(t=[]);const n=N.useRef(null);return N.useEffect(()=>{n.current=null},t),N.useEffect(()=>{const r=s!==Ib;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?OB(s,n.current):Ib}function Sws(s){N.useEffect(()=>{if(!Tve)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 Cws(s,t){return N.useMemo(()=>s.reduce((n,r)=>{let{eventName:a,handler:i}=r;return n[a]=l=>{i(l,t)},n},{}),[s,t])}function Ayt(s){return N.useMemo(()=>s?Q_s(s):null,[s])}const lGe=[];function Tws(s,t){t===void 0&&(t=iR);const[n]=s,r=Ayt(n?o0(n):null),[a,i]=N.useState(lGe);function l(){i(()=>s.length?s.map(c=>kyt(c)?r:new aPe(t(c),c)):lGe)}const o=Pve({callback:l});return Rw(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function Ews(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return EU(t)?t:s}function Aws(s){let{measure:t}=s;const[n,r]=N.useState(null),a=N.useCallback(d=>{for(const{target:u}of d)if(EU(u)){r(h=>{const p=t(u);return h?{...h,width:p.width,height:p.height}:p});break}},[t]),i=Pve({callback:a}),l=N.useCallback(d=>{const u=Ews(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=Lxe(l);return N.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const Mws=[{sensor:oR,options:{}},{sensor:Ive,options:{}}],Iws={current:{}},rpe={draggable:{measure:eGe},droppable:{measure:eGe,strategy:FB.WhileDragging,frequency:T3e.Optimized},dragOverlay:{measure:iR}};class jz 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 Pws={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new jz,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Dxe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:rpe,measureDroppableContainers:Dxe,windowRect:null,measuringScheduled:!1},Lws={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Dxe,draggableNodes:new Map,over:null,measureDroppableContainers:Dxe},Lve=N.createContext(Lws),Myt=N.createContext(Pws);function Dws(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new jz}}}function Rws(s,t){switch(t.type){case Lm.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Lm.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 Lm.DragEnd:case Lm.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Lm.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new jz(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case Lm.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 jz(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case Lm.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new jz(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function Ows(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=N.useContext(Lve),i=N3e(r),l=N3e(n==null?void 0:n.id);return N.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!rPe(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=M_s(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function Fws(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function zws(s){return N.useMemo(()=>({draggable:{...rpe.draggable,...s==null?void 0:s.draggable},droppable:{...rpe.droppable,...s==null?void 0:s.droppable},dragOverlay:{...rpe.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 Bws(s){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=s;const i=N.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;Rw(()=>{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=_yt(u,r);if(l||(h.x=0),o||(h.y=0),i.current=!0,Math.abs(h.x)>0||Math.abs(h.y)>0){const p=wyt(d);p&&p.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const Iyt=N.createContext({...Ib,scaleX:1,scaleY:1});var nS;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(nS||(nS={}));const Dve=N.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=Mws,collisionDetection:h=V_s,measuring:p,modifiers:f,...g}=t;const b=N.useReducer(Rws,void 0,Dws),[v,j]=b,[_,S]=O_s(),[A,T]=N.useState(nS.Uninitialized),D=A===nS.Initialized,{draggable:{active:L,nodes:M,translate:F},droppable:{containers:z}}=v,V=L!=null?M.get(L):null,W=N.useRef({initial:null,translated:null}),K=N.useMemo(()=>{var Us;return L!=null?{id:L,data:(Us=V==null?void 0:V.data)!=null?Us:Iws,rect:W}:null},[L,V]),Y=N.useRef(null),[ee,ne]=N.useState(null),[oe,pe]=N.useState(null),ce=RB(g,Object.values(g)),de=MU("DndDescribedBy",l),ie=N.useMemo(()=>z.getEnabled(),[z]),ye=zws(p),{droppableRects:_e,measureDroppableContainers:Me,measuringScheduled:Te}=vws(ie,{dragging:D,dependencies:[F.x,F.y],config:ye.droppable}),Ce=gws(M,L),Ee=N.useMemo(()=>oe?k3e(oe):null,[oe]),De=Bs(),Ie=bws(Ce,ye.draggable.measure);Bws({activeNode:L!=null?M.get(L):null,config:De.layoutShiftCompensation,initialRect:Ie,measure:ye.draggable.measure});const Fe=aGe(Ce,ye.draggable.measure,Ie),qe=aGe(Ce?Ce.parentElement:null),ve=N.useRef({activatorEvent:null,active:null,activeNode:Ce,collisionRect:null,collisions:null,droppableRects:_e,draggableNodes:M,draggingNode:null,draggingNodeRect:null,droppableContainers:z,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Je=z.getNodeFor((n=ve.current.over)==null?void 0:n.id),we=Aws({measure:ye.dragOverlay.measure}),it=(r=we.nodeRef.current)!=null?r:Ce,Ne=D?(a=we.rect)!=null?a:Fe:null,He=!!(we.nodeRef.current&&we.rect),$e=jws(He?null:Fe),Ye=Ayt(it?o0(it):null),Ke=Nws(D?Je??Ce:null),rt=Tws(Ke),tt=Fws(f,{transform:{x:F.x-$e.x,y:F.y-$e.y,scaleX:1,scaleY:1},activatorEvent:oe,active:K,activeNodeRect:Fe,containerNodeRect:qe,draggingNodeRect:Ne,over:ve.current.over,overlayNodeRect:we.rect,scrollableAncestors:Ke,scrollableAncestorRects:rt,windowRect:Ye}),at=Ee?UL(Ee,F):null,Ge=kws(Ke),dt=oGe(Ge),Bt=oGe(Ge,[Fe]),kt=UL(tt,dt),Qt=Ne?W_s(Ne,tt):null,ns=K&&Qt?h({active:K,collisionRect:Qt,droppableRects:_e,droppableContainers:ie,pointerCoordinates:at}):null,$s=byt(ns,"id"),[Ds,Dt]=N.useState(null),St=He?tt:UL(tt,Bt),$t=H_s(St,(i=Ds==null?void 0:Ds.rect)!=null?i:null,Fe),ht=N.useRef(null),Ut=N.useCallback((Us,sn)=>{let{sensor:Jn,options:fn}=sn;if(Y.current==null)return;const Sn=M.get(Y.current);if(!Sn)return;const Gn=Us.nativeEvent,Hr=new Jn({active:Y.current,activeNode:Sn,event:Gn,options:fn,context:ve,onAbort(Ms){if(!M.get(Ms))return;const{onDragAbort:Rr}=ce.current,er={id:Ms};Rr==null||Rr(er),_({type:"onDragAbort",event:er})},onPending(Ms,bi,Rr,er){if(!M.get(Ms))return;const{onDragPending:Fs}=ce.current,$n={id:Ms,constraint:bi,initialCoordinates:Rr,offset:er};Fs==null||Fs($n),_({type:"onDragPending",event:$n})},onStart(Ms){const bi=Y.current;if(bi==null)return;const Rr=M.get(bi);if(!Rr)return;const{onDragStart:er}=ce.current,lr={activatorEvent:Gn,active:{id:bi,data:Rr.data,rect:W}};Gx.unstable_batchedUpdates(()=>{er==null||er(lr),T(nS.Initializing),j({type:Lm.DragStart,initialCoordinates:Ms,active:bi}),_({type:"onDragStart",event:lr}),ne(ht.current),pe(Gn)})},onMove(Ms){j({type:Lm.DragMove,coordinates:Ms})},onEnd:pi(Lm.DragEnd),onCancel:pi(Lm.DragCancel)});ht.current=Hr;function pi(Ms){return async function(){const{active:Rr,collisions:er,over:lr,scrollAdjustedTranslate:Fs}=ve.current;let $n=null;if(Rr&&Fs){const{cancelDrop:Cr}=ce.current;$n={activatorEvent:Gn,active:Rr,collisions:er,delta:Fs,over:lr},Ms===Lm.DragEnd&&typeof Cr=="function"&&await Promise.resolve(Cr($n))&&(Ms=Lm.DragCancel)}Y.current=null,Gx.unstable_batchedUpdates(()=>{j({type:Ms}),T(nS.Uninitialized),Dt(null),ne(null),pe(null),ht.current=null;const Cr=Ms===Lm.DragEnd?"onDragEnd":"onDragCancel";if($n){const ts=ce.current[Cr];ts==null||ts($n),_({type:Cr,event:$n})}})}}},[M]),Es=N.useCallback((Us,sn)=>(Jn,fn)=>{const Sn=Jn.nativeEvent,Gn=M.get(fn);if(Y.current!==null||!Gn||Sn.dndKit||Sn.defaultPrevented)return;const Hr={active:Gn};Us(Jn,sn.options,Hr)===!0&&(Sn.dndKit={capturedBy:sn.sensor},Y.current=fn,Ut(Jn,sn))},[M,Ut]),Xt=yws(u,Es);Sws(u),Rw(()=>{Fe&&A===nS.Initializing&&T(nS.Initialized)},[Fe,A]),N.useEffect(()=>{const{onDragMove:Us}=ce.current,{active:sn,activatorEvent:Jn,collisions:fn,over:Sn}=ve.current;if(!sn||!Jn)return;const Gn={active:sn,activatorEvent:Jn,collisions:fn,delta:{x:kt.x,y:kt.y},over:Sn};Gx.unstable_batchedUpdates(()=>{Us==null||Us(Gn),_({type:"onDragMove",event:Gn})})},[kt.x,kt.y]),N.useEffect(()=>{const{active:Us,activatorEvent:sn,collisions:Jn,droppableContainers:fn,scrollAdjustedTranslate:Sn}=ve.current;if(!Us||Y.current==null||!sn||!Sn)return;const{onDragOver:Gn}=ce.current,Hr=fn.get($s),pi=Hr&&Hr.rect.current?{id:Hr.id,rect:Hr.rect.current,data:Hr.data,disabled:Hr.disabled}:null,Ms={active:Us,activatorEvent:sn,collisions:Jn,delta:{x:Sn.x,y:Sn.y},over:pi};Gx.unstable_batchedUpdates(()=>{Dt(pi),Gn==null||Gn(Ms),_({type:"onDragOver",event:Ms})})},[$s]),Rw(()=>{ve.current={activatorEvent:oe,active:K,activeNode:Ce,collisionRect:Qt,collisions:ns,droppableRects:_e,draggableNodes:M,draggingNode:it,draggingNodeRect:Ne,droppableContainers:z,over:Ds,scrollableAncestors:Ke,scrollAdjustedTranslate:kt},W.current={initial:Ne,translated:Qt}},[K,Ce,ns,Qt,M,it,Ne,_e,z,Ds,Ke,kt]),pws({...De,delta:F,draggingRect:Qt,pointerCoordinates:at,scrollableAncestors:Ke,scrollableAncestorRects:rt});const Ys=N.useMemo(()=>({active:K,activeNode:Ce,activeNodeRect:Fe,activatorEvent:oe,collisions:ns,containerNodeRect:qe,dragOverlay:we,draggableNodes:M,droppableContainers:z,droppableRects:_e,over:Ds,measureDroppableContainers:Me,scrollableAncestors:Ke,scrollableAncestorRects:rt,measuringConfiguration:ye,measuringScheduled:Te,windowRect:Ye}),[K,Ce,Fe,oe,ns,qe,we,M,z,_e,Ds,Me,Ke,rt,ye,Te,Ye]),Ss=N.useMemo(()=>({activatorEvent:oe,activators:Xt,active:K,activeNodeRect:Fe,ariaDescribedById:{draggable:de},dispatch:j,draggableNodes:M,over:Ds,measureDroppableContainers:Me}),[oe,Xt,K,Fe,j,de,M,Ds,Me]);return Nt.createElement(gyt.Provider,{value:S},Nt.createElement(Lve.Provider,{value:Ss},Nt.createElement(Myt.Provider,{value:Ys},Nt.createElement(Iyt.Provider,{value:$t},d)),Nt.createElement(Ows,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Nt.createElement(B_s,{...o,hiddenTextDescribedById:de}));function Bs(){const Us=(ee==null?void 0:ee.autoScrollEnabled)===!1,sn=typeof c=="object"?c.enabled===!1:c===!1,Jn=D&&!Us&&!sn;return typeof c=="object"?{...c,enabled:Jn}:{enabled:Jn}}}),$ws=N.createContext(null),cGe="button",Uws="Draggable";function qws(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=MU(Uws),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:p}=N.useContext(Lve),{role:f=cGe,roleDescription:g="draggable",tabIndex:b=0}=a??{},v=(c==null?void 0:c.id)===t,j=N.useContext(v?Iyt:$ws),[_,S]=Lxe(),[A,T]=Lxe(),D=Cws(l,t),L=RB(n);Rw(()=>(h.set(t,{id:t,key:i,node:_,activatorNode:A,data:L}),()=>{const F=h.get(t);F&&F.key===i&&h.delete(t)}),[h,t]);const M=N.useMemo(()=>({role:f,tabIndex:b,"aria-disabled":r,"aria-pressed":v&&f===cGe?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[r,f,b,v,g,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:M,isDragging:v,listeners:r?void 0:D,node:_,over:p,setNodeRef:S,setActivatorNodeRef:T,transform:j}}function Vws(){return N.useContext(Myt)}const Hws="Droppable",Gws={timeout:25};function Wws(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=MU(Hws),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=N.useContext(Lve),u=N.useRef({disabled:n}),h=N.useRef(!1),p=N.useRef(null),f=N.useRef(null),{disabled:g,updateMeasurementsFor:b,timeout:v}={...Gws,...a},j=RB(b??r),_=N.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(j.current)?j.current:[j.current]),f.current=null},v)},[v]),S=Pve({callback:_,disabled:g||!l}),A=N.useCallback((M,F)=>{S&&(F&&(S.unobserve(F),h.current=!1),M&&S.observe(M))},[S]),[T,D]=Lxe(A),L=RB(t);return N.useEffect(()=>{!S||!T.current||(S.disconnect(),h.current=!1,S.observe(T.current))},[T,S]),N.useEffect(()=>(o({type:Lm.RegisterDroppable,element:{id:r,key:i,disabled:n,node:T,rect:p,data:L}}),()=>o({type:Lm.UnregisterDroppable,key:i,id:r})),[r]),N.useEffect(()=>{n!==u.current.disabled&&(o({type:Lm.SetDroppableDisabled,id:r,key:i,disabled:n}),u.current.disabled=n)},[r,i,n,o]),{active:l,rect:p,isOver:(c==null?void 0:c.id)===r,node:T,over:c,setNodeRef:D}}function Rve(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function Kws(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function ZH(s){return s!==null&&s>=0}function Yws(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=Qws(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...QH}:l=i?{x:o.width+c,y:0,...QH}:{x:0,y:0,...QH}};function Qws(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=Rve(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}},XH={scaleX:1,scaleY:1},Xws=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,...XH}:a=l?{x:0,y:o.height+c,...XH}:{x:0,y:0,...XH}};function Jws(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(D=>typeof D=="object"&&"id"in D?D.id:D),[r]),g=l!=null,b=l?f.indexOf(l.id):-1,v=d?f.indexOf(d.id):-1,j=N.useRef(f),_=!Yws(f,j.current),S=v!==-1&&b===-1||_,A=Zws(i);Rw(()=>{_&&g&&u(f)},[_,f,g,u]),N.useEffect(()=>{j.current=f},[f]);const T=N.useMemo(()=>({activeIndex:b,containerId:h,disabled:A,disableTransforms:S,items:f,overIndex:v,useDragOverlay:p,sortedRects:Kws(f,c),strategy:a}),[b,h,A.draggable,A.droppable,S,f,v,c,p,a]);return Nt.createElement(Lyt.Provider,{value:T},t)}const ejs=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return Rve(n,r,a).indexOf(t)},tjs=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},sjs={duration:200,easing:"ease"},Dyt="transform",njs=F4.Transition.toString({property:Dyt,duration:0,easing:"linear"}),rjs={roleDescription:"sortable"};function ajs(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=N.useState(null),o=N.useRef(n);return Rw(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=iR(r.current,{ignoreTransform:!0}),u={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(u.x||u.y)&&l(u)}}n!==o.current&&(o.current=n)},[t,n,r,a]),N.useEffect(()=>{i&&l(null)},[i]),i}function Fve(s){let{animateLayoutChanges:t=tjs,attributes:n,disabled:r,data:a,getNewIndex:i=ejs,id:l,strategy:o,resizeObserverConfig:c,transition:d=sjs}=s;const{items:u,containerId:h,activeIndex:p,disabled:f,disableTransforms:g,sortedRects:b,overIndex:v,useDragOverlay:j,strategy:_}=N.useContext(Lyt),S=ijs(r,f),A=u.indexOf(l),T=N.useMemo(()=>({sortable:{containerId:h,index:A,items:u},...a}),[h,a,A,u]),D=N.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:L,node:M,isOver:F,setNodeRef:z}=Wws({id:l,data:T,disabled:S.droppable,resizeObserverConfig:{updateMeasurementsFor:D,...c}}),{active:V,activatorEvent:W,activeNodeRect:K,attributes:Y,setNodeRef:ee,listeners:ne,isDragging:oe,over:pe,setActivatorNodeRef:ce,transform:de}=qws({id:l,data:T,attributes:{...rjs,...n},disabled:S.draggable}),ie=C_s(z,ee),ye=!!V,_e=ye&&!g&&ZH(p)&&ZH(v),Me=!j&&oe,Te=Me&&_e?de:null,Ee=_e?Te??(o??_)({rects:b,activeNodeRect:K,activeIndex:p,overIndex:v,index:A}):null,De=ZH(p)&&ZH(v)?i({id:l,items:u,activeIndex:p,overIndex:v}):A,Ie=V==null?void 0:V.id,Fe=N.useRef({activeId:Ie,items:u,newIndex:De,containerId:h}),qe=u!==Fe.current.items,ve=t({active:V,containerId:h,isDragging:oe,isSorting:ye,id:l,index:A,items:u,newIndex:Fe.current.newIndex,previousItems:Fe.current.items,previousContainerId:Fe.current.containerId,transition:d,wasDragging:Fe.current.activeId!=null}),Je=ajs({disabled:!ve,index:A,node:M,rect:L});return N.useEffect(()=>{ye&&Fe.current.newIndex!==De&&(Fe.current.newIndex=De),h!==Fe.current.containerId&&(Fe.current.containerId=h),u!==Fe.current.items&&(Fe.current.items=u)},[ye,De,h,u]),N.useEffect(()=>{if(Ie===Fe.current.activeId)return;if(Ie!=null&&Fe.current.activeId==null){Fe.current.activeId=Ie;return}const it=setTimeout(()=>{Fe.current.activeId=Ie},50);return()=>clearTimeout(it)},[Ie]),{active:V,activeIndex:p,attributes:Y,data:T,rect:L,index:A,newIndex:De,items:u,isOver:F,isSorting:ye,isDragging:oe,listeners:ne,node:M,overIndex:v,over:pe,setNodeRef:ie,setActivatorNodeRef:ce,setDroppableNodeRef:z,setDraggableNodeRef:ee,transform:Je??Ee,transition:we()};function we(){if(Je||qe&&Fe.current.newIndex===A)return njs;if(!(Me&&!rPe(W)||!d)&&(ye||ve))return F4.Transition.toString({...d,property:Dyt})}}function ijs(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 Oxe(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 ojs=[Cl.Down,Cl.Right,Cl.Up,Cl.Left],Ryt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(ojs.includes(s.code)){if(s.preventDefault(),!n||!r)return;const c=[];i.getEnabled().forEach(h=>{if(!h||h!=null&&h.disabled)return;const p=a.get(h.id);if(p)switch(s.code){case Cl.Down:r.topp.top&&c.push(h);break;case Cl.Left:r.left>p.left&&c.push(h);break;case Cl.Right:r.left1&&(u=d[1].id),u!=null){const h=i.get(n.id),p=i.get(u),f=p?a.get(p.id):null,g=p==null?void 0:p.node.current;if(g&&f&&h&&p){const v=Mve(g).some((D,L)=>o[L]!==D),j=Oyt(h,p),_=ljs(h,p),S=v||!j?{x:0,y:0}:{x:_?r.width-f.width:0,y:_?r.height-f.height:0},A={x:f.left,y:f.top};return S.x&&S.y?A:OB(A,S)}}}};function Oyt(s,t){return!Oxe(s)||!Oxe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function ljs(s,t){return!Oxe(s)||!Oxe(t)||!Oyt(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>n(s),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(ze,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(yr,{className:"h-2.5 w-2.5"}),ks(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Ae,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:Et("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"h-3 w-3"}),s.post_date?ks(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(zo,{className:"w-auto p-0",align:"start",children:[e.jsx(ag,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?ks(h,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>r(s.id,null),children:"Clear date"})})]})]})]})]})})}const djs=()=>{const s=Gt(),[t,n]=N.useState("all"),[r,a]=N.useState(!1),[i,l]=N.useState(ks(new Date,"yyyy-MM")),[o,c]=N.useState([]),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,g]=N.useState(null),[b,v]=N.useState(""),[j,_]=N.useState(null),[S,A]=N.useState(!1),[T,D]=N.useState(!1),[L,M]=N.useState(ks(new Date,"yyyy-MM")),[F,z]=N.useState(null),[V,W]=N.useState(""),[K,Y]=N.useState(""),[ee,ne]=N.useState(""),[oe,pe]=N.useState(!1),ce=Eve(z8(oR,{activationConstraint:{distance:5}}),z8(Ive,{coordinateGetter:Ryt})),{data:de=[],isLoading:ie}=lt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:at,error:Ge}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(Ge)throw Ge;return at}}),{data:ye=[]}=lt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:at,error:Ge}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(Ge)throw Ge;return at}}),{data:_e=[]}=lt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:at,error:Ge}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(Ge)throw Ge;return at}}),Me=[...new Set(de.map(at=>at.month))].sort((at,Ge)=>Ge.localeCompare(at)),Te=t==="all"?de:de.filter(at=>at.month===t),Ce=at=>{const Ge=mMe(at,"yyyy-MM",new Date);return ks(Ge,"MMMM yyyy")},Ee=at=>{g(at),v(at.caption),_(at.post_date)},De=async()=>{if(f){A(!0);try{const{error:at}=await q.from("social_swag_2").update({caption:b,post_date:j}).eq("id",f.id);if(at)throw at;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{A(!1)}}},Ie=async at=>{const{active:Ge,over:dt}=at;if(!dt||Ge.id===dt.id)return;const Bt=Te,kt=Bt.findIndex($s=>$s.id===Ge.id),Qt=Bt.findIndex($s=>$s.id===dt.id);if(kt===-1||Qt===-1)return;const ns=Rve(Bt,kt,Qt);s.setQueryData(["admin-social-swag-2"],$s=>{if(!$s)return $s;const Ds={};return ns.forEach((Dt,St)=>{Ds[Dt.id]=St}),$s.map(Dt=>Ds[Dt.id]!==void 0?{...Dt,sort_order:Ds[Dt.id]}:Dt).sort((Dt,St)=>Dt.month!==St.month?St.month.localeCompare(Dt.month):Dt.sort_order-St.sort_order)});try{await Promise.all(ns.map(($s,Ds)=>q.from("social_swag_2").update({sort_order:Ds}).eq("id",$s.id)))}catch{ae.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Fe=at=>{const dt=Array.from(at.target.files||[]).sort((Bt,kt)=>Bt.name.localeCompare(kt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(Bt=>({file:Bt,preview:URL.createObjectURL(Bt),caption:""}));c(Bt=>[...Bt,...dt].slice(0,16))},qe=at=>{c(Ge=>{const dt=[...Ge];return URL.revokeObjectURL(dt[at].preview),dt.splice(at,1),dt})},ve=(at,Ge)=>{c(dt=>{const Bt=[...dt];return Bt[at]={...Bt[at],caption:Ge},Bt})},Je=async()=>{var Ge;if(o.length===0){ae.error("Please add at least one image");return}if(o.filter(dt=>!dt.caption.trim()).length>0){ae.error("Please add captions to all images");return}u(!0);try{const{data:dt}=await q.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),Bt=(((Ge=dt==null?void 0:dt[0])==null?void 0:Ge.sort_order)??-1)+1;for(let kt=0;kt{const Ge=at.image_url.split("/social-swag-2/");Ge[1]&&await q.storage.from("social-swag-2").remove([Ge[1]]);const{error:dt}=await q.from("social_swag_2").delete().eq("id",at.id);if(dt)throw dt},onSuccess:()=>{ae.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>ae.error("Failed to delete image")}),it=gt({mutationFn:async({id:at,postDate:Ge})=>{const{error:dt}=await q.from("social_swag_2").update({post_date:Ge}).eq("id",at);if(dt)throw dt},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")}),Ne=gt({mutationFn:async({month:at,link:Ge})=>{const{error:dt}=await q.from("social_swag_2_months").upsert({month:at,canva_link:Ge||null},{onConflict:"month"});if(dt)throw dt},onSuccess:()=>{ae.success("Canva link updated"),p(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>ae.error("Failed to update Canva link")}),He=at=>{var Ge;return((Ge=ye.find(dt=>dt.month===at))==null?void 0:Ge.canva_link)||""},$e=at=>_e.find(Ge=>Ge.month===at)||null,Ye=at=>{var dt;const Ge=(dt=at.target.files)==null?void 0:dt[0];Ge&&(z(Ge),W(URL.createObjectURL(Ge)))},Ke=()=>{V&&URL.revokeObjectURL(V),z(null),W(""),Y(""),ne("")},rt=async()=>{if(!F){ae.error("Please select an image");return}pe(!0);try{const at=F.name.split(".").pop(),Ge=`reels/${L}-${Date.now()}.${at}`,{error:dt}=await q.storage.from("social-swag-2").upload(Ge,F);if(dt)throw dt;const{data:{publicUrl:Bt}}=q.storage.from("social-swag-2").getPublicUrl(Ge),{error:kt}=await q.from("social_swag_2_reels").upsert({month:L,image_url:Bt,canva_link:ee||null,caption:K||null},{onConflict:"month"});if(kt)throw kt;ae.success("Reel uploaded successfully!"),j3e(`${Ce(L)} Reel`,"social-swag-2"),Ke(),D(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(at){console.error("Reel upload error:",at),ae.error("Failed to upload reel")}finally{pe(!1)}},tt=gt({mutationFn:async at=>{const Ge=at.image_url.split("/social-swag-2/");Ge[1]&&await q.storage.from("social-swag-2").remove([Ge[1]]);const{error:dt}=await q.from("social_swag_2_reels").delete().eq("id",at.id);if(dt)throw dt},onSuccess:()=>{ae.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>ae.error("Failed to delete reel")});return e.jsxs(Cs,{title:"Admin - Social Swag 2.0",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Social Swag 2.0"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage monthly social media images and captions"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(bs,{open:r,onOpenChange:a,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Month"}),e.jsx(ge,{type:"month",value:i,onChange:at=>l(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{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:Fe,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(Sa,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select images (max 16)"})]})]})]}),o.length>0&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:o.map((at,Ge)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative aspect-[4/5] rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:at.preview,alt:`Upload ${Ge+1}`,className:"w-full h-full object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>qe(Ge),children:e.jsx(Fn,{className:"h-3 w-3"})})]}),e.jsx(Ts,{placeholder:"Caption...",value:at.caption,onChange:dt=>ve(Ge,dt.target.value),className:"text-xs h-20"})]},Ge))}),e.jsx(B,{onClick:Je,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(bs,{open:T,onOpenChange:at=>{D(at),at||Ke()},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(Ph,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(vs,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Month"}),e.jsx(ge,{type:"month",value:L,onChange:at=>M(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Reel Preview Image"}),V?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:V,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(V),z(null),W("")},children:e.jsx(Fn,{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:Ye,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(Ph,{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(se,{children:"Canva Download Link"}),e.jsx(ge,{value:ee,onChange:at=>ne(at.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Caption"}),e.jsx(Ts,{value:K,onChange:at=>Y(at.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(B,{onClick:rt,disabled:oe||!F,className:"w-full gap-2",children:oe?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:de.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:Me.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx($r,{value:t,onValueChange:n,children:e.jsxs(Ur,{children:[e.jsx(Zt,{value:"all",children:"All"}),Me.map(at=>e.jsx(Zt,{value:at,children:Ce(at)},at))]})}),t!=="all"&&e.jsx(fe,{children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(se,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",Ce(t)]}),(h==null?void 0:h.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(ge,{value:h.link,onChange:at=>p({...h,link:at.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(B,{size:"sm",onClick:()=>Ne.mutate(h),children:"Save"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>p(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:He(t)||"No link set"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>p({month:t,link:He(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(fe,{children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Ph,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(se,{className:"text-sm text-muted-foreground",children:["Reel for ",Ce(t)]}),(()=>{const at=$e(t);return at?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:at.image_url,alt:"Reel preview",className:"w-16 h-28 object-cover rounded"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("p",{className:"line-clamp-2",children:at.caption||"No caption"}),at.canva_link&&e.jsx("a",{href:at.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx(B,{variant:"destructive",size:"sm",onClick:()=>tt.mutate(at),children:e.jsx(bn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),ie?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):Te.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(nl,{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(Dve,{sensors:ce,collisionDetection:Ave,onDragEnd:Ie,children:e.jsx(Ove,{items:Te.map(at=>at.id),strategy:IU,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:Te.map(at=>e.jsx(cjs,{item:at,onEdit:Ee,onDelete:Ge=>we.mutate(Ge),onDateChange:(Ge,dt)=>it.mutate({id:Ge,postDate:dt})},at.id))})})})]}),e.jsx(bs,{open:!!f,onOpenChange:at=>{at||g(null)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Edit Image"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"aspect-[4/5] max-h-48 w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:f.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Caption"}),e.jsx(Ts,{value:b,onChange:at=>v(at.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("flex-1 justify-start gap-2 font-normal",!j&&"text-muted-foreground"),children:[e.jsx(yr,{className:"h-4 w-4"}),j?ks(new Date(j+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:j?new Date(j+"T00:00:00"):void 0,onSelect:at=>_(at?ks(at,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),j&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>_(null),children:e.jsx(Fn,{className:"h-4 w-4"})})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(null),children:"Cancel"}),e.jsx(B,{onClick:De,disabled:S,className:"gap-2",children:S?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},ujs=()=>{const{toast:s}=Ua(),t=Gt(),[n,r]=N.useState("categories"),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState({name:"",description:"",icon:""}),[u,h]=N.useState(!1),[p,f]=N.useState(null),[g,b]=N.useState({name:"",description:"",icon:""}),[v,j]=N.useState(!1),[_,S]=N.useState(null),[A,T]=N.useState(""),{data:D=[],isLoading:L}=lt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Ie,error:Fe}=await q.from("community_categories").select("*").order("sort_order");if(Fe)throw Fe;return Ie}}),{data:M=[],isLoading:F}=lt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Ie,error:Fe}=await q.from("community_private_groups").select("*").order("sort_order");if(Fe)throw Fe;return Ie}}),{data:z=[]}=lt({queryKey:["admin-group-members",_==null?void 0:_.id],queryFn:async()=>{if(!_)return[];const{data:Ie,error:Fe}=await q.from("community_private_group_members").select("*").eq("group_id",_.id);if(Fe)throw Fe;return Ie},enabled:!!_}),{data:V=[]}=lt({queryKey:["admin-all-profiles"],queryFn:async()=>{let Fe=[],qe=0,ve=!0;for(;ve;){const{data:Je,error:we}=await q.from("profiles").select("id, name, email, brokerage_id").order("name").range(qe,qe+1e3-1);if(we)throw we;Je&&Je.length>0?(Fe=[...Fe,...Je],qe+=1e3,ve=Je.length===1e3):ve=!1}return Fe}}),{data:W=[]}=lt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Ie,error:Fe}=await q.from("brokerages").select("*").order("name");if(Fe)throw Fe;return Ie}}),K=gt({mutationFn:async Ie=>{if(Ie.id){const{error:Fe}=await q.from("community_categories").update({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null}).eq("id",Ie.id);if(Fe)throw Fe}else{const Fe=Math.max(...D.map(ve=>ve.sort_order),0),{error:qe}=await q.from("community_categories").insert({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null,sort_order:Fe+1});if(qe)throw qe}},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"})}}),Y=gt({mutationFn:async Ie=>{const{error:Fe}=await q.from("community_categories").delete().eq("id",Ie);if(Fe)throw Fe},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),ee=gt({mutationFn:async({id:Ie,direction:Fe})=>{const qe=D.findIndex(ve=>ve.id===Ie);if(Fe==="up"&&qe>0){const ve=D[qe-1],Je=D[qe];await q.from("community_categories").update({sort_order:Je.sort_order}).eq("id",ve.id),await q.from("community_categories").update({sort_order:ve.sort_order}).eq("id",Je.id)}else if(Fe==="down"&&qet.invalidateQueries({queryKey:["admin-community-categories"]})}),ne=gt({mutationFn:async Ie=>{if(Ie.id){const{error:Fe}=await q.from("community_private_groups").update({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null}).eq("id",Ie.id);if(Fe)throw Fe}else{const Fe=Math.max(...M.map(ve=>ve.sort_order),0),{error:qe}=await q.from("community_private_groups").insert({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null,sort_order:Fe+1});if(qe)throw qe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),f(null),b({name:"",description:"",icon:""}),s({title:p?"Private group updated!":"Private group created!"})},onError:Ie=>{s({title:"Error",description:Ie.message,variant:"destructive"})}}),oe=gt({mutationFn:async Ie=>{const{error:Fe}=await q.from("community_private_groups").delete().eq("id",Ie);if(Fe)throw Fe},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),pe=gt({mutationFn:async({id:Ie,direction:Fe})=>{const qe=M.findIndex(ve=>ve.id===Ie);if(Fe==="up"&&qe>0){const ve=M[qe-1],Je=M[qe];await q.from("community_private_groups").update({sort_order:Je.sort_order}).eq("id",ve.id),await q.from("community_private_groups").update({sort_order:ve.sort_order}).eq("id",Je.id)}else if(Fe==="down"&&qet.invalidateQueries({queryKey:["admin-private-groups"]})}),ce=gt({mutationFn:async({groupId:Ie,userId:Fe,isMember:qe})=>{if(qe){const{error:ve}=await q.from("community_private_group_members").delete().eq("group_id",Ie).eq("user_id",Fe);if(ve)throw ve}else{const{error:ve}=await q.from("community_private_group_members").insert({group_id:Ie,user_id:Fe});if(ve)throw ve}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",_==null?void 0:_.id]})}}),de=gt({mutationFn:async({groupId:Ie,brokerageId:Fe,isMember:qe})=>{if(qe){const{error:ve}=await q.from("community_private_group_members").delete().eq("group_id",Ie).eq("brokerage_id",Fe);if(ve)throw ve}else{const{error:ve}=await q.from("community_private_group_members").insert({group_id:Ie,brokerage_id:Fe});if(ve)throw ve}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",_==null?void 0:_.id]})}}),ie=Ie=>{o(Ie),d({name:Ie.name,description:Ie.description||"",icon:Ie.icon||""}),i(!0)},ye=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},_e=Ie=>{f(Ie),b({name:Ie.name,description:Ie.description||"",icon:Ie.icon||""}),h(!0)},Me=()=>{f(null),b({name:"",description:"",icon:""}),h(!0)},Te=Ie=>{S(Ie),T(""),j(!0)},Ce=Ie=>z.some(Fe=>Fe.user_id===Ie),Ee=Ie=>z.some(Fe=>Fe.brokerage_id===Ie),De=V.filter(Ie=>Ie.name.toLowerCase().includes(A.toLowerCase())||Ie.email.toLowerCase().includes(A.toLowerCase()));return e.jsx(Cs,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs($r,{value:n,onValueChange:r,children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"categories",children:"Public Categories"}),e.jsxs(Zt,{value:"private-groups",children:[e.jsx(Rc,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(ls,{value:"categories",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Categories visible to all community members"}),e.jsxs(B,{onClick:ye,children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-[50px]",children:"Order"}),e.jsx(Ct,{className:"w-[80px]",children:"Icon"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(pa,{children:L?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):D.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):D.map((Ie,Fe)=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Fe===0,onClick:()=>ee.mutate({id:Ie.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Fe===D.length-1,onClick:()=>ee.mutate({id:Ie.id,direction:"down"}),children:"↓"})]})}),e.jsx(ut,{className:"text-2xl",children:Ie.icon||"📁"}),e.jsx(ut,{className:"font-medium",children:Ie.name}),e.jsx(ut,{className:"text-muted-foreground",children:Ie.description||"—"}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ie(Ie),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this category? Posts will be uncategorized.")&&Y.mutate(Ie.id)},children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},Ie.id))})]})})})]}),e.jsxs(ls,{value:"private-groups",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Private groups visible only to assigned members or brokerages"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ga,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(B,{onClick:Me,children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-[50px]",children:"Order"}),e.jsx(Ct,{className:"w-[80px]",children:"Icon"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{className:"w-[120px]",children:"Members"}),e.jsx(Ct,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(pa,{children:F?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):M.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):M.map((Ie,Fe)=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Fe===0,onClick:()=>pe.mutate({id:Ie.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Fe===M.length-1,onClick:()=>pe.mutate({id:Ie.id,direction:"down"}),children:"↓"})]})}),e.jsx(ut,{className:"text-2xl",children:Ie.icon||"🔒"}),e.jsx(ut,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ie.name,Ie.brokerage_id?e.jsxs(ze,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Ga,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[e.jsx(Rc,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(ut,{className:"text-muted-foreground",children:Ie.description||"—"}),e.jsx(ut,{children:e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Te(Ie),children:[e.jsx(_n,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1",children:[!Ie.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>_e(Ie),children:e.jsx(ja,{className:"h-4 w-4"})}),!Ie.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this private group? All posts in this group will be deleted.")&&oe.mutate(Ie.id)},children:e.jsx(bn,{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(bs,{open:a,onOpenChange:i,children:e.jsxs(vs,{children:[e.jsx(ws,{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(ge,{value:c.icon,onChange:Ie=>d(Fe=>({...Fe,icon:Ie.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(ge,{value:c.name,onChange:Ie=>d(Fe=>({...Fe,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(Ts,{value:c.description,onChange:Ie=>d(Fe=>({...Fe,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(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>K.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(bs,{open:u,onOpenChange:h,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:p?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(ge,{value:g.icon,onChange:Ie=>b(Fe=>({...Fe,icon:Ie.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(ge,{value:g.name,onChange:Ie=>b(Fe=>({...Fe,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(Ts,{value:g.description,onChange:Ie=>b(Fe=>({...Fe,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(B,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>ne.mutate({...g,id:p==null?void 0:p.id}),disabled:!g.name.trim(),children:p?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(bs,{open:v,onOpenChange:j,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Manage Members: ",_==null?void 0:_.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs($r,{defaultValue:"brokerages",children:[e.jsxs(Ur,{className:"w-full",children:[e.jsx(Zt,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Zt,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(ls,{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(mi,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[W.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(hi,{checked:Ee(Ie.id),onCheckedChange:()=>{_&&de.mutate({groupId:_.id,brokerageId:Ie.id,isMember:Ee(Ie.id)})}}),e.jsx("span",{className:"font-medium",children:Ie.name})]}),e.jsxs(ze,{variant:"secondary",children:[V.filter(Fe=>Fe.brokerage_id===Ie.id).length," agents"]})]},Ie.id)),W.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(ls,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search users...",value:A,onChange:Ie=>T(Ie.target.value),className:"pl-9"})]}),e.jsx(mi,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[De.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(hi,{checked:Ce(Ie.id),onCheckedChange:()=>{_&&ce.mutate({groupId:_.id,userId:Ie.id,isMember:Ce(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)),De.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No users found"})]})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{onClick:()=>j(!1),children:"Done"})})]})]})})]})})},dGe=s=>{switch(s){case"academy_video":return e.jsx(Al,{className:"h-3 w-3"});case"template":return e.jsx(Nr,{className:"h-3 w-3"});case"toolbox":return e.jsx(Oc,{className:"h-3 w-3"});case"newsletter":return e.jsx(iy,{className:"h-3 w-3"});case"social_swag":return e.jsx(un,{className:"h-3 w-3"});default:return e.jsx(tr,{className:"h-3 w-3"})}},hjs=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}},mjs=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}},pjs=()=>{const{toast:s}=Ua(),[t,n]=N.useState([]),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState(!0),[d,u]=N.useState(""),[h,p]=N.useState(null),[f,g]=N.useState([]),[b,v]=N.useState([]);N.useEffect(()=>{j()},[]);const j=async()=>{try{c(!0);const{data:z,error:V}=await q.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(V)throw V;const{data:W,error:K}=await q.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(K)throw K;const Y=[...new Set((W==null?void 0:W.map(ie=>ie.user_id))||[])],{data:ee}=await q.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",Y),ne=new Map((ee==null?void 0:ee.map(ie=>[ie.id,ie]))||[]),oe=(z==null?void 0:z.map(ie=>{var ye,_e,Me,Te;return{id:ie.id,user_id:ie.user_id,app_name:ie.app_name,launched_at:ie.launched_at,user_name:((ye=ie.profiles)==null?void 0:ye.name)||"Unknown",user_email:((_e=ie.profiles)==null?void 0:_e.email)||"Unknown",brokerage_name:((Te=(Me=ie.profiles)==null?void 0:Me.brokerages)==null?void 0:Te.name)||null}}))||[],pe=(W==null?void 0:W.map(ie=>{var _e;const ye=ne.get(ie.user_id);return{id:ie.id,user_id:ie.user_id,resource_type:ie.resource_type,resource_id:ie.resource_id,resource_title:ie.resource_title,action_type:ie.action_type,created_at:ie.created_at,user_name:(ye==null?void 0:ye.name)||"Unknown",user_email:(ye==null?void 0:ye.email)||"Unknown",brokerage_name:((_e=ye==null?void 0:ye.brokerages)==null?void 0:_e.name)||null}}))||[];n(oe),a(pe);const ce=new Map;oe.forEach(ie=>{if(!ce.has(ie.user_id))ce.set(ie.user_id,{user_id:ie.user_id,user_name:ie.user_name,user_email:ie.user_email,brokerage_name:ie.brokerage_name,last_activity_type:"app",last_activity_name:ie.app_name,last_activity_at:ie.launched_at,total_app_launches:1,total_content_views:0});else{const ye=ce.get(ie.user_id);ye.total_app_launches++,new Date(ie.launched_at)>new Date(ye.last_activity_at)&&(ye.last_activity_type="app",ye.last_activity_name=ie.app_name,ye.last_activity_at=ie.launched_at)}}),pe.forEach(ie=>{if(!ce.has(ie.user_id))ce.set(ie.user_id,{user_id:ie.user_id,user_name:ie.user_name,user_email:ie.user_email,brokerage_name:ie.brokerage_name,last_activity_type:ie.resource_type,last_activity_name:ie.resource_title,last_activity_at:ie.created_at,total_app_launches:0,total_content_views:1});else{const ye=ce.get(ie.user_id);ye.total_content_views++,new Date(ie.created_at)>new Date(ye.last_activity_at)&&(ye.last_activity_type=ie.resource_type,ye.last_activity_name=ie.resource_title,ye.last_activity_at=ie.created_at)}});const de=Array.from(ce.values()).sort((ie,ye)=>new Date(ye.last_activity_at).getTime()-new Date(ie.last_activity_at).getTime());l(de)}catch(z){console.error("Error loading activity:",z),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},_=z=>{p({id:z.user_id,name:z.user_name,email:z.user_email});const V=t.filter(K=>K.user_id===z.user_id),W=r.filter(K=>K.user_id===z.user_id);g(V),v(W)},S=()=>{p(null),g([]),v([])},{sortKey:A,sortDirection:T,handleSort:D,sortData:L}=CU("last_activity_at","desc"),M=i.filter(z=>{var W;if(!d)return!0;const V=d.toLowerCase();return z.user_name.toLowerCase().includes(V)||z.user_email.toLowerCase().includes(V)||((W=z.brokerage_name)==null?void 0:W.toLowerCase().includes(V))}),F=L(M,{user:z=>{var V;return((V=z.user_name)==null?void 0:V.toLowerCase())||""},brokerage:z=>{var V;return((V=z.brokerage_name)==null?void 0:V.toLowerCase())||""},last_activity_at:z=>new Date(z.last_activity_at).getTime(),apps:z=>z.total_app_launches,content:z=>z.total_content_views});return o?e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"User Activity"}),e.jsx(Hn,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:z=>u(z.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Pc,{sortKey:"user",currentSortKey:A,currentDirection:T,onSort:D,children:"User"}),e.jsx(Pc,{sortKey:"brokerage",currentSortKey:A,currentDirection:T,onSort:D,children:"Brokerage"}),e.jsx(Ct,{children:"Last Activity"}),e.jsx(Pc,{sortKey:"last_activity_at",currentSortKey:A,currentDirection:T,onSort:D,children:"Last Active"}),e.jsx(Pc,{sortKey:"apps",currentSortKey:A,currentDirection:T,onSort:D,className:"text-right",children:"Apps"}),e.jsx(Pc,{sortKey:"content",currentSortKey:A,currentDirection:T,onSort:D,className:"text-right",children:"Content"})]})}),e.jsx(pa,{children:F.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):F.map(z=>e.jsxs(Gs,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>_(z),children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:z.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:z.user_email})]})}),e.jsx(ut,{children:z.brokerage_name?e.jsx(ze,{variant:"outline",children:z.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ut,{children:e.jsx("div",{className:"flex items-center gap-2",children:z.last_activity_type==="app"?e.jsxs(ze,{variant:"secondary",children:[e.jsx(tr,{className:"h-3 w-3 mr-1"}),z.last_activity_name]}):e.jsxs(ze,{variant:"outline",className:"flex items-center gap-1",children:[dGe(z.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:z.last_activity_name})]})})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Go(new Date(z.last_activity_at),{addSuffix:!0})}),e.jsx(ut,{className:"text-right",children:e.jsx(ze,{variant:"outline",children:z.total_app_launches})}),e.jsx(ut,{className:"text-right",children:e.jsx(ze,{variant:"outline",children:z.total_content_views})})]},z.user_id))})]})})]})]}),e.jsx(bs,{open:!!h,onOpenChange:z=>!z&&S(),children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Qn,{children:h==null?void 0:h.email})]}),e.jsxs($r,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"content",children:["Content (",b.length,")"]}),e.jsxs(Zt,{value:"apps",children:["App Launches (",f.length,")"]})]}),e.jsx(ls,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Resource"}),e.jsx(Ct,{children:"Action"}),e.jsx(Ct,{children:"Time"})]})}),e.jsx(pa,{children:b.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):b.map(z=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs(ze,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[dGe(z.resource_type),hjs(z.resource_type)]})}),e.jsx(ut,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:z.resource_title})}),e.jsx(ut,{children:e.jsx(ze,{variant:"secondary",children:mjs(z.action_type)})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Go(new Date(z.created_at),{addSuffix:!0})})]},z.id))})]})})}),e.jsx(ls,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"App"}),e.jsx(Ct,{children:"Time"})]})}),e.jsx(pa,{children:f.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):f.map(z=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsx(ze,{variant:"secondary",children:z.app_name})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Go(new Date(z.launched_at),{addSuffix:!0})})]},z.id))})]})})})]})]})})]})},fjs=()=>{const{toast:s}=Ua(),[t,n]=N.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[r,a]=N.useState(!0);N.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await q.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await q.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await q.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await q.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:p}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),f=new Date;f.setMonth(f.getMonth()-1);const{count:g}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",f.toISOString()),{data:b}=await q.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),v=new Set(b==null?void 0:b.map(j=>j.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:p||0,launchesThisMonth:g||0,uniqueActiveThisWeek:v})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return r?e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(_n,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalUsers}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.activeUsers," active, ",t.pendingUsers," pending"]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(zi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.activeUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.totalUsers>0?`${Math.round(t.activeUsers/t.totalUsers*100)}% of total`:"0% of total"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(gr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.pendingUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalBrokerages}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total brokerages"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(am,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(am,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(am,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(mo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},uGe={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},hGe={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 Fyt({brokerageOnly:s=!1,brokerageId:t}){const[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(""),[c,d]=N.useState("all");N.useEffect(()=>{u()},[t]);const u=async()=>{i(!0);try{let D=[];if(s&&t){const{data:Y}=await q.from("profiles").select("id").eq("brokerage_id",t);if(D=(Y==null?void 0:Y.map(ee=>ee.id))||[],D.length===0){r([]),i(!1);return}}let L=q.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&D.length>0&&(L=L.or(`sender_id.in.(${D.join(",")}),recipient_id.in.(${D.join(",")})`));const{data:M,error:F}=await L;if(F)throw F;const z=new Set;M==null||M.forEach(Y=>{z.add(Y.sender_id),z.add(Y.recipient_id)});const{data:V}=await q.from("profiles").select("id, name, email").in("id",Array.from(z)),W=new Map((V==null?void 0:V.map(Y=>[Y.id,Y]))||[]),K=(M==null?void 0:M.map(Y=>({...Y,sender:W.get(Y.sender_id),recipient:W.get(Y.recipient_id)})))||[];r(K)}catch(D){console.error("Error loading shares:",D)}finally{i(!1)}},{sortKey:h,sortDirection:p,handleSort:f,sortData:g}=CU("created_at","desc"),b=n.filter(D=>{var F,z;const L=l===""||D.resource_title.toLowerCase().includes(l.toLowerCase())||((F=D.sender)==null?void 0:F.name.toLowerCase().includes(l.toLowerCase()))||((z=D.recipient)==null?void 0:z.name.toLowerCase().includes(l.toLowerCase())),M=c==="all"||D.resource_type===c;return L&&M}),v=g(b,{resource:D=>{var L;return((L=D.resource_title)==null?void 0:L.toLowerCase())||""},type:D=>D.resource_type,sender:D=>{var L,M;return((M=(L=D.sender)==null?void 0:L.name)==null?void 0:M.toLowerCase())||""},recipient:D=>{var L,M;return((M=(L=D.recipient)==null?void 0:L.name)==null?void 0:M.toLowerCase())||""},status:D=>D.is_read?1:0,created_at:D=>new Date(D.created_at).getTime()}),j=n.length,_=new Set(n.map(D=>D.sender_id)).size,S=new Set(n.map(D=>D.recipient_id)).size,A=n.length>0?Math.round(n.filter(D=>D.is_read).length/n.length*100):0,T=n.reduce((D,L)=>(D[L.resource_type]=(D[L.resource_type]||0)+1,D),{});return a?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((D,L)=>e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(Ae,{children:e.jsx(Ws,{className:"h-8 w-16"})})]},L))}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-6",children:e.jsx(Ws,{className:"h-[300px]"})})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(Hl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:j})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(_n,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:_})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(mo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:S})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ae,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[A,"%"]})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Ae,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(T).map(([D,L])=>e.jsxs(ze,{variant:"secondary",className:hGe[D],children:[uGe[D],": ",L]},D)),Object.keys(T).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Share History"}),e.jsxs(Hn,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Ae,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:D=>o(D.target.value),className:"pl-9"})]}),e.jsxs(us,{value:c,onValueChange:d,children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"Resource type"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),e.jsx(Ze,{value:"event",children:"Events"}),e.jsx(Ze,{value:"template",children:"Templates"}),e.jsx(Ze,{value:"academy_video",children:"Academy Videos"}),e.jsx(Ze,{value:"resource_kit",children:"Resource Kits"}),e.jsx(Ze,{value:"newsletter",children:"Newsletters"}),e.jsx(Ze,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(mi,{className:"h-[400px]",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Pc,{sortKey:"resource",currentSortKey:h,currentDirection:p,onSort:f,children:"Resource"}),e.jsx(Pc,{sortKey:"type",currentSortKey:h,currentDirection:p,onSort:f,children:"Type"}),e.jsx(Pc,{sortKey:"sender",currentSortKey:h,currentDirection:p,onSort:f,children:"Sender"}),e.jsx(Pc,{sortKey:"recipient",currentSortKey:h,currentDirection:p,onSort:f,children:"Recipient"}),e.jsx(Pc,{sortKey:"status",currentSortKey:h,currentDirection:p,onSort:f,children:"Status"}),e.jsx(Pc,{sortKey:"created_at",currentSortKey:h,currentDirection:p,onSort:f,children:"Date"})]})}),e.jsx(pa,{children:v.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):v.map(D=>{var L,M;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium max-w-[200px] truncate",children:D.resource_title}),e.jsx(ut,{children:e.jsx(ze,{variant:"secondary",className:hGe[D.resource_type],children:uGe[D.resource_type]})}),e.jsx(ut,{children:((L=D.sender)==null?void 0:L.name)||"Unknown"}),e.jsx(ut,{children:((M=D.recipient)==null?void 0:M.name)||"Unknown"}),e.jsx(ut,{children:e.jsx(ze,{variant:D.is_read?"default":"outline",children:D.is_read?"Read":"Unread"})}),e.jsx(ut,{className:"text-muted-foreground",children:ks(new Date(D.created_at),"MMM d, yyyy")})]},D.id)})})]})})]})]})]})}const Y2e={academy_video:{label:"Academy Videos",icon:vr,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:Ir},template:{label:"Templates",icon:E2,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:Fm},toolbox:{label:"Toolkit",icon:wb,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:Da},newsletter:{label:"Newsletters",icon:Hs,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:Fm},social_swag:{label:"Social Swag",icon:xl,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:Fm},event:{label:"Events",icon:yr,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:Fm}};function mGe(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function xjs(s,t){return s==="toolbox"?t.downloads:t.clicks}function gjs(){var D;const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(null),l=N.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=CU("total_views","desc");N.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:L,error:M}=await q.rpc("get_admin_content_engagement");if(M)throw M;t(L||[])}catch(L){console.error("Error loading content engagement:",L)}finally{r(!1)}},p=L=>{i(M=>{const F=M===L?null:L;return requestAnimationFrame(()=>{var z;(z=l.current)==null||z.scrollIntoView({behavior:"smooth",block:"start"})}),F})};if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-4",children:[...Array(4)].map((L,M)=>e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(Ae,{children:e.jsx(Ws,{className:"h-8 w-16"})})]},M))}),e.jsx(fe,{children:e.jsx(Ae,{className:"py-8",children:e.jsx(Ws,{className:"h-64 w-full"})})})]});const f=s.reduce((L,M)=>L+M.total_views,0),g=s.reduce((L,M)=>L+M.total_clicks,0),b=s.reduce((L,M)=>L+M.total_downloads,0),v=s.length,j=s.reduce((L,M)=>(L[M.resource_type]||(L[M.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),L[M.resource_type].views+=M.total_views,L[M.resource_type].clicks+=M.total_clicks,L[M.resource_type].downloads+=M.total_downloads,L[M.resource_type].assets+=1,L[M.resource_type].uniqueUsers+=M.unique_users,L),{}),_=a?s.filter(L=>L.resource_type===a):s,S=u(_,{asset:L=>{var M;return((M=L.resource_title)==null?void 0:M.toLowerCase())||""},type:L=>L.resource_type,views:L=>L.total_views,actions:L=>mGe(L),unique_users:L=>L.unique_users,last_activity:L=>L.last_engaged_at?new Date(L.last_engaged_at).getTime():0}),A=a?Y2e[a]||{label:a,icon:Ir,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Fm}:null,T=A==null?void 0:A.icon;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-5",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(Ir,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:f.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(Fm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:b.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(mo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(Fm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[f>0?Math.round((g+b)/f*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Hn,{children:"Click a category to see individual asset performance"})]}),e.jsx(Ae,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(j).map(([L,M])=>{const F=Y2e[L]||{label:L,icon:Ir,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Fm},z=F.icon,V=a===L;return e.jsxs("button",{type:"button",onClick:()=>p(L),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${V?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${F.color}`,children:e.jsx(z,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:F.label}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ir,{className:"h-3 w-3"})," ",M.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(F.actionIcon,{className:"h-3 w-3"})," ",xjs(L,M)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_n,{className:"h-3 w-3"})," ",M.uniqueUsers]})]})]}),e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:[M.assets," items"]})]},L)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{className:"text-sm font-medium flex items-center gap-2",children:A&&T?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"h-4 w-4"}),A.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(Hn,{children:a?`${_.length} ${((D=A==null?void 0:A.label)==null?void 0:D.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Ae,{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(mi,{className:"h-[400px]",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-[40px]",children:"#"}),e.jsx(Pc,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Pc,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Pc,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Pc,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:A?A.actionLabel:"Actions"}),e.jsx(Pc,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Pc,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(pa,{children:S.map((L,M)=>{const F=Y2e[L.resource_type]||{label:L.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Fm};return e.jsxs(Gs,{children:[e.jsx(ut,{className:"text-muted-foreground text-xs",children:M+1}),e.jsx(ut,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:L.resource_title})}),!a&&e.jsx(ut,{children:e.jsx(ze,{className:`text-[10px] ${F.color}`,children:F.label})}),e.jsx(ut,{className:"text-right font-medium",children:L.total_views}),e.jsx(ut,{className:"text-right font-medium",children:mGe(L)}),e.jsx(ut,{className:"text-right",children:L.unique_users}),e.jsx(ut,{className:"text-xs text-muted-foreground",children:L.last_engaged_at?Go(new Date(L.last_engaged_at),{addSuffix:!0}):"—"})]},`${L.resource_type}-${L.resource_id}`)})})]})})})]})})]})}var yjs=Array.isArray,l0=yjs,vjs=typeof Ih=="object"&&Ih&&Ih.Object===Object&&Ih,zyt=vjs,bjs=zyt,_js=typeof self=="object"&&self&&self.Object===Object&&self,wjs=bjs||_js||Function("return this")(),ej=wjs,jjs=ej,Njs=jjs.Symbol,PU=Njs,pGe=PU,Byt=Object.prototype,kjs=Byt.hasOwnProperty,Sjs=Byt.toString,CF=pGe?pGe.toStringTag:void 0;function Cjs(s){var t=kjs.call(s,CF),n=s[CF];try{s[CF]=void 0;var r=!0}catch{}var a=Sjs.call(s);return r&&(t?s[CF]=n:delete s[CF]),a}var Tjs=Cjs,Ejs=Object.prototype,Ajs=Ejs.toString;function Mjs(s){return Ajs.call(s)}var Ijs=Mjs,fGe=PU,Pjs=Tjs,Ljs=Ijs,Djs="[object Null]",Rjs="[object Undefined]",xGe=fGe?fGe.toStringTag:void 0;function Ojs(s){return s==null?s===void 0?Rjs:Djs:xGe&&xGe in Object(s)?Pjs(s):Ljs(s)}var AN=Ojs;function Fjs(s){return s!=null&&typeof s=="object"}var MN=Fjs,zjs=AN,Bjs=MN,$js="[object Symbol]";function Ujs(s){return typeof s=="symbol"||Bjs(s)&&zjs(s)==$js}var lR=Ujs,qjs=l0,Vjs=lR,Hjs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Gjs=/^\w*$/;function Wjs(s,t){if(qjs(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||Vjs(s)?!0:Gjs.test(s)||!Hjs.test(s)||t!=null&&s in Object(t)}var oPe=Wjs;function Kjs(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var uC=Kjs;const cR=jl(uC);var Yjs=AN,Zjs=uC,Qjs="[object AsyncFunction]",Xjs="[object Function]",Jjs="[object GeneratorFunction]",e2s="[object Proxy]";function t2s(s){if(!Zjs(s))return!1;var t=Yjs(s);return t==Xjs||t==Jjs||t==Qjs||t==e2s}var lPe=t2s;const ho=jl(lPe);var s2s=ej,n2s=s2s["__core-js_shared__"],r2s=n2s,Z2e=r2s,gGe=function(){var s=/[^.]+$/.exec(Z2e&&Z2e.keys&&Z2e.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function a2s(s){return!!gGe&&gGe in s}var i2s=a2s,o2s=Function.prototype,l2s=o2s.toString;function c2s(s){if(s!=null){try{return l2s.call(s)}catch{}try{return s+""}catch{}}return""}var $yt=c2s,d2s=lPe,u2s=i2s,h2s=uC,m2s=$yt,p2s=/[\\^$.*+?()[\]{}|]/g,f2s=/^\[object .+?Constructor\]$/,x2s=Function.prototype,g2s=Object.prototype,y2s=x2s.toString,v2s=g2s.hasOwnProperty,b2s=RegExp("^"+y2s.call(v2s).replace(p2s,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _2s(s){if(!h2s(s)||u2s(s))return!1;var t=d2s(s)?b2s:f2s;return t.test(m2s(s))}var w2s=_2s;function j2s(s,t){return s==null?void 0:s[t]}var N2s=j2s,k2s=w2s,S2s=N2s;function C2s(s,t){var n=S2s(s,t);return k2s(n)?n:void 0}var n6=C2s,T2s=n6,E2s=T2s(Object,"create"),zve=E2s,yGe=zve;function A2s(){this.__data__=yGe?yGe(null):{},this.size=0}var M2s=A2s;function I2s(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var P2s=I2s,L2s=zve,D2s="__lodash_hash_undefined__",R2s=Object.prototype,O2s=R2s.hasOwnProperty;function F2s(s){var t=this.__data__;if(L2s){var n=t[s];return n===D2s?void 0:n}return O2s.call(t,s)?t[s]:void 0}var z2s=F2s,B2s=zve,$2s=Object.prototype,U2s=$2s.hasOwnProperty;function q2s(s){var t=this.__data__;return B2s?t[s]!==void 0:U2s.call(t,s)}var V2s=q2s,H2s=zve,G2s="__lodash_hash_undefined__";function W2s(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=H2s&&t===void 0?G2s:t,this}var K2s=W2s,Y2s=M2s,Z2s=P2s,Q2s=z2s,X2s=V2s,J2s=K2s;function dR(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var xNs=fNs,gNs=Bve;function yNs(s,t){var n=this.__data__,r=gNs(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var vNs=yNs,bNs=sNs,_Ns=dNs,wNs=mNs,jNs=xNs,NNs=vNs;function uR(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},sA=function(t){return AM(t)&&t.indexOf("%")===t.length-1},ca=function(t){return Gks(t)&&!LU(t)},Zks=function(t){return No(t)},Um=function(t){return ca(t)||AM(t)},Qks=0,mR=function(t){var n=++Qks;return"".concat(t||"").concat(n)},Jx=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(!ca(t)&&!AM(t))return r;var i;if(sA(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return LU(i)&&(i=r),a&&i>n&&(i=n),i},gS=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},Xks=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 aSs(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 A3e(s){"@babel/helpers - typeof";return A3e=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},A3e(s)}var kGe={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"},nN=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},SGe=null,X2e=null,yPe=function s(t){if(t===SGe&&Array.isArray(X2e))return X2e;var n=[];return N.Children.forEach(t,function(r){No(r)||($ks.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),X2e=n,SGe=t,n};function xy(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return nN(a)}):r=[nN(t)],yPe(s).forEach(function(a){var i=fy(a,"type.displayName")||fy(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function V0(s,t){var n=xy(s,t);return n&&n[0]}var CGe=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!ca(r)||r<=0||!ca(a)||a<=0)},iSs=["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"],oSs=function(t){return t&&t.type&&AM(t.type)&&iSs.indexOf(t.type)>=0},lSs=function(t){return t&&A3e(t)==="object"&&"clipDot"in t},cSs=function(t,n,r,a){var i,l=(i=Q2e==null?void 0:Q2e[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!ho(t)&&(a&&l.includes(n)||tSs.includes(n))||r&&gPe.includes(n)},Wi=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(N.isValidElement(t)&&(a=t.props),!cR(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;cSs((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},M3e=function s(t,n){if(t===n)return!0;var r=N.Children.count(t);if(r!==N.Children.count(n))return!1;if(r===0)return!0;if(r===1)return TGe(Array.isArray(t)?t[0]:t,Array.isArray(n)?n[0]:n);for(var a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function pSs(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 P3e(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=mSs(s,hSs),u=a||{width:n,height:r,x:0,y:0},h=So("recharts-surface",i);return Nt.createElement("svg",I3e({},Wi(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),Nt.createElement("title",null,o),Nt.createElement("desc",null,c),t)}var fSs=["children","className"];function L3e(){return L3e=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 gSs(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 Kl=Nt.forwardRef(function(s,t){var n=s.children,r=s.className,a=xSs(s,fSs),i=So("recharts-layer",r);return Nt.createElement("g",L3e({className:i},Wi(a,!0),{ref:t}),n)}),kb=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:bSs(s,t,n)}var wSs=_Ss,jSs="\\ud800-\\udfff",NSs="\\u0300-\\u036f",kSs="\\ufe20-\\ufe2f",SSs="\\u20d0-\\u20ff",CSs=NSs+kSs+SSs,TSs="\\ufe0e\\ufe0f",ESs="\\u200d",ASs=RegExp("["+ESs+jSs+CSs+TSs+"]");function MSs(s){return ASs.test(s)}var Qyt=MSs;function ISs(s){return s.split("")}var PSs=ISs,Xyt="\\ud800-\\udfff",LSs="\\u0300-\\u036f",DSs="\\ufe20-\\ufe2f",RSs="\\u20d0-\\u20ff",OSs=LSs+DSs+RSs,FSs="\\ufe0e\\ufe0f",zSs="["+Xyt+"]",D3e="["+OSs+"]",R3e="\\ud83c[\\udffb-\\udfff]",BSs="(?:"+D3e+"|"+R3e+")",Jyt="[^"+Xyt+"]",evt="(?:\\ud83c[\\udde6-\\uddff]){2}",tvt="[\\ud800-\\udbff][\\udc00-\\udfff]",$Ss="\\u200d",svt=BSs+"?",nvt="["+FSs+"]?",USs="(?:"+$Ss+"(?:"+[Jyt,evt,tvt].join("|")+")"+nvt+svt+")*",qSs=nvt+svt+USs,VSs="(?:"+[Jyt+D3e+"?",D3e,evt,tvt,zSs].join("|")+")",HSs=RegExp(R3e+"(?="+R3e+")|"+VSs+qSs,"g");function GSs(s){return s.match(HSs)||[]}var WSs=GSs,KSs=PSs,YSs=Qyt,ZSs=WSs;function QSs(s){return YSs(s)?ZSs(s):KSs(s)}var XSs=QSs,JSs=wSs,e4s=Qyt,t4s=XSs,s4s=Hyt;function n4s(s){return function(t){t=s4s(t);var n=e4s(t)?t4s(t):void 0,r=n?n[0]:t.charAt(0),a=n?JSs(n,1).join(""):t.slice(1);return r[s]()+a}}var r4s=n4s,a4s=r4s,i4s=a4s("toUpperCase"),o4s=i4s;const e1e=jl(o4s);function vd(s){return function(){return s}}const rvt=Math.cos,Bxe=Math.sin,zb=Math.sqrt,$xe=Math.PI,t1e=2*$xe,O3e=Math.PI,F3e=2*O3e,PE=1e-6,l4s=F3e-PE;function avt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return avt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aPE)if(!(Math.abs(h*c-d*u)>PE)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let f=r-l,g=a-o,b=c*c+d*d,v=f*f+g*g,j=Math.sqrt(b),_=Math.sqrt(p),S=i*Math.tan((O3e-Math.acos((b+p-v)/(2*j*_)))/2),A=S/_,T=S/j;Math.abs(A-1)>PE&&this._append`L${t+A*u},${n+A*h}`,this._append`A${i},${i},0,0,${+(h*f>u*g)},${this._x1=t+T*c},${this._y1=n+T*d}`}}arc(t,n,r,a,i,l){if(t=+t,n=+n,r=+r,l=!!l,r<0)throw new Error(`negative radius: ${r}`);let o=r*Math.cos(a),c=r*Math.sin(a),d=t+o,u=n+c,h=1^l,p=l?a-i:i-a;this._x1===null?this._append`M${d},${u}`:(Math.abs(this._x1-d)>PE||Math.abs(this._y1-u)>PE)&&this._append`L${d},${u}`,r&&(p<0&&(p=p%F3e+F3e),p>l4s?this._append`A${r},${r},0,1,${h},${t-o},${n-c}A${r},${r},0,1,${h},${this._x1=d},${this._y1=u}`:p>PE&&this._append`A${r},${r},0,${+(p>=O3e)},${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 vPe(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 d4s(t)}function bPe(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function ivt(s){this._context=s}ivt.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 s1e(s){return new ivt(s)}function ovt(s){return s[0]}function lvt(s){return s[1]}function cvt(s,t){var n=vd(!0),r=null,a=s1e,i=null,l=vPe(o);s=typeof s=="function"?s:s===void 0?ovt:vd(s),t=typeof t=="function"?t:t===void 0?lvt:vd(t);function o(c){var d,u=(c=bPe(c)).length,h,p=!1,f;for(r==null&&(i=a(f=l())),d=0;d<=u;++d)!(d=f;--g)o.point(S[g],A[g]);o.lineEnd(),o.areaEnd()}j&&(S[p]=+s(v,p,h),A[p]=+t(v,p,h),o.point(r?+r(v,p,h):S[p],n?+n(v,p,h):A[p]))}if(_)return o=null,_+""||null}function u(){return cvt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:vd(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:vd(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:vd(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:vd(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:vd(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:vd(+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:vd(!!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 dvt{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 u4s(s){return new dvt(s,!0)}function h4s(s){return new dvt(s,!1)}const _Pe={draw(s,t){const n=zb(t/$xe);s.moveTo(n,0),s.arc(0,0,n,0,t1e)}},m4s={draw(s,t){const n=zb(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()}},uvt=zb(1/3),p4s=uvt*2,f4s={draw(s,t){const n=zb(t/p4s),r=n*uvt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},x4s={draw(s,t){const n=zb(t),r=-n/2;s.rect(r,r,n,n)}},g4s=.8908130915292852,hvt=Bxe($xe/10)/Bxe(7*$xe/10),y4s=Bxe(t1e/10)*hvt,v4s=-rvt(t1e/10)*hvt,b4s={draw(s,t){const n=zb(t*g4s),r=y4s*n,a=v4s*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=t1e*i/5,o=rvt(l),c=Bxe(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},J2e=zb(3),_4s={draw(s,t){const n=-zb(t/(J2e*3));s.moveTo(0,n*2),s.lineTo(-J2e*n,-n),s.lineTo(J2e*n,-n),s.closePath()}},iv=-.5,ov=zb(3)/2,z3e=1/zb(12),w4s=(z3e/2+1)*3,j4s={draw(s,t){const n=zb(t/w4s),r=n/2,a=n*z3e,i=r,l=n*z3e+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(iv*r-ov*a,ov*r+iv*a),s.lineTo(iv*i-ov*l,ov*i+iv*l),s.lineTo(iv*o-ov*c,ov*o+iv*c),s.lineTo(iv*r+ov*a,iv*a-ov*r),s.lineTo(iv*i+ov*l,iv*l-ov*i),s.lineTo(iv*o+ov*c,iv*c-ov*o),s.closePath()}};function N4s(s,t){let n=null,r=vPe(a);s=typeof s=="function"?s:vd(s||_Pe),t=typeof t=="function"?t:vd(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:vd(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:vd(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function Uxe(){}function qxe(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 mvt(s){this._context=s}mvt.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:qxe(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:qxe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function k4s(s){return new mvt(s)}function pvt(s){this._context=s}pvt.prototype={areaStart:Uxe,areaEnd:Uxe,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:qxe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function S4s(s){return new pvt(s)}function fvt(s){this._context=s}fvt.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:qxe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function C4s(s){return new fvt(s)}function xvt(s){this._context=s}xvt.prototype={areaStart:Uxe,areaEnd:Uxe,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 T4s(s){return new xvt(s)}function AGe(s){return s<0?-1:1}function MGe(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(AGe(i)+AGe(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function IGe(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function eNe(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 Vxe(s){this._context=s}Vxe.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:eNe(this,this._t0,IGe(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,eNe(this,IGe(this,n=MGe(this,s,t)),n);break;default:eNe(this,this._t0,n=MGe(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function gvt(s){this._context=new yvt(s)}(gvt.prototype=Object.create(Vxe.prototype)).point=function(s,t){Vxe.prototype.point.call(this,t,s)};function yvt(s){this._context=s}yvt.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 E4s(s){return new Vxe(s)}function A4s(s){return new gvt(s)}function vvt(s){this._context=s}vvt.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=PGe(s),a=PGe(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 I4s(s){return new n1e(s,.5)}function P4s(s){return new n1e(s,0)}function L4s(s){return new n1e(s,1)}function B8(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 D4s(s,t){return s[t]}function R4s(s){const t=[];return t.key=s,t}function O4s(){var s=vd([]),t=B3e,n=B8,r=D4s;function a(i){var l=Array.from(s.apply(this,arguments),R4s),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 G4s(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 bvt={symbolCircle:_Pe,symbolCross:m4s,symbolDiamond:f4s,symbolSquare:x4s,symbolStar:b4s,symbolTriangle:_4s,symbolWye:j4s},W4s=Math.PI/180,K4s=function(t){var n="symbol".concat(e1e(t));return bvt[n]||_Pe},Y4s=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*W4s;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}},Z4s=function(t,n){bvt["symbol".concat(e1e(t))]=n},wPe=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=H4s(t,$4s),d=DGe(DGe({},c),{},{type:r,size:i,sizeType:o}),u=function(){var v=K4s(r),j=N4s().type(v).size(Y4s(i,o,r));return j()},h=d.className,p=d.cx,f=d.cy,g=Wi(d,!0);return p===+p&&f===+f&&i===+i?Nt.createElement("path",$3e({},g,{className:So("recharts-symbols",h),transform:"translate(".concat(p,", ").concat(f,")"),d:u()})):null};wPe.registerSymbol=Z4s;function $8(s){"@babel/helpers - typeof";return $8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$8(s)}function U3e(){return U3e=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var _=f.inactive?d:f.color;return Nt.createElement("li",U3e({className:v,style:h,key:"legend-item-".concat(g)},MM(r.props,f,g)),Nt.createElement(P3e,{width:l,height:l,viewBox:u,style:p},r.renderIcon(f)),Nt.createElement("span",{className:"recharts-legend-item-text",style:{color:_}},b?b(j,f,g):j))})}},{key:"render",value:function(){var r=this.props,a=r.payload,i=r.layout,l=r.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return Nt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(N.PureComponent);BB(jPe,"displayName","Legend");BB(jPe,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var iCs=$ve;function oCs(){this.__data__=new iCs,this.size=0}var lCs=oCs;function cCs(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var dCs=cCs;function uCs(s){return this.__data__.get(s)}var hCs=uCs;function mCs(s){return this.__data__.has(s)}var pCs=mCs,fCs=$ve,xCs=dPe,gCs=uPe,yCs=200;function vCs(s,t){var n=this.__data__;if(n instanceof fCs){var r=n.__data__;if(!xCs||r.lengtho))return!1;var d=i.get(s),u=i.get(t);if(d&&u)return d==t&&u==s;var h=-1,p=!0,f=n&$Cs?new OCs:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=H3s}var CPe=G3s,W3s=AN,K3s=CPe,Y3s=MN,Z3s="[object Arguments]",Q3s="[object Array]",X3s="[object Boolean]",J3s="[object Date]",e5s="[object Error]",t5s="[object Function]",s5s="[object Map]",n5s="[object Number]",r5s="[object Object]",a5s="[object RegExp]",i5s="[object Set]",o5s="[object String]",l5s="[object WeakMap]",c5s="[object ArrayBuffer]",d5s="[object DataView]",u5s="[object Float32Array]",h5s="[object Float64Array]",m5s="[object Int8Array]",p5s="[object Int16Array]",f5s="[object Int32Array]",x5s="[object Uint8Array]",g5s="[object Uint8ClampedArray]",y5s="[object Uint16Array]",v5s="[object Uint32Array]",Rd={};Rd[u5s]=Rd[h5s]=Rd[m5s]=Rd[p5s]=Rd[f5s]=Rd[x5s]=Rd[g5s]=Rd[y5s]=Rd[v5s]=!0;Rd[Z3s]=Rd[Q3s]=Rd[c5s]=Rd[X3s]=Rd[d5s]=Rd[J3s]=Rd[e5s]=Rd[t5s]=Rd[s5s]=Rd[n5s]=Rd[r5s]=Rd[a5s]=Rd[i5s]=Rd[o5s]=Rd[l5s]=!1;function b5s(s){return Y3s(s)&&K3s(s.length)&&!!Rd[W3s(s)]}var _5s=b5s;function w5s(s){return function(t){return s(t)}}var Mvt=w5s,Kxe={exports:{}};Kxe.exports;(function(s,t){var n=zyt,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})(Kxe,Kxe.exports);var j5s=Kxe.exports,N5s=_5s,k5s=Mvt,UGe=j5s,qGe=UGe&&UGe.isTypedArray,S5s=qGe?k5s(qGe):N5s,Ivt=S5s,C5s=A3s,T5s=kPe,E5s=l0,A5s=Avt,M5s=SPe,I5s=Ivt,P5s=Object.prototype,L5s=P5s.hasOwnProperty;function D5s(s,t){var n=E5s(s),r=!n&&T5s(s),a=!n&&!r&&A5s(s),i=!n&&!r&&!a&&I5s(s),l=n||r||a||i,o=l?C5s(s.length,String):[],c=o.length;for(var d in s)(t||L5s.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||M5s(d,c)))&&o.push(d);return o}var R5s=D5s,O5s=Object.prototype;function F5s(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||O5s;return s===n}var z5s=F5s;function B5s(s,t){return function(n){return s(t(n))}}var Pvt=B5s,$5s=Pvt,U5s=$5s(Object.keys,Object),q5s=U5s,V5s=z5s,H5s=q5s,G5s=Object.prototype,W5s=G5s.hasOwnProperty;function K5s(s){if(!V5s(s))return H5s(s);var t=[];for(var n in Object(s))W5s.call(s,n)&&n!="constructor"&&t.push(n);return t}var Y5s=K5s,Z5s=lPe,Q5s=CPe;function X5s(s){return s!=null&&Q5s(s.length)&&!Z5s(s)}var DU=X5s,J5s=R5s,eTs=Y5s,tTs=DU;function sTs(s){return tTs(s)?J5s(s):eTs(s)}var r1e=sTs,nTs=y3s,rTs=T3s,aTs=r1e;function iTs(s){return nTs(s,aTs,rTs)}var oTs=iTs,VGe=oTs,lTs=1,cTs=Object.prototype,dTs=cTs.hasOwnProperty;function uTs(s,t,n,r,a,i){var l=n&lTs,o=VGe(s),c=o.length,d=VGe(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var p=o[h];if(!(l?p in t:dTs.call(t,p)))return!1}var f=i.get(s),g=i.get(t);if(f&&g)return f==t&&g==s;var b=!0;i.set(s,t),i.set(t,s);for(var v=l;++h-1}var cAs=lAs;function dAs(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=kAs){var d=t?null:jAs(s);if(d)return NAs(d);l=!1,a=wAs,c=new vAs}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function $As(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 UAs(s){return s.value}function qAs(s,t){if(Nt.isValidElement(s))return Nt.cloneElement(s,t);if(typeof s=="function")return Nt.createElement(s,t);t.ref;var n=BAs(t,IAs);return Nt.createElement(jPe,n)}var iWe=1,JA=function(s){function t(){var n;PAs(this,t);for(var r=arguments.length,a=new Array(r),i=0;iiWe||Math.abs(a.height-this.lastBoundingBox.height)>iWe)&&(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?c2({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(r){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,u=a.chartHeight,h,p;if(!r||(r.left===void 0||r.left===null)&&(r.right===void 0||r.right===null))if(l==="center"&&i==="vertical"){var f=this.getBBoxSnapshot();h={left:((d||0)-f.width)/2}}else h=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!r||(r.top===void 0||r.top===null)&&(r.bottom===void 0||r.bottom===null))if(o==="middle"){var g=this.getBBoxSnapshot();p={top:((u||0)-g.height)/2}}else p=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return c2(c2({},h),p)}},{key:"render",value:function(){var r=this,a=this.props,i=a.content,l=a.width,o=a.height,c=a.wrapperStyle,d=a.payloadUniqBy,u=a.payload,h=c2(c2({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Nt.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(f){r.wrapperNode=f}},qAs(i,c2(c2({},this.props),{},{payload:Bvt(u,d,UAs)})))}}],[{key:"getWithHeight",value:function(r,a){var i=c2(c2({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&ca(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(N.PureComponent);a1e(JA,"displayName","Legend");a1e(JA,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var oWe=PU,VAs=kPe,HAs=l0,lWe=oWe?oWe.isConcatSpreadable:void 0;function GAs(s){return HAs(s)||VAs(s)||!!(lWe&&s&&s[lWe])}var WAs=GAs,KAs=Tvt,YAs=WAs;function qvt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=YAs),a||(a=[]);++i0&&n(o)?t>1?qvt(o,t-1,n,r,a):KAs(a,o):r||(a[a.length]=o)}return a}var Vvt=qvt;function ZAs(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 QAs=ZAs,XAs=QAs,JAs=XAs(),eMs=JAs,tMs=eMs,sMs=r1e;function nMs(s,t){return s&&tMs(s,t,sMs)}var Hvt=nMs,rMs=DU;function aMs(s,t){return function(n,r){if(n==null)return n;if(!rMs(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 vMs=yMs,rNe=mPe,bMs=pPe,_Ms=tj,wMs=Gvt,jMs=pMs,NMs=Mvt,kMs=vMs,SMs=xR,CMs=l0;function TMs(s,t,n){t.length?t=rNe(t,function(i){return CMs(i)?function(l){return bMs(l,i.length===1?i[0]:i)}:i}):t=[SMs];var r=-1;t=rNe(t,NMs(_Ms));var a=wMs(s,function(i,l,o){var c=rNe(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return jMs(a,function(i,l){return kMs(i,l,n)})}var EMs=TMs;function AMs(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 MMs=AMs,IMs=MMs,dWe=Math.max;function PMs(s,t,n){return t=dWe(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=dWe(r.length-t,0),l=Array(i);++a0){if(++t>=qMs)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var WMs=GMs,KMs=UMs,YMs=WMs,ZMs=YMs(KMs),QMs=ZMs,XMs=xR,JMs=LMs,e6s=QMs;function t6s(s,t){return e6s(JMs(s,t,XMs),s+"")}var s6s=t6s,n6s=cPe,r6s=DU,a6s=SPe,i6s=uC;function o6s(s,t,n){if(!i6s(n))return!1;var r=typeof t;return(r=="number"?r6s(n)&&a6s(t,n.length):r=="string"&&t in n)?n6s(n[t],s):!1}var i1e=o6s,l6s=Vvt,c6s=EMs,d6s=s6s,hWe=i1e,u6s=d6s(function(s,t){if(s==null)return[];var n=t.length;return n>1&&hWe(s,t[0],t[1])?t=[]:n>2&&hWe(t[0],t[1],t[2])&&(t=[t[0]]),c6s(s,l6s(t,1),[])}),h6s=u6s;const APe=jl(h6s);function $B(s){"@babel/helpers - typeof";return $B=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},$B(s)}function Z3e(){return Z3e=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(TF,"-left"),ca(n)&&t&&ca(t.x)&&n=t.y),"".concat(TF,"-top"),ca(r)&&t&&ca(t.y)&&rb?Math.max(u,c[r]):Math.max(h,c[r])}function C6s(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 T6s(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=fWe({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=fWe({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=C6s({translateX:u,translateY:h,useTranslate3d:o})):d=k6s,{cssProperties:d,cssClasses:S6s({translateX:u,translateY:h,coordinate:n})}}function q8(s){"@babel/helpers - typeof";return q8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},q8(s)}function xWe(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 gWe(s){for(var t=1;tyWe||Math.abs(r.height-this.state.lastBoundingBox.height)>yWe)&&this.setState({lastBoundingBox:{width:r.width,height:r.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var r,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var r=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,u=a.coordinate,h=a.hasPayload,p=a.isAnimationActive,f=a.offset,g=a.position,b=a.reverseDirection,v=a.useTranslate3d,j=a.viewBox,_=a.wrapperStyle,S=T6s({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:f,position:g,reverseDirection:b,tooltipBox:this.state.lastBoundingBox,useTranslate3d:v,viewBox:j}),A=S.cssClasses,T=S.cssProperties,D=gWe(gWe({transition:p&&i?"transform ".concat(o,"ms ").concat(c):void 0},T),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&h?"visible":"hidden",position:"absolute",top:0,left:0},_);return Nt.createElement("div",{tabIndex:-1,className:A,style:D,ref:function(M){r.wrapperNode=M}},d)}}])}(N.PureComponent),F6s=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},kw={isSsr:F6s(),get:function(t){return kw[t]},set:function(t,n){if(typeof t=="string")kw[t]=n;else{var r=Object.keys(t);r&&r.length&&r.forEach(function(a){kw[a]=t[a]})}}};function V8(s){"@babel/helpers - typeof";return V8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},V8(s)}function vWe(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 bWe(s){for(var t=1;t0;return Nt.createElement(O6s,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:p,active:i,coordinate:u,hasPayload:D,offset:f,position:v,reverseDirection:j,useTranslate3d:_,viewBox:S,wrapperStyle:A},K6s(d,bWe(bWe({},this.props),{},{payload:T})))}}])}(N.PureComponent);MPe(kp,"displayName","Tooltip");MPe(kp,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!kw.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 Y6s=ej,Z6s=function(){return Y6s.Date.now()},Q6s=Z6s,X6s=/\s/;function J6s(s){for(var t=s.length;t--&&X6s.test(s.charAt(t)););return t}var eIs=J6s,tIs=eIs,sIs=/^\s+/;function nIs(s){return s&&s.slice(0,tIs(s)+1).replace(sIs,"")}var rIs=nIs,aIs=rIs,_We=uC,iIs=lR,wWe=NaN,oIs=/^[-+]0x[0-9a-f]+$/i,lIs=/^0b[01]+$/i,cIs=/^0o[0-7]+$/i,dIs=parseInt;function uIs(s){if(typeof s=="number")return s;if(iIs(s))return wWe;if(_We(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=_We(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=aIs(s);var n=lIs.test(s);return n||cIs.test(s)?dIs(s.slice(2),n?2:8):oIs.test(s)?wWe:+s}var Xvt=uIs,hIs=uC,iNe=Q6s,jWe=Xvt,mIs="Expected a function",pIs=Math.max,fIs=Math.min;function xIs(s,t,n){var r,a,i,l,o,c,d=0,u=!1,h=!1,p=!0;if(typeof s!="function")throw new TypeError(mIs);t=jWe(t)||0,hIs(n)&&(u=!!n.leading,h="maxWait"in n,i=h?pIs(jWe(n.maxWait)||0,t):i,p="trailing"in n?!!n.trailing:p);function f(D){var L=r,M=a;return r=a=void 0,d=D,l=s.apply(M,L),l}function g(D){return d=D,o=setTimeout(j,t),u?f(D):l}function b(D){var L=D-c,M=D-d,F=t-L;return h?fIs(F,i-M):F}function v(D){var L=D-c,M=D-d;return c===void 0||L>=t||L<0||h&&M>=i}function j(){var D=iNe();if(v(D))return _(D);o=setTimeout(j,b(D))}function _(D){return o=void 0,p&&r?f(D):(r=a=void 0,l)}function S(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function A(){return o===void 0?l:_(iNe())}function T(){var D=iNe(),L=v(D);if(r=arguments,a=this,c=D,L){if(o===void 0)return g(c);if(h)return clearTimeout(o),o=setTimeout(j,t),f(c)}return o===void 0&&(o=setTimeout(j,t)),l}return T.cancel=S,T.flush=A,T}var gIs=xIs,yIs=gIs,vIs=uC,bIs="Expected a function";function _Is(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(bIs);return vIs(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),yIs(s,t,{leading:r,maxWait:t,trailing:a})}var wIs=_Is;const Jvt=jl(wIs);function qB(s){"@babel/helpers - typeof";return qB=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qB(s)}function NWe(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 sG(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(K=Jvt(K,b,{trailing:!0,leading:!1}));var Y=new ResizeObserver(K),ee=T.current.getBoundingClientRect(),ne=ee.width,oe=ee.height;return V(ne,oe),Y.observe(T.current),function(){Y.disconnect()}},[V,b]);var W=N.useMemo(function(){var K=F.containerWidth,Y=F.containerHeight;if(K<0||Y<0)return null;kb(sA(l)||sA(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),kb(!n||n>0,"The aspect(%s) must be greater than zero.",n);var ee=sA(l)?K:l,ne=sA(c)?Y:c;n&&n>0&&(ee?ne=ee/n:ne&&(ee=ne*n),p&&ne>p&&(ne=p)),kb(ee>0||ne>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the height and width.`,ee,ne,l,c,u,h,n);var oe=!Array.isArray(f)&&nN(f.type).endsWith("Chart");return Nt.Children.map(f,function(pe){return Nt.isValidElement(pe)?N.cloneElement(pe,sG({width:ee,height:ne},oe?{style:sG({height:"100%",width:"100%",maxHeight:ne,maxWidth:ee},pe.props.style)}:{})):pe})},[n,f,c,p,h,u,F,l]);return Nt.createElement("div",{id:v?"".concat(v):void 0,className:So("recharts-responsive-container",j),style:sG(sG({},A),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:p}),ref:T},W)}),gR=function(t){return null};gR.displayName="Cell";function VB(s){"@babel/helpers - typeof";return VB=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},VB(s)}function SWe(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 e5e(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||kw.isSsr)return{width:0,height:0};var r=RIs(n),a=JSON.stringify({text:t,copyStyle:r});if(RI.widthCache[a])return RI.widthCache[a];try{var i=document.getElementById(CWe);i||(i=document.createElement("span"),i.setAttribute("id",CWe),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=e5e(e5e({},DIs),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return RI.widthCache[a]=c,++RI.cacheCount>LIs&&(RI.cacheCount=0,RI.widthCache={}),c}catch{return{width:0,height:0}}},OIs=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function HB(s){"@babel/helpers - typeof";return HB=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},HB(s)}function Xxe(s,t){return $Is(s)||BIs(s,t)||zIs(s,t)||FIs()}function FIs(){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 zIs(s,t){if(s){if(typeof s=="string")return TWe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return TWe(s,t)}}function TWe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function tPs(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 LWe(s,t){return aPs(s)||rPs(s,t)||nPs(s,t)||sPs()}function sPs(){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 nPs(s,t){if(s){if(typeof s=="string")return DWe(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 DWe(s,t)}}function DWe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&arguments[0]!==void 0?arguments[0]:[];return ee.reduce(function(ne,oe){var pe=oe.word,ce=oe.width,de=ne[ne.length-1];if(de&&(a==null||i||de.width+ce+roe.width?ne:oe})};if(!u)return f;for(var b="…",v=function(ee){var ne=h.slice(0,ee),oe=n1t({breakAll:d,style:c,children:ne+b}).wordsWithComputedWidth,pe=p(oe),ce=pe.length>l||g(pe).width>Number(a);return[ce,pe]},j=0,_=h.length-1,S=0,A;j<=_&&S<=h.length-1;){var T=Math.floor((j+_)/2),D=T-1,L=v(D),M=LWe(L,2),F=M[0],z=M[1],V=v(T),W=LWe(V,1),K=W[0];if(!F&&!K&&(j=T+1),F&&K&&(_=T-1),!F&&K){A=z;break}S++}return A||f},RWe=function(t){var n=No(t)?[]:t.toString().split(s1t);return[{words:n}]},oPs=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!kw.isSsr){var c,d,u=n1t({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,p=u.spaceWidth;c=h,d=p}else return RWe(a);return iPs({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return RWe(a)},OWe="#808080",IM=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,u=t.scaleToFit,h=u===void 0?!1:u,p=t.textAnchor,f=p===void 0?"start":p,g=t.verticalAnchor,b=g===void 0?"end":g,v=t.fill,j=v===void 0?OWe:v,_=PWe(t,JIs),S=N.useMemo(function(){return oPs({breakAll:_.breakAll,children:_.children,maxLines:_.maxLines,scaleToFit:h,style:_.style,width:_.width})},[_.breakAll,_.children,_.maxLines,h,_.style,_.width]),A=_.dx,T=_.dy,D=_.angle,L=_.className,M=_.breakAll,F=PWe(_,ePs);if(!Um(r)||!Um(i))return null;var z=r+(ca(A)?A:0),V=i+(ca(T)?T:0),W;switch(b){case"start":W=oNe("calc(".concat(d,")"));break;case"middle":W=oNe("calc(".concat((S.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:W=oNe("calc(".concat(S.length-1," * -").concat(o,")"));break}var K=[];if(h){var Y=S[0].width,ee=_.width;K.push("scale(".concat((ca(ee)?ee/Y:1)/Y,")"))}return D&&K.push("rotate(".concat(D,", ").concat(z,", ").concat(V,")")),K.length&&(F.transform=K.join(" ")),Nt.createElement("text",t5e({},Wi(F,!0),{x:z,y:V,className:So("recharts-text",L),textAnchor:f,fill:j.includes("url")?OWe:j}),S.map(function(ne,oe){var pe=ne.words.join(M?"":" ");return Nt.createElement("tspan",{x:z,dy:oe===0?W:o,key:"".concat(pe,"-").concat(oe)},pe)}))};function w4(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function lPs(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function IPe(s){let t,n,r;s.length!==2?(t=w4,n=(o,c)=>w4(s(o),c),r=(o,c)=>s(o)-c):(t=s===w4||s===lPs?s:cPs,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 cPs(){return 0}function r1t(s){return s===null?NaN:+s}function*dPs(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const uPs=IPe(w4),RU=uPs.right;IPe(r1t).center;class FWe extends Map{constructor(t,n=pPs){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(zWe(this,t))}has(t){return super.has(zWe(this,t))}set(t,n){return super.set(hPs(this,t),n)}delete(t){return super.delete(mPs(this,t))}}function zWe({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function hPs({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function mPs({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function pPs(s){return s!==null&&typeof s=="object"?s.valueOf():s}function fPs(s=w4){if(s===w4)return a1t;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 a1t(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const xPs=Math.sqrt(50),gPs=Math.sqrt(10),yPs=Math.sqrt(2);function Jxe(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>=xPs?10:i>=gPs?5:i>=yPs?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 $We(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function i1t(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?a1t:fPs(a);r>n;){if(r-n>600){const c=r-n+1,d=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*h*(c-h)/c)*(d-c/2<0?-1:1),f=Math.max(n,Math.floor(t-d*h/c+p)),g=Math.min(r,Math.floor(t+(c-d)*h/c+p));i1t(s,t,f,g,a)}const i=s[t];let l=n,o=r;for(EF(s,n,t),a(s[r],i)>0&&EF(s,n,r);l0;)--o}a(s[n],i)===0?EF(s,n,o):(++o,EF(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function EF(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function vPs(s,t,n){if(s=Float64Array.from(dPs(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return $We(s);if(t>=1)return BWe(s);var r,a=(r-1)*t,i=Math.floor(a),l=BWe(i1t(s,i).subarray(0,i+1)),o=$We(s.subarray(i+1));return l+(o-l)*(a-i)}}function bPs(s,t,n=r1t){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 _Ps(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?rG(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?rG(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=jPs.exec(s))?new Bg(t[1],t[2],t[3],1):(t=NPs.exec(s))?new Bg(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=kPs.exec(s))?rG(t[1],t[2],t[3],t[4]):(t=SPs.exec(s))?rG(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=CPs.exec(s))?KWe(t[1],t[2]/100,t[3]/100,1):(t=TPs.exec(s))?KWe(t[1],t[2]/100,t[3]/100,t[4]):UWe.hasOwnProperty(s)?HWe(UWe[s]):s==="transparent"?new Bg(NaN,NaN,NaN,0):null}function HWe(s){return new Bg(s>>16&255,s>>8&255,s&255,1)}function rG(s,t,n,r){return r<=0&&(s=t=n=NaN),new Bg(s,t,n,r)}function MPs(s){return s instanceof OU||(s=YB(s)),s?(s=s.rgb(),new Bg(s.r,s.g,s.b,s.opacity)):new Bg}function i5e(s,t,n,r){return arguments.length===1?MPs(s):new Bg(s,t,n,r??1)}function Bg(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}LPe(Bg,i5e,l1t(OU,{brighter(s){return s=s==null?ege:Math.pow(ege,s),new Bg(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?WB:Math.pow(WB,s),new Bg(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new Bg(eM(this.r),eM(this.g),eM(this.b),tge(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:GWe,formatHex:GWe,formatHex8:IPs,formatRgb:WWe,toString:WWe}));function GWe(){return`#${nA(this.r)}${nA(this.g)}${nA(this.b)}`}function IPs(){return`#${nA(this.r)}${nA(this.g)}${nA(this.b)}${nA((isNaN(this.opacity)?1:this.opacity)*255)}`}function WWe(){const s=tge(this.opacity);return`${s===1?"rgb(":"rgba("}${eM(this.r)}, ${eM(this.g)}, ${eM(this.b)}${s===1?")":`, ${s})`}`}function tge(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function eM(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function nA(s){return s=eM(s),(s<16?"0":"")+s.toString(16)}function KWe(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new ob(s,t,n,r)}function c1t(s){if(s instanceof ob)return new ob(s.h,s.s,s.l,s.opacity);if(s instanceof OU||(s=YB(s)),!s)return new ob;if(s instanceof ob)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 ob(l,o,c,s.opacity)}function PPs(s,t,n,r){return arguments.length===1?c1t(s):new ob(s,t,n,r??1)}function ob(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}LPe(ob,PPs,l1t(OU,{brighter(s){return s=s==null?ege:Math.pow(ege,s),new ob(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?WB:Math.pow(WB,s),new ob(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 Bg(lNe(s>=240?s-240:s+120,a,r),lNe(s,a,r),lNe(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new ob(YWe(this.h),aG(this.s),aG(this.l),tge(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=tge(this.opacity);return`${s===1?"hsl(":"hsla("}${YWe(this.h)}, ${aG(this.s)*100}%, ${aG(this.l)*100}%${s===1?")":`, ${s})`}`}}));function YWe(s){return s=(s||0)%360,s<0?s+360:s}function aG(s){return Math.max(0,Math.min(1,s||0))}function lNe(s,t,n){return(s<60?t+(n-t)*s/60:s<180?n:s<240?t+(n-t)*(240-s)/60:t)*255}const DPe=s=>()=>s;function LPs(s,t){return function(n){return s+n*t}}function DPs(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 RPs(s){return(s=+s)==1?d1t:function(t,n){return n-t?DPs(t,n,s):DPe(isNaN(t)?n:t)}}function d1t(s,t){var n=t-s;return n?LPs(s,n):DPe(isNaN(s)?t:s)}const ZWe=function s(t){var n=RPs(t);function r(a,i){var l=n((a=i5e(a)).r,(i=i5e(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=d1t(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 OPs(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:sge(r,a)})),n=cNe.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function KPs(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?YPs:KPs,c=d=null,h}function h(p){return p==null||isNaN(p=+p)?i:(c||(c=o(s.map(r),t,n)))(r(l(p)))}return h.invert=function(p){return l(a((d||(d=o(t,s.map(r),sge)))(p)))},h.domain=function(p){return arguments.length?(s=Array.from(p,nge),u()):s.slice()},h.range=function(p){return arguments.length?(t=Array.from(p),u()):t.slice()},h.rangeRound=function(p){return t=Array.from(p),n=RPe,u()},h.clamp=function(p){return arguments.length?(l=p?!0:eg,u()):l!==eg},h.interpolate=function(p){return arguments.length?(n=p,u()):n},h.unknown=function(p){return arguments.length?(i=p,h):i},function(p,f){return r=p,a=f,u()}}function OPe(){return o1e()(eg,eg)}function ZPs(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function rge(s,t){if((n=(s=t?s.toExponential(t-1):s.toExponential()).indexOf("e"))<0)return null;var n,r=s.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+s.slice(n+1)]}function H8(s){return s=rge(Math.abs(s)),s?s[1]:NaN}function QPs(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 XPs(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var JPs=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function ZB(s){if(!(t=JPs.exec(s)))throw new Error("invalid format: "+s);var t;return new FPe({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]})}ZB.prototype=FPe.prototype;function FPe(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+""}FPe.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 eLs(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 u1t;function tLs(s,t){var n=rge(s,t);if(!n)return s+"";var r=n[0],a=n[1],i=a-(u1t=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")+rge(s,Math.max(0,t+i-1))[0]}function XWe(s,t){var n=rge(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 JWe={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:ZPs,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)=>XWe(s*100,t),r:XWe,s:tLs,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function eKe(s){return s}var tKe=Array.prototype.map,sKe=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function sLs(s){var t=s.grouping===void 0||s.thousands===void 0?eKe:QPs(tKe.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?eKe:XPs(tKe.call(s.numerals,String)),l=s.percent===void 0?"%":s.percent+"",o=s.minus===void 0?"−":s.minus+"",c=s.nan===void 0?"NaN":s.nan+"";function d(h){h=ZB(h);var p=h.fill,f=h.align,g=h.sign,b=h.symbol,v=h.zero,j=h.width,_=h.comma,S=h.precision,A=h.trim,T=h.type;T==="n"?(_=!0,T="g"):JWe[T]||(S===void 0&&(S=12),A=!0,T="g"),(v||p==="0"&&f==="=")&&(v=!0,p="0",f="=");var D=b==="$"?n:b==="#"&&/[boxX]/.test(T)?"0"+T.toLowerCase():"",L=b==="$"?r:/[%p]/.test(T)?l:"",M=JWe[T],F=/[defgprs%]/.test(T);S=S===void 0?6:/[gprs]/.test(T)?Math.max(1,Math.min(21,S)):Math.max(0,Math.min(20,S));function z(V){var W=D,K=L,Y,ee,ne;if(T==="c")K=M(V)+K,V="";else{V=+V;var oe=V<0||1/V<0;if(V=isNaN(V)?c:M(Math.abs(V),S),A&&(V=eLs(V)),oe&&+V==0&&g!=="+"&&(oe=!1),W=(oe?g==="("?g:o:g==="-"||g==="("?"":g)+W,K=(T==="s"?sKe[8+u1t/3]:"")+K+(oe&&g==="("?")":""),F){for(Y=-1,ee=V.length;++Yne||ne>57){K=(ne===46?a+V.slice(Y+1):V.slice(Y))+K,V=V.slice(0,Y);break}}}_&&!v&&(V=t(V,1/0));var pe=W.length+V.length+K.length,ce=pe>1)+W+V+K+ce.slice(pe);break;default:V=ce+W+V+K;break}return i(V)}return z.toString=function(){return h+""},z}function u(h,p){var f=d((h=ZB(h),h.type="f",h)),g=Math.max(-8,Math.min(8,Math.floor(H8(p)/3)))*3,b=Math.pow(10,-g),v=sKe[8+g/3];return function(j){return f(b*j)+v}}return{format:d,formatPrefix:u}}var iG,zPe,h1t;nLs({thousands:",",grouping:[3],currency:["$",""]});function nLs(s){return iG=sLs(s),zPe=iG.format,h1t=iG.formatPrefix,iG}function rLs(s){return Math.max(0,-H8(Math.abs(s)))}function aLs(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(H8(t)/3)))*3-H8(Math.abs(s)))}function iLs(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,H8(t)-H8(s))+1}function m1t(s,t,n,r){var a=r5e(s,t,n),i;switch(r=ZB(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=aLs(a,l))&&(r.precision=i),h1t(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=iLs(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=rLs(a))&&(r.precision=i-(r.type==="%")*2);break}}return zPe(r)}function hC(s){var t=s.domain;return s.ticks=function(n){var r=t();return s5e(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return m1t(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=n5e(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 age(){var s=OPe();return s.copy=function(){return FU(s,age())},s1.apply(s,arguments),hC(s)}function p1t(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,nge),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return p1t(s).unknown(t)},s=arguments.length?Array.from(s,nge):[0,1],hC(n)}function f1t(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 uLs(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 aKe(s){return(t,n)=>-s(-t,n)}function BPe(s){const t=s(nKe,rKe),n=t.domain;let r=10,a,i;function l(){return a=uLs(r),i=dLs(r),n()[0]<0?(a=aKe(a),i=aKe(i),s(oLs,lLs)):s(nKe,rKe),t}return t.base=function(o){return arguments.length?(r=+o,l()):r},t.domain=function(o){return arguments.length?(n(o),l()):n()},t.ticks=o=>{const c=n();let d=c[0],u=c[c.length-1];const h=u0){for(;p<=f;++p)for(g=1;gu)break;j.push(b)}}else for(;p<=f;++p)for(g=r-1;g>=1;--g)if(b=p>0?g/i(-p):g*i(p),!(bu)break;j.push(b)}j.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=ZB(c)).precision==null&&(c.trim=!0),c=zPe(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(f1t(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function x1t(){const s=BPe(o1e()).domain([1,10]);return s.copy=()=>FU(s,x1t()).base(s.base()),s1.apply(s,arguments),s}function iKe(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function oKe(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function $Pe(s){var t=1,n=s(iKe(t),oKe(t));return n.constant=function(r){return arguments.length?s(iKe(t=+r),oKe(t)):t},hC(n)}function g1t(){var s=$Pe(o1e());return s.copy=function(){return FU(s,g1t()).constant(s.constant())},s1.apply(s,arguments)}function lKe(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function hLs(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function mLs(s){return s<0?-s*s:s*s}function UPe(s){var t=s(eg,eg),n=1;function r(){return n===1?s(eg,eg):n===.5?s(hLs,mLs):s(lKe(n),lKe(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},hC(t)}function qPe(){var s=UPe(o1e());return s.copy=function(){return FU(s,qPe()).exponent(s.exponent())},s1.apply(s,arguments),s}function pLs(){return qPe.apply(null,arguments).exponent(.5)}function cKe(s){return Math.sign(s)*s*s}function fLs(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function y1t(){var s=OPe(),t=[0,1],n=!1,r;function a(i){var l=fLs(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(cKe(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,nge)).map(cKe)),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 y1t(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},s1.apply(a,arguments),hC(a)}function v1t(){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 b1t().domain([s,t]).range(a).unknown(i)},s1.apply(hC(l),arguments)}function _1t(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[RU(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 _1t().domain(s).range(t).unknown(n)},s1.apply(a,arguments)}const dNe=new Date,uNe=new Date;function Xm(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(dXm(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)=>(dNe.setTime(+i),uNe.setTime(+l),s(dNe),s(uNe),Math.floor(n(dNe,uNe))),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 ige=Xm(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);ige.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?Xm(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):ige);ige.range;const $2=1e3,Pv=$2*60,U2=Pv*60,xN=U2*24,VPe=xN*7,dKe=xN*30,hNe=xN*365,rA=Xm(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*$2)},(s,t)=>(t-s)/$2,s=>s.getUTCSeconds());rA.range;const HPe=Xm(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*$2)},(s,t)=>{s.setTime(+s+t*Pv)},(s,t)=>(t-s)/Pv,s=>s.getMinutes());HPe.range;const GPe=Xm(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*Pv)},(s,t)=>(t-s)/Pv,s=>s.getUTCMinutes());GPe.range;const WPe=Xm(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*$2-s.getMinutes()*Pv)},(s,t)=>{s.setTime(+s+t*U2)},(s,t)=>(t-s)/U2,s=>s.getHours());WPe.range;const KPe=Xm(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*U2)},(s,t)=>(t-s)/U2,s=>s.getUTCHours());KPe.range;const zU=Xm(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*Pv)/xN,s=>s.getDate()-1);zU.range;const l1e=Xm(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/xN,s=>s.getUTCDate()-1);l1e.range;const w1t=Xm(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/xN,s=>Math.floor(s/xN));w1t.range;function r6(s){return Xm(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())*Pv)/VPe)}const c1e=r6(0),oge=r6(1),xLs=r6(2),gLs=r6(3),G8=r6(4),yLs=r6(5),vLs=r6(6);c1e.range;oge.range;xLs.range;gLs.range;G8.range;yLs.range;vLs.range;function a6(s){return Xm(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-s)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>(n-t)/VPe)}const d1e=a6(0),lge=a6(1),bLs=a6(2),_Ls=a6(3),W8=a6(4),wLs=a6(5),jLs=a6(6);d1e.range;lge.range;bLs.range;_Ls.range;W8.range;wLs.range;jLs.range;const YPe=Xm(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());YPe.range;const ZPe=Xm(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());ZPe.range;const gN=Xm(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());gN.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Xm(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)});gN.range;const yN=Xm(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());yN.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Xm(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)});yN.range;function j1t(s,t,n,r,a,i){const l=[[rA,1,$2],[rA,5,5*$2],[rA,15,15*$2],[rA,30,30*$2],[i,1,Pv],[i,5,5*Pv],[i,15,15*Pv],[i,30,30*Pv],[a,1,U2],[a,3,3*U2],[a,6,6*U2],[a,12,12*U2],[r,1,xN],[r,2,2*xN],[n,1,VPe],[t,1,dKe],[t,3,3*dKe],[s,1,hNe]];function o(d,u,h){const p=uv).right(l,p);if(f===l.length)return s.every(r5e(d/hNe,u/hNe,h));if(f===0)return ige.every(Math.max(r5e(d,u,h),1));const[g,b]=l[p/l[f-1][2]53)return null;"w"in ve||(ve.w=1),"Z"in ve?(we=pNe(AF(ve.y,0,1)),it=we.getUTCDay(),we=it>4||it===0?lge.ceil(we):lge(we),we=l1e.offset(we,(ve.V-1)*7),ve.y=we.getUTCFullYear(),ve.m=we.getUTCMonth(),ve.d=we.getUTCDate()+(ve.w+6)%7):(we=mNe(AF(ve.y,0,1)),it=we.getDay(),we=it>4||it===0?oge.ceil(we):oge(we),we=zU.offset(we,(ve.V-1)*7),ve.y=we.getFullYear(),ve.m=we.getMonth(),ve.d=we.getDate()+(ve.w+6)%7)}else("W"in ve||"U"in ve)&&("w"in ve||(ve.w="u"in ve?ve.u%7:"W"in ve?1:0),it="Z"in ve?pNe(AF(ve.y,0,1)).getUTCDay():mNe(AF(ve.y,0,1)).getDay(),ve.m=0,ve.d="W"in ve?(ve.w+6)%7+ve.W*7-(it+5)%7:ve.w+ve.U*7-(it+6)%7);return"Z"in ve?(ve.H+=ve.Z/100|0,ve.M+=ve.Z%100,pNe(ve)):mNe(ve)}}function M(Ie,Fe,qe,ve){for(var Je=0,we=Fe.length,it=qe.length,Ne,He;Je=it)return-1;if(Ne=Fe.charCodeAt(Je++),Ne===37){if(Ne=Fe.charAt(Je++),He=T[Ne in uKe?Fe.charAt(Je++):Ne],!He||(ve=He(Ie,qe,ve))<0)return-1}else if(Ne!=qe.charCodeAt(ve++))return-1}return ve}function F(Ie,Fe,qe){var ve=d.exec(Fe.slice(qe));return ve?(Ie.p=u.get(ve[0].toLowerCase()),qe+ve[0].length):-1}function z(Ie,Fe,qe){var ve=f.exec(Fe.slice(qe));return ve?(Ie.w=g.get(ve[0].toLowerCase()),qe+ve[0].length):-1}function V(Ie,Fe,qe){var ve=h.exec(Fe.slice(qe));return ve?(Ie.w=p.get(ve[0].toLowerCase()),qe+ve[0].length):-1}function W(Ie,Fe,qe){var ve=j.exec(Fe.slice(qe));return ve?(Ie.m=_.get(ve[0].toLowerCase()),qe+ve[0].length):-1}function K(Ie,Fe,qe){var ve=b.exec(Fe.slice(qe));return ve?(Ie.m=v.get(ve[0].toLowerCase()),qe+ve[0].length):-1}function Y(Ie,Fe,qe){return M(Ie,t,Fe,qe)}function ee(Ie,Fe,qe){return M(Ie,n,Fe,qe)}function ne(Ie,Fe,qe){return M(Ie,r,Fe,qe)}function oe(Ie){return l[Ie.getDay()]}function pe(Ie){return i[Ie.getDay()]}function ce(Ie){return c[Ie.getMonth()]}function de(Ie){return o[Ie.getMonth()]}function ie(Ie){return a[+(Ie.getHours()>=12)]}function ye(Ie){return 1+~~(Ie.getMonth()/3)}function _e(Ie){return l[Ie.getUTCDay()]}function Me(Ie){return i[Ie.getUTCDay()]}function Te(Ie){return c[Ie.getUTCMonth()]}function Ce(Ie){return o[Ie.getUTCMonth()]}function Ee(Ie){return a[+(Ie.getUTCHours()>=12)]}function De(Ie){return 1+~~(Ie.getUTCMonth()/3)}return{format:function(Ie){var Fe=D(Ie+="",S);return Fe.toString=function(){return Ie},Fe},parse:function(Ie){var Fe=L(Ie+="",!1);return Fe.toString=function(){return Ie},Fe},utcFormat:function(Ie){var Fe=D(Ie+="",A);return Fe.toString=function(){return Ie},Fe},utcParse:function(Ie){var Fe=L(Ie+="",!0);return Fe.toString=function(){return Ie},Fe}}}var uKe={"-":"",_:" ",0:"0"},Lp=/^\s*\d+/,ELs=/^%/,ALs=/[\\^$*+?|[\]().{}]/g;function Xl(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function ILs(s,t,n){var r=Lp.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function PLs(s,t,n){var r=Lp.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function LLs(s,t,n){var r=Lp.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function DLs(s,t,n){var r=Lp.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function RLs(s,t,n){var r=Lp.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function hKe(s,t,n){var r=Lp.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function mKe(s,t,n){var r=Lp.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function OLs(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 FLs(s,t,n){var r=Lp.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function zLs(s,t,n){var r=Lp.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function pKe(s,t,n){var r=Lp.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function BLs(s,t,n){var r=Lp.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function fKe(s,t,n){var r=Lp.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function $Ls(s,t,n){var r=Lp.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function ULs(s,t,n){var r=Lp.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function qLs(s,t,n){var r=Lp.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function VLs(s,t,n){var r=Lp.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function HLs(s,t,n){var r=ELs.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function GLs(s,t,n){var r=Lp.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function WLs(s,t,n){var r=Lp.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function xKe(s,t){return Xl(s.getDate(),t,2)}function KLs(s,t){return Xl(s.getHours(),t,2)}function YLs(s,t){return Xl(s.getHours()%12||12,t,2)}function ZLs(s,t){return Xl(1+zU.count(gN(s),s),t,3)}function N1t(s,t){return Xl(s.getMilliseconds(),t,3)}function QLs(s,t){return N1t(s,t)+"000"}function XLs(s,t){return Xl(s.getMonth()+1,t,2)}function JLs(s,t){return Xl(s.getMinutes(),t,2)}function e8s(s,t){return Xl(s.getSeconds(),t,2)}function t8s(s){var t=s.getDay();return t===0?7:t}function s8s(s,t){return Xl(c1e.count(gN(s)-1,s),t,2)}function k1t(s){var t=s.getDay();return t>=4||t===0?G8(s):G8.ceil(s)}function n8s(s,t){return s=k1t(s),Xl(G8.count(gN(s),s)+(gN(s).getDay()===4),t,2)}function r8s(s){return s.getDay()}function a8s(s,t){return Xl(oge.count(gN(s)-1,s),t,2)}function i8s(s,t){return Xl(s.getFullYear()%100,t,2)}function o8s(s,t){return s=k1t(s),Xl(s.getFullYear()%100,t,2)}function l8s(s,t){return Xl(s.getFullYear()%1e4,t,4)}function c8s(s,t){var n=s.getDay();return s=n>=4||n===0?G8(s):G8.ceil(s),Xl(s.getFullYear()%1e4,t,4)}function d8s(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Xl(t/60|0,"0",2)+Xl(t%60,"0",2)}function gKe(s,t){return Xl(s.getUTCDate(),t,2)}function u8s(s,t){return Xl(s.getUTCHours(),t,2)}function h8s(s,t){return Xl(s.getUTCHours()%12||12,t,2)}function m8s(s,t){return Xl(1+l1e.count(yN(s),s),t,3)}function S1t(s,t){return Xl(s.getUTCMilliseconds(),t,3)}function p8s(s,t){return S1t(s,t)+"000"}function f8s(s,t){return Xl(s.getUTCMonth()+1,t,2)}function x8s(s,t){return Xl(s.getUTCMinutes(),t,2)}function g8s(s,t){return Xl(s.getUTCSeconds(),t,2)}function y8s(s){var t=s.getUTCDay();return t===0?7:t}function v8s(s,t){return Xl(d1e.count(yN(s)-1,s),t,2)}function C1t(s){var t=s.getUTCDay();return t>=4||t===0?W8(s):W8.ceil(s)}function b8s(s,t){return s=C1t(s),Xl(W8.count(yN(s),s)+(yN(s).getUTCDay()===4),t,2)}function _8s(s){return s.getUTCDay()}function w8s(s,t){return Xl(lge.count(yN(s)-1,s),t,2)}function j8s(s,t){return Xl(s.getUTCFullYear()%100,t,2)}function N8s(s,t){return s=C1t(s),Xl(s.getUTCFullYear()%100,t,2)}function k8s(s,t){return Xl(s.getUTCFullYear()%1e4,t,4)}function S8s(s,t){var n=s.getUTCDay();return s=n>=4||n===0?W8(s):W8.ceil(s),Xl(s.getUTCFullYear()%1e4,t,4)}function C8s(){return"+0000"}function yKe(){return"%"}function vKe(s){return+s}function bKe(s){return Math.floor(+s/1e3)}var OI,T1t,E1t;T8s({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 T8s(s){return OI=TLs(s),T1t=OI.format,OI.parse,E1t=OI.utcFormat,OI.utcParse,OI}function E8s(s){return new Date(s)}function A8s(s){return s instanceof Date?+s:+new Date(+s)}function QPe(s,t,n,r,a,i,l,o,c,d){var u=OPe(),h=u.invert,p=u.domain,f=d(".%L"),g=d(":%S"),b=d("%I:%M"),v=d("%I %p"),j=d("%a %d"),_=d("%b %d"),S=d("%B"),A=d("%Y");function T(D){return(c(D)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>vPs(s,i/r))},n.copy=function(){return P1t(t).domain(s)},IN.apply(n,arguments)}function h1e(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=eg,u,h=!1,p;function f(b){return isNaN(b=+b)?p:(b=.5+((b=+u(b))-i)*(r*bt}var O1t=O8s,F8s=m1e,z8s=O1t,B8s=xR;function $8s(s){return s&&s.length?F8s(s,B8s,z8s):void 0}var U8s=$8s;const p1e=jl(U8s);function q8s(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};ni.decimalPlaces=ni.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*zd;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};ni.dividedBy=ni.div=function(s){return rN(this,new this.constructor(s))};ni.dividedToIntegerBy=ni.idiv=function(s){var t=this,n=t.constructor;return ad(rN(t,new n(s),0,1),n.precision)};ni.equals=ni.eq=function(s){return!this.cmp(s)};ni.exponent=function(){return hm(this)};ni.greaterThan=ni.gt=function(s){return this.cmp(s)>0};ni.greaterThanOrEqualTo=ni.gte=function(s){return this.cmp(s)>=0};ni.isInteger=ni.isint=function(){return this.e>this.d.length-2};ni.isNegative=ni.isneg=function(){return this.s<0};ni.isPositive=ni.ispos=function(){return this.s>0};ni.isZero=function(){return this.s===0};ni.lessThan=ni.lt=function(s){return this.cmp(s)<0};ni.lessThanOrEqualTo=ni.lte=function(s){return this.cmp(s)<1};ni.logarithm=ni.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(ey))throw Error(Zv+"NaN");if(n.s<1)throw Error(Zv+(n.s?"NaN":"-Infinity"));return n.eq(ey)?new r(0):(uu=!1,t=rN(QB(n,i),QB(s,i),i),uu=!0,ad(t,a))};ni.minus=ni.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?U1t(t,s):B1t(t,(s.s=-s.s,s))};ni.modulo=ni.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(Zv+"NaN");return n.s?(uu=!1,t=rN(n,s,0,1).times(s),uu=!0,n.minus(t)):ad(new r(n),a)};ni.naturalExponential=ni.exp=function(){return $1t(this)};ni.naturalLogarithm=ni.ln=function(){return QB(this)};ni.negated=ni.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};ni.plus=ni.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?B1t(t,s):U1t(t,(s.s=-s.s,s))};ni.precision=ni.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(tM+s);if(t=hm(a)+1,r=a.d.length-1,n=r*zd+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};ni.squareRoot=ni.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(Zv+"NaN")}for(s=hm(o),uu=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=ow(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=bR((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(rN(o,i,l+2)).times(.5),ow(i.d).slice(0,l)===(t=ow(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(ad(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return uu=!0,ad(r,n)};ni.times=ni.mul=function(s){var t,n,r,a,i,l,o,c,d,u=this,h=u.constructor,p=u.d,f=(s=new h(s)).d;if(!u.s||!s.s)return new h(0);for(s.s*=u.s,n=u.e+s.e,c=p.length,d=f.length,c=0;){for(t=0,a=c+r;a>r;)o=i[a]+f[r]*p[a-r-1]+t,i[a--]=o%bp|0,t=o/bp|0;i[a]=(i[a]+t)%bp|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,uu?ad(s,h.precision):s};ni.toDecimalPlaces=ni.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(Ow(s,0,vR),t===void 0?t=r.rounding:Ow(t,0,8),ad(n,s+hm(n)+1,t))};ni.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=PM(r,!0):(Ow(s,0,vR),t===void 0?t=a.rounding:Ow(t,0,8),r=ad(new a(r),s+1,t),n=PM(r,!0,s+1)),n};ni.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?PM(a):(Ow(s,0,vR),t===void 0?t=i.rounding:Ow(t,0,8),r=ad(new i(a),s+hm(a)+1,t),n=PM(r.abs(),!1,s+hm(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};ni.toInteger=ni.toint=function(){var s=this,t=s.constructor;return ad(new t(s),hm(s)+1,t.rounding)};ni.toNumber=function(){return+this};ni.toPower=ni.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(ey);if(o=new c(o),!o.s){if(s.s<1)throw Error(Zv+"Infinity");return o}if(o.eq(ey))return o;if(r=c.precision,s.eq(ey))return ad(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=z1t){for(a=new c(ey),t=Math.ceil(r/zd+4),uu=!1;n%2&&(a=a.times(o),jKe(a.d,t)),n=bR(n/2),n!==0;)o=o.times(o),jKe(o.d,t);return uu=!0,s.s<0?new c(ey).div(a):ad(a,r)}}else if(i<0)throw Error(Zv+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,uu=!1,a=s.times(QB(o,r+d)),uu=!0,a=$1t(a),a.s=i,a};ni.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=hm(a),r=PM(a,n<=i.toExpNeg||n>=i.toExpPos)):(Ow(s,1,vR),t===void 0?t=i.rounding:Ow(t,0,8),a=ad(new i(a),s,t),n=hm(a),r=PM(a,s<=n||n<=i.toExpNeg,s)),r};ni.toSignificantDigits=ni.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(Ow(s,1,vR),t===void 0?t=r.rounding:Ow(t,0,8)),ad(new r(n),s,t)};ni.toString=ni.valueOf=ni.val=ni.toJSON=ni[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=hm(s),n=s.constructor;return PM(s,t<=n.toExpNeg||t>=n.toExpPos)};function B1t(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)),uu?ad(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/zd),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)/bp|0,c[i]%=bp;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,uu?ad(t,h):t}function Ow(s,t,n){if(s!==~~s||sn)throw Error(tM+s)}function ow(s){var t,n,r,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function n(r,a,i){for(var l=0;i--;)r[i]-=l,l=r[i]1;)r.shift()}return function(r,a,i,l){var o,c,d,u,h,p,f,g,b,v,j,_,S,A,T,D,L,M,F=r.constructor,z=r.s==a.s?1:-1,V=r.d,W=a.d;if(!r.s)return new F(r);if(!a.s)throw Error(Zv+"Division by zero");for(c=r.e-a.e,L=W.length,T=V.length,f=new F(z),g=f.d=[],d=0;W[d]==(V[d]||0);)++d;if(W[d]>(V[d]||0)&&--c,i==null?_=i=F.precision:l?_=i+(hm(r)-hm(a))+1:_=i,_<0)return new F(0);if(_=_/zd+2|0,d=0,L==1)for(u=0,W=W[0],_++;(d1&&(W=s(W,u),V=s(V,u),L=W.length,T=V.length),A=L,b=V.slice(0,L),v=b.length;v=bp/2&&++D;do u=0,o=t(W,b,L,v),o<0?(j=b[0],L!=v&&(j=j*bp+(b[1]||0)),u=j/D|0,u>1?(u>=bp&&(u=bp-1),h=s(W,u),p=h.length,v=b.length,o=t(h,b,p,v),o==1&&(u--,n(h,L16)throw Error(eLe+hm(s));if(!s.s)return new u(ey);for(t==null?(uu=!1,o=h):o=t,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(DE(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(ey),u.precision=o;;){if(a=ad(a.times(s),o),n=n.times(++c),l=i.plus(rN(a,n,o)),ow(l.d).slice(0,o)===ow(i.d).slice(0,o)){for(;d--;)i=ad(i.times(i),o);return u.precision=h,t==null?(uu=!0,ad(i,h)):i}i=l}}function hm(s){for(var t=s.e*zd,n=s.d[0];n>=10;n/=10)t++;return t}function fNe(s,t,n){if(t>s.LN10.sd())throw uu=!0,n&&(s.precision=n),Error(Zv+"LN10 precision limit exceeded");return ad(new s(s.LN10),t)}function rS(s){for(var t="";s--;)t+="0";return t}function QB(s,t){var n,r,a,i,l,o,c,d,u,h=1,p=10,f=s,g=f.d,b=f.constructor,v=b.precision;if(f.s<1)throw Error(Zv+(f.s?"NaN":"-Infinity"));if(f.eq(ey))return new b(0);if(t==null?(uu=!1,d=v):d=t,f.eq(10))return t==null&&(uu=!0),fNe(b,d);if(d+=p,b.precision=d,n=ow(g),r=n.charAt(0),i=hm(f),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(s),n=ow(f.d),r=n.charAt(0),h++;i=hm(f),r>1?(f=new b("0."+n),i++):f=new b(r+"."+n.slice(1))}else return c=fNe(b,d+2,v).times(i+""),f=QB(new b(r+"."+n.slice(1)),d-p).plus(c),b.precision=v,t==null?(uu=!0,ad(f,v)):f;for(o=l=f=rN(f.minus(ey),f.plus(ey),d),u=ad(f.times(f),d),a=3;;){if(l=ad(l.times(u),d),c=o.plus(rN(l,new b(a),d)),ow(c.d).slice(0,d)===ow(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(fNe(b,d+2,v).times(i+""))),o=rN(o,new b(h),d),b.precision=v,t==null?(uu=!0,ad(o,v)):o;o=c,a+=2}}function wKe(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=bR(n/zd),s.d=[],r=(n+1)%zd,n<0&&(r+=zd),rcge||s.e<-cge))throw Error(eLe+n)}else s.s=0,s.e=0,s.d=[0];return s}function ad(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+=zd,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/zd),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=zd,a=r-zd+l}if(n!==void 0&&(i=DE(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/DE(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=hm(s),h.length=1,t=t-i-1,h[0]=DE(10,(zd-t%zd)%zd),s.e=bR(-t/zd)||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=DE(10,zd-r),h[u]=a>0?(d/DE(10,l-a)%DE(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==bp&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=bp)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(uu&&(s.e>cge||s.e<-cge))throw Error(eLe+hm(s));return s}function U1t(s,t){var n,r,a,i,l,o,c,d,u,h,p=s.constructor,f=p.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new p(s),uu?ad(t,f):t;if(c=s.d,h=t.d,r=t.e,d=s.e,c=c.slice(),l=d-r,l){for(u=l<0,u?(n=c,l=-l,o=h.length):(n=h,r=d,o=c.length),a=Math.max(Math.ceil(f/zd),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)+rS(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+rS(-a-1)+i,n&&(r=n-l)>0&&(i+=rS(r))):a>=l?(i+=rS(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+rS(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=rS(r))),s.s<0?"-"+i:i}function jKe(s,t){if(s.length>t)return s.length=t,!0}function q1t(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(tM+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 wKe(l,i.toString())}else if(typeof i!="string")throw Error(tM+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,dDs.test(i))wKe(l,i);else throw Error(tM+i)}if(a.prototype=ni,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=q1t,a.config=a.set=uDs,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(tM+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(tM+n+": "+r);return this}var tLe=q1t(cDs);ey=new tLe(1);const Hc=tLe;function hDs(s){return xDs(s)||fDs(s)||pDs(s)||mDs()}function mDs(){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 pDs(s,t){if(s){if(typeof s=="string")return c5e(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 c5e(s,t)}}function fDs(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function xDs(s){if(Array.isArray(s))return c5e(s)}function c5e(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,NKe(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 MDs(s){if(Array.isArray(s))return s}function K1t(s){var t=XB(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function Y1t(s,t,n){if(s.lte(0))return new Hc(0);var r=g1e.getDigitCount(s.toNumber()),a=new Hc(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new Hc(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new Hc(Math.ceil(c))}function IDs(s,t,n){var r=1,a=new Hc(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new Hc(10).pow(g1e.getDigitCount(s)-1),a=new Hc(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new Hc(Math.floor(s)))}else s===0?a=new Hc(Math.floor((t-1)/2)):n||(a=new Hc(Math.floor(s)));var l=Math.floor((t-1)/2),o=bDs(vDs(function(c){return a.add(new Hc(c-l).mul(r)).toNumber()}),d5e);return o(0,t)}function Z1t(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 Hc(0),tickMin:new Hc(0),tickMax:new Hc(0)};var i=Y1t(new Hc(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new Hc(0):(l=new Hc(s).add(t).div(2),l=l.sub(new Hc(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new Hc(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?Z1t(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new Hc(o).mul(i)),tickMax:l.add(new Hc(c).mul(i))})}function PDs(s){var t=XB(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=K1t([n,r]),c=XB(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(h5e(d5e(0,a-1).map(function(){return 1/0}))):[].concat(h5e(d5e(0,a-1).map(function(){return-1/0})),[u]);return n>r?u5e(h):h}if(d===u)return IDs(d,a,i);var p=Z1t(d,u,l,i),f=p.step,g=p.tickMin,b=p.tickMax,v=g1e.rangeStep(g,b.add(new Hc(.1).mul(f)),f);return n>r?u5e(v):v}function LDs(s,t){var n=XB(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=K1t([r,a]),o=XB(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=Y1t(new Hc(d).sub(c).div(u-1),i,0),p=[].concat(h5e(g1e.rangeStep(new Hc(c),new Hc(d).sub(new Hc(.99).mul(h)),h)),[d]);return r>a?u5e(p):p}var DDs=G1t(PDs),RDs=G1t(LDs),ODs="Invariant failed";function LM(s,t){throw new Error(ODs)}var FDs=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function K8(s){"@babel/helpers - typeof";return K8=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},K8(s)}function dge(){return dge=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 HDs(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 GDs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function WDs(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:[],a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,l=-1,o=(n=r==null?void 0:r.length)!==null&&n!==void 0?n:0;if(o<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,d=0;d0?a[d-1].coordinate:a[o-1].coordinate,h=a[d].coordinate,p=d>=o-1?a[0].coordinate:a[d+1].coordinate,f=void 0;if(Xx(h-u)!==Xx(p-h)){var g=[];if(Xx(p-h)===Xx(c[1]-c[0])){f=p;var b=h+c[1]-c[0];g[0]=Math.min(b,(b+u)/2),g[1]=Math.max(b,(b+u)/2)}else{f=u;var v=p+c[1]-c[0];g[0]=Math.min(h,(v+h)/2),g[1]=Math.max(h,(v+h)/2)}var j=[Math.min(h,(f+h)/2),Math.max(h,(f+h)/2)];if(t>j[0]&&t<=j[1]||t>=g[0]&&t<=g[1]){l=a[d].index;break}}else{var _=Math.min(u,p),S=Math.max(u,p);if(t>(_+h)/2&&t<=(S+h)/2){l=a[d].index;break}}}else for(var A=0;A0&&A(r[A].coordinate+r[A-1].coordinate)/2&&t<=(r[A].coordinate+r[A+1].coordinate)/2||A===o-1&&t>(r[A].coordinate+r[A-1].coordinate)/2){l=r[A].index;break}return l},sLe=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?ih(ih({},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},dRs=function(t){var n=t.barSize,r=t.totalSize,a=t.stackGroups,i=a===void 0?{}:a;if(!i)return{};for(var l={},o=Object.keys(i),c=0,d=o.length;c=0});if(j&&j.length){var _=j[0].type.defaultProps,S=_!==void 0?ih(ih({},_),j[0].props):j[0].props,A=S.barSize,T=S[v];l[T]||(l[T]=[]);var D=No(A)?n:A;l[T].push({item:j[0],stackList:j.slice(1),barSize:No(D)?void 0:Jx(D,r,0)})}}return l},uRs=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=Jx(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var p=!1,f=a/c,g=l.reduce(function(A,T){return A+T.barSize||0},0);g+=(c-1)*d,g>=a&&(g-=(c-1)*d,d=0),g>=a&&f>0&&(p=!0,f*=.9,g=c*f);var b=(a-g)/2>>0,v={offset:b-d,size:0};u=l.reduce(function(A,T){var D={item:T.item,position:{offset:v.offset+v.size+d,size:p?f:T.barSize}},L=[].concat(CKe(A),[D]);return v=L[L.length-1].position,T.stackList&&T.stackList.length&&T.stackList.forEach(function(M){L.push({item:M,position:v})}),L},h)}else{var j=Jx(r,a,0,!0);a-2*j-(c-1)*d<=0&&(d=0);var _=(a-2*j-(c-1)*d)/c;_>1&&(_>>=0);var S=o===+o?Math.min(_,o):_;u=l.reduce(function(A,T,D){var L=[].concat(CKe(A),[{item:T.item,position:{offset:j+(_+d)*D+(_-S)/2,size:S}}]);return T.stackList&&T.stackList.length&&T.stackList.forEach(function(M){L.push({item:M,position:L[L.length-1].position})}),L},h)}return u},hRs=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=ebt({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,p=u.height,f=d.align,g=d.verticalAlign,b=d.layout;if((b==="vertical"||b==="horizontal"&&g==="middle")&&f!=="center"&&ca(t[f]))return ih(ih({},t),{},HL({},f,t[f]+(h||0)));if((b==="horizontal"||b==="vertical"&&f==="center")&&g!=="middle"&&ca(t[g]))return ih(ih({},t),{},HL({},g,t[g]+(p||0)))}return t},mRs=function(t,n,r){return No(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},tbt=function(t,n,r,a,i){var l=n.props.children,o=xy(l,$U).filter(function(d){return mRs(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=zm(u,r);if(No(h))return d;var p=Array.isArray(h)?[f1e(h),p1e(h)]:[h,h],f=c.reduce(function(g,b){var v=zm(u,b,0),j=p[0]-Math.abs(Array.isArray(v)?v[0]:v),_=p[1]+Math.abs(Array.isArray(v)?v[1]:v);return[Math.min(j,g[0]),Math.max(_,g[1])]},[1/0,-1/0]);return[Math.min(f[0],d[0]),Math.max(f[1],d[1])]},[1/0,-1/0])}return null},pRs=function(t,n,r,a,i){var l=n.map(function(o){return tbt(t,o,r,i,a)}).filter(function(o){return!No(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},sbt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&tbt(t,c,d,a)||Sz(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?Xx(o[0]-o[1])*2*d:d,n&&(t.ticks||t.niceTicks)){var u=(t.ticks||t.niceTicks).map(function(h){var p=i?i.indexOf(h):h;return{coordinate:a(p)+d,value:h,offset:d}});return u.filter(function(h){return!LU(h.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(h,p){return{coordinate:a(h)+d,value:h,index:p,offset:d}}):a.ticks&&!r?a.ticks(t.tickCount).map(function(h){return{coordinate:a(h)+d,value:h,offset:d}}):a.domain().map(function(h,p){return{coordinate:a(h)+d,value:i?i[h]:h,index:p,offset:d}})},xNe=new WeakMap,oG=function(t,n){if(typeof n!="function")return t;xNe.has(t)||xNe.set(t,new WeakMap);var r=xNe.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},abt=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:GB(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:age(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:kz(),realScaleType:"point"}:i==="category"?{scale:GB(),realScaleType:"band"}:{scale:age(),realScaleType:"linear"};if(AM(a)){var c="scale".concat(e1e(a));return{scale:(_Ke[c]||kz)(),realScaleType:_Ke[c]?c:"point"}}return ho(a)?{scale:a}:{scale:kz(),realScaleType:"point"}},EKe=1e-4,ibt=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])-EKe,l=Math.max(a[0],a[1])+EKe,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},fRs=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])}},yRs=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)}},vRs={sign:gRs,expand:F4s,none:B8,silhouette:z4s,wiggle:B4s,positive:yRs},bRs=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=vRs[r],l=O4s().keys(a).value(function(o,c){return+zm(o,c,0)}).order(B3e).offset(i);return l(t)},_Rs=function(t,n,r,a,i,l){if(!t)return null;var o=l?n.reverse():n,c={},d=o.reduce(function(h,p){var f,g=(f=p.type)!==null&&f!==void 0&&f.defaultProps?ih(ih({},p.type.defaultProps),p.props):p.props,b=g.stackId,v=g.hide;if(v)return h;var j=g[r],_=h[j]||{hasStack:!1,stackGroups:{}};if(Um(b)){var S=_.stackGroups[b]||{numericAxisId:r,cateAxisId:a,items:[]};S.items.push(p),_.hasStack=!0,_.stackGroups[b]=S}else _.stackGroups[mR("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[p]};return ih(ih({},h),{},HL({},j,_))},c),u={};return Object.keys(d).reduce(function(h,p){var f=d[p];if(f.hasStack){var g={};f.stackGroups=Object.keys(f.stackGroups).reduce(function(b,v){var j=f.stackGroups[v];return ih(ih({},b),{},HL({},v,{numericAxisId:r,cateAxisId:a,items:j.items,stackedData:bRs(t,j.items,i)}))},g)}return ih(ih({},h),{},HL({},p,f))},u)},obt=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=DDs(d,i,o);return t.domain([f1e(u),p1e(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),p=RDs(h,i,o);return{niceTicks:p}}return null};function AKe(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&&!No(a[t.dataKey])){var o=Fxe(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=zm(a,No(l)?t.dataKey:l);return No(c)?null:t.scale(c)}var MKe=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=zm(l,n.dataKey,n.domain[o]);return No(c)?null:n.scale(c)-i/2+a},wRs=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]},jRs=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?ih(ih({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(Um(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},NRs=function(t){return t.reduce(function(n,r){return[f1e(r.concat([n[0]]).filter(ca)),p1e(r.concat([n[1]]).filter(ca))]},[1/0,-1/0])},lbt=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=NRs(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})},IKe=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,PKe=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,x5e=function(t,n,r){if(ho(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(ca(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(IKe.test(t[0])){var i=+IKe.exec(t[0])[1];a[0]=n[0]-i}else ho(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(ca(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(PKe.test(t[1])){var l=+PKe.exec(t[1])[1];a[1]=n[1]+l}else ho(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},hge=function(t,n,r){if(t&&t.scale&&t.scale.bandwidth){var a=t.scale.bandwidth();if(!r||a>0)return a}if(t&&n&&n.length>=2){for(var i=APe(n,function(h){return h.coordinate}),l=1/0,o=1,c=i.length;os.length)&&(t=s.length);for(var n=0,r=new Array(t);n2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(r.left||0)-(r.right||0)),Math.abs(n-(r.top||0)-(r.bottom||0)))/2},PRs=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=Jx(t.cx,l,l/2),h=Jx(t.cy,o,o/2),p=ubt(l,o,r),f=Jx(t.innerRadius,p,0),g=Jx(t.outerRadius,p,p*.8),b=Object.keys(n);return b.reduce(function(v,j){var _=n[j],S=_.domain,A=_.reversed,T;if(No(_.range))a==="angleAxis"?T=[c,d]:a==="radiusAxis"&&(T=[f,g]),A&&(T=[T[1],T[0]]);else{T=_.range;var D=T,L=CRs(D,2);c=L[0],d=L[1]}var M=abt(_,i),F=M.realScaleType,z=M.scale;z.domain(S).range(T),ibt(z);var V=obt(z,N2(N2({},_),{},{realScaleType:F})),W=N2(N2(N2({},_),V),{},{range:T,radius:g,realScaleType:F,scale:z,cx:u,cy:h,innerRadius:f,outerRadius:g,startAngle:c,endAngle:d});return N2(N2({},v),{},dbt({},j,W))},{})},LRs=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))},DRs=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=LRs({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:IRs(d),angleInRadian:d}},RRs=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}},ORs=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},OKe=function(t,n){var r=t.x,a=t.y,i=DRs({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=RRs(n),h=u.startAngle,p=u.endAngle,f=o,g;if(h<=p){for(;f>p;)f-=360;for(;f=h&&f<=p}else{for(;f>h;)f-=360;for(;f=p&&f<=h}return g?N2(N2({},n),{},{radius:l,angle:ORs(f,n)}):null},hbt=function(t){return!N.isValidElement(t)&&!ho(t)&&typeof t!="boolean"?t.className:""};function s$(s){"@babel/helpers - typeof";return s$=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},s$(s)}var FRs=["offset"];function zRs(s){return qRs(s)||URs(s)||$Rs(s)||BRs()}function BRs(){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 $Rs(s,t){if(s){if(typeof s=="string")return g5e(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 g5e(s,t)}}function URs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function qRs(s){if(Array.isArray(s))return g5e(s)}function g5e(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 HRs(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 FKe(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 Tm(s){for(var t=1;t=0?1:-1,S,A;a==="insideStart"?(S=f+_*l,A=b):a==="insideEnd"?(S=g-_*l,A=!b):a==="end"&&(S=g+_*l,A=b),A=j<=0?A:!A;var T=wd(d,u,v,S),D=wd(d,u,v,S+(A?1:-1)*359),L="M".concat(T.x,",").concat(T.y,` A`).concat(v,",").concat(v,",0,1,").concat(A?0:1,`, `).concat(D.x,",").concat(D.y),M=No(t.id)?mR("recharts-radial-line-"):t.id;return Nt.createElement("text",n$({},r,{dominantBaseline:"central",className:So("recharts-radial-bar-label",o)}),Nt.createElement("defs",null,Nt.createElement("path",{id:M,d:L})),Nt.createElement("textPath",{xlinkHref:"#".concat(M)},n))},XRs=function(t){var n=t.viewBox,r=t.offset,a=t.position,i=n,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,u=i.startAngle,h=i.endAngle,p=(u+h)/2;if(a==="outside"){var f=wd(l,o,d+r,p),g=f.x,b=f.y;return{x:g,y:b,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 v=(c+d)/2,j=wd(l,o,v,p),_=j.x,S=j.y;return{x:_,y:S,textAnchor:"middle",verticalAnchor:"middle"}},JRs=function(t){var n=t.viewBox,r=t.parentViewBox,a=t.offset,i=t.position,l=n,o=l.x,c=l.y,d=l.width,u=l.height,h=u>=0?1:-1,p=h*a,f=h>0?"end":"start",g=h>0?"start":"end",b=d>=0?1:-1,v=b*a,j=b>0?"end":"start",_=b>0?"start":"end";if(i==="top"){var S={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:f};return Tm(Tm({},S),r?{height:Math.max(c-r.y,0),width:d}:{})}if(i==="bottom"){var A={x:o+d/2,y:c+u+p,textAnchor:"middle",verticalAnchor:g};return Tm(Tm({},A),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var T={x:o-v,y:c+u/2,textAnchor:j,verticalAnchor:"middle"};return Tm(Tm({},T),r?{width:Math.max(T.x-r.x,0),height:u}:{})}if(i==="right"){var D={x:o+d+v,y:c+u/2,textAnchor:_,verticalAnchor:"middle"};return Tm(Tm({},D),r?{width:Math.max(r.x+r.width-D.x,0),height:u}:{})}var L=r?{width:d,height:u}:{};return i==="insideLeft"?Tm({x:o+v,y:c+u/2,textAnchor:_,verticalAnchor:"middle"},L):i==="insideRight"?Tm({x:o+d-v,y:c+u/2,textAnchor:j,verticalAnchor:"middle"},L):i==="insideTop"?Tm({x:o+d/2,y:c+p,textAnchor:"middle",verticalAnchor:g},L):i==="insideBottom"?Tm({x:o+d/2,y:c+u-p,textAnchor:"middle",verticalAnchor:f},L):i==="insideTopLeft"?Tm({x:o+v,y:c+p,textAnchor:_,verticalAnchor:g},L):i==="insideTopRight"?Tm({x:o+d-v,y:c+p,textAnchor:j,verticalAnchor:g},L):i==="insideBottomLeft"?Tm({x:o+v,y:c+u-p,textAnchor:_,verticalAnchor:f},L):i==="insideBottomRight"?Tm({x:o+d-v,y:c+u-p,textAnchor:j,verticalAnchor:f},L):cR(i)&&(ca(i.x)||sA(i.x))&&(ca(i.y)||sA(i.y))?Tm({x:o+Jx(i.x,d),y:c+Jx(i.y,u),textAnchor:"end",verticalAnchor:"end"},L):Tm({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},L)},eOs=function(t){return"cx"in t&&ca(t.cx)};function Sp(s){var t=s.offset,n=t===void 0?5:t,r=VRs(s,FRs),a=Tm({offset:n},r),i=a.viewBox,l=a.position,o=a.value,c=a.children,d=a.content,u=a.className,h=u===void 0?"":u,p=a.textBreakAll;if(!i||No(o)&&No(c)&&!N.isValidElement(d)&&!ho(d))return null;if(N.isValidElement(d))return N.cloneElement(d,a);var f;if(ho(d)){if(f=N.createElement(d,a),N.isValidElement(f))return f}else f=YRs(a);var g=eOs(i),b=Wi(a,!0);if(g&&(l==="insideStart"||l==="insideEnd"||l==="end"))return QRs(a,f,b);var v=g?XRs(a):JRs(a);return Nt.createElement(IM,n$({className:So("recharts-label",h)},b,v,{breakAll:p}),f)}Sp.displayName="Label";var mbt=function(t){var n=t.cx,r=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,u=t.outerRadius,h=t.x,p=t.y,f=t.top,g=t.left,b=t.width,v=t.height,j=t.clockWise,_=t.labelViewBox;if(_)return _;if(ca(b)&&ca(v)){if(ca(h)&&ca(p))return{x:h,y:p,width:b,height:v};if(ca(f)&&ca(g))return{x:f,y:g,width:b,height:v}}return ca(h)&&ca(p)?{x:h,y:p,width:0,height:0}:ca(n)&&ca(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:j}:t.viewBox?t.viewBox:{}},tOs=function(t,n){return t?t===!0?Nt.createElement(Sp,{key:"label-implicit",viewBox:n}):Um(t)?Nt.createElement(Sp,{key:"label-implicit",viewBox:n,value:t}):N.isValidElement(t)?t.type===Sp?N.cloneElement(t,{key:"label-implicit",viewBox:n}):Nt.createElement(Sp,{key:"label-implicit",content:t,viewBox:n}):ho(t)?Nt.createElement(Sp,{key:"label-implicit",content:t,viewBox:n}):cR(t)?Nt.createElement(Sp,n$({viewBox:n},t,{key:"label-implicit"})):null:null},sOs=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=mbt(t),l=xy(a,Sp).map(function(c,d){return N.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=tOs(t.label,n||i);return[o].concat(zRs(l))};Sp.parseViewBox=mbt;Sp.renderCallByParent=sOs;function nOs(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var rOs=nOs;const aOs=jl(rOs);function r$(s){"@babel/helpers - typeof";return r$=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},r$(s)}var iOs=["valueAccessor"],oOs=["data","dataKey","clockWise","id","textBreakAll"];function lOs(s){return hOs(s)||uOs(s)||dOs(s)||cOs()}function cOs(){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 dOs(s,t){if(s){if(typeof s=="string")return y5e(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 y5e(s,t)}}function uOs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function hOs(s){if(Array.isArray(s))return y5e(s)}function y5e(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 xOs(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 gOs=function(t){return Array.isArray(t.value)?aOs(t.value):t.value};function aN(s){var t=s.valueAccessor,n=t===void 0?gOs:t,r=$Ke(s,iOs),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=$Ke(r,oOs);return!a||!a.length?null:Nt.createElement(Kl,{className:"recharts-label-list"},a.map(function(u,h){var p=No(i)?n(u,h):zm(u&&u.payload,i),f=No(o)?{}:{id:"".concat(o,"-").concat(h)};return Nt.createElement(Sp,pge({},Wi(u,!0),d,f,{parentViewBox:u.parentViewBox,value:p,textBreakAll:c,viewBox:Sp.parseViewBox(No(l)?u:BKe(BKe({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}aN.displayName="LabelList";function yOs(s,t){return s?s===!0?Nt.createElement(aN,{key:"labelList-implicit",data:t}):Nt.isValidElement(s)||ho(s)?Nt.createElement(aN,{key:"labelList-implicit",data:t,content:s}):cR(s)?Nt.createElement(aN,pge({data:t},s,{key:"labelList-implicit"})):null:null}function vOs(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=xy(r,aN).map(function(l,o){return N.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=yOs(s.label,t);return[i].concat(lOs(a))}aN.renderCallByParent=vOs;function a$(s){"@babel/helpers - typeof";return a$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a$(s)}function v5e(){return v5e=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(h.x,",").concat(h.y,` `);if(a>0){var f=wd(n,r,a,l),g=wd(n,r,a,d);p+="L ".concat(g.x,",").concat(g.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(f.x,",").concat(f.y," Z")}else p+="L ".concat(n,",").concat(r," Z");return p},NOs=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=Xx(u-d),p=lG({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),f=p.circleTangency,g=p.lineTangency,b=p.theta,v=lG({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),j=v.circleTangency,_=v.lineTangency,S=v.theta,A=c?Math.abs(d-u):Math.abs(d-u)-b-S;if(A<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 `):pbt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var T="M ".concat(g.x,",").concat(g.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(f.x,",").concat(f.y,` A`).concat(i,",").concat(i,",0,").concat(+(A>180),",").concat(+(h<0),",").concat(j.x,",").concat(j.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(_.x,",").concat(_.y,` `);if(a>0){var D=lG({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),L=D.circleTangency,M=D.lineTangency,F=D.theta,z=lG({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),V=z.circleTangency,W=z.lineTangency,K=z.theta,Y=c?Math.abs(d-u):Math.abs(d-u)-F-K;if(Y<0&&l===0)return"".concat(T,"L").concat(n,",").concat(r,"Z");T+="L".concat(W.x,",").concat(W.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(V.x,",").concat(V.y,` A`).concat(a,",").concat(a,",0,").concat(+(Y>180),",").concat(+(h>0),",").concat(L.x,",").concat(L.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(M.x,",").concat(M.y,"Z")}else T+="L".concat(n,",").concat(r,"Z");return T},kOs={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},fbt=function(t){var n=qKe(qKe({},kOs),t),r=n.cx,a=n.cy,i=n.innerRadius,l=n.outerRadius,o=n.cornerRadius,c=n.forceCornerRadius,d=n.cornerIsExternal,u=n.startAngle,h=n.endAngle,p=n.className;if(l0&&Math.abs(u-h)<360?v=NOs({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(b,g/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):v=pbt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),Nt.createElement("path",v5e({},Wi(n,!0),{className:f,d:v,role:"img"}))};function i$(s){"@babel/helpers - typeof";return i$=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},i$(s)}function b5e(){return b5e=Object.assign?Object.assign.bind():function(s){for(var t=1;t0;)if(!n.equals(s[r],t[r],r,r,s,t,n))return!1;return!0}function BOs(s,t){return _R(s.getTime(),t.getTime())}function QKe(s,t,n){if(s.size!==t.size)return!1;for(var r={},a=s.entries(),i=0,l,o;(l=a.next())&&!l.done;){for(var c=t.entries(),d=!1,u=0;(o=c.next())&&!o.done;){var h=l.value,p=h[0],f=h[1],g=o.value,b=g[0],v=g[1];!d&&!r[u]&&(d=n.equals(p,b,i,u,s,t,n)&&n.equals(f,v,p,b,s,t,n))&&(r[u]=!0),u++}if(!d)return!1;i++}return!0}function $Os(s,t,n){var r=ZKe(s),a=r.length;if(ZKe(t).length!==a)return!1;for(var i;a-- >0;)if(i=r[a],i===bbt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!vbt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n))return!1;return!0}function DF(s,t,n){var r=KKe(s),a=r.length;if(KKe(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=r[a],i===bbt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!vbt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n)||(l=YKe(s,i),o=YKe(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function UOs(s,t){return _R(s.valueOf(),t.valueOf())}function qOs(s,t){return s.source===t.source&&s.flags===t.flags}function XKe(s,t,n){if(s.size!==t.size)return!1;for(var r={},a=s.values(),i,l;(i=a.next())&&!i.done;){for(var o=t.values(),c=!1,d=0;(l=o.next())&&!l.done;)!c&&!r[d]&&(c=n.equals(i.value,l.value,i.value,l.value,s,t,n))&&(r[d]=!0),d++;if(!c)return!1}return!0}function VOs(s,t){var n=s.length;if(t.length!==n)return!1;for(;n-- >0;)if(s[n]!==t[n])return!1;return!0}var HOs="[object Arguments]",GOs="[object Boolean]",WOs="[object Date]",KOs="[object Map]",YOs="[object Number]",ZOs="[object Object]",QOs="[object RegExp]",XOs="[object Set]",JOs="[object String]",eFs=Array.isArray,JKe=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,eYe=Object.assign,tFs=Object.prototype.toString.call.bind(Object.prototype.toString);function sFs(s){var t=s.areArraysEqual,n=s.areDatesEqual,r=s.areMapsEqual,a=s.areObjectsEqual,i=s.arePrimitiveWrappersEqual,l=s.areRegExpsEqual,o=s.areSetsEqual,c=s.areTypedArraysEqual;return function(u,h,p){if(u===h)return!0;if(u==null||h==null||typeof u!="object"||typeof h!="object")return u!==u&&h!==h;var f=u.constructor;if(f!==h.constructor)return!1;if(f===Object)return a(u,h,p);if(eFs(u))return t(u,h,p);if(JKe!=null&&JKe(u))return c(u,h,p);if(f===Date)return n(u,h,p);if(f===RegExp)return l(u,h,p);if(f===Map)return r(u,h,p);if(f===Set)return o(u,h,p);var g=tFs(u);return g===WOs?n(u,h,p):g===QOs?l(u,h,p):g===KOs?r(u,h,p):g===XOs?o(u,h,p):g===ZOs?typeof u.then!="function"&&typeof h.then!="function"&&a(u,h,p):g===HOs?a(u,h,p):g===GOs||g===YOs||g===JOs?i(u,h,p):!1}}function nFs(s){var t=s.circular,n=s.createCustomConfig,r=s.strict,a={areArraysEqual:r?DF:zOs,areDatesEqual:BOs,areMapsEqual:r?WKe(QKe,DF):QKe,areObjectsEqual:r?DF:$Os,arePrimitiveWrappersEqual:UOs,areRegExpsEqual:qOs,areSetsEqual:r?WKe(XKe,DF):XKe,areTypedArraysEqual:r?DF:VOs};if(n&&(a=eYe({},a,n(a))),t){var i=dG(a.areArraysEqual),l=dG(a.areMapsEqual),o=dG(a.areObjectsEqual),c=dG(a.areSetsEqual);a=eYe({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function rFs(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function aFs(s){var t=s.circular,n=s.comparator,r=s.createState,a=s.equals,i=s.strict;if(r)return function(c,d){var u=r(),h=u.cache,p=h===void 0?t?new WeakMap:void 0:h,f=u.meta;return n(c,d,{cache:p,equals:a,meta:f,strict:i})};if(t)return function(c,d){return n(c,d,{cache:new WeakMap,equals:a,meta:void 0,strict:i})};var l={cache:void 0,equals:a,meta:void 0,strict:i};return function(c,d){return n(c,d,l)}}var iFs=pC();pC({strict:!0});pC({circular:!0});pC({circular:!0,strict:!0});pC({createInternalComparator:function(){return _R}});pC({strict:!0,createInternalComparator:function(){return _R}});pC({circular:!0,createInternalComparator:function(){return _R}});pC({circular:!0,createInternalComparator:function(){return _R},strict:!0});function pC(s){s===void 0&&(s={});var t=s.circular,n=t===void 0?!1:t,r=s.createInternalComparator,a=s.createState,i=s.strict,l=i===void 0?!1:i,o=nFs(s),c=sFs(o),d=r?r(c):rFs(c);return aFs({circular:n,comparator:c,createState:a,equals:d,strict:l})}function oFs(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function tYe(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):oFs(a)};requestAnimationFrame(r)}function _5e(s){"@babel/helpers - typeof";return _5e=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},_5e(s)}function lFs(s){return hFs(s)||uFs(s)||dFs(s)||cFs()}function cFs(){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 dFs(s,t){if(s){if(typeof s=="string")return sYe(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 sYe(s,t)}}function sYe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1?1:j<0?0:j},b=function(j){for(var _=j>1?1:j,S=_,A=0;A<8;++A){var T=h(S)-_,D=f(S);if(Math.abs(T-_)0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,h,p){var f=-(u-h)*r,g=p*i,b=p+(f-g)*o/1e3,v=p*o/1e3+u;return Math.abs(v-h)s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function qFs(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 gNe(s){return WFs(s)||GFs(s)||HFs(s)||VFs()}function VFs(){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 HFs(s,t){if(s){if(typeof s=="string")return S5e(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return S5e(s,t)}}function GFs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function WFs(s){if(Array.isArray(s))return S5e(s)}function S5e(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function yge(s){return yge=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},yge(s)}var Fw=function(s){XFs(n,s);var t=JFs(n);function n(r,a){var i;KFs(this,n),i=t.call(this,r,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,u=l.to,h=l.steps,p=l.children,f=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(E5e(i)),i.changeStyle=i.changeStyle.bind(E5e(i)),!o||f<=0)return i.state={style:{}},typeof p=="function"&&(i.state={style:u}),T5e(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof p=="function")return i.state={style:d},T5e(i);i.state={style:c?T7({},c,d):d}}else i.state={style:{}};return i}return ZFs(n,[{key:"componentDidMount",value:function(){var a=this.props,i=a.isActive,l=a.canBegin;this.mounted=!0,!(!i||!l)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(a){var i=this.props,l=i.isActive,o=i.canBegin,c=i.attributeName,d=i.shouldReAnimate,u=i.to,h=i.from,p=this.state.style;if(o){if(!l){var f={style:c?T7({},c,u):u};this.state&&p&&(c&&p[c]!==u||!c&&p!==u)&&this.setState(f);return}if(!(iFs(a.to,u)&&a.canBegin&&a.isActive)){var g=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var b=g||d?h:a.to;if(this.state&&p){var v={style:c?T7({},c,b):b};(c&&p[c]!==b||!c&&p!==b)&&this.setState(v)}this.runAnimation(B1(B1({},this.props),{},{from:b,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var a=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),a&&a()}},{key:"handleStyleChange",value:function(a){this.changeStyle(a)}},{key:"changeStyle",value:function(a){this.mounted&&this.setState({style:a})}},{key:"runJSAnimation",value:function(a){var i=this,l=a.from,o=a.to,c=a.duration,d=a.easing,u=a.begin,h=a.onAnimationEnd,p=a.onAnimationStart,f=BFs(l,o,EFs(d),c,this.changeStyle),g=function(){i.stopJSAnimation=f()};this.manager.start([p,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,p=h===void 0?0:h,f=function(b,v,j){if(j===0)return b;var _=v.duration,S=v.easing,A=S===void 0?"ease":S,T=v.style,D=v.properties,L=v.onAnimationEnd,M=j>0?l[j-1]:v,F=D||Object.keys(T);if(typeof A=="function"||A==="spring")return[].concat(gNe(b),[i.runJSAnimation.bind(i,{from:M.style,to:T,duration:_,easing:A}),_]);var z=aYe(F,_,A),V=B1(B1(B1({},M.style),T),{},{transition:z});return[].concat(gNe(b),[V,_,L]).filter(gFs)};return this.manager.start([c].concat(gNe(l.reduce(f,[u,Math.max(p,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=mFs());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,u=a.onAnimationStart,h=a.onAnimationEnd,p=a.steps,f=a.children,g=this.manager;if(this.unSubscribe=g.subscribe(this.handleStyleChange),typeof d=="function"||typeof f=="function"||d==="spring"){this.runJSAnimation(a);return}if(p.length>1){this.runStepAnimation(a);return}var b=o?T7({},o,c):c,v=aYe(Object.keys(b),l,d);g.start([u,i,B1(B1({},b),{},{transition:v}),l,h])}},{key:"render",value:function(){var a=this.props,i=a.children;a.begin;var l=a.duration;a.attributeName,a.easing;var o=a.isActive;a.steps,a.from,a.to,a.canBegin,a.onAnimationEnd,a.shouldReAnimate,a.onAnimationReStart;var c=UFs(a,$Fs),d=N.Children.count(i),u=this.state.style;if(typeof i=="function")return i(u);if(!o||d===0||l<=0)return i;var h=function(f){var g=f.props,b=g.style,v=b===void 0?{}:b,j=g.className,_=N.cloneElement(f,B1(B1({},c),{},{style:B1(B1({},v),u),className:j}));return _};return d===1?h(N.Children.only(i)):Nt.createElement("div",null,N.Children.map(i,function(p){return h(p)}))}}]),n}(N.PureComponent);Fw.displayName="Animate";Fw.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};Fw.propTypes={from:xc.oneOfType([xc.object,xc.string]),to:xc.oneOfType([xc.object,xc.string]),attributeName:xc.string,duration:xc.number,begin:xc.number,easing:xc.oneOfType([xc.string,xc.func]),steps:xc.arrayOf(xc.shape({duration:xc.number.isRequired,style:xc.object.isRequired,easing:xc.oneOfType([xc.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),xc.func]),properties:xc.arrayOf("string"),onAnimationEnd:xc.func})),children:xc.oneOfType([xc.node,xc.func]),isActive:xc.bool,canBegin:xc.bool,onAnimationEnd:xc.func,shouldReAnimate:xc.bool,onAnimationStart:xc.func,onAnimationReStart:xc.func};function c$(s){"@babel/helpers - typeof";return c$=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},c$(s)}function vge(){return vge=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0?1:-1,c=r>=0?1:-1,d=a>=0&&r>=0||a<0&&r<0?1:0,u;if(l>0&&i instanceof Array){for(var h=[0,0,0,0],p=0,f=4;pl?l:i[p];u="M".concat(t,",").concat(n+o*h[0]),h[0]>0&&(u+="A ".concat(h[0],",").concat(h[0],",0,0,").concat(d,",").concat(t+c*h[0],",").concat(n)),u+="L ".concat(t+r-c*h[1],",").concat(n),h[1]>0&&(u+="A ".concat(h[1],",").concat(h[1],",0,0,").concat(d,`, `).concat(t+r,",").concat(n+o*h[1])),u+="L ".concat(t+r,",").concat(n+a-o*h[2]),h[2]>0&&(u+="A ".concat(h[2],",").concat(h[2],",0,0,").concat(d,`, `).concat(t+r-c*h[2],",").concat(n+a)),u+="L ".concat(t+c*h[3],",").concat(n+a),h[3]>0&&(u+="A ".concat(h[3],",").concat(h[3],",0,0,").concat(d,`, `).concat(t,",").concat(n+a-o*h[3])),u+="Z"}else if(l>0&&i===+i&&i>0){var 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},c7s=function(t,n){if(!t||!n)return!1;var r=t.x,a=t.y,i=n.x,l=n.y,o=n.width,c=n.height;if(Math.abs(o)>0&&Math.abs(c)>0){var d=Math.min(i,i+o),u=Math.max(i,i+o),h=Math.min(l,l+c),p=Math.max(l,l+c);return r>=d&&r<=u&&a>=h&&a<=p}return!1},d7s={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},nLe=function(t){var n=mYe(mYe({},d7s),t),r=N.useRef(),a=N.useState(-1),i=t7s(a,2),l=i[0],o=i[1];N.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var A=r.current.getTotalLength();A&&o(A)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,p=n.radius,f=n.className,g=n.animationEasing,b=n.animationDuration,v=n.animationBegin,j=n.isAnimationActive,_=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var S=So("recharts-rectangle",f);return _?Nt.createElement(Fw,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:b,animationEasing:g,isActive:_},function(A){var T=A.width,D=A.height,L=A.x,M=A.y;return Nt.createElement(Fw,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:b,isActive:j,easing:g},Nt.createElement("path",vge({},Wi(n,!0),{className:S,d:pYe(L,M,T,D,p),ref:r})))}):Nt.createElement("path",vge({},Wi(n,!0),{className:S,d:pYe(c,d,u,h,p)}))},u7s=["points","className","baseLinePoints","connectNulls"];function OP(){return OP=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 m7s(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 fYe(s){return g7s(s)||x7s(s)||f7s(s)||p7s()}function p7s(){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 f7s(s,t){if(s){if(typeof s=="string")return A5e(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 A5e(s,t)}}function x7s(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function g7s(s){if(Array.isArray(s))return A5e(s)}function A5e(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){xYe(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),xYe(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},Tz=function(t,n){var r=y7s(t);n&&(r=[r.reduce(function(i,l){return[].concat(fYe(i),fYe(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},v7s=function(t,n,r){var a=Tz(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(Tz(n.reverse(),r).slice(1))},b7s=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=h7s(t,u7s);if(!n||!n.length)return null;var o=So("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=v7s(n,a,i);return Nt.createElement("g",{className:o},Nt.createElement("path",OP({},Wi(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Nt.createElement("path",OP({},Wi(l,!0),{fill:"none",d:Tz(n,i)})):null,c?Nt.createElement("path",OP({},Wi(l,!0),{fill:"none",d:Tz(a,i)})):null)}var u=Tz(n,i);return Nt.createElement("path",OP({},Wi(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function M5e(){return M5e=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 C7s(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 T7s=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},E7s=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.top,o=l===void 0?0:l,c=t.left,d=c===void 0?0:c,u=t.width,h=u===void 0?0:u,p=t.height,f=p===void 0?0:p,g=t.className,b=S7s(t,_7s),v=w7s({x:r,y:i,top:o,left:d,width:h,height:f},b);return!ca(r)||!ca(i)||!ca(h)||!ca(f)||!ca(o)||!ca(d)?null:Nt.createElement("path",I5e({},Wi(v,!0),{className:So("recharts-cross",g),d:T7s(r,i,h,f,o,d)}))},A7s=m1e,M7s=O1t,I7s=tj;function P7s(s,t){return s&&s.length?A7s(s,I7s(t),M7s):void 0}var L7s=P7s;const D7s=jl(L7s);var R7s=m1e,O7s=tj,F7s=F1t;function z7s(s,t){return s&&s.length?R7s(s,O7s(t),F7s):void 0}var B7s=z7s;const $7s=jl(B7s);var U7s=["cx","cy","angle","ticks","axisLine"],q7s=["ticks","tick","angle","tickFormatter","stroke"];function Z8(s){"@babel/helpers - typeof";return Z8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Z8(s)}function Ez(){return Ez=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 V7s(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 H7s(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function bYe(s,t){for(var n=0;njYe?l=a==="outer"?"start":"end":i<-jYe?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=x3(x3({},Wi(this.props,!1)),{},{fill:"none"},Wi(o,!1));if(c==="circle")return Nt.createElement(y1e,qE({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(p){return wd(a,i,l,p.coordinate)});return Nt.createElement(b7s,qE({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=Wi(this.props,!1),h=Wi(l,!1),p=x3(x3({},u),{},{fill:"none"},Wi(o,!1)),f=i.map(function(g,b){var v=r.getTickLineCoord(g),j=r.getTickTextAnchor(g),_=x3(x3(x3({textAnchor:j},u),{},{stroke:"none",fill:d},h),{},{index:b,payload:g,x:v.x2,y:v.y2});return Nt.createElement(Kl,qE({className:So("recharts-polar-angle-axis-tick",hbt(l)),key:"tick-".concat(g.coordinate)},MM(r.props,g,b)),o&&Nt.createElement("line",qE({className:"recharts-polar-angle-axis-tick-line"},p,v)),l&&t.renderTickItem(l,_,c?c(g.value,b):g.value))});return Nt.createElement(Kl,{className:"recharts-polar-angle-axis-ticks"},f)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:Nt.createElement(Kl,{className:So("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return Nt.isValidElement(r)?l=Nt.cloneElement(r,a):ho(r)?l=r(a):l=Nt.createElement(IM,qE({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(N.PureComponent);_1e(w1e,"displayName","PolarAngleAxis");_1e(w1e,"axisType","angleAxis");_1e(w1e,"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 i9s=Pvt,o9s=i9s(Object.getPrototypeOf,Object),l9s=o9s,c9s=AN,d9s=l9s,u9s=MN,h9s="[object Object]",m9s=Function.prototype,p9s=Object.prototype,Mbt=m9s.toString,f9s=p9s.hasOwnProperty,x9s=Mbt.call(Object);function g9s(s){if(!u9s(s)||c9s(s)!=h9s)return!1;var t=d9s(s);if(t===null)return!0;var n=f9s.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&Mbt.call(n)==x9s}var y9s=g9s;const v9s=jl(y9s);var b9s=AN,_9s=MN,w9s="[object Boolean]";function j9s(s){return s===!0||s===!1||_9s(s)&&b9s(s)==w9s}var N9s=j9s;const k9s=jl(N9s);function u$(s){"@babel/helpers - typeof";return u$=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},u$(s)}function wge(){return wge=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0,from:{upperWidth:0,lowerWidth:0,height:p,x:c,y:d},to:{upperWidth:u,lowerWidth:h,height:p,x:c,y:d},duration:b,animationEasing:g,isActive:j},function(S){var A=S.upperWidth,T=S.lowerWidth,D=S.height,L=S.x,M=S.y;return Nt.createElement(Fw,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:b,easing:g},Nt.createElement("path",wge({},Wi(n,!0),{className:_,d:CYe(L,M,A,T,D),ref:r})))}):Nt.createElement("g",null,Nt.createElement("path",wge({},Wi(n,!0),{className:_,d:CYe(c,d,u,h,p)})))},R9s=["option","shapeType","propTransformer","activeClassName","isActive"];function h$(s){"@babel/helpers - typeof";return h$=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},h$(s)}function O9s(s,t){if(s==null)return{};var n=F9s(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 F9s(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function TYe(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function jge(s){for(var t=1;t0?fy(S,"paddingAngle",0):0;if(T){var L=Y0(T.endAngle-T.startAngle,S.endAngle-S.startAngle),M=yd(yd({},S),{},{startAngle:_+D,endAngle:_+L(b)+D});v.push(M),_=M.endAngle}else{var F=S.endAngle,z=S.startAngle,V=Y0(0,F-z),W=V(b),K=yd(yd({},S),{},{startAngle:_+D,endAngle:_+W+D});v.push(K),_=K.endAngle}}),Nt.createElement(Kl,null,r.renderSectorsStatically(v))})}},{key:"attachKeyboardHandlers",value:function(r){var a=this;r.onkeydown=function(i){if(!i.altKey)switch(i.key){case"ArrowLeft":{var l=++a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[l].focus(),a.setState({sectorToFocus:l});break}case"ArrowRight":{var o=--a.state.sectorToFocus<0?a.sectorRefs.length-1:a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[o].focus(),a.setState({sectorToFocus:o});break}case"Escape":{a.sectorRefs[a.state.sectorToFocus].blur(),a.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var r=this.props,a=r.sectors,i=r.isAnimationActive,l=this.state.prevSectors;return i&&a&&a.length&&(!l||!BU(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var r=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,u=a.cy,h=a.innerRadius,p=a.outerRadius,f=a.isAnimationActive,g=this.state.isAnimationFinished;if(i||!l||!l.length||!ca(d)||!ca(u)||!ca(h)||!ca(p))return null;var b=So("recharts-pie",o);return Nt.createElement(Kl,{tabIndex:this.props.rootTabIndex,className:b,ref:function(j){r.pieRef=j}},this.renderSectors(),c&&this.renderLabels(l),Sp.renderCallByParent(this.props,null,!1),(!f||g)&&aN.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,A=v-_*f-S,T=a.reduce(function(M,F){var z=zm(F,j,0);return M+(ca(z)?z:0)},0),D;if(T>0){var L;D=a.map(function(M,F){var z=zm(M,j,0),V=zm(M,u,F),W=(ca(z)?z:0)/T,K;F?K=L.endAngle+Xx(b)*c*(z!==0?1:0):K=l;var Y=K+Xx(b)*((z!==0?f:0)+W*A),ee=(K+Y)/2,ne=(g.innerRadius+g.outerRadius)/2,oe=[{name:V,value:z,payload:M,dataKey:j,type:p}],pe=wd(g.cx,g.cy,ne,ee);return L=yd(yd(yd({percent:W,cornerRadius:i,name:V,tooltipPayload:oe,midAngle:ee,middleRadius:ne,tooltipPosition:pe},M),g),{},{value:zm(M,j),startAngle:K,endAngle:Y,payload:M,paddingAngle:Xx(b)*c}),L})}return yd(yd({},g),{},{sectors:D,data:a})});var azs=Math.ceil,izs=Math.max;function ozs(s,t,n,r){for(var a=-1,i=izs(azs((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var lzs=ozs,czs=Xvt,IYe=1/0,dzs=17976931348623157e292;function uzs(s){if(!s)return s===0?s:0;if(s=czs(s),s===IYe||s===-IYe){var t=s<0?-1:1;return t*dzs}return s===s?s:0}var Dbt=uzs,hzs=lzs,mzs=i1e,yNe=Dbt;function pzs(s){return function(t,n,r){return r&&typeof r!="number"&&mzs(t,n,r)&&(n=r=void 0),t=yNe(t),n===void 0?(n=t,t=0):n=yNe(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),B0(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()}),B0(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),B0(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),B0(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),B0(r,"handleSlideDragStart",function(a){var i=OYe(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 Tzs(t,s),Nzs(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(r){var a=r.startX,i=r.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,u=d.length-1,h=Math.min(a,i),p=Math.max(a,i),f=t.getIndexInRange(l,h),g=t.getIndexInRange(l,p);return{startIndex:f-f%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=zm(i[r],o,r);return ho(l)?l(c,r):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(r){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,u=c.width,h=c.travellerWidth,p=c.startIndex,f=c.endIndex,g=c.onChange,b=r.pageX-i;b>0?b=Math.min(b,d+u-h-o,d+u-h-l):b<0&&(b=Math.max(b,d-l,d-o));var v=this.getIndex({startX:l+b,endX:o+b});(v.startIndex!==p||v.endIndex!==f)&&g&&g(v),this.setState({startX:l+b,endX:o+b,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=OYe(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:r,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(r){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],u=this.props,h=u.x,p=u.width,f=u.travellerWidth,g=u.onChange,b=u.gap,v=u.data,j={startX:this.state.startX,endX:this.state.endX},_=r.pageX-i;_>0?_=Math.min(_,h+p-f-d):_<0&&(_=Math.max(_,h-d)),j[l]=d+_;var S=this.getIndex(j),A=S.startIndex,T=S.endIndex,D=function(){var M=v.length-1;return l==="startX"&&(o>c?A%b===0:T%b===0)||oc?T%b===0:A%b===0)||o>c&&T===M};this.setState(B0(B0({},l,d+_),"brushMoveStartX",r.pageX),function(){g&&D()&&g(S)})}},{key:"handleTravellerMoveKeyboard",value:function(r,a){var i=this,l=this.state,o=l.scaleValues,c=l.startX,d=l.endX,u=this.state[a],h=o.indexOf(u);if(h!==-1){var p=h+r;if(!(p===-1||p>=o.length)){var f=o[p];a==="startX"&&f>=d||a==="endX"&&f<=c||this.setState(B0({},a,f),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.fill,d=r.stroke;return Nt.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.data,d=r.children,u=r.padding,h=N.Children.only(d);return h?Nt.cloneElement(h,{x:a,y:i,width:l,height:o,margin:u,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(r,a){var i,l,o=this,c=this.props,d=c.y,u=c.travellerWidth,h=c.height,p=c.traveller,f=c.ariaLabel,g=c.data,b=c.startIndex,v=c.endIndex,j=Math.max(r,this.props.x),_=vNe(vNe({},Wi(this.props,!1)),{},{x:j,y:d,width:u,height:h}),S=f||"Min value: ".concat((i=g[b])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=g[v])===null||l===void 0?void 0:l.name);return Nt.createElement(Kl,{tabIndex:0,role:"slider","aria-label":S,"aria-valuenow":r,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(T){["ArrowLeft","ArrowRight"].includes(T.key)&&(T.preventDefault(),T.stopPropagation(),o.handleTravellerMoveKeyboard(T.key==="ArrowRight"?1:-1,a))},onFocus:function(){o.setState({isTravellerFocused:!0})},onBlur:function(){o.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(p,_))}},{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 Nt.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:u,y:l,width:h,height:o})}},{key:"renderText",value:function(){var r=this.props,a=r.startIndex,i=r.endIndex,l=r.y,o=r.height,c=r.travellerWidth,d=r.stroke,u=this.state,h=u.startX,p=u.endX,f=5,g={pointerEvents:"none",fill:d};return Nt.createElement(Kl,{className:"recharts-brush-texts"},Nt.createElement(IM,Sge({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,p)-f,y:l+o/2},g),this.getTextOfTick(a)),Nt.createElement(IM,Sge({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,p)+c+f,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,p=this.state,f=p.startX,g=p.endX,b=p.isTextActive,v=p.isSlideMoving,j=p.isTravellerMoving,_=p.isTravellerFocused;if(!a||!a.length||!ca(o)||!ca(c)||!ca(d)||!ca(u)||d<=0||u<=0)return null;var S=So("recharts-brush",i),A=Nt.Children.count(l)===1,T=wzs("userSelect","none");return Nt.createElement(Kl,{className:S,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:T},this.renderBackground(),A&&this.renderPanorama(),this.renderSlide(f,g),this.renderTravellerLayer(f,"startX"),this.renderTravellerLayer(g,"endX"),(b||v||j||_||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 Nt.createElement(Nt.Fragment,null,Nt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Nt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Nt.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 Nt.isValidElement(r)?i=Nt.cloneElement(r,a):ho(r)?i=r(a):i=t.renderDefaultTraveller(a),i}},{key:"getDerivedStateFromProps",value:function(r,a){var i=r.data,l=r.width,o=r.x,c=r.travellerWidth,d=r.updateId,u=r.startIndex,h=r.endIndex;if(i!==a.prevData||d!==a.prevUpdateId)return vNe({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?Azs({data:i,width:l,x:o,travellerWidth:c,startIndex:u,endIndex:h}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var p=a.scale.domain().map(function(f){return a.scale(f)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(r.startIndex),endX:a.scale(r.endIndex),scaleValues:p}}return null}},{key:"getIndexInRange",value:function(r,a){for(var i=r.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);r[c]>a?o=c:l=c}return a>=r[o]?o:l}}])}(N.PureComponent);B0(eD,"displayName","Brush");B0(eD,"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 Mzs=EPe;function Izs(s,t){var n;return Mzs(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var Pzs=Izs,Lzs=kvt,Dzs=tj,Rzs=Pzs,Ozs=l0,Fzs=i1e;function zzs(s,t,n){var r=Ozs(s)?Lzs:Rzs;return n&&Fzs(s,t,n)&&(t=void 0),r(s,Dzs(t))}var Bzs=zzs;const $zs=jl(Bzs);var Tw=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},FYe=Wvt;function Uzs(s,t,n){t=="__proto__"&&FYe?FYe(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var qzs=Uzs,Vzs=qzs,Hzs=Hvt,Gzs=tj;function Wzs(s,t){var n={};return t=Gzs(t),Hzs(s,function(r,a,i){Vzs(n,a,t(r,a,i))}),n}var Kzs=Wzs;const Yzs=jl(Kzs);function Zzs(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 mBs(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 pBs(s,t){var n=s.x,r=s.y,a=hBs(s,lBs),i="".concat(n),l=parseInt(i,10),o="".concat(r),c=parseInt(o,10),d="".concat(t.height||a.height),u=parseInt(d,10),h="".concat(t.width||a.width),p=parseInt(h,10);return RF(RF(RF(RF(RF({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:p,name:t.name,radius:t.radius})}function BYe(s){return Nt.createElement(Ibt,O5e({shapeType:"rectangle",propTransformer:pBs,activeClassName:"recharts-active-bar"},s))}var fBs=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=ca(r)||Zks(r);return i?t(r,a):(i||LM(),n)}},xBs=["value","background"],Bbt;function tD(s){"@babel/helpers - typeof";return tD=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},tD(s)}function gBs(s,t){if(s==null)return{};var n=yBs(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 yBs(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 Tge(){return Tge=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(ee)0&&Math.abs(Y)0&&(K=Math.min((Me||0)-(Y[Te-1]||0),K))}),Number.isFinite(K)){var ee=K/W,ne=b.layout==="vertical"?r.height:r.width;if(b.padding==="gap"&&(L=ee*ne/2),b.padding==="no-gap"){var oe=Jx(t.barCategoryGap,ee*ne),pe=ee*ne/2;L=pe-oe-(pe-oe)/ne*oe}}}a==="xAxis"?M=[r.left+(S.left||0)+(L||0),r.left+r.width-(S.right||0)-(L||0)]:a==="yAxis"?M=c==="horizontal"?[r.top+r.height-(S.bottom||0),r.top+(S.top||0)]:[r.top+(S.top||0)+(L||0),r.top+r.height-(S.bottom||0)-(L||0)]:M=b.range,T&&(M=[M[1],M[0]]);var ce=abt(b,i,p),de=ce.scale,ie=ce.realScaleType;de.domain(j).range(M),ibt(de);var ye=obt(de,X1(X1({},b),{},{realScaleType:ie}));a==="xAxis"?(V=v==="top"&&!A||v==="bottom"&&A,F=r.left,z=h[D]-V*b.height):a==="yAxis"&&(V=v==="left"&&!A||v==="right"&&A,F=h[D]-V*b.width,z=r.top);var _e=X1(X1(X1({},b),ye),{},{realScaleType:ie,x:F,y:z,scale:de,width:a==="xAxis"?r.width:b.width,height:a==="yAxis"?r.height:b.height});return _e.bandSize=hge(_e,ye),!b.hide&&a==="xAxis"?h[D]+=(V?-1:1)*_e.height:b.hide||(h[D]+=(V?-1:1)*_e.width),X1(X1({},f),{},k1e({},g,_e))},{})},Hbt=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)}},EBs=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return Hbt({x:n,y:r},{x:a,y:i})},Gbt=function(){function s(t){SBs(this,s),this.scale=t}return CBs(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)}}])}();k1e(Gbt,"EPS",1e-4);var rLe=function(t){var n=Object.keys(t).reduce(function(r,a){return X1(X1({},r),{},k1e({},a,Gbt.create(t[a])))},{});return X1(X1({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return Yzs(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return zbt(a,function(i,l){return n[l].isInRange(i)})}})};function ABs(s){return(s%180+180)%180}var MBs=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=ABs(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var RBs=DBs,OBs=Dbt;function FBs(s){var t=OBs(s),n=t%1;return t===t?n?t-n:t:0}var zBs=FBs,BBs=zvt,$Bs=tj,UBs=zBs,qBs=Math.max;function VBs(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:UBs(n);return a<0&&(a=qBs(r+a,0)),BBs(s,$Bs(t),a)}var HBs=VBs,GBs=RBs,WBs=HBs,KBs=GBs(WBs),YBs=KBs;const ZBs=jl(YBs);var QBs=eks(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("")}),aLe=N.createContext(void 0),iLe=N.createContext(void 0),Wbt=N.createContext(void 0),Kbt=N.createContext({}),Ybt=N.createContext(void 0),Zbt=N.createContext(0),Qbt=N.createContext(0),HYe=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=QBs(i);return Nt.createElement(aLe.Provider,{value:r},Nt.createElement(iLe.Provider,{value:a},Nt.createElement(Kbt.Provider,{value:i},Nt.createElement(Wbt.Provider,{value:u},Nt.createElement(Ybt.Provider,{value:l},Nt.createElement(Zbt.Provider,{value:d},Nt.createElement(Qbt.Provider,{value:c},o)))))))},XBs=function(){return N.useContext(Ybt)},Xbt=function(t){var n=N.useContext(aLe);n==null&&LM();var r=n[t];return r==null&&LM(),r},JBs=function(){var t=N.useContext(aLe);return gS(t)},e$s=function(){var t=N.useContext(iLe),n=ZBs(t,function(r){return zbt(r.domain,Number.isFinite)});return n||gS(t)},Jbt=function(t){var n=N.useContext(iLe);n==null&&LM();var r=n[t];return r==null&&LM(),r},t$s=function(){var t=N.useContext(Wbt);return t},s$s=function(){return N.useContext(Kbt)},oLe=function(){return N.useContext(Qbt)},lLe=function(){return N.useContext(Zbt)};function sD(s){"@babel/helpers - typeof";return sD=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},sD(s)}function n$s(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function r$s(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 z$s(s,t){return i_t(s,t+1)}function B$s(s,t,n,r,a){for(var i=(r||[]).slice(),l=t.start,o=t.end,c=0,d=1,u=l,h=function(){var g=r==null?void 0:r[c];if(g===void 0)return{v:i_t(r,d)};var b=c,v,j=function(){return v===void 0&&(v=n(g,b)),v},_=g.coordinate,S=c===0||Pge(s,_,j,u,o);S||(c=0,u=l,d+=1),S&&(u=_+s*(j()/2+a),c+=d)},p;d<=i.length;)if(p=h(),p)return p.v;return[]}function g$(s){"@babel/helpers - typeof";return g$=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},g$(s)}function JYe(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function Yf(s){for(var t=1;t0?f.coordinate-v*s:f.coordinate})}else i[p]=f=Yf(Yf({},f),{},{tickCoord:f.coordinate});var j=Pge(s,f.tickCoord,b,o,c);j&&(c=f.tickCoord-s*(b()/2+a),i[p]=Yf(Yf({},f),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function H$s(s,t,n,r,a,i){var l=(r||[]).slice(),o=l.length,c=t.start,d=t.end;if(i){var u=r[o-1],h=n(u,o-1),p=s*(u.coordinate+s*h/2-d);l[o-1]=u=Yf(Yf({},u),{},{tickCoord:p>0?u.coordinate-p*s:u.coordinate});var f=Pge(s,u.tickCoord,function(){return h},c,d);f&&(d=u.tickCoord-s*(h/2+a),l[o-1]=Yf(Yf({},u),{},{isShow:!0}))}for(var g=i?o-1:o,b=function(_){var S=l[_],A,T=function(){return A===void 0&&(A=n(S,_)),A};if(_===0){var D=s*(S.coordinate-s*T()/2-c);l[_]=S=Yf(Yf({},S),{},{tickCoord:D<0?S.coordinate-D*s:S.coordinate})}else l[_]=S=Yf(Yf({},S),{},{tickCoord:S.coordinate});var L=Pge(s,S.tickCoord,T,c,d);L&&(c=S.tickCoord+s*(T()/2+a),l[_]=Yf(Yf({},S),{},{isShow:!0}))},v=0;v=2?Xx(a[1].coordinate-a[0].coordinate):1,j=F$s(i,v,f);return c==="equidistantPreserveStart"?B$s(v,j,b,a,l):(c==="preserveStart"||c==="preserveStartEnd"?p=H$s(v,j,b,a,l,c==="preserveStartEnd"):p=V$s(v,j,b,a,l),p.filter(function(_){return _.isShow}))}var G$s=["viewBox"],W$s=["viewBox"],K$s=["ticks"];function aD(s){"@babel/helpers - typeof";return aD=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},aD(s)}function zP(){return zP=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 Y$s(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Z$s(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function tZe(s,t){for(var n=0;n0?c(this.props):c(f)),l<=0||o<=0||!g||!g.length?null:Nt.createElement(Kl,{className:So("recharts-cartesian-axis",d),ref:function(v){r.layerReference=v}},i&&this.renderAxisLine(),this.renderTicks(g,this.state.fontSize,this.state.letterSpacing),Sp.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=So(a.className,"recharts-cartesian-axis-tick-value");return Nt.isValidElement(r)?l=Nt.cloneElement(r,Cm(Cm({},a),{},{className:o})):ho(r)?l=r(Cm(Cm({},a),{},{className:o})):l=Nt.createElement(IM,zP({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(N.Component);hLe(wR,"displayName","CartesianAxis");hLe(wR,"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 nUs=["x1","y1","x2","y2","key"],rUs=["offset"];function DM(s){"@babel/helpers - typeof";return DM=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},DM(s)}function sZe(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 Jf(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function lUs(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 cUs=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 Nt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function c_t(s,t){var n;if(Nt.isValidElement(s))n=Nt.cloneElement(s,t);else if(ho(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=nZe(t,nUs),d=Wi(c,!1);d.offset;var u=nZe(d,rUs);n=Nt.createElement("line",aA({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function dUs(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=Jf(Jf({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return c_t(a,d)});return Nt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function uUs(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=Jf(Jf({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return c_t(a,d)});return Nt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function hUs(s){var t=s.horizontalFill,n=s.fillOpacity,r=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var u=o.map(function(p){return Math.round(p+a-a)}).sort(function(p,f){return p-f});a!==u[0]&&u.unshift(0);var h=u.map(function(p,f){var g=!u[f+1],b=g?a+l-p:u[f+1]-p;if(b<=0)return null;var v=f%t.length;return Nt.createElement("rect",{key:"react-".concat(f),y:p,x:r,height:b,width:i,stroke:"none",fill:t[v],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return Nt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function mUs(s){var t=s.vertical,n=t===void 0?!0:t,r=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!n||!r||!r.length)return null;var u=d.map(function(p){return Math.round(p+i-i)}).sort(function(p,f){return p-f});i!==u[0]&&u.unshift(0);var h=u.map(function(p,f){var g=!u[f+1],b=g?i+o-p:u[f+1]-p;if(b<=0)return null;var v=f%r.length;return Nt.createElement("rect",{key:"react-".concat(f),x:p,y:l,width:b,height:c,stroke:"none",fill:r[v],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Nt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var pUs=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return rbt(uLe(Jf(Jf(Jf({},wR.defaultProps),r),{},{ticks:q2(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},fUs=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return rbt(uLe(Jf(Jf(Jf({},wR.defaultProps),r),{},{ticks:q2(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},FI={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function mLe(s){var t,n,r,a,i,l,o=oLe(),c=lLe(),d=s$s(),u=Jf(Jf({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:FI.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:FI.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:FI.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:FI.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:FI.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:FI.verticalFill,x:ca(s.x)?s.x:d.left,y:ca(s.y)?s.y:d.top,width:ca(s.width)?s.width:d.width,height:ca(s.height)?s.height:d.height}),h=u.x,p=u.y,f=u.width,g=u.height,b=u.syncWithTicks,v=u.horizontalValues,j=u.verticalValues,_=JBs(),S=e$s();if(!ca(f)||f<=0||!ca(g)||g<=0||!ca(h)||h!==+h||!ca(p)||p!==+p)return null;var A=u.verticalCoordinatesGenerator||pUs,T=u.horizontalCoordinatesGenerator||fUs,D=u.horizontalPoints,L=u.verticalPoints;if((!D||!D.length)&&ho(T)){var M=v&&v.length,F=T({yAxis:S?Jf(Jf({},S),{},{ticks:M?v:S.ticks}):void 0,width:o,height:c,offset:d},M?!0:b);kb(Array.isArray(F),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(DM(F),"]")),Array.isArray(F)&&(D=F)}if((!L||!L.length)&&ho(A)){var z=j&&j.length,V=A({xAxis:_?Jf(Jf({},_),{},{ticks:z?j:_.ticks}):void 0,width:o,height:c,offset:d},z?!0:b);kb(Array.isArray(V),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(DM(V),"]")),Array.isArray(V)&&(L=V)}return Nt.createElement("g",{className:"recharts-cartesian-grid"},Nt.createElement(cUs,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Nt.createElement(dUs,aA({},u,{offset:d,horizontalPoints:D,xAxis:_,yAxis:S})),Nt.createElement(uUs,aA({},u,{offset:d,verticalPoints:L,xAxis:_,yAxis:S})),Nt.createElement(hUs,aA({},u,{horizontalPoints:D})),Nt.createElement(mUs,aA({},u,{verticalPoints:L})))}mLe.displayName="CartesianGrid";var xUs=["type","layout","connectNulls","ref"],gUs=["key"];function iD(s){"@babel/helpers - typeof";return iD=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},iD(s)}function rZe(s,t){if(s==null)return{};var n=yUs(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 yUs(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 Az(){return Az=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);nh){f=[].concat(zI(c.slice(0,g)),[h-b]);break}var v=f.length%2===0?[0,p]:[p];return[].concat(zI(t.repeat(c,u)),zI(f),v).map(function(j){return"".concat(j,"px")}).join(", ")}),J1(n,"id",mR("recharts-line-")),J1(n,"pathRef",function(l){n.mainCurve=l}),J1(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),J1(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return TUs(t,s),NUs(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=xy(u,$U);if(!h)return null;var p=function(b,v){return{x:b.x,y:b.y,value:b.value,errorVal:zm(b.payload,v)}},f={clipPath:r?"url(#clipPath-".concat(a,")"):null};return Nt.createElement(Kl,f,h.map(function(g){return Nt.cloneElement(g,{key:"bar-".concat(g.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:p})}))}},{key:"renderDots",value:function(r,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,u=o.dataKey,h=Wi(this.props,!1),p=Wi(c,!0),f=d.map(function(b,v){var j=O0(O0(O0({key:"dot-".concat(v),r:3},h),p),{},{index:v,cx:b.x,cy:b.y,value:b.value,dataKey:u,payload:b.payload,points:d});return t.renderDotItem(c,j)}),g={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Nt.createElement(Kl,Az({className:"recharts-line-dots",key:"dots"},g),f)}},{key:"renderCurveStatically",value:function(r,a,i,l){var o=this.props,c=o.type,d=o.layout,u=o.connectNulls;o.ref;var h=rZe(o,xUs),p=O0(O0(O0({},Wi(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 Nt.createElement(fge,Az({},p,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(r,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,u=l.animationBegin,h=l.animationDuration,p=l.animationEasing,f=l.animationId,g=l.animateNewValues,b=l.width,v=l.height,j=this.state,_=j.prevPoints,S=j.totalLength;return Nt.createElement(Fw,{begin:u,duration:h,isActive:d,easing:p,from:{t:0},to:{t:1},key:"line-".concat(f),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(A){var T=A.t;if(_){var D=_.length/o.length,L=o.map(function(W,K){var Y=Math.floor(K*D);if(_[Y]){var ee=_[Y],ne=Y0(ee.x,W.x),oe=Y0(ee.y,W.y);return O0(O0({},W),{},{x:ne(T),y:oe(T)})}if(g){var pe=Y0(b*2,W.x),ce=Y0(v/2,W.y);return O0(O0({},W),{},{x:pe(T),y:ce(T)})}return O0(O0({},W),{},{x:W.x,y:W.y})});return i.renderCurveStatically(L,r,a)}var M=Y0(0,S),F=M(T),z;if(c){var V="".concat(c).split(/[,\s]+/gim).map(function(W){return parseFloat(W)});z=i.getStrokeDasharray(F,S,V)}else z=i.generateSimpleStrokeDasharray(S,F);return i.renderCurveStatically(o,r,a,{strokeDasharray:z})})}},{key:"renderCurve",value:function(r,a){var i=this.props,l=i.points,o=i.isAnimationActive,c=this.state,d=c.prevPoints,u=c.totalLength;return o&&l&&l.length&&(!d&&u>0||!BU(d,l))?this.renderCurveWithAnimation(r,a):this.renderCurveStatically(l,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,u=a.yAxis,h=a.top,p=a.left,f=a.width,g=a.height,b=a.isAnimationActive,v=a.id;if(i||!o||!o.length)return null;var j=this.state.isAnimationFinished,_=o.length===1,S=So("recharts-line",c),A=d&&d.allowDataOverflow,T=u&&u.allowDataOverflow,D=A||T,L=No(v)?this.id:v,M=(r=Wi(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},F=M.r,z=F===void 0?3:F,V=M.strokeWidth,W=V===void 0?2:V,K=lSs(l)?l:{},Y=K.clipDot,ee=Y===void 0?!0:Y,ne=z*2+W;return Nt.createElement(Kl,{className:S},A||T?Nt.createElement("defs",null,Nt.createElement("clipPath",{id:"clipPath-".concat(L)},Nt.createElement("rect",{x:A?p:p-f/2,y:T?h:h-g/2,width:A?f:f*2,height:T?g:g*2})),!ee&&Nt.createElement("clipPath",{id:"clipPath-dots-".concat(L)},Nt.createElement("rect",{x:p-ne/2,y:h-ne/2,width:f+ne,height:g+ne}))):null,!_&&this.renderCurve(D,L),this.renderErrorBar(D,L),(_||l)&&this.renderDots(D,ee,L),(!b||j)&&aN.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(zI(r),[0]):r,l=[],o=0;os.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function 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}function yqs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function vqs(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&ca(a)&&ca(i)?t.slice(a,i+1):[]};function k_t(s){return s==="number"?[0,"auto"]:void 0}var sTe=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=A1e(n,t);return r<0||!i||!i.length||r>=o.length?null:i.reduce(function(c,d){var u,h=(u=d.props.data)!==null&&u!==void 0?u:n;h&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(h=h.slice(t.dataStartIndex,t.dataEndIndex+1));var p;if(l.dataKey&&!l.allowDuplicatedCategory){var f=h===void 0?o:h;p=Fxe(f,l.dataKey,a)}else p=h&&h[r]||o[r];return p?[].concat(dD(c),[cbt(d,p)]):c},[])},hZe=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=Mqs(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=cRs(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,p=sTe(t,n,u,h),f=Iqs(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:p,activeCoordinate:f}}return null},Pqs=function(t,n){var r=n.axes,a=n.graphicalItems,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,p=t.stackOffset,f=nbt(u,i);return r.reduce(function(g,b){var v,j=b.type.defaultProps!==void 0?or(or({},b.type.defaultProps),b.props):b.props,_=j.type,S=j.dataKey,A=j.allowDataOverflow,T=j.allowDuplicatedCategory,D=j.scale,L=j.ticks,M=j.includeHidden,F=j[l];if(g[F])return g;var z=A1e(t.data,{graphicalItems:a.filter(function(ye){var _e,Me=l in ye.props?ye.props[l]:(_e=ye.type.defaultProps)===null||_e===void 0?void 0:_e[l];return Me===F}),dataStartIndex:c,dataEndIndex:d}),V=z.length,W,K,Y;aqs(j.domain,A,_)&&(W=x5e(j.domain,null,A),f&&(_==="number"||D!=="auto")&&(Y=Sz(z,S,"category")));var ee=k_t(_);if(!W||W.length===0){var ne,oe=(ne=j.domain)!==null&&ne!==void 0?ne:ee;if(S){if(W=Sz(z,S,_),_==="category"&&f){var pe=Xks(W);T&&pe?(K=W,W=kge(0,V)):T||(W=LKe(oe,W,b).reduce(function(ye,_e){return ye.indexOf(_e)>=0?ye:[].concat(dD(ye),[_e])},[]))}else if(_==="category")T?W=W.filter(function(ye){return ye!==""&&!No(ye)}):W=LKe(oe,W,b).reduce(function(ye,_e){return ye.indexOf(_e)>=0||_e===""||No(_e)?ye:[].concat(dD(ye),[_e])},[]);else if(_==="number"){var ce=pRs(z,a.filter(function(ye){var _e,Me,Te=l in ye.props?ye.props[l]:(_e=ye.type.defaultProps)===null||_e===void 0?void 0:_e[l],Ce="hide"in ye.props?ye.props.hide:(Me=ye.type.defaultProps)===null||Me===void 0?void 0:Me.hide;return Te===F&&(M||!Ce)}),S,i,u);ce&&(W=ce)}f&&(_==="number"||D!=="auto")&&(Y=Sz(z,S,"category"))}else f?W=kge(0,V):o&&o[F]&&o[F].hasStack&&_==="number"?W=p==="expand"?[0,1]:lbt(o[F].stackGroups,c,d):W=sbt(z,a.filter(function(ye){var _e=l in ye.props?ye.props[l]:ye.type.defaultProps[l],Me="hide"in ye.props?ye.props.hide:ye.type.defaultProps.hide;return _e===F&&(M||!Me)}),_,u,!0);if(_==="number")W=J5e(h,W,F,i,L),oe&&(W=x5e(oe,W,A));else if(_==="category"&&oe){var de=oe,ie=W.every(function(ye){return de.indexOf(ye)>=0});ie&&(W=de)}}return or(or({},g),{},eo({},F,or(or({},j),{},{axisType:i,domain:W,categoricalDomain:Y,duplicateDomain:K,originalDomain:(v=j.domain)!==null&&v!==void 0?v:ee,isCategorical:f,layout:u})))},{})},Lqs=function(t,n){var r=n.graphicalItems,a=n.Axis,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,p=A1e(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),f=p.length,g=nbt(u,i),b=-1;return r.reduce(function(v,j){var _=j.type.defaultProps!==void 0?or(or({},j.type.defaultProps),j.props):j.props,S=_[l],A=k_t("number");if(!v[S]){b++;var T;return g?T=kge(0,f):o&&o[S]&&o[S].hasStack?(T=lbt(o[S].stackGroups,c,d),T=J5e(h,T,S,i)):(T=x5e(A,sbt(p,r.filter(function(D){var L,M,F=l in D.props?D.props[l]:(L=D.type.defaultProps)===null||L===void 0?void 0:L[l],z="hide"in D.props?D.props.hide:(M=D.type.defaultProps)===null||M===void 0?void 0:M.hide;return F===S&&!z}),"number",u),a.defaultProps.allowDataOverflow),T=J5e(h,T,S,i)),or(or({},v),{},eo({},S,or(or({axisType:i},a.defaultProps),{},{hide:!0,orientation:fy(Eqs,"".concat(i,".").concat(b%2),null),domain:T,originalDomain:A,isCategorical:g,layout:u})))}return v},{})},Dqs=function(t,n){var r=n.axisType,a=r===void 0?"xAxis":r,i=n.AxisComp,l=n.graphicalItems,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.children,h="".concat(a,"Id"),p=xy(u,i),f={};return p&&p.length?f=Pqs(t,{axes:p,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(f=Lqs(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),f},Rqs=function(t){var n=gS(t),r=q2(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:APe(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:hge(n,r)}},mZe=function(t){var n=t.children,r=t.defaultShowTooltip,a=V0(n,eD),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}},Oqs=function(t){return!t||!t.length?!1:t.some(function(n){var r=nN(n&&n.type);return r&&r.indexOf("Bar")>=0})},pZe=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"}},Fqs=function(t,n){var r=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=r.width,u=r.height,h=r.children,p=r.margin||{},f=V0(h,eD),g=V0(h,JA),b=Object.keys(c).reduce(function(T,D){var L=c[D],M=L.orientation;return!L.mirror&&!L.hide?or(or({},T),{},eo({},M,T[M]+L.width)):T},{left:p.left||0,right:p.right||0}),v=Object.keys(l).reduce(function(T,D){var L=l[D],M=L.orientation;return!L.mirror&&!L.hide?or(or({},T),{},eo({},M,fy(T,"".concat(M))+L.height)):T},{top:p.top||0,bottom:p.bottom||0}),j=or(or({},v),b),_=j.bottom;f&&(j.bottom+=f.props.height||eD.defaultProps.height),g&&n&&(j=hRs(j,a,r,n));var S=d-j.left-j.right,A=u-j.top-j.bottom;return or(or({brushBottom:_},j),{},{width:Math.max(S,0),height:Math.max(A,0)})},zqs=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},pLe=function(t){var n=t.chartName,r=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,l=t.validateTooltipEventTypes,o=l===void 0?["axis"]:l,c=t.axisComponents,d=t.legendContent,u=t.formatAxisMap,h=t.defaultProps,p=function(j,_){var S=_.graphicalItems,A=_.stackGroups,T=_.offset,D=_.updateId,L=_.dataStartIndex,M=_.dataEndIndex,F=j.barSize,z=j.layout,V=j.barGap,W=j.barCategoryGap,K=j.maxBarSize,Y=pZe(z),ee=Y.numericAxisName,ne=Y.cateAxisName,oe=Oqs(S),pe=[];return S.forEach(function(ce,de){var ie=A1e(j.data,{graphicalItems:[ce],dataStartIndex:L,dataEndIndex:M}),ye=ce.type.defaultProps!==void 0?or(or({},ce.type.defaultProps),ce.props):ce.props,_e=ye.dataKey,Me=ye.maxBarSize,Te=ye["".concat(ee,"Id")],Ce=ye["".concat(ne,"Id")],Ee={},De=c.reduce(function(rt,tt){var at=_["".concat(tt.axisType,"Map")],Ge=ye["".concat(tt.axisType,"Id")];at&&at[Ge]||tt.axisType==="zAxis"||LM();var dt=at[Ge];return or(or({},rt),{},eo(eo({},tt.axisType,dt),"".concat(tt.axisType,"Ticks"),q2(dt)))},Ee),Ie=De[ne],Fe=De["".concat(ne,"Ticks")],qe=A&&A[Te]&&A[Te].hasStack&&jRs(ce,A[Te].stackGroups),ve=nN(ce.type).indexOf("Bar")>=0,Je=hge(Ie,Fe),we=[],it=oe&&dRs({barSize:F,stackGroups:A,totalSize:zqs(De,ne)});if(ve){var Ne,He,$e=No(Me)?K:Me,Ye=(Ne=(He=hge(Ie,Fe,!0))!==null&&He!==void 0?He:$e)!==null&&Ne!==void 0?Ne:0;we=uRs({barGap:V,barCategoryGap:W,bandSize:Ye!==Je?Ye:Je,sizeList:it[Ce],maxBarSize:$e}),Ye!==Je&&(we=we.map(function(rt){return or(or({},rt),{},{position:or(or({},rt.position),{},{offset:rt.position.offset-Ye/2})})}))}var Ke=ce&&ce.type&&ce.type.getComposedData;Ke&&pe.push({props:or(or({},Ke(or(or({},De),{},{displayedData:ie,props:j,dataKey:_e,item:ce,bandSize:Je,barPosition:we,offset:T,stackedData:qe,layout:z,dataStartIndex:L,dataEndIndex:M}))),{},eo(eo(eo({key:ce.key||"item-".concat(de)},ee,De[ee]),ne,De[ne]),"animationId",D)),childIndex:uSs(ce,j.children),item:ce})}),pe},f=function(j,_){var S=j.props,A=j.dataStartIndex,T=j.dataEndIndex,D=j.updateId;if(!CGe({props:S}))return null;var L=S.children,M=S.layout,F=S.stackOffset,z=S.data,V=S.reverseStackOrder,W=pZe(M),K=W.numericAxisName,Y=W.cateAxisName,ee=xy(L,r),ne=_Rs(z,ee,"".concat(K,"Id"),"".concat(Y,"Id"),F,V),oe=c.reduce(function(ye,_e){var Me="".concat(_e.axisType,"Map");return or(or({},ye),{},eo({},Me,Dqs(S,or(or({},_e),{},{graphicalItems:ee,stackGroups:_e.axisType===K&&ne,dataStartIndex:A,dataEndIndex:T}))))},{}),pe=Fqs(or(or({},oe),{},{props:S,graphicalItems:ee}),_==null?void 0:_.legendBBox);Object.keys(oe).forEach(function(ye){oe[ye]=u(S,oe[ye],pe,ye.replace("Map",""),n)});var ce=oe["".concat(Y,"Map")],de=Rqs(ce),ie=p(S,or(or({},oe),{},{dataStartIndex:A,dataEndIndex:T,updateId:D,graphicalItems:ee,stackGroups:ne,offset:pe}));return or(or({formattedGraphicalItems:ie,graphicalItems:ee,offset:pe,stackGroups:ne},de),oe)},g=function(v){function j(_){var S,A,T;return yqs(this,j),T=_qs(this,j,[_]),eo(T,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),eo(T,"accessibilityManager",new rqs),eo(T,"handleLegendBBoxUpdate",function(D){if(D){var L=T.state,M=L.dataStartIndex,F=L.dataEndIndex,z=L.updateId;T.setState(or({legendBBox:D},f({props:T.props,dataStartIndex:M,dataEndIndex:F,updateId:z},or(or({},T.state),{},{legendBBox:D}))))}}),eo(T,"handleReceiveSyncEvent",function(D,L,M){if(T.props.syncId===D){if(M===T.eventEmitterSymbol&&typeof T.props.syncMethod!="function")return;T.applySyncEvent(L)}}),eo(T,"handleBrushChange",function(D){var L=D.startIndex,M=D.endIndex;if(L!==T.state.dataStartIndex||M!==T.state.dataEndIndex){var F=T.state.updateId;T.setState(function(){return or({dataStartIndex:L,dataEndIndex:M},f({props:T.props,dataStartIndex:L,dataEndIndex:M,updateId:F},T.state))}),T.triggerSyncEvent({dataStartIndex:L,dataEndIndex:M})}}),eo(T,"handleMouseEnter",function(D){var L=T.getMouseInfo(D);if(L){var M=or(or({},L),{},{isTooltipActive:!0});T.setState(M),T.triggerSyncEvent(M);var F=T.props.onMouseEnter;ho(F)&&F(M,D)}}),eo(T,"triggeredAfterMouseMove",function(D){var L=T.getMouseInfo(D),M=L?or(or({},L),{},{isTooltipActive:!0}):{isTooltipActive:!1};T.setState(M),T.triggerSyncEvent(M);var F=T.props.onMouseMove;ho(F)&&F(M,D)}),eo(T,"handleItemMouseEnter",function(D){T.setState(function(){return{isTooltipActive:!0,activeItem:D,activePayload:D.tooltipPayload,activeCoordinate:D.tooltipPosition||{x:D.cx,y:D.cy}}})}),eo(T,"handleItemMouseLeave",function(){T.setState(function(){return{isTooltipActive:!1}})}),eo(T,"handleMouseMove",function(D){D.persist(),T.throttleTriggeredAfterMouseMove(D)}),eo(T,"handleMouseLeave",function(D){T.throttleTriggeredAfterMouseMove.cancel();var L={isTooltipActive:!1};T.setState(L),T.triggerSyncEvent(L);var M=T.props.onMouseLeave;ho(M)&&M(L,D)}),eo(T,"handleOuterEvent",function(D){var L=dSs(D),M=fy(T.props,"".concat(L));if(L&&ho(M)){var F,z;/.*touch.*/i.test(L)?z=T.getMouseInfo(D.changedTouches[0]):z=T.getMouseInfo(D),M((F=z)!==null&&F!==void 0?F:{},D)}}),eo(T,"handleClick",function(D){var L=T.getMouseInfo(D);if(L){var M=or(or({},L),{},{isTooltipActive:!0});T.setState(M),T.triggerSyncEvent(M);var F=T.props.onClick;ho(F)&&F(M,D)}}),eo(T,"handleMouseDown",function(D){var L=T.props.onMouseDown;if(ho(L)){var M=T.getMouseInfo(D);L(M,D)}}),eo(T,"handleMouseUp",function(D){var L=T.props.onMouseUp;if(ho(L)){var M=T.getMouseInfo(D);L(M,D)}}),eo(T,"handleTouchMove",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&T.throttleTriggeredAfterMouseMove(D.changedTouches[0])}),eo(T,"handleTouchStart",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&T.handleMouseDown(D.changedTouches[0])}),eo(T,"handleTouchEnd",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&T.handleMouseUp(D.changedTouches[0])}),eo(T,"handleDoubleClick",function(D){var L=T.props.onDoubleClick;if(ho(L)){var M=T.getMouseInfo(D);L(M,D)}}),eo(T,"handleContextMenu",function(D){var L=T.props.onContextMenu;if(ho(L)){var M=T.getMouseInfo(D);L(M,D)}}),eo(T,"triggerSyncEvent",function(D){T.props.syncId!==void 0&&_Ne.emit(wNe,T.props.syncId,D,T.eventEmitterSymbol)}),eo(T,"applySyncEvent",function(D){var L=T.props,M=L.layout,F=L.syncMethod,z=T.state.updateId,V=D.dataStartIndex,W=D.dataEndIndex;if(D.dataStartIndex!==void 0||D.dataEndIndex!==void 0)T.setState(or({dataStartIndex:V,dataEndIndex:W},f({props:T.props,dataStartIndex:V,dataEndIndex:W,updateId:z},T.state)));else if(D.activeTooltipIndex!==void 0){var K=D.chartX,Y=D.chartY,ee=D.activeTooltipIndex,ne=T.state,oe=ne.offset,pe=ne.tooltipTicks;if(!oe)return;if(typeof F=="function")ee=F(pe,D);else if(F==="value"){ee=-1;for(var ce=0;ce=0){var qe,ve;if(K.dataKey&&!K.allowDuplicatedCategory){var Je=typeof K.dataKey=="function"?Fe:"payload.".concat(K.dataKey.toString());qe=Fxe(ce,Je,ee),ve=de&&ie&&Fxe(ie,Je,ee)}else qe=ce==null?void 0:ce[Y],ve=de&&ie&&ie[Y];if(Ce||Te){var we=D.props.activeIndex!==void 0?D.props.activeIndex:Y;return[N.cloneElement(D,or(or(or({},F.props),De),{},{activeIndex:we})),null,null]}if(!No(qe))return[Ie].concat(dD(T.renderActivePoints({item:F,activePoint:qe,basePoint:ve,childIndex:Y,isRange:de})))}else{var it,Ne=(it=T.getItemByXY(T.state.activeCoordinate))!==null&&it!==void 0?it:{graphicalItem:Ie},He=Ne.graphicalItem,$e=He.item,Ye=$e===void 0?D:$e,Ke=He.childIndex,rt=or(or(or({},F.props),De),{},{activeIndex:Ke});return[N.cloneElement(Ye,rt),null,null]}return de?[Ie,null,null]:[Ie,null]}),eo(T,"renderCustomized",function(D,L,M){return N.cloneElement(D,or(or({key:"recharts-customized-".concat(M)},T.props),T.state))}),eo(T,"renderMap",{CartesianGrid:{handler:hG,once:!0},ReferenceArea:{handler:T.renderReferenceElement},ReferenceLine:{handler:hG},ReferenceDot:{handler:T.renderReferenceElement},XAxis:{handler:hG},YAxis:{handler:hG},Brush:{handler:T.renderBrush,once:!0},Bar:{handler:T.renderGraphicChild},Line:{handler:T.renderGraphicChild},Area:{handler:T.renderGraphicChild},Radar:{handler:T.renderGraphicChild},RadialBar:{handler:T.renderGraphicChild},Scatter:{handler:T.renderGraphicChild},Pie:{handler:T.renderGraphicChild},Funnel:{handler:T.renderGraphicChild},Tooltip:{handler:T.renderCursor,once:!0},PolarGrid:{handler:T.renderPolarGrid,once:!0},PolarAngleAxis:{handler:T.renderPolarAxis},PolarRadiusAxis:{handler:T.renderPolarAxis},Customized:{handler:T.renderCustomized}}),T.clipPathId="".concat((S=_.id)!==null&&S!==void 0?S:mR("recharts"),"-clip"),T.throttleTriggeredAfterMouseMove=Jvt(T.triggeredAfterMouseMove,(A=_.throttleDelay)!==null&&A!==void 0?A:1e3/60),T.state={},T}return Nqs(j,v),bqs(j,[{key:"componentDidMount",value:function(){var S,A;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(S=this.props.margin.left)!==null&&S!==void 0?S:0,top:(A=this.props.margin.top)!==null&&A!==void 0?A:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var S=this.props,A=S.children,T=S.data,D=S.height,L=S.layout,M=V0(A,kp);if(M){var F=M.props.defaultIndex;if(!(typeof F!="number"||F<0||F>this.state.tooltipTicks.length-1)){var z=this.state.tooltipTicks[F]&&this.state.tooltipTicks[F].value,V=sTe(this.state,T,F,z),W=this.state.tooltipTicks[F].coordinate,K=(this.state.offset.top+D)/2,Y=L==="horizontal",ee=Y?{x:W,y:K}:{y:W,x:K},ne=this.state.formattedGraphicalItems.find(function(pe){var ce=pe.item;return ce.type.name==="Scatter"});ne&&(ee=or(or({},ee),ne.props.points[F].tooltipPosition),V=ne.props.points[F].tooltipPayload);var oe={activeTooltipIndex:F,isTooltipActive:!0,activeLabel:z,activePayload:V,activeCoordinate:ee};this.setState(oe),this.renderCursor(M),this.accessibilityManager.setIndex(F)}}}},{key:"getSnapshotBeforeUpdate",value:function(S,A){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==A.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==S.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==S.margin){var T,D;this.accessibilityManager.setDetails({offset:{left:(T=this.props.margin.left)!==null&&T!==void 0?T:0,top:(D=this.props.margin.top)!==null&&D!==void 0?D:0}})}return null}},{key:"componentDidUpdate",value:function(S){M3e([V0(S.children,kp)],[V0(this.props.children,kp)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var S=V0(this.props.children,kp);if(S&&typeof S.props.shared=="boolean"){var A=S.props.shared?"axis":"item";return o.indexOf(A)>=0?A:i}return i}},{key:"getMouseInfo",value:function(S){if(!this.container)return null;var A=this.container,T=A.getBoundingClientRect(),D=OIs(T),L={chartX:Math.round(S.pageX-D.left),chartY:Math.round(S.pageY-D.top)},M=T.width/A.offsetWidth||1,F=this.inRange(L.chartX,L.chartY,M);if(!F)return null;var z=this.state,V=z.xAxisMap,W=z.yAxisMap,K=this.getTooltipEventType(),Y=hZe(this.state,this.props.data,this.props.layout,F);if(K!=="axis"&&V&&W){var ee=gS(V).scale,ne=gS(W).scale,oe=ee&&ee.invert?ee.invert(L.chartX):null,pe=ne&&ne.invert?ne.invert(L.chartY):null;return or(or({},L),{},{xValue:oe,yValue:pe},Y)}return Y?or(or({},L),Y):null}},{key:"inRange",value:function(S,A){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,D=this.props.layout,L=S/T,M=A/T;if(D==="horizontal"||D==="vertical"){var F=this.state.offset,z=L>=F.left&&L<=F.left+F.width&&M>=F.top&&M<=F.top+F.height;return z?{x:L,y:M}:null}var V=this.state,W=V.angleAxisMap,K=V.radiusAxisMap;if(W&&K){var Y=gS(W);return OKe({x:L,y:M},Y)}return null}},{key:"parseEventsOfWrapper",value:function(){var S=this.props.children,A=this.getTooltipEventType(),T=V0(S,kp),D={};T&&A==="axis"&&(T.props.trigger==="click"?D={onClick:this.handleClick}:D={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var L=zxe(this.props,this.handleOuterEvent);return or(or({},L),D)}},{key:"addListener",value:function(){_Ne.on(wNe,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){_Ne.removeListener(wNe,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(S,A,T){for(var D=this.state.formattedGraphicalItems,L=0,M=D.length;L{const{data:_,error:S}=await q.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(S)throw S;return _}}),{data:r}=lt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:_,error:S}=await q.from("profiles").select("id, name, email");if(S)throw S;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((_,S)=>_+(S.sent_count||0),0),o=a.reduce((_,S)=>_+(S.open_count||0),0),c=a.reduce((_,S)=>_+(S.click_count||0),0),d=a.reduce((_,S)=>_+(S.bounce_count||0),0),u=a.reduce((_,S)=>_+(S.complaint_count||0),0),h=l>0?(o/l*100).toFixed(1):"0.0",p=l>0?(c/l*100).toFixed(1):"0.0",f=[{label:"Campaigns Sent",value:a.length,icon:cr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:_n,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:Ir,color:"text-blue-600"},{label:"Avg Click Rate",value:`${p}%`,icon:Fm,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:Dl,color:"text-orange-600"},{label:"Complaints",value:u,icon:mo,color:"text-destructive"}],g=new Map;a.forEach(_=>{var T,D;const S=_.user_id,A=g.get(S)||{name:((T=i.get(S))==null?void 0:T.name)||((D=i.get(S))==null?void 0:D.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};A.campaigns++,A.sent+=_.sent_count||0,A.opens+=_.open_count||0,A.clicks+=_.click_count||0,g.set(S,A)});const b=[...g.entries()].map(([_,S])=>({id:_,...S,openRate:S.sent>0?+(S.opens/S.sent*100).toFixed(1):0})).sort((_,S)=>S.sent-_.sent),v=b.slice(0,6).map(_=>({name:_.name,value:_.sent})),j=a.map(_=>{var S;return{name:_.name.length>20?_.name.slice(0,20)+"…":_.name,agent:((S=i.get(_.user_id))==null?void 0:S.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?ks(new Date(_.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(cr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No campaigns sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Campaign analytics will appear here after the first send."})]})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:f.map(_=>e.jsx(fe,{children:e.jsxs(Ae,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Ae,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(Sw,{width:"100%",height:"100%",children:e.jsxs(xLe,{data:j,children:[e.jsx(Bw,{dataKey:"date",fontSize:11}),e.jsx($w,{fontSize:11,unit:"%"}),e.jsx(kp,{formatter:_=>`${_}%`}),e.jsx(zw,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(zw,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Ae,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(Sw,{width:"100%",height:"100%",children:e.jsxs(gLe,{children:[e.jsx(Bb,{data:v,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:_,percent:S})=>`${_} (${(S*100).toFixed(0)}%)`,fontSize:11,children:v.map((_,S)=>e.jsx(gR,{fill:fZe[S%fZe.length]},S))}),e.jsx(kp,{})]})})})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Ae,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(Sw,{width:"100%",height:"100%",children:e.jsxs(fLe,{data:j,children:[e.jsx(Bw,{dataKey:"date",fontSize:11}),e.jsx($w,{fontSize:11}),e.jsx(kp,{}),e.jsx(i6,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Agent Performance"})}),e.jsx(Ae,{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:b.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(ze,{variant:"outline",children:[_.openRate,"%"]})})]},_.id))})]})})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Ae,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((_,S)=>{const A=_.sent_count>0?_.open_count/_.sent_count:0;return(S.sent_count>0?S.open_count/S.sent_count:0)-A}).slice(0,10).map((_,S)=>{const A=_.sent_count>0?(_.open_count/_.sent_count*100).toFixed(1):"0.0",T=_.sent_count>0?(_.click_count/_.sent_count*100).toFixed(1):"0.0",D=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:["#",S+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:[(D==null?void 0:D.name)||"Unknown"," · ",_.sent_at?ks(new Date(_.sent_at),"MMM d, yyyy"):""," · ",_.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Ir,{className:"h-3 w-3"})," ",A,"%"]}),e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Fm,{className:"h-3 w-3"})," ",T,"%"]})]})]},_.id)})})})]})]})})}const $qs=()=>{const{toast:s}=Ua(),[t,n]=N.useState(!0),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});N.useEffect(()=>{d()},[]);const d=async()=>{try{n(!0);const u=new Date;u.setDate(u.getDate()-30);const h=u.toISOString(),{data:p}=await q.from("website_apps").select("slug, name").order("sort_order"),f=[];let g=0;for(;;){const{data:T,error:D}=await q.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(g,g+999);if(D)throw D;if(f.push(...T||[]),!T||T.length<1e3)break;g+=1e3}const b=[];for(g=0;;){const{data:T,error:D}=await q.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(D)throw D;if(b.push(...T||[]),!T||T.length<1e3||(g+=1e3,g>2e4))break}const v=new Map;for(const T of p||[])v.set(T.slug,{app_slug:T.slug,app_name:T.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const T of f){const D=v.get(T.app_slug);D&&(D.installs+=1,T.enabled&&(D.enabled+=1))}for(const T of b){const D=v.get(T.app_slug);D&&(T.event_type==="impression"?D.impressions+=1:T.event_type==="expand"?D.expands+=1:T.event_type==="cta_click"?D.cta_clicks+=1:T.event_type==="lead_capture"&&(D.lead_captures+=1))}const j=new Map;for(const T of f){if(!T.enabled)continue;const D=j.get(T.user_id)||{user_id:T.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};D.apps_enabled.includes(T.app_slug)||D.apps_enabled.push(T.app_slug),j.set(T.user_id,D)}for(const T of b){const D=j.get(T.user_id);D&&(D.events_30d+=1,T.event_type==="lead_capture"&&(D.leads_30d+=1))}const _=Array.from(j.keys());if(_.length>0){const{data:T}=await q.from("profiles").select("id, name, email").in("id",_);for(const D of T||[]){const L=j.get(D.id);L&&(L.name=D.name,L.email=D.email)}}const S=Array.from(v.values()),A=Array.from(j.values()).sort((T,D)=>D.events_30d-T.events_30d);a(S),l(A),c({installs:S.reduce((T,D)=>T+D.enabled,0),activeAgents:A.length,impressions30d:S.reduce((T,D)=>T+D.impressions,0),leads30d:S.reduce((T,D)=>T+D.lead_captures,0)})}catch(u){console.error(u),s({title:"Error",description:u.message||"Failed to load website app analytics",variant:"destructive"})}finally{n(!1)}};return t?e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(lc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.installs}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Apps turned on across all agents"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(_n,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"At least one app enabled"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(Ir,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.impressions30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Widget views on lead sites"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(Hs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.leads30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total submissions"})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"App Performance (last 30 days)"})}),e.jsx(Ae,{children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"App"}),e.jsx(Ct,{className:"text-right",children:"Installs"}),e.jsx(Ct,{className:"text-right",children:"Enabled"}),e.jsx(Ct,{className:"text-right",children:"Impressions"}),e.jsx(Ct,{className:"text-right",children:"Expands"}),e.jsx(Ct,{className:"text-right",children:"CTA Clicks"}),e.jsx(Ct,{className:"text-right",children:"Leads"}),e.jsx(Ct,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(pa,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:u.app_name}),e.jsx(ut,{className:"text-right",children:u.installs}),e.jsx(ut,{className:"text-right",children:u.enabled}),e.jsx(ut,{className:"text-right",children:u.impressions}),e.jsx(ut,{className:"text-right",children:u.expands}),e.jsx(ut,{className:"text-right",children:u.cta_clicks}),e.jsx(ut,{className:"text-right font-semibold",children:u.lead_captures}),e.jsx(ut,{className:"text-right text-muted-foreground",children:h==="—"?"—":`${h}%`})]},u.app_slug)}),r.length===0&&e.jsx(Gs,{children:e.jsx(ut,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Ae,{children:[e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Apps Enabled"}),e.jsx(Ct,{className:"text-right",children:"Events (30d)"}),e.jsx(Ct,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(pa,{children:[i.slice(0,100).map(u=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:u.name||"—"}),e.jsx(ut,{className:"text-muted-foreground",children:u.email||"—"}),e.jsx(ut,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:u.apps_enabled.map(h=>e.jsx(ze,{variant:"secondary",className:"text-xs",children:h},h))})}),e.jsx(ut,{className:"text-right",children:u.events_30d}),e.jsx(ut,{className:"text-right font-semibold",children:u.leads_30d})]},u.user_id)),i.length===0&&e.jsx(Gs,{children:e.jsx(ut,{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."]})]})]})]})},Uqs=()=>{const[s,t]=N.useState([]),[n,r]=N.useState([]),[a,i]=N.useState({}),[l,o]=N.useState(!0);N.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:h},{data:p}]=await Promise.all([q.rpc("get_extension_usage_summary"),q.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),f=h||[],g=p||[];t(f),r(g);const b=Array.from(new Set(g.map(v=>v.user_id)));if(b.length){const{data:v}=await q.from("profiles").select("id, name, email").in("id",b),j={};(v||[]).forEach(_=>{j[_.id]={name:_.name,email:_.email}}),i(j)}}finally{o(!1)}},d=s.reduce((h,p)=>({users:h.users+1,contacts:h.contacts+Number(p.contacts_saved||0),listings:h.listings+Number(p.listings_imported||0),activities:h.activities+Number(p.activities_logged||0),events:h.events+Number(p.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});const u=h=>{switch(h){case"contact_saved":return"Contact saved";case"listing_imported":return"Listing imported";case"activity_logged":return"Activity logged";case"template_used":return"Template used";case"paired":return"Extension paired";default:return h}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(_n,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.users}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Using extension"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(kA,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.events}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All events"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(zr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(Ci,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Users by Extension Activity"})}),e.jsx(Ae,{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(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"User"}),e.jsx(Ct,{className:"text-right",children:"Total"}),e.jsx(Ct,{className:"text-right",children:"Contacts"}),e.jsx(Ct,{className:"text-right",children:"Listings"}),e.jsx(Ct,{className:"text-right",children:"Activities"}),e.jsx(Ct,{children:"First Used"}),e.jsx(Ct,{children:"Last Used"})]})}),e.jsx(pa,{children:s.map(h=>e.jsxs(Gs,{children:[e.jsxs(ut,{children:[e.jsx("div",{className:"font-medium",children:h.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]}),e.jsx(ut,{className:"text-right font-medium",children:h.total_events}),e.jsx(ut,{className:"text-right",children:h.contacts_saved}),e.jsx(ut,{className:"text-right",children:h.listings_imported}),e.jsx(ut,{className:"text-right",children:h.activities_logged}),e.jsx(ut,{className:"text-xs text-muted-foreground",children:h.first_event_at?ks(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(ut,{className:"text-xs text-muted-foreground",children:h.last_event_at?ks(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Recent Activity"})}),e.jsx(Ae,{children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No recent events."}):e.jsx("div",{className:"space-y-2",children:n.map(h=>{const p=a[h.user_id];return e.jsxs("div",{className:"flex items-center justify-between border-b pb-2 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ze,{variant:"secondary",children:u(h.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(p==null?void 0:p.name)||(p==null?void 0:p.email)||h.user_id.slice(0,8)}),h.metadata&&Object.keys(h.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(h.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ks(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},qqs=()=>e.jsx(Cs,{title:"Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Analytics & Activity"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Platform-wide usage statistics and user activity"})]}),e.jsxs($r,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"analytics",children:"Analytics"}),e.jsx(Zt,{value:"website-apps",children:"Website Apps"}),e.jsx(Zt,{value:"extension",children:"Chrome Extension"}),e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Zt,{value:"activity",children:"Activity"}),e.jsx(Zt,{value:"shares",children:"Shares"})]}),e.jsx(ls,{value:"analytics",className:"space-y-4",children:e.jsx(fjs,{})}),e.jsx(ls,{value:"website-apps",className:"space-y-4",children:e.jsx($qs,{})}),e.jsx(ls,{value:"extension",className:"space-y-4",children:e.jsx(Uqs,{})}),e.jsx(ls,{value:"content",className:"space-y-4",children:e.jsx(gjs,{})}),e.jsx(ls,{value:"email-campaigns",className:"space-y-4",children:e.jsx(Bqs,{})}),e.jsx(ls,{value:"activity",className:"space-y-4",children:e.jsx(pjs,{})}),e.jsx(ls,{value:"shares",className:"space-y-4",children:e.jsx(Fyt,{})})]})]})});function Vqs(){const s=Gt(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,p]=N.useState([]),[f,g]=N.useState([]),[b,v]=N.useState([]),[j,_]=N.useState(!1),[S,A]=N.useState(null),[T,D]=N.useState(""),{data:L,isLoading:M}=lt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:ve,error:Je}=await q.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Je)throw Je;return ve}}),{data:F}=lt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:ve,error:Je}=await q.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Je)throw Je;return ve}}),{data:z}=lt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:ve,error:Je}=await q.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Je)throw Je;return ve}}),{data:V}=lt({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:ve,error:Je}=await q.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Je)throw Je;return ve}}),{data:W,isLoading:K}=lt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:ve,error:Je}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Je)throw Je;return ve}}),Y=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),p([]),g([]),v([]),a(null),D("")},ee=ve=>{a(ve),l({title:ve.title,description:ve.description||"",publish_date:ve.publish_date.split("T")[0],is_published:ve.is_published,category_id:ve.category_id||""}),u(ve.preview_image_url||""),D("");const Je=(F==null?void 0:F.filter(Ne=>Ne.resource_id===ve.id))||[];p(Je.map(Ne=>({id:Ne.id,name:Ne.name,file_url:Ne.file_url,file_size:Ne.file_size,sort_order:Ne.sort_order})));const we=(z==null?void 0:z.filter(Ne=>Ne.resource_id===ve.id))||[];g(we.map(Ne=>({id:Ne.id,title:Ne.title,video_url:Ne.video_url,sort_order:Ne.sort_order})));const it=(V==null?void 0:V.filter(Ne=>Ne.resource_id===ve.id))||[];v(it.map(Ne=>({id:Ne.id,title:Ne.title,canva_share_link:Ne.canva_share_link,sort_order:Ne.sort_order}))),n(!0)},ne=ve=>{var we;const Je=(we=ve.target.files)==null?void 0:we[0];Je&&(c(Je),u(URL.createObjectURL(Je)))},oe=()=>{p([...h,{name:"",file_url:"",sort_order:h.length}])},pe=ve=>{p(h.filter((Je,we)=>we!==ve))},ce=(ve,Je,we)=>{const it=[...h];if(Je==="file"&&we instanceof File){const Ne=we.name.replace(/\.[^/.]+$/,"");it[ve]={...it[ve],file:we,file_size:we.size,name:it[ve].name||Ne}}else it[ve]={...it[ve],[Je]:we};p(it)},de=()=>{g([...f,{title:"",video_url:"",sort_order:f.length}])},ie=ve=>{g(f.filter((Je,we)=>we!==ve))},ye=(ve,Je,we)=>{const it=[...f];Je==="file"&&we instanceof File?it[ve]={...it[ve],file:we}:it[ve]={...it[ve],[Je]:we},g(it)},_e=()=>{v([...b,{title:"",canva_share_link:"",sort_order:b.length}])},Me=ve=>{v(b.filter((Je,we)=>we!==ve))},Te=(ve,Je,we)=>{const it=[...b];it[ve]={...it[ve],[Je]:we},v(it)},Ce=async(ve,Je)=>{try{const we=await q.functions.invoke("bunny-upload",{body:{action:"create",title:ve.name}});if(we.error)throw we.error;const{videoId:it,uploadUrl:Ne,libraryId:He}=we.data,$e=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:it,libraryId:He}});if($e.error)throw $e.error;const{uploadUrl:Ye,apiKey:Ke}=$e.data,rt=new XMLHttpRequest;return rt.open("PUT",Ye,!0),rt.setRequestHeader("AccessKey",Ke),rt.upload.onprogress=tt=>{if(tt.lengthComputable){const at=Math.round(tt.loaded/tt.total*100),Ge=[...f];Ge[Je]={...Ge[Je],uploadProgress:at},g(Ge)}},await new Promise((tt,at)=>{rt.onload=()=>rt.status>=200&&rt.status<300?tt():at(new Error("Upload failed")),rt.onerror=()=>at(new Error("Upload failed")),rt.send(ve)}),`https://iframe.mediadelivery.net/embed/${He}/${it}`}catch(we){throw console.error("Bunny upload error:",we),we}},Ee=gt({mutationFn:async ve=>{const{data:Je,error:we}=await q.from("brokerage_resource_categories").insert({name:ve,sort_order:(W==null?void 0:W.length)||0}).select().single();if(we)throw we;return Je},onSuccess:ve=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:ve.id}),D(""),ae.success("Category created")},onError:ve=>{ae.error("Failed to create category: "+ve.message)}}),De=gt({mutationFn:async()=>{_(!0);let ve=(r==null?void 0:r.preview_image_url)||null;if(o){const it=o.name.split(".").pop(),Ne=`${Date.now()}.${it}`,{error:He}=await q.storage.from("brokerage-resources").upload(`previews/${Ne}`,o);if(He)throw He;const{data:$e}=q.storage.from("brokerage-resources").getPublicUrl(`previews/${Ne}`);ve=$e.publicUrl}const Je={title:i.title,description:i.description||null,preview_image_url:ve,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let we;if(r){const{error:it}=await q.from("brokerage_resources").update(Je).eq("id",r.id);if(it)throw it;we=r.id;const Ne=(F==null?void 0:F.filter(dt=>dt.resource_id===r.id).map(dt=>dt.id))||[],He=h.filter(dt=>dt.id).map(dt=>dt.id),$e=Ne.filter(dt=>!He.includes(dt));$e.length>0&&await q.from("brokerage_resource_pdfs").delete().in("id",$e);const Ye=(z==null?void 0:z.filter(dt=>dt.resource_id===r.id).map(dt=>dt.id))||[],Ke=f.filter(dt=>dt.id).map(dt=>dt.id),rt=Ye.filter(dt=>!Ke.includes(dt));rt.length>0&&await q.from("brokerage_resource_videos").delete().in("id",rt);const tt=(V==null?void 0:V.filter(dt=>dt.resource_id===r.id).map(dt=>dt.id))||[],at=b.filter(dt=>dt.id).map(dt=>dt.id),Ge=tt.filter(dt=>!at.includes(dt));Ge.length>0&&await q.from("brokerage_resource_links").delete().in("id",Ge)}else{const{data:it,error:Ne}=await q.from("brokerage_resources").insert(Je).select().single();if(Ne)throw Ne;we=it.id}for(let it=0;it{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ae.success(r?"Resource updated":"Resource created"),n(!1),Y(),_(!1)},onError:ve=>{ae.error("Failed to save resource: "+ve.message),_(!1)}}),Ie=gt({mutationFn:async ve=>{const{error:Je}=await q.from("brokerage_resources").delete().eq("id",ve);if(Je)throw Je},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ae.success("Resource deleted")},onError:ve=>{ae.error("Failed to delete: "+ve.message)}}),Fe=ve=>{if(ve.preventDefault(),!i.title){ae.error("Please enter a title");return}De.mutate()},qe=ve=>{const Je=(F==null?void 0:F.filter(Ne=>Ne.resource_id===ve).length)||0,we=(z==null?void 0:z.filter(Ne=>Ne.resource_id===ve).length)||0,it=(V==null?void 0:V.filter(Ne=>Ne.resource_id===ve).length)||0;return{pdfCount:Je,videoCount:we,linkCount:it}};return e.jsx(Cs,{title:"Brokerage Resources Management",description:"Create and manage resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:(L==null?void 0:L.length)||0})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:(L==null?void 0:L.filter(ve=>ve.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{Y(),n(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Category"}),e.jsx(Ct,{children:"Content"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:M?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(L==null?void 0:L.length)===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):L==null?void 0:L.map(ve=>{const{pdfCount:Je,videoCount:we,linkCount:it}=qe(ve.id),Ne=W==null?void 0:W.find(He=>He.id===ve.category_id);return e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ve.preview_image_url?e.jsx("img",{src:ve.preview_image_url,alt:ve.title,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Vm,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ve.title}),ve.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ve.description})]})]})}),e.jsx(ut,{children:Ne?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Ne.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ut,{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(Nr,{className:"h-3.5 w-3.5"}),Je]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vr,{className:"h-3.5 w-3.5"}),we]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tl,{className:"h-3.5 w-3.5"}),it]})]})}),e.jsx(ut,{children:ks(new Date(ve.publish_date),"MMM d, yyyy")}),e.jsx(ut,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ve.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ve.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{const He=(F==null?void 0:F.filter(Ke=>Ke.resource_id===ve.id))||[],$e=(z==null?void 0:z.filter(Ke=>Ke.resource_id===ve.id))||[],Ye=(V==null?void 0:V.filter(Ke=>Ke.resource_id===ve.id))||[];A({...ve,pdfs:He,videos:$e,links:Ye})},children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ee(ve),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource?")&&Ie.mutate(ve.id)},children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},ve.id)})})]})})}),e.jsx(bs,{open:t,onOpenChange:n,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Fe,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(Vm,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(ge,{type:"file",accept:"image/*",onChange:ne})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ge,{id:"title",value:i.title,onChange:ve=>l({...i,title:ve.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(mh,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:i.category_id,onValueChange:ve=>l({...i,category_id:ve}),children:[e.jsx(cs,{className:"flex-1",children:e.jsx(hs,{placeholder:"Select a category"})}),e.jsx(ds,{children:W==null?void 0:W.map(ve=>e.jsx(Ze,{value:ve.id,children:ve.name},ve.id))})]}),i.category_id&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(Fn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{placeholder:"Or create new category...",value:T,onChange:ve=>D(ve.target.value),className:"flex-1"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:!T.trim()||Ee.isPending,onClick:()=>Ee.mutate(T.trim()),children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Db,{content:i.description,onChange:ve=>l({...i,description:ve}),placeholder:"Brief description of this resource",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ge,{id:"publish_date",type:"date",value:i.publish_date,onChange:ve=>l({...i,publish_date:ve.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(vn,{checked:i.is_published,onCheckedChange:ve=>l({...i,is_published:ve})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:i.is_published?"Visible to brokerage managers":"Hidden from brokerage managers"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Nr,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:oe,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((ve,Je)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(ge,{placeholder:"PDF Name",value:ve.name,onChange:we=>ce(Je,"name",we.target.value),className:"flex-1"}),e.jsx(ge,{type:"file",accept:".pdf",onChange:we=>{var Ne;const it=(Ne=we.target.files)==null?void 0:Ne[0];it&&ce(Je,"file",it)},className:"flex-1"}),ve.file_url&&!ve.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>pe(Je),children:e.jsx(Fn,{className:"h-4 w-4"})})]},Je))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-4 w-4"}),"Videos (",f.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:de,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),f.map((ve,Je)=>e.jsxs("div",{className:"space-y-2 p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{placeholder:"Video Title",value:ve.title,onChange:we=>ye(Je,"title",we.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>ie(Je),children:e.jsx(Fn,{className:"h-4 w-4"})})]}),e.jsx(ge,{type:"file",accept:"video/*",onChange:we=>{var Ne;const it=(Ne=we.target.files)==null?void 0:Ne[0];it&&ye(Je,"file",it)}}),ve.uploadProgress!==void 0&&ve.uploadProgress>0&&e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${ve.uploadProgress}%`}})}),ve.video_url&&!ve.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Je))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(tl,{className:"h-4 w-4"}),"Canva Links (",b.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:_e,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),b.map((ve,Je)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(ge,{placeholder:"Link Title",value:ve.title,onChange:we=>Te(Je,"title",we.target.value),className:"flex-1"}),e.jsx(ge,{placeholder:"Canva Share Link",value:ve.canva_share_link,onChange:we=>Te(Je,"canva_share_link",we.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>Me(Je),children:e.jsx(Fn,{className:"h-4 w-4"})})]},Je))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:De.isPending||j,children:De.isPending||j?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(bs,{open:!!S,onOpenChange:()=>A(null),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:S==null?void 0:S.title})}),S&&e.jsxs("div",{className:"space-y-4",children:[S.preview_image_url&&e.jsx("img",{src:S.preview_image_url,alt:S.title,className:"w-full h-48 object-cover rounded-lg"}),S.description&&e.jsx("p",{className:"text-muted-foreground",children:S.description}),S.pdfs&&S.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Nr,{className:"h-4 w-4"}),"PDF Documents (",S.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:S.pdfs.map(ve=>e.jsx("a",{href:ve.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ve.name},ve.id))})]}),S.videos&&S.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(vr,{className:"h-4 w-4"}),"Videos (",S.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:S.videos.map(ve=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:ve.title})},ve.id))})]}),S.links&&S.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(tl,{className:"h-4 w-4"}),"Canva Links (",S.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:S.links.map(ve=>e.jsx("a",{href:ve.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ve.title},ve.id))})]})]})]})})]})})}const S_t=[{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 Hqs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,b]=N.useState(""),[v,j]=N.useState(""),[_,S]=N.useState(""),[A,T]=N.useState(""),[D,L]=N.useState("Learn More"),[M,F]=N.useState("top"),[z,V]=N.useState(""),[W,K]=N.useState(!0),[Y,ee]=N.useState(""),[ne,oe]=N.useState("");N.useEffect(()=>{pe()},[]);const pe=async()=>{try{const{data:Ee,error:De}=await q.from("dashboard_banners").select("*").order("placement").order("sort_order");if(De)throw De;t(Ee||[])}catch(Ee){ae.error("Failed to load banners: "+Ee.message)}finally{r(!1)}},ce=()=>{b(""),j(""),S(""),T(""),L("Learn More"),F("top"),V(""),K(!0),ee(""),oe(""),d(null)},de=Ee=>{d(Ee),b(Ee.title),j(Ee.description||""),S(Ee.image_url),T(Ee.link_url||""),L(Ee.link_text||"Learn More"),F(Ee.placement),V(Ee.section_after||""),K(Ee.is_active),ee(Ee.start_date?ks(new Date(Ee.start_date),"yyyy-MM-dd'T'HH:mm"):""),oe(Ee.end_date?ks(new Date(Ee.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},ie=async Ee=>{var Ie;const De=(Ie=Ee.target.files)==null?void 0:Ie[0];if(De){h(!0);try{const Fe=De.name.split(".").pop(),qe=`${Date.now()}.${Fe}`,{error:ve}=await q.storage.from("banner-images").upload(qe,De);if(ve)throw ve;const{data:{publicUrl:Je}}=q.storage.from("banner-images").getPublicUrl(qe);S(Je),ae.success("Image uploaded successfully")}catch(Fe){ae.error("Failed to upload image: "+Fe.message)}finally{h(!1)}}},ye=async()=>{if(!g.trim()||!_){ae.error("Please fill in required fields (title and image)");return}f(!0);try{const Ee={title:g.trim(),description:v.trim()||null,image_url:_,link_url:A.trim()||null,link_text:D.trim()||"Learn More",placement:M,section_after:M==="between"?z:null,is_active:W,start_date:Y?new Date(Y).toISOString():null,end_date:ne?new Date(ne).toISOString():null};if(c){const{error:De}=await q.from("dashboard_banners").update(Ee).eq("id",c.id);if(De)throw De;ae.success("Banner updated successfully")}else{const De=s.filter(Fe=>Fe.placement===M).length,{error:Ie}=await q.from("dashboard_banners").insert({...Ee,sort_order:De});if(Ie)throw Ie;ae.success("Banner created successfully")}i(!1),ce(),pe()}catch(Ee){ae.error("Failed to save banner: "+Ee.message)}finally{f(!1)}},_e=async()=>{if(c)try{const{error:Ee}=await q.from("dashboard_banners").delete().eq("id",c.id);if(Ee)throw Ee;ae.success("Banner deleted successfully"),o(!1),d(null),pe()}catch(Ee){ae.error("Failed to delete banner: "+Ee.message)}},Me=async Ee=>{try{const{error:De}=await q.from("dashboard_banners").update({is_active:!Ee.is_active}).eq("id",Ee.id);if(De)throw De;ae.success(Ee.is_active?"Banner deactivated":"Banner activated"),pe()}catch(De){ae.error("Failed to update banner: "+De.message)}},Te=s.filter(Ee=>Ee.placement==="top"),Ce=s.filter(Ee=>Ee.placement==="between");return n?e.jsx(Cs,{title:"Dashboard Management",children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):e.jsxs(Cs,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(nl,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(Hn,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(bs,{open:a&&M==="top",onOpenChange:Ee=>{Ee||ce(),i(Ee),Ee&&F("top")},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ce(),F("top")},children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Qn,{children:"Configure the banner's content and display settings"})]}),e.jsx(xZe,{title:g,setTitle:b,description:v,setDescription:j,imageUrl:_,linkUrl:A,setLinkUrl:T,linkText:D,setLinkText:L,placement:M,setPlacement:F,sectionAfter:z,setSectionAfter:V,isActive:W,setIsActive:K,startDate:Y,setStartDate:ee,endDate:ne,setEndDate:oe,handleImageUpload:ie,uploading:u,showPlacementOptions:!1}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ce()},children:"Cancel"}),e.jsx(B,{onClick:ye,disabled:p,children:p?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Ae,{children:Te.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:Te.map(Ee=>e.jsx(gZe,{banner:Ee,onEdit:()=>de(Ee),onDelete:()=>{d(Ee),o(!0)},onToggleActive:()=>Me(Ee)},Ee.id))})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(nl,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(Hn,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(bs,{open:a&&M==="between",onOpenChange:Ee=>{Ee||ce(),i(Ee),Ee&&F("between")},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ce(),F("between")},children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Qn,{children:"Configure where this banner appears between sections"})]}),e.jsx(xZe,{title:g,setTitle:b,description:v,setDescription:j,imageUrl:_,linkUrl:A,setLinkUrl:T,linkText:D,setLinkText:L,placement:M,setPlacement:F,sectionAfter:z,setSectionAfter:V,isActive:W,setIsActive:K,startDate:Y,setStartDate:ee,endDate:ne,setEndDate:oe,handleImageUpload:ie,uploading:u,showPlacementOptions:!0}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ce()},children:"Cancel"}),e.jsx(B,{onClick:ye,disabled:p,children:p?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Ae,{children:Ce.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No section banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:Ce.map(Ee=>e.jsx(gZe,{banner:Ee,onEdit:()=>de(Ee),onDelete:()=>{d(Ee),o(!0)},onToggleActive:()=>Me(Ee),showSection:!0},Ee.id))})})]})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete Banner"}),e.jsxs(Qn,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:_e,children:"Delete"})]})]})})]})}function xZe({title:s,setTitle:t,description:n,setDescription:r,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:u,sectionAfter:h,setSectionAfter:p,isActive:f,setIsActive:g,startDate:b,setStartDate:v,endDate:j,setEndDate:_,handleImageUpload:S,uploading:A,showPlacementOptions:T}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ge,{id:"title",placeholder:"Banner headline...",value:s,onChange:D=>t(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{id:"description",placeholder:"Optional banner description...",value:n,onChange:D=>r(D.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(ge,{type:"file",accept:"image/*",onChange:S,disabled:A,className:"flex-1"}),A&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),a&&e.jsx("div",{className:"mt-2 relative rounded-lg overflow-hidden border",children:e.jsx("img",{src:a,alt:"Preview",className:"w-full h-40 object-cover"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(ge,{id:"linkUrl",placeholder:"https://...",value:i,onChange:D=>l(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"linkText",children:"Button Text"}),e.jsx(ge,{id:"linkText",placeholder:"Learn More",value:o,onChange:D=>c(D.target.value)})]})]}),T&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Placement"}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select section placement..."})}),e.jsx(ds,{children:S_t.map(D=>e.jsx(Ze,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(ge,{id:"startDate",type:"datetime-local",value:b,onChange:D=>v(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(ge,{id:"endDate",type:"datetime-local",value:j,onChange:D=>_(D.target.value)})]})]}),e.jsx("div",{className:"flex items-center justify-between pt-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{id:"isActive",checked:f,onCheckedChange:g}),e.jsx(se,{htmlFor:"isActive",children:"Active"})]})})]})}function gZe({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=S_t.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=N.useState(null);return N.useEffect(()=>{(async()=>{const{count:u}=await q.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(u??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Uu,{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(ze,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(ze,{variant:"outline",children:"Scheduled"})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.description}),a&&i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i})]}),l!==null&&e.jsxs("div",{className:"flex items-center gap-1 text-destructive",title:"Button clicks",children:[e.jsx(oc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-semibold",children:l})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s.link_url&&e.jsx("a",{href:s.link_url,target:"_blank",rel:"noopener noreferrer",children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(tr,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(Ir,{className:"h-4 w-4"}):e.jsx(gf,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})]})}const mG={open:{label:"Open",icon:gr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ql,color:"bg-blue-500"},resolved:{label:"Resolved",icon:zi,color:"bg-green-500"},closed:{label:"Closed",icon:Gc,color:"bg-muted-foreground"}},yZe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Gqs(){var M,F;const{user:s}=gs(),t=Gt(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState([]),[c,d]=N.useState("all"),[u,h]=N.useState("all"),[p,f]=N.useState(!1),{data:g=[],isLoading:b}=lt({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let z=q.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(z=z.eq("status",c)),u!=="all"&&(z=z.eq("category",u));const{data:V,error:W}=await z;if(W)throw W;return V}}),{data:v=[]}=lt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:z,error:V}=await q.from("user_roles").select("user_id").eq("role","admin");if(V)throw V;const W=z.map(pe=>pe.user_id),{data:K,error:Y}=await q.from("profiles").select("id, name, email").in("id",W);if(Y)throw Y;const{data:ee,error:ne}=await q.from("support_notification_settings").select("user_id, receive_notifications");if(ne)throw ne;const oe=new Map((ee==null?void 0:ee.map(pe=>[pe.user_id,pe.receive_notifications]))||[]);return K.map(pe=>({...pe,receives_notifications:oe.get(pe.id)||!1}))}}),{data:j=[]}=lt({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:z,error:V}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(V)throw V;return z},enabled:!!n}),_=gt({mutationFn:async({userId:z,enabled:V})=>{const{data:W}=await q.from("support_notification_settings").select("id").eq("user_id",z).maybeSingle();if(W){const{error:K}=await q.from("support_notification_settings").update({receive_notifications:V}).eq("user_id",z);if(K)throw K}else{const{error:K}=await q.from("support_notification_settings").insert({user_id:z,receive_notifications:V});if(K)throw K}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),ae.success("Notification settings updated")},onError:()=>{ae.error("Failed to update settings")}}),S=gt({mutationFn:async({ticketId:z,status:V})=>{const{error:W}=await q.from("support_tickets").update({status:V}).eq("id",z);if(W)throw W},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),n&&r({...n,status:n.status}),ae.success("Status updated")},onError:()=>{ae.error("Failed to update status")}}),A=gt({mutationFn:async({ticketId:z,assignedTo:V})=>{const{error:W}=await q.from("support_tickets").update({assigned_to:V}).eq("id",z);if(W)throw W},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),ae.success("Ticket assigned")},onError:()=>{ae.error("Failed to assign ticket")}}),T=gt({mutationFn:async({content:z,attachments:V})=>{var K,Y;if(!n||!s)throw new Error("Missing data");const{error:W}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:z,is_admin_reply:!0,attachments:V});if(W)throw W;try{await q.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:z,userEmail:(K=n.profiles)==null?void 0:K.email,userName:(Y=n.profiles)==null?void 0:Y.name}})}catch(ee){console.error("Failed to send reply notification:",ee)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ae.success("Reply sent!")},onError:()=>{ae.error("Failed to send reply")}}),D=()=>{!a.trim()&&l.length===0||T.mutate({content:a,attachments:l})};N.useEffect(()=>{const z=q.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{q.removeChannel(z)}},[t]);const L=g.filter(z=>z.status==="open").length;return n?(mG[n.status].icon,e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(Wr,{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(ze,{variant:"secondary",children:yZe[n.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((M=n.profiles)==null?void 0:M.name)||"Unknown"," (",(F=n.profiles)==null?void 0:F.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm",children:"Status"})}),e.jsx(Ae,{children:e.jsxs(us,{value:n.status,onValueChange:z=>{S.mutate({ticketId:n.id,status:z}),r({...n,status:z})},children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"open",children:"Open"}),e.jsx(Ze,{value:"in_progress",children:"In Progress"}),e.jsx(Ze,{value:"resolved",children:"Resolved"}),e.jsx(Ze,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm",children:"Assigned To"})}),e.jsx(Ae,{children:e.jsxs(us,{value:n.assigned_to||"unassigned",onValueChange:z=>{const V=z==="unassigned"?null:z;A.mutate({ticketId:n.id,assignedTo:V}),r({...n,assigned_to:V})},children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Unassigned"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"unassigned",children:"Unassigned"}),v.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))]})]})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Hn,{children:["Created on ",ks(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Ae,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ae,{children:[e.jsx(mi,{className:"h-[300px] pr-4",children:j.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:j.map(z=>{var V,W;return e.jsxs("div",{className:`p-4 rounded-lg ${z.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:z.is_admin_reply?`${((V=z.profiles)==null?void 0:V.name)||"Admin"} (Support)`:((W=z.profiles)==null?void 0:W.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ks(new Date(z.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:z.content}),z.attachments&&z.attachments.length>0&&e.jsx(iyt,{attachments:z.attachments})]},z.id)})})}),e.jsx(cl,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ts,{placeholder:"Type your reply...",value:a,onChange:z=>i(z.target.value),className:"min-h-[80px]"}),e.jsx(B,{onClick:D,disabled:!a.trim()&&l.length===0||T.isPending,className:"self-end",children:e.jsx(cr,{className:"h-4 w-4"})})]}),e.jsx(ayt,{value:l,onChange:o,disabled:T.isPending})]})]})]})]})})):e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Support Tickets"}),e.jsxs("p",{className:"text-muted-foreground",children:["Manage support requests from agents",L>0&&e.jsxs(ze,{variant:"destructive",className:"ml-2",children:[L," open"]})]})]}),e.jsxs(bs,{open:p,onOpenChange:f,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(Vo,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Email Notification Settings"}),e.jsx(Qn,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:v.map(z=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Xi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:z.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:z.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[z.receives_notifications?e.jsx(lm,{className:"h-4 w-4 text-primary"}):e.jsx(fw,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(vn,{checked:z.receives_notifications,onCheckedChange:V=>_.mutate({userId:z.id,enabled:V})})]})]},z.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx($r,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(Ur,{children:[e.jsx(Zt,{value:"all",children:"All"}),e.jsx(Zt,{value:"open",children:"Open"}),e.jsx(Zt,{value:"in_progress",children:"In Progress"}),e.jsx(Zt,{value:"resolved",children:"Resolved"}),e.jsx(Zt,{value:"closed",children:"Closed"})]})}),e.jsxs(us,{value:u,onValueChange:h,children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"All Categories"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Categories"}),e.jsx(Ze,{value:"general",children:"General Support"}),e.jsx(Ze,{value:"technology",children:"Technology Support"}),e.jsx(Ze,{value:"crm",children:"CRM Support"}),e.jsx(Ze,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:b?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):g.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"text-center py-12",children:[e.jsx(Ql,{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(z=>{var W,K;const V=mG[z.status].icon;return e.jsx(fe,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(z),children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:z.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(ze,{variant:"outline",className:"text-xs",children:yZe[z.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(W=z.profiles)==null?void 0:W.name," • ",ks(new Date(z.created_at),"MMM d, yyyy")]}),z.assigned_to&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Xi,{className:"h-3 w-3"}),((K=v.find(Y=>Y.id===z.assigned_to))==null?void 0:K.name)||"Assigned"]})]})]}),e.jsxs(ze,{className:mG[z.status].color,children:[e.jsx(V,{className:"h-3 w-3 mr-1"}),mG[z.status].label]})]})})},z.id)})})})]})]})})}const C_t=Tf.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 Wqs({content:s,onChange:t,variables:n}){const r=eIe({extensions:[sIe,hIe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),mIe.configure({types:["heading","paragraph"]}),pIe,C_t],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});N.useEffect(()=>{r&&s!==r.getHTML()&&r.commands.setContent(s)},[s,r]);const a=l=>{r&&r.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!r)return;const l=r.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){r.chain().focus().extendMarkRange("link").unsetLink().run();return}r.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return r?e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBold().run(),className:r.isActive("bold")?"bg-muted":"",children:e.jsx(YS,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleItalic().run(),className:r.isActive("italic")?"bg-muted":"",children:e.jsx(e4,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBulletList().run(),className:r.isActive("bulletList")?"bg-muted":"",children:e.jsx(Ep,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleOrderedList().run(),className:r.isActive("orderedList")?"bg-muted":"",children:e.jsx(zv,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("left").run(),className:r.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(wA,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("center").run(),className:r.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(_A,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("right").run(),className:r.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx(jA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:i,className:r.isActive("link")?"bg-muted":"",children:e.jsx(tl,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleCodeBlock().run(),className:r.isActive("codeBlock")?"bg-muted":"",children:e.jsx(SA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),children:e.jsx(u4,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),children:e.jsx(l4,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(kL,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(cc,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(Xr,{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(X6e,{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(ze,{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 Kqs(){const s=Gt(),[t,n]=N.useState(null),[r,a]=N.useState(null),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(!0),[f,g]=N.useState("visual"),{data:b,isLoading:v}=lt({queryKey:["email-templates"],queryFn:async()=>{const{data:T,error:D}=await q.from("email_templates").select("*").order("name");if(D)throw D;return T.map(L=>({...L,available_variables:L.available_variables||[]}))}}),j=gt({mutationFn:async T=>{const{error:D}=await q.from("email_templates").update({subject:T.subject,body_html:T.body_html,description:T.description,is_active:T.is_active}).eq("id",T.id);if(D)throw D},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),ae.success("Email template updated successfully"),n(null)},onError:T=>{ae.error("Failed to update template: "+T.message)}}),_=T=>{n(T),l(T.subject),c(T.body_html),u(T.description||""),p(T.is_active),g("visual")},S=()=>{t&&j.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},A=(T,D)=>{let L=T;return D.forEach(M=>{const F=`{{${M.key}}}`,z=`[${M.label}]`;L=L.replace(new RegExp(F.replace(/[{}]/g,"\\$&"),"g"),z)}),L};return t?e.jsxs(Cs,{title:"Edit Email Template",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(B,{variant:"ghost",onClick:()=>n(null),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(B,{variant:"outline",onClick:()=>a(t),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{onClick:S,disabled:j.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),j.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5"}),t.name]}),e.jsxs(Hn,{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(se,{htmlFor:"active-toggle",children:"Active"}),e.jsx(vn,{id:"active-toggle",checked:h,onCheckedChange:p})]})]})}),e.jsxs(Ae,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{id:"description",value:d,onChange:T=>u(T.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"subject",children:"Email Subject"}),e.jsx(ge,{id:"subject",value:i,onChange:T=>l(T.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(se,{children:"Email Body"}),e.jsx($r,{value:f,onValueChange:T=>g(T),children:e.jsxs(Ur,{className:"h-8",children:[e.jsxs(Zt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(gb,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Zt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(SA,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),f==="visual"?e.jsx(Wqs,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Ts,{value:o,onChange:T=>c(T.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(bs,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Email Preview"}),e.jsxs(Qn,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:A(o,t.available_variables)}})})]})})]}):e.jsx(Cs,{title:"Email Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),v?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((T,D)=>e.jsx(fe,{children:e.jsxs(Mt,{children:[e.jsx(Ws,{className:"h-5 w-48"}),e.jsx(Ws,{className:"h-4 w-96"})]})},D))}):e.jsx("div",{className:"grid gap-4",children:b==null?void 0:b.map(T=>e.jsxs(fe,{className:"hover:shadow-md transition-shadow",children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Pt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Hs,{className:"h-5 w-5 text-muted-foreground"}),T.name,!T.is_active&&e.jsx(ze,{variant:"secondary",children:"Inactive"})]}),e.jsx(Hn,{children:T.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>a(T),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{size:"sm",onClick:()=>_(T),children:[e.jsx(Tu,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Ae,{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:T.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:T.available_variables.map(D=>e.jsx(ze,{variant:"outline",className:"font-mono text-xs",children:`{{${D.key}}}`},D.key))})]})]})})]},T.id))}),e.jsx(bs,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(Qn,{children:["Subject: ",r==null?void 0:r.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),r&&e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:A(r.body_html,r.available_variables)}})})]})})]})})}function Yqs(){const s=Gt(),[t,n]=N.useState("templates"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[f,g]=N.useState({name:"",description:"",icon:"📧"}),{data:b=[]}=lt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:z,error:V}=await q.from("email_template_categories").select("*").order("sort_order");if(V)throw V;return z}}),{data:v=[],isLoading:j}=lt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:z,error:V}=await q.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(V)throw V;return z}}),_=gt({mutationFn:async z=>{const V={title:z.title,subject:z.subject,body:z.body,description:z.description||null,tone:z.tone||null,category_id:z.category_id||null,is_active:z.is_active};if(z.id){const{error:W}=await q.from("agent_email_templates").update(V).eq("id",z.id);if(W)throw W}else{const{error:W}=await q.from("agent_email_templates").insert(V);if(W)throw W}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),ae.success(r?"Template updated":"Template created")},onError:()=>ae.error("Failed to save template")}),S=gt({mutationFn:async z=>{const{error:V}=await q.from("agent_email_templates").delete().eq("id",z);if(V)throw V},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),ae.success("Template deleted")}}),A=gt({mutationFn:async z=>{const V={name:z.name,description:z.description||null,icon:z.icon};if(z.id){const{error:W}=await q.from("email_template_categories").update(V).eq("id",z.id);if(W)throw W}else{const W=b.length>0?Math.max(...b.map(Y=>Y.sort_order))+1:0,{error:K}=await q.from("email_template_categories").insert({...V,sort_order:W});if(K)throw K}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),ae.success(i?"Category updated":"Category created")},onError:()=>ae.error("Failed to save category")}),T=gt({mutationFn:async z=>{const{error:V}=await q.from("email_template_categories").delete().eq("id",z);if(V)throw V},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),ae.success("Category deleted")}}),D=()=>{a(null),p({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},L=z=>{a(z),p({title:z.title,subject:z.subject,body:z.body,description:z.description||"",tone:z.tone||"",category_id:z.category_id||"",is_active:z.is_active}),c(!0)},M=()=>{l(null),g({name:"",description:"",icon:"📧"}),u(!0)},F=z=>{l(z),g({name:z.name,description:z.description||"",icon:z.icon}),u(!0)};return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(Vd,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs($r,{value:t,onValueChange:n,children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"templates",className:"gap-2",children:[e.jsx(Hs,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Zt,{value:"categories",className:"gap-2",children:[e.jsx(yf,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(ls,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:D,className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Template"}),e.jsx(Ct,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Ct,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:j?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8",children:e.jsx(ss,{className:"h-6 w-6 animate-spin mx-auto"})})}):v.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):v.map(z=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:z.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:z.subject})]})}),e.jsx(ut,{className:"hidden md:table-cell",children:z.category?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[z.category.icon," ",z.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ut,{className:"hidden md:table-cell",children:z.tone?e.jsx(ze,{variant:"secondary",children:z.tone}):"—"}),e.jsx(ut,{children:e.jsx(ze,{variant:z.is_active?"default":"secondary",children:z.is_active?"Active":"Inactive"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>L(z),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&S.mutate(z.id)},children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},z.id))})]})})})]}),e.jsxs(ls,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:M,className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:b.map(z=>e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:z.icon})," ",z.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>F(z),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>{confirm("Delete this category?")&&T.mutate(z.id)},children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ae,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:z.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[v.filter(V=>V.category_id===z.id).length," templates"]})]})]},z.id))})]})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Title"}),e.jsx(ge,{value:h.title,onChange:z=>p(V=>({...V,title:z.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsxs(us,{value:h.category_id,onValueChange:z=>p(V=>({...V,category_id:z})),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select category"})}),e.jsx(ds,{children:b.map(z=>e.jsxs(Ze,{value:z.id,children:[z.icon," ",z.name]},z.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Subject Line"}),e.jsx(ge,{value:h.subject,onChange:z=>p(V=>({...V,subject:z.target.value})),placeholder:"e.g. Hey {{first_name}}, just checking in!"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}",", ","{{full_name}}"," for merge variables"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email Body"}),e.jsx(Ts,{value:h.body,onChange:z=>p(V=>({...V,body:z.target.value})),rows:12,placeholder:"Write your email template...",className:"resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description (internal)"}),e.jsx(ge,{value:h.description,onChange:z=>p(V=>({...V,description:z.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Tone"}),e.jsx(ge,{value:h.tone,onChange:z=>p(V=>({...V,tone:z.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{checked:h.is_active,onCheckedChange:z=>p(V=>({...V,is_active:z}))}),e.jsx(se,{children:"Active"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>_.mutate({...h,id:r==null?void 0:r.id}),disabled:_.isPending||!h.title||!h.subject||!h.body,children:[_.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(bs,{open:d,onOpenChange:u,children:e.jsxs(vs,{className:"sm:max-w-[450px]",children:[e.jsx(ws,{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(se,{children:"Icon"}),e.jsx(ge,{value:f.icon,onChange:z=>g(V=>({...V,icon:z.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Name"}),e.jsx(ge,{value:f.name,onChange:z=>g(V=>({...V,name:z.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(ge,{value:f.description,onChange:z=>g(V=>({...V,description:z.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>A.mutate({...f,id:i==null?void 0:i.id}),disabled:A.isPending||!f.name,children:[A.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const Zqs=({brokerageId:s})=>{var Cr,ts;const{toast:t}=Ua(),n=In(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,p]=N.useState(new Set),[f,g]=N.useState(!1),[b,v]=N.useState({}),[j,_]=N.useState(!1),[S,A]=N.useState(!1),[T,D]=N.useState({email:"",name:"",password:"",phone:""}),[L,M]=N.useState(!1),[F,z]=N.useState(null),[V,W]=N.useState(!1),[K,Y]=N.useState(!1),[ee,ne]=N.useState(!1),[oe,pe]=N.useState(""),[ce,de]=N.useState(!1),[ie,ye]=N.useState([]),[_e,Me]=N.useState(!1),[Te,Ce]=N.useState(!1),[Ee,De]=N.useState(null),[Ie,Fe]=N.useState({name:"",phone:"",email:""}),[qe,ve]=N.useState(!1),[Je,we]=N.useState(!1),[it,Ne]=N.useState(null),[He,$e]=N.useState("asc"),[Ye,Ke]=N.useState(!1),[rt,tt]=N.useState(null),[at,Ge]=N.useState(!1),[dt,Bt]=N.useState(null),[kt,Qt]=N.useState(""),[ns,$s]=N.useState(!1),[Ds,Dt]=N.useState(null);N.useEffect(()=>{$t(),St()},[s]);const St=async()=>{try{const{data:Oe,error:Qe}=await q.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(Qe)throw Qe;ye((Oe==null?void 0:Oe.map(ct=>ct.user_id))||[])}catch(Oe){console.error("Error loading brokerage managers:",Oe)}},$t=async()=>{try{l(!0);const{data:Oe,error:Qe}=await q.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(Qe)throw Qe;const ct=Oe.agents||[];if(a(ct),ct.length>0){const vt=ct.map(qt=>qt.id),{data:It}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",vt);if(It&&It.length>0){const qt=It.map(Ns=>Ns.assistant_id),{data:xs}=await q.from("profiles").select("id, name, email").in("id",qt),as={};for(const Ns of It){const ln=xs==null?void 0:xs.find(Ks=>Ks.id===Ns.assistant_id);ln&&(as[Ns.agent_id]={name:ln.name||"",email:ln.email||""})}v(as)}else v({})}}catch(Oe){console.error("Error loading agents:",Oe),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},ht=async()=>{if(!T.email||!T.name||!T.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}A(!0);try{const{data:{session:Oe}}=await q.auth.getSession(),Qe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oe==null?void 0:Oe.access_token}`},body:JSON.stringify({...T,brokerageId:s})}),ct=await Qe.json();if(!Qe.ok)throw new Error(ct.error||"Failed to create agent");t({title:"Success",description:`Agent ${T.email} created successfully`}),D({email:"",name:"",password:"",phone:""}),_(!1),$t()}catch(Oe){console.error("Error creating agent:",Oe),t({title:"Error",description:Oe.message||"Failed to create agent",variant:"destructive"})}finally{A(!1)}},Ut=async Oe=>{try{const{data:{session:Qe}}=await q.auth.getSession(),ct=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qe==null?void 0:Qe.access_token}`},body:JSON.stringify({userId:Oe})}),vt=await ct.json();if(!ct.ok)throw new Error(vt.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(Qe){console.error("Error resending welcome email:",Qe),t({title:"Error",description:Qe.message||"Failed to resend welcome email",variant:"destructive"})}},Es=async(Oe,Qe)=>{try{const{error:ct}=await q.functions.invoke("send-password-reset",{body:{email:Oe,redirectTo:window.location.origin}});if(ct)throw ct;t({title:"Password Reset Sent",description:`Password reset email sent to ${Qe}`})}catch(ct){console.error("Error sending password reset:",ct),t({title:"Error",description:ct.message||"Failed to send password reset email",variant:"destructive"})}},Xt=Oe=>{z(Oe),M(!0)},Ys=Oe=>{De(Oe),Fe({name:Oe.name,phone:Oe.phone||"",email:Oe.email}),Ce(!0)},Ss=async()=>{if(!Ee)return;if(!Ie.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Oe=Ie.email.trim().toLowerCase()!==Ee.email.toLowerCase();ve(!0);try{if(Oe){if(!Ie.email.trim())throw new Error("Email is required");we(!0);const{data:{session:ct}}=await q.auth.getSession(),vt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ct==null?void 0:ct.access_token}`},body:JSON.stringify({agentId:Ee.id,newEmail:Ie.email.trim(),brokerageId:s})}),It=await vt.json();if(we(!1),!vt.ok)throw new Error(It.error||"Failed to update email")}const{error:Qe}=await q.from("profiles").update({name:Ie.name.trim(),phone:Ie.phone.trim()||null}).eq("id",Ee.id);if(Qe)throw Qe;t({title:"Success",description:"Agent profile updated successfully"}),Ce(!1),De(null),$t()}catch(Qe){console.error("Error updating agent:",Qe),t({title:"Error",description:Qe.message||"Failed to update agent",variant:"destructive"})}finally{ve(!1),we(!1)}},Bs=async()=>{if(!oe){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}de(!0);try{const{data:{session:Oe}}=await q.auth.getSession(),Qe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oe==null?void 0:Oe.access_token}`},body:JSON.stringify({userId:oe,role:"brokerage_manager",action:"add",brokerageId:s})}),ct=await Qe.json();if(!Qe.ok)throw new Error(ct.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),ne(!1),pe(""),St()}catch(Oe){console.error("Error adding brokerage manager:",Oe),t({title:"Error",description:Oe.message||"Failed to add brokerage manager",variant:"destructive"})}finally{de(!1)}},Us=async Oe=>{try{const{data:{session:Qe}}=await q.auth.getSession(),ct=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qe==null?void 0:Qe.access_token}`},body:JSON.stringify({userId:Oe,role:"brokerage_manager",action:"remove",brokerageId:s})}),vt=await ct.json();if(!ct.ok)throw new Error(vt.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),St()}catch(Qe){console.error("Error removing brokerage manager:",Qe),t({title:"Error",description:Qe.message||"Failed to remove brokerage manager",variant:"destructive"})}},sn=Oe=>ie.includes(Oe),Jn=Oe=>{Bt(Oe),Qt(""),Ge(!0)},fn=async()=>{if(!(!dt||!kt)){if(kt.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}$s(!0);try{const{data:{session:Oe}}=await q.auth.getSession(),Qe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oe==null?void 0:Oe.access_token}`},body:JSON.stringify({agentId:dt.id,brokerageId:s,action:"set_password",newPassword:kt})}),ct=await Qe.json();if(!Qe.ok)throw new Error(ct.error||"Failed to set password");t({title:"Success",description:`Password set for ${dt.name}`}),Ge(!1),Bt(null),Qt("")}catch(Oe){console.error("Error setting password:",Oe),t({title:"Error",description:Oe.message||"Failed to set password",variant:"destructive"})}finally{$s(!1)}}},Sn=async Oe=>{Dt(Oe.id);try{const{data:{session:Qe}}=await q.auth.getSession(),ct=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qe==null?void 0:Qe.access_token}`},body:JSON.stringify({agentId:Oe.id,brokerageId:s,action:"claim_account"})}),vt=await ct.json();if(!ct.ok)throw new Error(vt.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Oe.name}`}),$t()}catch(Qe){console.error("Error claiming account:",Qe),t({title:"Error",description:Qe.message||"Failed to claim account",variant:"destructive"})}finally{Dt(null)}},Gn=async()=>{if(F){W(!0);try{const{data:{session:Oe}}=await q.auth.getSession(),Qe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oe==null?void 0:Oe.access_token}`},body:JSON.stringify({userId:F.id,brokerageId:s})}),ct=await Qe.json();if(!Qe.ok)throw new Error(ct.error||"Failed to remove agent");t({title:"Success",description:`${F.name} has been removed from your brokerage`}),M(!1),z(null),$t()}catch(Oe){console.error("Error removing agent:",Oe),t({title:"Error",description:Oe.message||"Failed to remove agent",variant:"destructive"})}finally{W(!1)}}},Hr=Oe=>{const Qe=Oe.trim().split(" ");return Qe.length>1?Qe[Qe.length-1].toLowerCase():Oe.toLowerCase()},pi=Oe=>{it===Oe?$e(He==="asc"?"desc":"asc"):(Ne(Oe),$e("asc"))},Ms=Oe=>it!==Oe?e.jsx(sm,{className:"ml-1 h-4 w-4"}):He==="asc"?e.jsx(Bu,{className:"ml-1 h-4 w-4"}):e.jsx(om,{className:"ml-1 h-4 w-4"}),bi=r.filter(Oe=>{if(d==="active"&&!Oe.claimed||d==="pending"&&Oe.claimed)return!1;if(!o)return!0;const Qe=o.toLowerCase();return Oe.name.toLowerCase().includes(Qe)||Oe.email.toLowerCase().includes(Qe)}),Rr=[...bi].sort((Oe,Qe)=>{if(!it)return 0;let ct=0;return it==="name"?ct=Hr(Oe.name).localeCompare(Hr(Qe.name)):it==="status"&&(ct=Oe.claimed===Qe.claimed?0:Oe.claimed?-1:1),He==="asc"?ct:-ct});bi.filter(Oe=>Oe.claimed&&!sn(Oe.id));const er=Oe=>{p(Qe=>{const ct=new Set(Qe);return ct.has(Oe)?ct.delete(Oe):ct.add(Oe),ct})},lr=()=>{h.size===Rr.length?p(new Set):p(new Set(Rr.map(Oe=>Oe.id)))},Fs=()=>{p(new Set)},$n=async()=>{const Oe=Array.from(h);if(Oe.length===0)return;g(!0);let Qe=0,ct=0;try{const{data:{session:vt}}=await q.auth.getSession();for(const It of Oe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${vt==null?void 0:vt.access_token}`},body:JSON.stringify({userId:It})})).ok?Qe++:ct++}catch{ct++}Qe>0?t({title:"Success",description:`Welcome emails sent to ${Qe} agent${Qe>1?"s":""}${ct>0?` (${ct} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Fs()}catch(vt){console.error("Error bulk sending welcome emails:",vt),t({title:"Error",description:vt.message||"Failed to send welcome emails",variant:"destructive"})}finally{g(!1)}};return i?e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Agents"}),e.jsx(Hn,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>ne(!0),children:[e.jsx(hh,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(B,{variant:"outline",onClick:()=>Y(!0),children:[e.jsx(yw,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(B,{onClick:()=>_(!0),children:[e.jsx(Fo,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Ae,{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(_r,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search agents...",value:o,onChange:Oe=>c(Oe.target.value),className:"pl-9"})]}),e.jsxs(us,{value:d,onValueChange:Oe=>u(Oe),children:[e.jsx(cs,{className:"w-[160px]",children:e.jsx(hs,{placeholder:"Filter by status"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Agents"}),e.jsx(Ze,{value:"active",children:"Active"}),e.jsx(Ze,{value:"pending",children:"Pending"})]})]})]}),h.size>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 rounded-lg border bg-muted/50 p-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[h.size," agent",h.size>1?"s":""," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{const Qe=r.filter(ct=>h.has(ct.id)&&ct.email).map(ct=>({email:ct.email,name:ct.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(Qe)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:Qe}})},disabled:f,children:[e.jsx(qd,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:$n,disabled:f,children:[e.jsx(Hs,{className:"mr-2 h-4 w-4"}),f?"Sending...":"Resend Welcome Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:Fs,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-[40px]",children:e.jsx(hi,{checked:Rr.length>0&&h.size===Rr.length,onCheckedChange:lr,"aria-label":"Select all"})}),e.jsx(Ct,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>pi("name"),children:["Name (Last)",Ms("name")]})}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>pi("status"),children:["Status",Ms("status")]})}),e.jsx(Ct,{children:"Actions"})]})}),e.jsx(pa,{children:Rr.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):Rr.map(Oe=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsx(hi,{checked:h.has(Oe.id),onCheckedChange:()=>er(Oe.id),"aria-label":`Select ${Oe.name}`})}),e.jsx(ut,{className:"font-medium",children:Oe.name}),e.jsx(ut,{children:Oe.email}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Oe.claimed?e.jsx(ze,{variant:"default",children:"Active"}):e.jsx(ze,{variant:"secondary",children:"Pending"}),sn(Oe.id)&&e.jsxs(ze,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(ng,{className:"mr-1 h-3 w-3"}),"Manager"]}),b[Oe.id]&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:[e.jsx(_n,{className:"mr-1 h-3 w-3"}),"Asst: ",b[Oe.id].name||b[Oe.id].email]})]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{tt(Oe),Ke(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(uh,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Ys(Oe),title:"Edit agent",children:e.jsx(ja,{className:"h-4 w-4"})}),!Oe.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Ut(Oe.id),title:"Resend welcome email",children:e.jsx(Hs,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Sn(Oe),title:"Claim account for agent",disabled:Ds===Oe.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(_b,{className:"h-4 w-4"})})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Jn(Oe),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(Rc,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Es(Oe.email,Oe.name),title:"Send password reset email",children:e.jsx(PA,{className:"h-4 w-4"})}),sn(Oe.id)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Us(Oe.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(hh,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Xt(Oe),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},Oe.id))})]})})]})]}),e.jsx(bs,{open:j,onOpenChange:_,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add New Agent"}),e.jsx(Qn,{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(se,{htmlFor:"name",children:"Name"}),e.jsx(ge,{id:"name",value:T.name,onChange:Oe=>D({...T,name:Oe.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ge,{id:"email",type:"email",value:T.email,onChange:Oe=>D({...T,email:Oe.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(ge,{id:"phone",type:"tel",value:T.phone,onChange:Oe=>D({...T,phone:Oe.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"password",children:"Temporary Password"}),e.jsx(ge,{id:"password",type:"password",value:T.password,onChange:Oe=>D({...T,password:Oe.target.value}),placeholder:"Temporary password"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsx(B,{onClick:ht,disabled:S,children:S?"Creating...":"Create Agent"})]})]})}),e.jsx(bs,{open:L,onOpenChange:M,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Remove Agent"}),e.jsxs(Qn,{children:["Are you sure you want to remove ",e.jsx("strong",{children:F==null?void 0:F.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>M(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Gn,disabled:V,children:V?"Removing...":"Remove Agent"})]})]})}),e.jsx(oyt,{open:K,onOpenChange:Y,fixedBrokerageId:s,onSuccess:$t}),e.jsx(bs,{open:ee,onOpenChange:ne,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add Brokerage Manager"}),e.jsx(Qn,{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(se,{children:"Select Agent"}),e.jsxs(Wo,{open:_e,onOpenChange:Me,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":_e,className:"w-full justify-between",children:[oe?((Cr=r.find(Oe=>Oe.id===oe))==null?void 0:Cr.name)+" ("+((ts=r.find(Oe=>Oe.id===oe))==null?void 0:ts.email)+")":"Select an agent to promote...",e.jsx(Hg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(zo,{className:"w-full p-0",align:"start",children:e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search by name or email..."}),e.jsxs(e0,{className:"max-h-[200px]",children:[e.jsx(t0,{children:"No eligible agents found."}),e.jsx(s0,{children:r.filter(Oe=>!sn(Oe.id)).map(Oe=>e.jsxs(ex,{value:`${Oe.name} ${Oe.email}`,onSelect:()=>{pe(Oe.id),Me(!1)},children:[e.jsx(Lr,{className:`mr-2 h-4 w-4 ${oe===Oe.id?"opacity-100":"opacity-0"}`}),Oe.name," (",Oe.email,")"]},Oe.id))})]})]})})]}),r.filter(Oe=>!sn(Oe.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsx(B,{onClick:Bs,disabled:ce||!oe,children:ce?"Adding...":"Add as Manager"})]})]})}),e.jsx(bs,{open:Te,onOpenChange:Ce,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Agent"}),e.jsxs(Qn,{children:["Update profile information for ",Ee==null?void 0:Ee.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"edit-name",children:"Name"}),e.jsx(ge,{id:"edit-name",value:Ie.name,onChange:Oe=>Fe({...Ie,name:Oe.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"edit-email",children:"Email"}),e.jsx(ge,{id:"edit-email",type:"email",value:Ie.email,onChange:Oe=>Fe({...Ie,email:Oe.target.value}),placeholder:"agent@example.com"}),Ie.email.trim().toLowerCase()!==(Ee==null?void 0:Ee.email.toLowerCase())&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Changing email will update their login credentials"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(ge,{id:"edit-phone",type:"tel",value:Ie.phone,onChange:Oe=>Fe({...Ie,phone:Oe.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ce(!1),children:"Cancel"}),e.jsx(B,{onClick:Ss,disabled:qe||Je,children:Je?"Updating email...":qe?"Saving...":"Save Changes"})]})]})}),rt&&e.jsx(lyt,{open:Ye,onOpenChange:Oe=>{Ke(Oe),Oe||tt(null)},userId:rt.id,userName:rt.name}),e.jsx(bs,{open:at,onOpenChange:Ge,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Set Password"}),e.jsxs(Qn,{children:["Set a new password for ",dt==null?void 0:dt.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(se,{htmlFor:"new-password",children:"New Password"}),e.jsx(ge,{id:"new-password",type:"password",value:kt,onChange:Oe=>Qt(Oe.target.value),placeholder:"Enter new password (min 6 characters)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Make sure to communicate this password to the agent through a secure channel."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ge(!1),children:"Cancel"}),e.jsx(B,{onClick:fn,disabled:ns||!kt||kt.length<6,children:ns?"Setting...":"Set Password"})]})]})})]})},Qqs={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},Xqs={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},Jqs=s=>{switch(s){case"academy_video":return e.jsx(vr,{className:"h-4 w-4"});case"template":return e.jsx(Nr,{className:"h-4 w-4"});case"toolbox":return e.jsx(Nr,{className:"h-4 w-4"});case"newsletter":return e.jsx(iy,{className:"h-4 w-4"});case"social_swag":return e.jsx(un,{className:"h-4 w-4"});case"event":return e.jsx(yr,{className:"h-4 w-4"});default:return e.jsx(tr,{className:"h-4 w-4"})}},eVs=({brokerageId:s})=>{const{toast:t}=Ua(),[n,r]=N.useState([]),[a,i]=N.useState([]),[l,o]=N.useState([]),[c,d]=N.useState(!0),[u,h]=N.useState(null);N.useEffect(()=>{p()},[s]);const p=async()=>{try{d(!0);const{data:b,error:v}=await q.from("profiles").select("id, name, email").eq("brokerage_id",s);if(v)throw v;const j=b.map(V=>V.id),_=new Map(b.map(V=>[V.id,V]));if(j.length===0){r([]),i([]),o([]);return}const{data:S,error:A}=await q.from("activity_logs").select("*").in("user_id",j).order("launched_at",{ascending:!1});if(A)throw A;const T=S.map(V=>{var W,K;return{id:V.id,user_id:V.user_id,app_name:V.app_name,launched_at:V.launched_at,user_name:((W=_.get(V.user_id))==null?void 0:W.name)||"Unknown",user_email:((K=_.get(V.user_id))==null?void 0:K.email)||"Unknown"}});r(T);const{data:D,error:L}=await q.from("content_engagement_logs").select("*").in("user_id",j).order("created_at",{ascending:!1});if(L)throw L;const M=(D||[]).map(V=>{var W,K;return{id:V.id,user_id:V.user_id,resource_type:V.resource_type,resource_id:V.resource_id,resource_title:V.resource_title,action_type:V.action_type,created_at:V.created_at,user_name:((W=_.get(V.user_id))==null?void 0:W.name)||"Unknown",user_email:((K=_.get(V.user_id))==null?void 0:K.email)||"Unknown"}});i(M);const F=new Map;b.forEach(V=>{F.set(V.id,{user_id:V.id,user_name:V.name,user_email:V.email,app_launches:0,content_views:0,last_activity:""})}),T.forEach(V=>{const W=F.get(V.user_id);W&&(W.app_launches++,(!W.last_activity||new Date(V.launched_at)>new Date(W.last_activity))&&(W.last_activity=V.launched_at))}),M.forEach(V=>{const W=F.get(V.user_id);W&&(W.content_views++,(!W.last_activity||new Date(V.created_at)>new Date(W.last_activity))&&(W.last_activity=V.created_at))});const z=Array.from(F.values()).filter(V=>V.app_launches>0||V.content_views>0).sort((V,W)=>new Date(W.last_activity).getTime()-new Date(V.last_activity).getTime());o(z)}catch(b){console.error("Error loading activity:",b),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},f=b=>n.filter(v=>v.user_id===b),g=b=>a.filter(v=>v.user_id===b);return c?e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Agent Activity"}),e.jsx(Hn,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Ae,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{className:"text-center",children:"App Launches"}),e.jsx(Ct,{className:"text-center",children:"Content Views"}),e.jsx(Ct,{children:"Last Active"})]})}),e.jsx(pa,{children:l.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(b=>e.jsxs(Gs,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>h({id:b.user_id,name:b.user_name,email:b.user_email}),children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:b.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:b.user_email})]})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Al,{className:"h-3 w-3"}),b.app_launches]})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Nr,{className:"h-3 w-3"}),b.content_views]})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:b.last_activity&&Go(new Date(b.last_activity),{addSuffix:!0})})]},b.user_id))})]})})})]}),e.jsx(bs,{open:!!u,onOpenChange:b=>!b&&h(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(Qn,{children:u==null?void 0:u.email})]}),e.jsxs($r,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"content",children:"Content Engagement"}),e.jsx(Zt,{value:"apps",children:"App Launches"})]}),e.jsx(ls,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Resource"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Action"}),e.jsx(Ct,{children:"Time"})]})}),e.jsx(pa,{children:u&&g(u.id).length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&g(u.id).map(b=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"max-w-[200px] truncate font-medium",children:b.resource_title}),e.jsx(ut,{children:e.jsxs(ze,{variant:"outline",className:"gap-1",children:[Jqs(b.resource_type),Qqs[b.resource_type]||b.resource_type]})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Xqs[b.action_type]||b.action_type})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Go(new Date(b.created_at),{addSuffix:!0})})]},b.id))})]})})}),e.jsx(ls,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"App"}),e.jsx(Ct,{children:"Time"})]})}),e.jsx(pa,{children:u&&f(u.id).length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&f(u.id).map(b=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsx(ze,{variant:"outline",children:b.app_name})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Go(new Date(b.launched_at),{addSuffix:!0})})]},b.id))})]})})})]})]})})]})},tVs=({brokerageId:s})=>{const{toast:t}=Ua(),[n,r]=N.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=N.useState(!0);N.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await q.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(T=>T.id),u=d.length;if(d.length===0){i(!1);return}const{data:h,error:p}=await q.from("profiles").select("id, email").in("id",d);if(p)throw p;const{count:f}=await q.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),g=f||0,b=u-g,{count:v}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),j=new Date;j.setDate(j.getDate()-7);const{count:_}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",j.toISOString()),S=new Date;S.setMonth(S.getMonth()-1);const{count:A}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",S.toISOString());r({totalAgents:u,activeAgents:g,pendingAgents:b,totalLaunches:v||0,launchesThisWeek:_||0,launchesThisMonth:A||0})}catch(o){console.error("Error loading analytics:",o),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return a?e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(_n,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalAgents}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.activeAgents," active, ",n.pendingAgents," pending"]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(zi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.totalAgents>0?`${Math.round(n.activeAgents/n.totalAgents*100)}% of total`:"0% of total"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(gr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.pendingAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(am,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"This Week"}),e.jsx(am,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"This Month"}),e.jsx(am,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ae,{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"})]})]})]})},sVs=({brokerageId:s})=>{const[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({description:"",maxUses:""});N.useEffect(()=>{h()},[s]);const h=async()=>{try{const{data:j,error:_}=await q.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(_)throw _;n(j||[])}catch(j){console.error("Error loading invite codes:",j),ae.error("Failed to load invite links")}finally{a(!1)}},p=()=>Math.random().toString(36).substring(2,8).toUpperCase(),f=async()=>{l(!0);try{const j=p(),{error:_}=await q.from("invite_codes").insert({code:j,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(_)throw _;ae.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(j){console.error("Error creating invite code:",j),ae.error("Failed to create invite link")}finally{l(!1)}},g=async j=>{try{const{error:_}=await q.from("invite_codes").delete().eq("id",j);if(_)throw _;ae.success("Invite link deleted"),n(t.filter(S=>S.id!==j))}catch(_){console.error("Error deleting invite code:",_),ae.error("Failed to delete invite link")}},b=async(j,_)=>{try{const{error:S}=await q.from("invite_codes").update({is_active:!_}).eq("id",j);if(S)throw S;n(t.map(A=>A.id===j?{...A,is_active:!_}:A)),ae.success(`Invite link ${_?"deactivated":"activated"}`)}catch(S){console.error("Error toggling invite code:",S),ae.error("Failed to update invite link")}},v=j=>{const _=`${window.location.origin}/join?code=${j}`;navigator.clipboard.writeText(_),ae.success("Link copied to clipboard!")};return r?e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center py-8",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(tl,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(Hn,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create Invite Link"}),e.jsx(Qn,{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(se,{htmlFor:"description",children:"Description (optional)"}),e.jsx(ge,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:j=>u({...d,description:j.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(ge,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:j=>u({...d,maxUses:j.target.value})})]}),e.jsx(B,{onClick:f,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Ae,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(tl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No invite links yet"}),e.jsx("p",{className:"text-sm",children:"Create one to start inviting agents"})]}):e.jsx("div",{className:"space-y-3",children:t.map(j=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-sm font-mono bg-muted px-2 py-0.5 rounded",children:j.code}),e.jsx(ze,{variant:j.is_active?"default":"secondary",children:j.is_active?"Active":"Inactive"})]}),j.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:j.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[j.uses_count," uses",j.max_uses&&` / ${j.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(j.code),title:"Copy link",children:e.jsx(ta,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>b(j.id,j.is_active),title:j.is_active?"Deactivate":"Activate",children:j.is_active?"Disable":"Enable"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>g(j.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(bn,{className:"h-4 w-4"})})]})]},j.id))})})]})},nVs=({open:s,onOpenChange:t,referralCode:n,brokerageId:r,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=N.useState(""),[d,u]=N.useState([]),[h,p]=N.useState(""),[f,g]=N.useState(!1),b=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A),v=()=>{const A=o.trim().toLowerCase();if(A&&b(A)&&!d.includes(A)){if(d.length>=10){ae.error("Maximum 10 emails per invite");return}u([...d,A]),c("")}else A&&!b(A)?ae.error("Please enter a valid email address"):d.includes(A)&&ae.error("Email already added")},j=A=>{u(d.filter(T=>T!==A))},_=A=>{(A.key==="Enter"||A.key===",")&&(A.preventDefault(),v())},S=async()=>{if(d.length===0){ae.error("Please add at least one email address");return}g(!0);try{const{data:A,error:T}=await q.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:h.trim()||void 0,referralCode:n,brokerageId:r,senderName:a,brokerageName:i}});if(T)throw T;A.successCount===A.totalCount?ae.success(`${A.successCount} invite${A.successCount>1?"s":""} sent successfully!`):ae.warning(`${A.successCount} of ${A.totalCount} invites sent. Some failed.`),u([]),p(""),t(!1),l==null||l()}catch(A){console.error("Error sending invites:",A),ae.error("Failed to send invites. Please try again.")}finally{g(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[550px]",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Qn,{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(Bi,{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(se,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:A=>c(A.target.value),onKeyDown:_,onBlur:v}),e.jsx(B,{type:"button",variant:"secondary",onClick:v,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(A=>e.jsxs(ze,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[A,e.jsx("button",{type:"button",onClick:()=>j(A),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(Fn,{className:"h-3 w-3"})})]},A))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Ts,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:A=>p(A.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"What they'll receive:"]}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Beautiful branded email from you"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Your personal message (if added)"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Key LevelUp features for brokerages"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Direct signup link with your referral code"]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:S,disabled:d.length===0||f,children:f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent mr-2"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},rVs=({brokerageId:s,refreshTrigger:t})=>{const[n,r]=N.useState([]),[a,i]=N.useState(!0);N.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await q.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;r(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(ze,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(zi,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(ze,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(Gc,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(gr,{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(Hs,{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 ",ks(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},aVs=()=>{const{brokerageId:s,user:t}=gs(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState([]),[u,h]=N.useState(!0),[p,f]=N.useState(!1),[g,b]=N.useState(0);N.useEffect(()=>{s&&v()},[s]);const v=async()=>{try{const[D,L]=await Promise.all([q.from("brokerages").select("name").eq("id",s).single(),t?q.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);D.data&&i(D.data.name),L.data&&o(L.data.name||"A LevelUp Member");const{data:M}=await q.from("referral_codes").select("code").eq("brokerage_id",s).single();if(M)r(M.code);else{const z=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await q.from("referral_codes").insert({brokerage_id:s,code:z}),r(z)}const{data:F}=await q.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(F||[])}catch(D){console.error("Error fetching referral data:",D)}finally{h(!1)}},j=()=>{const D=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(D),ae.success("Referral link copied to clipboard!")},_=c.filter(D=>D.status==="qualified").length,S=c.filter(D=>D.status==="pending").length,A=_*25,T=Math.max(0,Math.ceil((299-A)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-gradient-to-r from-primary/10 via-primary/5 to-background border-b",children:e.jsxs("div",{className:"px-6 py-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"bg-primary/20 rounded-full p-2",children:e.jsx(Bi,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold",children:"Referral Rewards Program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Earn $25/month off your membership for every broker you refer"})]})]}),e.jsx("div",{className:"mt-4 bg-background/80 rounded-lg p-4 border",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-3xl font-bold text-primary",children:["$",A]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),A>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(zi,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),T>0&&A<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",T," more = ",e.jsx("span",{className:"text-primary",children:"FREE membership!"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your membership could cost $0/month"})]}),A>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(un,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Ae,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs(B,{onClick:()=>f(!0),className:"w-full",size:"lg",children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(B,{onClick:j,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(ta,{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(Zl,{className:"h-5 w-5 mx-auto text-green-600 mb-1"}),e.jsxs("p",{className:"text-2xl font-bold text-green-700 dark:text-green-400",children:["$",A]}),e.jsx("p",{className:"text-xs text-green-600 dark:text-green-500",children:"Monthly Savings"})]}),e.jsxs("div",{className:"text-center p-4 bg-primary/5 rounded-lg border border-primary/20",children:[e.jsx(_n,{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(gr,{className:"h-5 w-5 mx-auto text-amber-600 mb-1"}),e.jsx("p",{className:"text-2xl font-bold text-amber-700 dark:text-amber-400",children:S}),e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-500",children:"Pending (30 days)"})]})]}),e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold text-sm mb-3",children:"How It Works"}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"1"}),e.jsx("p",{children:"Share your referral link or send an invite email to broker friends"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"2"}),e.jsx("p",{children:"They sign up and subscribe to LevelUp"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"3"}),e.jsx("p",{children:"After 30 days, you get $25/month off your membership - forever!"})]})]})]}),e.jsx(rVs,{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(D=>{var L,M;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:((L=D.referred_brokerage)==null?void 0:L.name)||((M=D.referred_user)==null?void 0:M.email)||"Pending setup"}),e.jsxs(ze,{variant:D.status==="qualified"?"default":D.status==="pending"?"secondary":"destructive",className:D.status==="qualified"?"bg-green-600":"",children:[D.status==="qualified"&&e.jsx(zi,{className:"h-3 w-3 mr-1"}),D.status]})]},D.id)})]})]})]}),e.jsx(nVs,{open:p,onOpenChange:f,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>b(D=>D+1)})]})},iVs=({brokerageId:s})=>{const t=In(),{teams:n,isLoading:r}=s6(s),{data:a,isLoading:i}=lt({queryKey:["team-aggregate-stats",s,n.map(u=>u.id)],queryFn:async()=>{if(n.length===0)return[];const u=n.map(D=>D.id),{data:h}=await q.from("team_members").select("team_id, user_id, role").in("team_id",u);if(!h||h.length===0)return n.map(D=>({team_id:D.id,team_name:D.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const p=h.map(D=>D.user_id),f=h.filter(D=>D.role==="team_leader").map(D=>D.user_id),{data:g}=await q.from("profiles").select("id, name, avatar_url").in("id",f),b=new Map((g||[]).map(D=>[D.id,D])),{data:v}=await q.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",p),{data:j}=await q.from("deal_pipeline").select("owner_user_id").in("owner_user_id",p),{data:_}=await q.from("agent_videos").select("owner_user_id").in("owner_user_id",p).eq("is_deleted",!1),S=new Map;(v||[]).forEach(D=>{S.set(D.owner_user_id,(S.get(D.owner_user_id)||0)+1)});const A=new Map;(j||[]).forEach(D=>{A.set(D.owner_user_id,(A.get(D.owner_user_id)||0)+1)});const T=new Map;return(_||[]).forEach(D=>{T.set(D.owner_user_id,(T.get(D.owner_user_id)||0)+1)}),n.map(D=>{const L=h.filter(Y=>Y.team_id===D.id),M=L.find(Y=>Y.role==="team_leader"),F=M?b.get(M.user_id):null,z=L.map(Y=>Y.user_id),V=z.reduce((Y,ee)=>Y+(S.get(ee)||0),0),W=z.reduce((Y,ee)=>Y+(A.get(ee)||0),0),K=z.reduce((Y,ee)=>Y+(T.get(ee)||0),0);return{team_id:D.id,team_name:D.name,member_count:L.length,leader_name:(F==null?void 0:F.name)||null,leader_avatar:(F==null?void 0:F.avatar_url)||null,total_contacts:V,total_deals:W,total_videos:K}})},enabled:n.length>0});if(r||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(u=>e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Ws,{className:"h-5 w-32"})}),e.jsx(Ae,{children:e.jsx(Ws,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(_n,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create teams to organize your agents and track their performance."}),e.jsx(B,{onClick:()=>t("/brokerage/teams"),children:"Manage Teams"})]})});const o=(a||[]).reduce((u,h)=>u+h.member_count,0),c=(a||[]).reduce((u,h)=>u+h.total_contacts,0),d=(a||[]).reduce((u,h)=>u+h.total_deals,0);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 grid-cols-2 md:grid-cols-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(_n,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(_n,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(CA,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Vm,{className:"h-4 w-4"})," Total Deals"]}),e.jsx("p",{className:"text-2xl font-bold",children:d.toLocaleString()})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:(a||[]).map(u=>e.jsxs(fe,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Pt,{className:"text-lg",children:u.team_name}),e.jsxs(ze,{variant:"secondary",children:[u.member_count," members"]})]}),u.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(aa,{className:"h-6 w-6",children:[e.jsx(ri,{src:u.leader_avatar||""}),e.jsx(ia,{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(xf,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Ae,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_contacts.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_deals.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_videos.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]},u.team_id))}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},oVs=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=gs(),o=In(),{toast:c}=Ua(),[d,u]=N.useState(""),[h,p]=N.useState(!0),f=i||(a.length>0?a[0].id:n);N.useEffect(()=>{if(!s||!t&&!r){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),f?g():a.length===0&&!n&&p(!1)},[s,t,r,f,o,a,i]);const g=async()=>{if(!f){p(!1);return}try{const{data:b,error:v}=await q.from("brokerages").select("name").eq("id",f).single();if(v)throw v;u(b.name)}catch(b){console.error("Error loading brokerage info:",b),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{p(!1)}};return h?e.jsx(Cs,{title:"Manage Brokerages",description:"Loading brokerage information...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):f?e.jsx(Cs,{title:d||"Manage Brokerages",description:"Brokerage Management Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(us,{value:i||"",onValueChange:l,children:[e.jsxs(cs,{className:"w-[280px]",children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),e.jsx(hs,{placeholder:"Select brokerage"})]}),e.jsx(ds,{children:a.map(b=>e.jsx(Ze,{value:b.id,children:b.name},b.id))})]})]}),e.jsxs($r,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Zt,{value:"agents",children:"Agents"}),e.jsx(Zt,{value:"teams",children:"Teams"}),e.jsx(Zt,{value:"invite",children:"Invite Links"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Zt,{value:"activity",children:"Activity"}),e.jsx(Zt,{value:"analytics",children:"Analytics"}),e.jsx(Zt,{value:"shares",children:"Shares"})]}),e.jsx(ls,{value:"agents",className:"space-y-4",children:e.jsx(Zqs,{brokerageId:f})}),e.jsx(ls,{value:"teams",className:"space-y-4",children:e.jsx(iVs,{brokerageId:f})}),e.jsx(ls,{value:"invite",className:"space-y-4",children:e.jsx(sVs,{brokerageId:f})}),e.jsx(ls,{value:"referrals",className:"space-y-4",children:e.jsx(aVs,{})}),e.jsx(ls,{value:"leaderboard",className:"space-y-4",children:e.jsx(Zxt,{brokerageId:f,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(ls,{value:"activity",className:"space-y-4",children:e.jsx(eVs,{brokerageId:f})}),e.jsx(ls,{value:"analytics",className:"space-y-4",children:e.jsx(tVs,{brokerageId:f})}),e.jsx(ls,{value:"shares",className:"space-y-4",children:e.jsx(Fyt,{brokerageOnly:!0,brokerageId:f})})]})]})}):e.jsx(Cs,{title:"Manage Brokerages",description:"Brokerage Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ga,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})})};function lVs({brokerageId:s,canManage:t}){const{user:n}=gs(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,g]=N.useState(!1),[b,v]=N.useState(""),[j,_]=N.useState(""),[S,A]=N.useState(!1),T=async()=>{try{const{data:z,error:V}=await q.from("brokerage_announcements").select("*").eq("brokerage_id",s).order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1});if(V)throw V;const W=z;if(W&&W.length>0){const K=[...new Set(W.map(oe=>oe.created_by))],{data:Y}=await q.from("profiles").select("id, name, avatar_url").in("id",K),ee=new Map((Y==null?void 0:Y.map(oe=>[oe.id,oe]))||[]),ne=W.map(oe=>({...oe,author:ee.get(oe.created_by)||{name:"Unknown",avatar_url:null}}));a(ne)}else a([])}catch(z){console.error("Error fetching announcements:",z)}finally{l(!1)}};N.useEffect(()=>{T()},[s]);const D=()=>{v(""),_(""),A(!1),u(null)},L=z=>{z?(u(z),v(z.title),_(z.content),A(z.is_pinned)):D(),c(!0)},M=async()=>{if(!b.trim()||!j.trim()){ae.error("Please fill in all fields");return}g(!0);try{if(d){const{error:z}=await q.from("brokerage_announcements").update({title:b.trim(),content:j.trim(),is_pinned:S,pinned_at:S?new Date().toISOString():null}).eq("id",d.id);if(z)throw z;ae.success("Announcement updated")}else{const{error:z}=await q.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:b.trim(),content:j.trim(),is_pinned:S,pinned_at:S?new Date().toISOString():null});if(z)throw z;ae.success("Announcement created")}c(!1),D(),T()}catch(z){console.error("Error saving announcement:",z),ae.error("Failed to save announcement")}finally{g(!1)}},F=async()=>{if(h)try{const{error:z}=await q.from("brokerage_announcements").delete().eq("id",h);if(z)throw z;ae.success("Announcement deleted"),T()}catch(z){console.error("Error deleting announcement:",z),ae.error("Failed to delete announcement")}finally{p(null)}};return i?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(qd,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:e.jsx("div",{className:"h-20 bg-muted rounded"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(qd,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>L(),className:"gap-1",children:[e.jsx(As,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Ae,{children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No announcements yet"}):e.jsx("div",{className:"space-y-4",children:r.map(z=>{var V,W,K,Y;return e.jsx("div",{className:`p-4 rounded-lg border ${z.is_pinned?"bg-primary/5 border-primary/20":"bg-muted/30"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[z.is_pinned&&e.jsx(o4,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:z.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:z.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(aa,{className:"h-5 w-5",children:[e.jsx(ri,{src:((V=z.author)==null?void 0:V.avatar_url)||void 0}),e.jsx(ia,{className:"text-[10px]",children:((K=(W=z.author)==null?void 0:W.name)==null?void 0:K.charAt(0))||"?"})]}),e.jsx("span",{children:(Y=z.author)==null?void 0:Y.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:ks(new Date(z.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>L(z),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>p(z.id),children:e.jsx(bn,{className:"h-4 w-4"})})]})]})},z.id)})})})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsx(ws,{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(se,{htmlFor:"title",children:"Title"}),e.jsx(ge,{id:"title",value:b,onChange:z=>v(z.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"content",children:"Content"}),e.jsx(Ts,{id:"content",value:j,onChange:z=>_(z.target.value),placeholder:"Write your announcement...",rows:4})]}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{id:"pinned",checked:S,onCheckedChange:A}),e.jsxs(se,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(o4,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:M,disabled:f,children:f?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Oo,{open:!!h,onOpenChange:()=>p(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Announcement"}),e.jsx(Mo,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:F,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function cVs({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=K0e(),{user:a}=gs(),[i,l]=N.useState([]),[o,c]=N.useState(!0),[d,u]=N.useState(""),[h,p]=N.useState(new Set);N.useEffect(()=>{(async()=>{try{const{data:b,error:v}=await q.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(v)throw v;if(l(b||[]),b&&b.length>0){const j=b.map(S=>S.id),{data:_}=await q.from("agent_assistant_assignments").select("agent_id").in("agent_id",j);_&&p(new Set(_.map(S=>S.agent_id)))}}catch(b){console.error("Error fetching agents:",b)}finally{c(!1)}})()},[s]);const f=i.filter(g=>{var b,v;return g.name.toLowerCase().includes(d.toLowerCase())||g.email.toLowerCase().includes(d.toLowerCase())||((b=g.title)==null?void 0:b.toLowerCase().includes(d.toLowerCase()))||((v=g.areas_served)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Ae,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(_n,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search agents...",value:d,onChange:g=>u(g.target.value),className:"pl-9"})]})]}),e.jsx(Ae,{children:f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d?"No agents match your search":"No agents in this brokerage yet"}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:f.map(g=>e.jsx(dVs,{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 dVs({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(aa,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(ri,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(ia,{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(ze,{variant:"outline",className:"text-[10px] mt-1",children:"Has Assistant"})]}),s.bio&&e.jsx("p",{className:"text-xs text-muted-foreground text-center line-clamp-2 mb-3",children:s.bio}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[s.areas_served&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ca,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.areas_served})]}),s.years_experience&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:[s.years_experience," ",s.years_experience===1?"year":"years"," experience"]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[n&&e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:r,disabled:a,children:e.jsx(LA,{className:"h-4 w-4"})})}),e.jsxs(yc,{children:["Login as ",s.name]})]}),s.phone&&e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`tel:${s.phone}`,title:`Call ${s.name}`,children:e.jsx(Pr,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`mailto:${s.email}`,title:`Email ${s.name}`,children:e.jsx(Hs,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.linkedin_url,target:"_blank",rel:"noopener noreferrer",title:"LinkedIn",children:e.jsx(bf,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.instagram_url,target:"_blank",rel:"noopener noreferrer",title:"Instagram",children:e.jsx(mu,{className:"h-4 w-4"})})})]})]})}function uVs({brokerageId:s}){const[t,n]=N.useState([]),[r,a]=N.useState(!0);if(N.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),a(!1);return}const u=c.map(b=>b.id),{data:h,error:p}=await q.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(p)throw p;const f=new Map(c.map(b=>[b.id,b])),g=(h||[]).filter(b=>b.total_points>0).map(b=>{const v=f.get(b.user_id);return{user_id:b.user_id,total_points:b.total_points,name:(v==null?void 0:v.name)||"Unknown",avatar_url:(v==null?void 0:v.avatar_url)||null}});n(g)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Ae,{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(X2,{className:Et("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Ae,{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:Et("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(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:o.avatar_url||void 0}),e.jsx(ia,{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 hVs({brokerageId:s}){const t=In(),[n,r]=N.useState([]),[a,i]=N.useState(!0);N.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),i(!1);return}const u=c.map(b=>b.id),h=new Map(c.map(b=>[b.id,b])),{data:p,error:f}=await q.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",u).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(f)throw f;const g=(p||[]).map(b=>({id:b.id,slug:b.slug,property_address:b.property_address,city:b.city,price:b.price,property_type:b.property_type,agent_id:b.agent_id,agent:h.get(b.agent_id)||null,photos:b.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(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[1,2].map(o=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-32 bg-muted rounded-lg"})},o))})})]}):e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(As,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Ae,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(zr,{className:"h-10 w-10 text-muted-foreground mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No active listings from your brokerage yet"}),e.jsxs(B,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(As,{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(zr,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsx("span",{className:"text-[10px] font-medium bg-primary text-primary-foreground px-1.5 py-0.5 rounded uppercase",children:o.property_type.replace("_"," ")})})]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("p",{className:"font-semibold text-sm text-primary",children:l(o.price)}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:o.property_address||"Address not available"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:o.city}),o.agent&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 truncate",children:["Listed by ",o.agent.name]})]})]},o.id))}),n.length>0&&e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(tr,{className:"h-3 w-3 ml-1"})]})]})]})}function mVs(){const{user:s,isAdmin:t,isBrokerageManager:n}=gs(),r=In(),[a,i]=N.useState(!0),[l,o]=N.useState(null),[c,d]=N.useState(""),[u,h]=N.useState(0),[p,f]=N.useState(!1),[g,b]=N.useState(!1);return N.useEffect(()=>{(async()=>{if(s)try{const{data:j}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(j!=null&&j.brokerage_id)){i(!1);return}o(j.brokerage_id);const{data:_}=await q.from("brokerages").select("name").eq("id",j.brokerage_id).maybeSingle();_&&d(_.name);const{count:S}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",j.brokerage_id);if(h(S||0),t)f(!0),b(!0);else if(n){const{data:A}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",j.brokerage_id).maybeSingle();f(!!A),b(!!A)}}catch(j){console.error("Error fetching brokerage info:",j)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(Cs,{title:"My Brokerage",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):l?e.jsx(Cs,{title:c||"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 bg-muted/50 rounded-lg px-4 py-2",children:[e.jsx(_n,{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(B,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx($u,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(B,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(zr,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(lVs,{brokerageId:l,canManage:p}),e.jsx(cVs,{brokerageId:l,canManage:p}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(uVs,{brokerageId:l}),e.jsx(hVs,{brokerageId:l})]})]})}):e.jsx(Cs,{title:"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ga,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You're not currently part of a brokerage team."})]})})}function pVs(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 fVs(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 vZe={video:{icon:Al,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Nr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:El,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:yr,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:xl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function xVs({item:s,canManage:t}){const[n,r]=N.useState(!1),[a,i]=N.useState(null),l=wrs(),o=In(),c=vZe[s.content_type]||vZe.link,d=c.icon,u=N.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?pVs(s.url):null,[s]);N.useEffect(()=>{u||!s.url||s.content_type!=="video"||!fVs(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,p=()=>{o(`/brokerage-content/${s.id}`)},f=async()=>{try{await l.mutateAsync(s.id),ae.success("Content deleted")}catch{ae.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:p,children:[h?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:h,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/30 flex items-center justify-center",children:e.jsx(d,{className:"h-12 w-12 text-muted-foreground/30"})}),e.jsx(Ae,{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(ze,{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(ze,{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:["📅 ",ks(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",ks(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,onClick:g=>g.stopPropagation(),children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Lg,{className:"h-4 w-4"})})}),e.jsx(cc,{align:"end",children:e.jsxs(Xr,{onClick:g=>{g.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Oo,{open:n,onOpenChange:r,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Content"}),e.jsxs(Mo,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:f,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function gVs(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 bZe=[{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 yVs({brokerageId:s,categories:t}){var ye;const{user:n}=gs(),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState("📁"),[h,p]=N.useState(!1);N.useRef(null);const[f,g]=N.useState("video"),[b,v]=N.useState(""),[j,_]=N.useState(""),[S,A]=N.useState(""),[T,D]=N.useState(""),[L,M]=N.useState(""),[F,z]=N.useState(""),[V,W]=N.useState(""),K=_rs(),Y=jrs(s),ee=Nrs(),ne=krs(s),oe=()=>{g("video"),v(""),_(""),A(""),D(""),M(""),z(""),W("")},pe=async(_e,Me)=>{var Ce;const Te=(Ce=_e.target.files)==null?void 0:Ce[0];if(Te){p(!0);try{const Ee=Te.name.split(".").pop(),De=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${Ee}`,{error:Ie}=await q.storage.from("brokerage-content").upload(De,Te);if(Ie)throw Ie;const{data:{publicUrl:Fe}}=q.storage.from("brokerage-content").getPublicUrl(De);Me==="file"?(D(Fe),f==="graphic"&&!L&&M(Fe)):M(Fe),ae.success("File uploaded")}catch(Ee){ae.error(Ee.message||"Upload failed")}finally{p(!1)}}},ce=async()=>{if(!b.trim()){ae.error("Title is required");return}if(n)try{await K.mutateAsync({brokerage_id:s,category_id:V||null,content_type:f,title:b.trim(),description:j.trim()||null,url:S.trim()||null,file_url:T.trim()||null,thumbnail_url:L.trim()||null,event_date:F?new Date(F).toISOString():null,created_by:n.id}),ae.success("Content added!"),oe(),a(!1)}catch(_e){ae.error(_e.message||"Failed to add content")}},de=async()=>{if(o.trim())try{await Y.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),ae.success("Category created")}catch(_e){ae.error(_e.message||"Failed to create category")}},ie=async()=>{try{await ne.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(bs,{open:r,onOpenChange:a,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Content Type"}),e.jsxs(us,{value:f,onValueChange:g,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:bZe.map(_e=>e.jsx(Ze,{value:_e.value,children:_e.label},_e.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(ye=bZe.find(_e=>_e.value===f))==null?void 0:ye.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsxs(us,{value:V,onValueChange:W,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select category (optional)"})}),e.jsx(ds,{children:t.map(_e=>e.jsxs(Ze,{value:_e.id,children:[_e.icon," ",_e.name]},_e.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title *"}),e.jsx(ge,{value:b,onChange:_e=>v(_e.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{value:j,onChange:_e=>_(_e.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:f==="video"?"Video URL":f==="graphic"?"Canva / Image URL":f==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(ge,{value:S,onChange:_e=>{const Me=_e.target.value;if(A(Me),f==="video"&&!L){const Te=gVs(Me);Te&&M(Te)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:f==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{type:"file",accept:f==="pdf"?".pdf,.doc,.docx":"image/*",onChange:_e=>pe(_e,"file"),disabled:h}),h&&e.jsx(ss,{className:"h-4 w-4 animate-spin"})]}),T&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Thumbnail Image (optional)"}),e.jsx(ge,{type:"file",accept:"image/*",onChange:_e=>pe(_e,"thumbnail"),disabled:h}),L&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:L,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>M(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx(Fn,{className:"h-3 w-3"})})]})]}),f==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Event Date & Time"}),e.jsx(ge,{type:"datetime-local",value:F,onChange:_e=>z(_e.target.value)})]}),e.jsxs(B,{onClick:ce,disabled:K.isPending||!b.trim(),className:"w-full",children:[K.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",children:[e.jsx(Vo,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{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(B,{variant:"outline",size:"sm",onClick:ie,disabled:ne.isPending,children:[ne.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(_e=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[_e.icon," ",_e.name]}),!_e.is_default&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await ee.mutateAsync(_e.id),ae.success("Category deleted")},children:e.jsx(Fn,{className:"h-4 w-4"})})]},_e.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(ge,{value:d,onChange:_e=>u(_e.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(ge,{value:o,onChange:_e=>c(_e.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:_e=>_e.key==="Enter"&&de()}),e.jsx(B,{size:"sm",onClick:de,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function vVs(){const{user:s,isAdmin:t,isBrokerageManager:n}=gs(),[r,a]=N.useState(!0),[i,l]=N.useState(null),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,g]=N.useState("");N.useEffect(()=>{(async()=>{if(s)try{const{data:A}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(A!=null&&A.brokerage_id)){a(!1);return}l(A.brokerage_id);const{data:T}=await q.from("brokerages").select("name").eq("id",A.brokerage_id).maybeSingle();if(T&&c(T.name),t)u(!0);else if(n){const{data:D}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",A.brokerage_id).maybeSingle();u(!!D)}}catch(A){console.error("Error fetching brokerage info:",A)}finally{a(!1)}})()},[s,t,n]);const{data:b=[]}=yrs(i),{data:v=[],isLoading:j}=vrs(i,h),_=N.useMemo(()=>{if(!f.trim())return v;const S=f.toLowerCase();return v.filter(A=>{var T;return A.title.toLowerCase().includes(S)||((T=A.description)==null?void 0:T.toLowerCase().includes(S))||A.content_type.toLowerCase().includes(S)})},[v,f]);return r?e.jsx(Cs,{title:"Brokerage Content",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):i?e.jsx(Cs,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(yVs,{brokerageId:i,categories:b}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search content...",value:f,onChange:S=>g(S.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{variant:h===null?"default":"outline",size:"sm",onClick:()=>p(null),children:"All"}),b.map(S=>e.jsxs(B,{variant:h===S.id?"default":"outline",size:"sm",onClick:()=>p(S.id),children:[e.jsx("span",{className:"mr-1",children:S.icon}),S.name]},S.id))]})]}),j?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):_.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(yf,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:f.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:f.trim()?"Try a different search term or category.":d?"Add your first piece of content above.":"Your brokerage hasn't added content yet."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:_.map(S=>e.jsx(xVs,{item:S,canManage:d},S.id))})]})}):e.jsx(Cs,{title:"Brokerage Content",description:"Content Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ga,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You're not currently part of a brokerage team."})]})})}const _Ze={video:{icon:Al,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Nr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:El,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:yr,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:xl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function bVs(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 _Vs(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function wVs(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function jVs(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function NVs(){const{contentId:s}=_i(),{data:t,isLoading:n}=lt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await q.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(u)throw u;return d},enabled:!!s});if(n)return e.jsx(Cs,{title:"Brokerage Content",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!t)return e.jsx(Cs,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ga,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Content not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This content may have been removed."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(Ln,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=_Ze[t.content_type]||_Ze.link,a=r.icon,i=t.url||t.file_url,l=i&&_Vs(i)?bVs(i):null,o=i&&wVs(i)?jVs(i):null,c=l||o;return e.jsx(Cs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Ln,{to:"/brokerage-content",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ze,{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(ze,{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 ",ks(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx("div",{className:"relative w-full bg-black",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:c,className:"absolute top-0 left-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:t.title})})}),t.content_type==="graphic"&&t.file_url&&!c&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx("img",{src:t.file_url,alt:t.title,className:"w-full max-h-[600px] object-contain bg-muted"})}),!c&&t.content_type!=="graphic"&&t.thumbnail_url&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx("img",{src:t.thumbnail_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),t.description&&e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.description})})}),t.content_type==="event"&&t.event_date&&e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(yr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Event Date"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:ks(new Date(t.event_date),"EEEE, MMMM d, yyyy · h:mm a")})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[t.file_url&&e.jsx(B,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx(B,{variant:t.file_url?"outline":"default",asChild:!0,size:"lg",children:e.jsxs("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),c?"Open on YouTube":t.content_type==="event"?"Join Event":t.content_type==="graphic"?"Open in Canva":"Open Link"]})})]})]})})}const zge={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 kVs(s="open"){const{user:t}=gs();return lt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let n=q.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, avatar_url)").order("created_at",{ascending:!1});if(s==="open")n=n.eq("status","open");else if(s==="mine")n=n.eq("requester_user_id",t.id);else if(s==="filled")n=n.in("status",["filled","completed"]);else if(s==="my_claims"){const{data:i}=await q.from("brokerage_help_claims").select("request_id").eq("claimant_user_id",t.id),l=(i||[]).map(o=>o.request_id);if(l.length===0)return[];n=n.in("id",l)}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function SVs(s){return lt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function CVs(s){return lt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("brokerage_help_claims").select("*, claimant:profiles!brokerage_help_claims_claimant_user_id_fkey(name, email, phone, avatar_url)").eq("request_id",s).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function TVs(){const s=Gt(),{user:t,brokerageId:n}=gs();return gt({mutationFn:async r=>{if(!t||!n)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await q.from("brokerage_help_requests").insert({...r,brokerage_id:n,requester_user_id:t.id}).select().single();if(i)throw i;try{await q.functions.invoke("brokerage-help-notify",{body:{request_id:a.id}})}catch(l){console.warn("notify failed (non-blocking):",l)}return a},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function EVs(){const s=Gt(),{user:t}=gs();return gt({mutationFn:async({request_id:n,note:r})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await q.from("brokerage_help_claims").insert({request_id:n,claimant_user_id:t.id,note:r}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function AVs(){const s=Gt();return gt({mutationFn:async({claim_id:t,request_id:n,claimant_user_id:r})=>{const{error:a}=await q.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await q.from("brokerage_help_requests").update({status:"filled",assigned_user_id:r}).eq("id",n);if(i)throw i;try{await q.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-request",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function MVs(){const s=Gt();return gt({mutationFn:async({claim_id:t})=>{const{error:n}=await q.from("brokerage_help_claims").update({status:"declined",responded_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]})}})}function IVs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_help_requests").update({status:"cancelled"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function PVs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_help_requests").update({status:"completed"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function LVs(){const{user:s,brokerageId:t}=gs(),n=Gt(),r=lt({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await q.from("brokerage_help_notification_prefs").select("*").eq("user_id",s.id).eq("brokerage_id",t).maybeSingle();if(l)throw l;return i},enabled:!!s&&!!t}),a=gt({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await q.from("brokerage_help_notification_prefs").upsert({user_id:s.id,brokerage_id:t,email_enabled:i},{onConflict:"user_id,brokerage_id"});if(l)throw l},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...r,setEmailEnabled:a.mutate,isSaving:a.isPending}}function DVs(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 RVs(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 OVs({req:s,onClick:t}){var i;const n=zge[s.request_type],r=DVs(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(fe,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Ae,{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(ze,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx(ze,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground group-hover:translate-x-0.5 transition"})]}),e.jsx("h3",{className:"font-semibold text-base mb-2 line-clamp-2",children:s.title}),e.jsxs("div",{className:"space-y-1.5 text-sm text-muted-foreground",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gr,{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(Ca,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:a})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zl,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:RVs(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 FVs(){var c;const s=In(),{brokerageId:t}=gs(),[n,r]=N.useState("open"),{data:a=[],isLoading:i}=kVs(n),l=LVs(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(Cs,{title:"Help Board",description:"Ask a teammate to cover an open house, showing, or shift.",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx($r,{value:n,onValueChange:d=>r(d),children:e.jsxs(Ur,{children:[e.jsx(Zt,{value:"open",children:"Open"}),e.jsx(Zt,{value:"mine",children:"My Posts"}),e.jsx(Zt,{value:"my_claims",children:"My Claims"}),e.jsx(Zt,{value:"filled",children:"Filled"})]})}),e.jsxs(B,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ae,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(lm,{className:"h-4 w-4 text-primary"}):e.jsx(fw,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(se,{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(vn,{id:"email-notif",checked:o,disabled:l.isLoading||l.isSaving,onCheckedChange:d=>l.setEmailEnabled(d)})]})}),i?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(sb,{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(OVs,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(Cs,{title:"Help Board",description:"Brokerage Help Board",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(sb,{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 zVs(){const s=In(),{toast:t}=Ua(),n=TVs(),[r,a]=N.useState("open_house"),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(""),[b,v]=N.useState(""),[j,_]=N.useState(""),[S,A]=N.useState(""),[T,D]=N.useState(""),[L,M]=N.useState(""),[F,z]=N.useState("goodwill"),[V,W]=N.useState(""),[K,Y]=N.useState(""),ee=r==="open_house"||r==="showing_coverage",ne=r!=="general",oe=(ce,de)=>!ce||!de?null:`${ce}T${de}:00`,pe=async ce=>{if(ce.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const de=oe(d,h),ie=oe(d,f);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:de,event_end_at:ie,address:ee&&b.trim()||null,city:ee&&j.trim()||null,state:ee&&S.trim()||null,zip:ee&&T.trim()||null,mls_number:L.trim()||null,compensation_type:F,compensation_amount:V?Number(V):null,compensation_notes:K.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(de){t({title:"Could not post",description:(de==null?void 0:de.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(Cs,{title:"Post a Help Request",description:"Ask a teammate to cover for you",children:e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:pe,children:e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(zge).map(ce=>{const de=zge[ce],ie=ce===r;return e.jsxs("button",{type:"button",onClick:()=>a(ce),className:`text-left p-3 rounded-lg border-2 transition ${ie?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:de.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:de.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:de.description})]},ce)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ge,{id:"title",value:i,onChange:ce=>l(ce.target.value),placeholder:r==="open_house"?"Open house at 123 Oak St — Sat 1-3pm":"Quick description",maxLength:120,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Details"}),e.jsx(Ts,{id:"description",value:o,onChange:ce=>c(ce.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),ne&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"date",children:"Date"}),e.jsx(ge,{id:"date",type:"date",value:d,onChange:ce=>u(ce.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"start",children:"Start"}),e.jsx(ge,{id:"start",type:"time",value:h,onChange:ce=>p(ce.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"end",children:"End"}),e.jsx(ge,{id:"end",type:"time",value:f,onChange:ce=>g(ce.target.value)})]})]}),ee&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"address",children:"Address"}),e.jsx(ge,{id:"address",value:b,onChange:ce=>v(ce.target.value),placeholder:"123 Oak St"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(ge,{id:"city",value:j,onChange:ce=>_(ce.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ge,{id:"state",value:S,onChange:ce=>A(ce.target.value.toUpperCase()),maxLength:2})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zip",children:"Zip"}),e.jsx(ge,{id:"zip",value:T,onChange:ce=>D(ce.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(ge,{id:"mls",value:L,onChange:ce=>M(ce.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(se,{children:"Compensation"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{val:"goodwill",label:"Goodwill",sub:"Pay it forward"},{val:"flat_fee",label:"Flat Fee",sub:"Dollar amount"},{val:"referral_percent",label:"Referral %",sub:"On the deal"}].map(ce=>{const de=F===ce.val;return e.jsxs("button",{type:"button",onClick:()=>z(ce.val),className:`text-left p-3 rounded-lg border-2 transition ${de?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:ce.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ce.sub})]},ce.val)})}),F!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"amount",children:F==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(ge,{id:"amount",type:"number",min:"0",step:F==="referral_percent"?"1":"5",value:V,onChange:ce=>W(ce.target.value),placeholder:F==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(ge,{id:"comp-notes",value:K,onChange:ce=>Y(ce.target.value),placeholder:"e.g. Venmo same day, or split any leads",maxLength:200})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:n.isPending,className:"gap-2",children:[n.isPending&&e.jsx(ss,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function BVs(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 NNe(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function $Vs(){var L,M,F,z,V,W,K,Y;const{id:s}=_i(),t=In(),{user:n}=gs(),{toast:r}=Ua(),{data:a,isLoading:i}=SVs(s),{data:l=[]}=CVs(s),o=EVs(),c=AVs(),d=MVs(),u=IVs(),h=PVs(),[p,f]=N.useState("");if(i)return e.jsx(Cs,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(Cs,{title:"Not Found",description:"",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(Wr,{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=zge[a.request_type],b=BVs(a.event_start_at,a.event_end_at),v=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),j=(n==null?void 0:n.id)===a.requester_user_id,_=l.find(ee=>ee.claimant_user_id===(n==null?void 0:n.id)),S=l.find(ee=>ee.status==="accepted"),A=a.status==="open",T=a.compensation_type==="flat_fee"?a.compensation_amount?`$${Number(a.compensation_amount).toFixed(0)} flat fee`:"Flat fee":a.compensation_type==="referral_percent"?a.compensation_amount?`${a.compensation_amount}% referral`:"Referral percentage":"Goodwill (paying it forward)",D=async()=>{if(!p.trim()){r({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:p.trim()}),r({title:"You're in!",description:"The requester will review and pick someone."}),f("")}catch(ee){r({title:"Could not submit",description:ee==null?void 0:ee.message,variant:"destructive"})}};return e.jsx(Cs,{title:a.title,description:`${g.emoji} ${g.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"})," Back to board"]}),e.jsx(fe,{children:e.jsxs(Ae,{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(ze,{variant:"secondary",children:[g.emoji," ",g.label]}),e.jsx(ze,{variant:A?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(aa,{className:"h-7 w-7",children:[e.jsx(ri,{src:((L=a.requester)==null?void 0:L.avatar_url)||void 0}),e.jsx(ia,{children:NNe((M=a.requester)==null?void 0:M.name)})]}),e.jsx("span",{children:((F=a.requester)==null?void 0:F.name)||"Teammate"})]})]}),e.jsx("h1",{className:"text-2xl font-bold",children:a.title}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2",children:[b&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(gr,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"When"}),e.jsx("div",{children:b})]})]}),v&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Ca,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Where"}),e.jsx("div",{children:v})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Zl,{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:T})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(JS,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"MLS"}),e.jsx("div",{children:a.mls_number})]})]})]}),a.description&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h3",{className:"text-xs uppercase tracking-wide font-semibold text-muted-foreground mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:a.description})]}),a.compensation_notes&&e.jsxs("p",{className:"text-sm text-muted-foreground italic",children:["💰 ",a.compensation_notes]})]})}),!j&&A&&!_&&e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Ts,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:p,onChange:ee=>f(ee.target.value),rows:3,maxLength:400}),e.jsxs(B,{onClick:D,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(ss,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!j&&_&&e.jsx(fe,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Ae,{className:"p-4 flex items-center gap-3",children:[e.jsx(Lr,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",_.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."]})]})]})}),S&&(j||S.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(fe,{className:"border-primary/30",children:e.jsxs(Ae,{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(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:((z=S.claimant)==null?void 0:z.avatar_url)||void 0}),e.jsx(ia,{children:NNe((V=S.claimant)==null?void 0:V.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(W=S.claimant)==null?void 0:W.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:[((K=S.claimant)==null?void 0:K.email)&&e.jsxs("a",{href:`mailto:${S.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Hs,{className:"h-4 w-4"})," ",S.claimant.email]}),((Y=S.claimant)==null?void 0:Y.phone)&&e.jsxs("a",{href:`tel:${S.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Pr,{className:"h-4 w-4"})," ",S.claimant.phone]})]})]})}),j&&e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6 space-y-3",children:[e.jsxs("h3",{className:"font-semibold",children:["Interested agents (",l.length,")"]}),l.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No claims yet. Hang tight — your teammates were just notified."}),l.map(ee=>{var ne,oe,pe,ce,de;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:((ne=ee.claimant)==null?void 0:ne.avatar_url)||void 0}),e.jsx(ia,{children:NNe((oe=ee.claimant)==null?void 0:oe.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx("div",{className:"font-medium",children:((pe=ee.claimant)==null?void 0:pe.name)||"Teammate"}),e.jsx(ze,{variant:"outline",className:"capitalize text-xs",children:ee.status})]}),ee.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',ee.note,'"']}),ee.status==="pending"&&A&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(B,{size:"sm",onClick:()=>c.mutate({claim_id:ee.id,request_id:a.id,claimant_user_id:ee.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(Lr,{className:"h-3.5 w-3.5"})," Pick ",((de=(ce=ee.claimant)==null?void 0:ce.name)==null?void 0:de.split(" ")[0])||"them"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:ee.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(Fn,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},ee.id)}),j&&A&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>u.mutate(a.id),disabled:u.isPending,children:"Cancel request"})}),j&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(B,{size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Mark complete"})})]})})]})})}function T_t({onSelect:s,maxHeight:t="460px"}){const[n,r]=N.useState(""),[a,i]=N.useState("all"),{data:l=[],isLoading:o}=lt({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:h}=await q.from("newsletter_graphics").select("*").eq("is_active",!0).order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0}).order("created_at",{ascending:!1});if(h)throw h;return u||[]}}),c=N.useMemo(()=>{const u=new Set;return l.forEach(h=>u.add(h.category||"general")),["all",...Array.from(u).sort()]},[l]),d=N.useMemo(()=>{const u=n.trim().toLowerCase();return l.filter(h=>a!=="all"&&h.category!==a?!1:u?h.title.toLowerCase().includes(u)||(h.description||"").toLowerCase().includes(u)||(h.tags||[]).some(p=>p.toLowerCase().includes(u)):!0)},[l,n,a]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ge,{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(mi,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ss,{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(nl,{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(ze,{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(ua,{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 UVs=[{key:"search",label:"Search for Properties",icon:_r,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:Pr,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:Hs,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:yr,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:zr,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:Zl,defaultText:"Get My Home Value",placeholder:"https://your-website.com/home-value",helper:"Link to your home valuation page"},{key:"openhouse",label:"See Open Houses",icon:Ca,defaultText:"See Open Houses",placeholder:"https://your-website.com/open-houses",helper:"Link to your open houses page"},{key:"forward",label:"Forward to a Friend",icon:Hl,defaultText:"Forward to a Friend",isForward:!0,placeholder:"Optional landing page (or leave blank)",helper:"Opens recipient's email pre-filled — leave blank to default"},{key:"custom",label:"Custom Button",icon:oc,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function wZe(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function qVs(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function E_t({html:s,onChange:t}){const{user:n}=gs(),r=N.useRef(null),a=N.useRef(""),i=N.useRef(t);i.current=t;const[l,o]=N.useState("desktop"),c=N.useRef(null),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f,g]=N.useState(""),b=N.useRef(null),v=()=>{var ht;const St=(ht=r.current)==null?void 0:ht.contentDocument,$t=St==null?void 0:St.getSelection();$t&&$t.rangeCount>0&&(St!=null&&St.body.contains($t.anchorNode))&&(b.current=$t.getRangeAt(0).cloneRange())},j=()=>{var Xt;const St=c.current,$t=(Xt=r.current)==null?void 0:Xt.contentDocument;if(!St||!$t)return;let ht=h.trim();ht&&!/^(https?:|mailto:|tel:|#|\/)/i.test(ht)&&(ht="https://"+ht),St.setAttribute("href",ht),St.setAttribute("target","_blank");const Ut=f.trim();Ut&&Ut!==(St.textContent||"").trim()&&(St.textContent=Ut);const Es=` `+$t.documentElement.outerHTML;a.current=Es,i.current(Es),u(!1)};N.useEffect(()=>{var ht,Ut;const St=r.current;if(!St||a.current===s)return;const $t=()=>{const Es=St.contentDocument;if(!Es)return;Es.open(),Es.write(s||""),Es.close(),a.current=s;const Xt=Es.body;if(!Xt)return;Xt.setAttribute("contenteditable","true"),Xt.style.outline="none",Xt.style.minHeight="400px",Xt.style.cursor="text";const Ys=()=>{const Bs=` `+Es.documentElement.outerHTML;a.current=Bs,i.current(Bs)};Xt.addEventListener("input",Ys),Xt.addEventListener("blur",Ys),Xt.addEventListener("mouseup",v),Xt.addEventListener("keyup",v),Es.addEventListener("selectionchange",v);const Ss=Bs=>{var Gn;const Us=Bs.target,sn=Us==null?void 0:Us.closest("a");if(sn){if(Bs.metaKey||Bs.ctrlKey||Bs.shiftKey)return;Bs.preventDefault(),Bs.stopPropagation(),c.current=sn,p(sn.getAttribute("href")||""),g((sn.textContent||"").trim()),u(!0);return}const Jn=Es.getSelection();if(!Jn)return;const fn=(Gn=Es.caretRangeFromPoint)==null?void 0:Gn.call(Es,Bs.clientX,Bs.clientY),Sn=fn==null?void 0:fn.startContainer;if(Sn&&Sn.nodeType===Node.TEXT_NODE){const Hr=Sn.textContent||"",pi=fn.startOffset,Ms=Hr.lastIndexOf("[",pi),bi=Hr.indexOf("]",pi);if(Ms!==-1&&bi!==-1&&bi>Ms){const Rr=Es.createRange();Rr.setStart(Sn,Ms),Rr.setEnd(Sn,bi+1),Jn.removeAllRanges(),Jn.addRange(Rr),b.current=Rr.cloneRange()}}};Xt.addEventListener("click",Ss,!0)};((ht=St.contentDocument)==null?void 0:ht.readyState)==="complete"||(Ut=St.contentDocument)!=null&&Ut.body?$t():St.addEventListener("load",$t,{once:!0})},[s]);const _=(St,$t)=>{var Es;const ht=(Es=r.current)==null?void 0:Es.contentDocument;if(!ht)return;ht.body.focus(),ht.execCommand(St,!1,$t);const Ut=` `+ht.documentElement.outerHTML;a.current=Ut,i.current(Ut)},S=()=>{const St=window.prompt("Enter URL (https://...)");St&&_("createLink",St)},A=(St,$t)=>{var Es;const ht=(Es=r.current)==null?void 0:Es.contentDocument;if(!ht)return;if(ht.body.focus(),$t==="cursor"&&b.current&&ht.body.contains(b.current.startContainer)){const Xt=ht.getSelection();if(Xt){Xt.removeAllRanges(),Xt.addRange(b.current),ht.execCommand("insertHTML",!1,St);const Ys=` `+ht.documentElement.outerHTML;a.current=Ys,i.current(Ys);return}}$t==="top"?ht.body.insertAdjacentHTML("afterbegin",St):ht.body.insertAdjacentHTML("beforeend",St);const Ut=` `+ht.documentElement.outerHTML;a.current=Ut,i.current(Ut)},[T,D]=N.useState(!1),[L,M]=N.useState(null),[F,z]=N.useState(""),[V,W]=N.useState(""),[K,Y]=N.useState("#406E71"),[ee,ne]=N.useState("cursor"),oe=St=>{M(St),z(St.defaultText),W(""),D(!0)},pe=()=>{if(!L)return;const St=V.trim();if(!L.isForward&&!St)return;let $t=St;if(L.isForward){const Xt=St||"",Ys=encodeURIComponent("You should see this newsletter"),Ss=encodeURIComponent(Xt?`I thought you'd like this — take a look: ${Xt} `:`I thought you'd like this newsletter — take a look! `);$t=`mailto:?subject=${Ys}&body=${Ss}`}else L.hrefPrefix==="tel:"?$t="tel:"+St.replace(/[^0-9+]/g,""):L.hrefPrefix==="mailto:"?$t="mailto:"+St:/^https?:\/\//i.test(St)||($t="https://"+St);const ht=(F||L.defaultText).replace(/[<>]/g,""),Ut=K||"#406E71",Es=`
${ht}

 

`;A(Es,ee),D(!1)},[ce,de]=N.useState(!1),[ie,ye]=N.useState(""),[_e,Me]=N.useState(""),[Te,Ce]=N.useState(""),[Ee,De]=N.useState("cursor"),Ie=(()=>{if(_e.trim())return _e.trim();const St=wZe(ie);return St?`https://i.ytimg.com/vi/${St}/hqdefault.jpg`:""})(),Fe=()=>{ye(""),Me(""),Ce(""),de(!0)},qe=()=>{const St=ie.trim();if(!St)return;let $t=St;/^https?:\/\//i.test($t)||($t="https://"+$t);const ht=wZe($t),Ut=ht?null:qVs($t);let Es=_e.trim();!Es&&ht&&(Es=`https://i.ytimg.com/vi/${ht}/hqdefault.jpg`),!Es&&Ut&&(Es=`https://vumbnail.com/${Ut}.jpg`),Es||(Es="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const Xt=(Te||"Watch the video").replace(/[<>]/g,""),Ys=`
${Xt}
▶ ${Xt}

 

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

 

`.trim();A(ht,Ke),Je(!1)},{data:Qt,isLoading:ns}=lt({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&ce,queryFn:async()=>{const{data:St,error:$t}=await q.from("agent_videos").select("id, title, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",n.id).eq("is_deleted",!1).eq("status","ready").not("share_token","is",null).order("created_at",{ascending:!1}).limit(50);if($t)throw $t;return St||[]}}),$s=St=>{St.share_token&&(ye(`https://video.relevelup.com/share/video/${St.share_token}`),Me(`https://video.relevelup.com/thumb/${St.share_token}`),Ce(St.title||"Watch the video"))},Ds=l==="mobile"?390:"100%",Dt=l==="mobile"?390:void 0;return e.jsxs("div",{className:"rounded-md border overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b bg-muted/40 px-2 py-1.5 flex-wrap",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("bold"),title:"Bold",children:e.jsx(YS,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("italic"),title:"Italic",children:e.jsx(e4,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("underline"),title:"Underline",children:e.jsx(NL,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("insertUnorderedList"),title:"Bullet list",children:e.jsx(Ep,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("insertOrderedList"),title:"Numbered list",children:e.jsx(zv,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:S,title:"Insert link",children:e.jsx(tl,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("undo"),title:"Undo",children:e.jsx(u4,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("redo"),title:"Redo",children:e.jsx(l4,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(oc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(cc,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(I4,{children:"Insert a call-to-action"}),e.jsx(Qg,{}),UVs.map(St=>{const $t=St.icon;return e.jsxs(Xr,{onClick:()=>oe(St),children:[e.jsx($t,{className:"h-4 w-4 mr-2"}),St.label]},St.key)})]})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:dt,children:[e.jsx(nl,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:Fe,children:[e.jsx(vr,{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($L,{type:"single",value:l,onValueChange:St=>St&&o(St),size:"sm",className:"h-7",children:[e.jsx(XA,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(gb,{className:"h-3.5 w-3.5"})}),e.jsx(XA,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(rg,{className:"h-3.5 w-3.5"})})]})})]}),e.jsxs("div",{className:"px-3 py-1.5 bg-primary/5 border-b text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(oc,{className:"h-3 w-3"}),e.jsxs("span",{children:["Tip: click where you want to add an image, video, or button — or click a ",e.jsx("em",{children:"[ bracketed placeholder ]"})," to replace it. Click any button/link to edit where it goes."]})]}),e.jsx("div",{className:"bg-muted/20 flex justify-center overflow-auto",style:{padding:l==="mobile"?16:0},children:e.jsx("iframe",{ref:r,title:"Newsletter visual editor",className:"bg-white",style:{width:Ds,maxWidth:Dt,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(bs,{open:d,onOpenChange:u,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{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(se,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(ge,{id:"link-edit-text",value:f,onChange:St=>g(St.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(ge,{id:"link-edit-href",value:h,onChange:St=>p(St.target.value),placeholder:"https://your-website.com/...",autoFocus:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use https://… for a web page, mailto:you@email.com for email, or tel:+15555551234 for a phone number."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:j,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(bs,{open:T,onOpenChange:D,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Insert ",(L==null?void 0:L.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"cta-text",children:"Button text"}),e.jsx(ge,{id:"cta-text",value:F,onChange:St=>z(St.target.value),placeholder:L==null?void 0:L.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"cta-value",children:L==null?void 0:L.helper}),e.jsx(ge,{id:"cta-value",value:V,onChange:St=>W(St.target.value),placeholder:L==null?void 0:L.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{id:"cta-color",type:"color",value:K,onChange:St=>Y(St.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(ge,{value:K,onChange:St=>Y(St.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Position"}),e.jsxs(db,{value:ee,onValueChange:St=>ne(St),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"cursor",id:"cta-cursor"}),e.jsxs(se,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(oc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"top",id:"cta-top"}),e.jsxs(se,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Bu,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"bottom",id:"cta-bottom"}),e.jsxs(se,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(om,{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:K,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:F||(L==null?void 0:L.defaultText)})})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:pe,disabled:!(L!=null&&L.isForward)&&!V.trim(),children:"Insert Button"})]})]})}),e.jsx(bs,{open:ce,onOpenChange:de,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Insert Video Block"})}),e.jsxs($r,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"library",children:"My Library"}),e.jsx(Zt,{value:"url",children:"From URL"}),e.jsx(Zt,{value:"record",children:"Record New"})]}),e.jsxs(ls,{value:"library",className:"space-y-3 mt-2",children:[ns?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(ss,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!Qt||Qt.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(vr,{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:Qt.map(St=>{const $t=ie.includes(St.share_token||"___"),ht=St.share_token?`https://video.relevelup.com/thumb/${St.share_token}`:St.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>$s(St),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${$t?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[ht?e.jsx("img",{src:ht,alt:St.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(vr,{className:"h-6 w-6"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-black/60 w-9 h-9 flex items-center justify-center",children:e.jsx(Al,{className:"h-4 w-4 text-white fill-white"})})})]}),e.jsx("div",{className:"p-1.5",children:e.jsx("p",{className:"text-xs font-medium line-clamp-1",children:St.title||"Untitled"})})]},St.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(ge,{id:"vid-title-lib",value:Te,onChange:St=>Ce(St.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(ls,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(ge,{id:"vid-url",value:ie,onChange:St=>ye(St.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(se,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(ge,{id:"vid-title",value:Te,onChange:St=>Ce(St.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(ge,{id:"vid-thumb",value:_e,onChange:St=>Me(St.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(ls,{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(vr,{className:"h-10 w-10 mx-auto text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Record a quick video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:`Record a personal intro, market update, or property tour. When you're done, it'll show up in "My Library" and you can pick it from there.`})]}),e.jsx(B,{type:"button",onClick:()=>{window.open("/mission-control/video/record","_blank")},children:"Open Video Recorder"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Opens in a new tab — come back here when you're done."})]})})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(se,{children:"Position"}),e.jsxs(db,{value:Ee,onValueChange:St=>De(St),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"cursor",id:"vid-cursor"}),e.jsxs(se,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(oc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"top",id:"vid-top"}),e.jsxs(se,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Bu,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"bottom",id:"vid-bottom"}),e.jsxs(se,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(om,{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:St=>{St.target.style.opacity="0.3"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-black/65 text-white flex items-center justify-center",style:{width:56,height:56,fontSize:24},children:"▶"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>de(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:qe,disabled:!ie.trim(),children:"Insert Video"})]})]})}),e.jsx(bs,{open:ve,onOpenChange:Je,children:e.jsxs(vs,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Insert Image"})}),e.jsxs($r,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"library",children:"Library"}),e.jsx(Zt,{value:"upload",children:"Upload"}),e.jsx(Zt,{value:"url",children:"From URL"})]}),e.jsx(ls,{value:"library",className:"mt-2",children:e.jsx(T_t,{maxHeight:"380px",onSelect:St=>{it(St.image_url),Ne||He(St.title)}})}),e.jsxs(ls,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:Ge,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:St=>{var ht;const $t=(ht=St.target.files)==null?void 0:ht[0];$t&&Bt($t),St.target.value=""}}),we?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:we,alt:"Preview",className:"w-full max-h-48 object-contain"}),e.jsxs("div",{className:"flex justify-between items-center p-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground truncate",children:"Uploaded ✓"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>it(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var St;return(St=Ge.current)==null?void 0:St.click()},disabled:tt,className:"w-full rounded-md border-2 border-dashed border-border hover:border-primary/50 hover:bg-muted/40 transition-colors py-10 text-center disabled:opacity-60",children:tt?e.jsxs(e.Fragment,{children:[e.jsx(ss,{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(Sa,{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(ls,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"img-url",children:"Image URL"}),e.jsx(ge,{id:"img-url",value:we,onChange:St=>it(St.target.value),placeholder:"https://..."})]}),we&&/^https?:\/\//i.test(we)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:we,alt:"Preview",className:"w-full max-h-48 object-contain",onError:St=>{St.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(se,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(ge,{id:"img-alt",value:Ne,onChange:St=>He(St.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Size"}),e.jsxs(db,{value:$e,onValueChange:St=>Ye(St),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"full",id:"img-full"}),e.jsx(se,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"half",id:"img-half"}),e.jsx(se,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Position"}),e.jsxs(db,{value:Ke,onValueChange:St=>rt(St),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"cursor",id:"img-cursor"}),e.jsxs(se,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(oc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"top",id:"img-top"}),e.jsxs(se,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Bu,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fd,{value:"bottom",id:"img-bottom"}),e.jsxs(se,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(om,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>Je(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:kt,disabled:!we.trim()||tt,children:"Insert Image"})]})]})})]})}const jZe="newsletter-content",VVs="inline-images";function HVs(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:M}=await q.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return M}}),T=(A==null?void 0:A.role)==="team_leader",D=(A==null?void 0:A.team_id)??null;N.useEffect(()=>{s&&(d((n==null?void 0:n.title)??""),h((n==null?void 0:n.description)??""),f((n==null?void 0:n.html_content)??KVs()),b((n==null?void 0:n.is_template)??!1),j((n==null?void 0:n.share_scope)??"private"))},[s,n]);const L=async()=>{if(a){if(!c.trim()){ae.error("Please enter a title");return}if(!p.trim()){ae.error("Newsletter content is empty");return}S(!0);try{const M=await GVs(p);M!==p&&f(M);const F={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:M,is_template:g,share_scope:v,shared_team_id:v==="team"?D:null,shared_brokerage_id:v==="brokerage"?o:null};if(v==="team"&&!D){ae.error("You must be a team leader to share with a team"),S(!1);return}if(v==="brokerage"&&!l){ae.error("Only brokerage managers can share to a brokerage"),S(!1);return}if(v==="global"&&!i){ae.error("Only admins can publish global starter templates"),S(!1);return}let z;if(n!=null&&n.id?{error:z}=await q.from("agent_custom_newsletters").update(F).eq("id",n.id):{error:z}=await q.from("agent_custom_newsletters").insert(F),z)throw z;ae.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(M){ae.error(M.message||"Failed to save")}finally{S(!1)}}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(ws,{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(se,{htmlFor:"acn-title",children:"Title *"}),e.jsx(ge,{id:"acn-title",value:c,onChange:M=>d(M.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(ge,{id:"acn-desc",value:u,onChange:M=>h(M.target.value),placeholder:"Short summary"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-muted/30 px-4 py-3",children:[e.jsx(vn,{id:"acn-template",checked:g,onCheckedChange:b}),e.jsx(se,{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"})]}),(T||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(se,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(db,{value:v,onValueChange:M=>j(M),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Fd,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(se,{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"})]})]}),T&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Fd,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(se,{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(Fd,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(se,{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(Fd,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(se,{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(se,{className:"mb-2 block",children:"Content"}),e.jsx(E_t,{html:p,onChange:f})]})]}),e.jsxs(Xn,{className:"px-6 py-3 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsxs(B,{onClick:L,disabled:_,children:[_?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function KVs(){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 yLe=/\[[^\]\[<>]{2,80}\]/g;function YVs(s){return s.match(yLe)||[]}function NZe(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function ZVs(s){const t=[],n=new RegExp(yLe.source,"g");let r;for(;(r=n.exec(s))!==null;)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 p;return d?p=u&&!/^#+$/.test(h)?`Date · ${NZe(h)}`:`Date ${i[l.token]}`:(p=NZe(c),a[l.token]>1&&(p+=` (${i[l.token]} of ${a[l.token]})`)),{index:o,token:l.token,label:p,hint:d?"Day of the month, e.g. 14":l.token}})}function QVs({html:s,onChange:t,originalHtml:n}){const r=N.useMemo(()=>ZVs(s),[s]),[a,i]=N.useState({}),[l,o]=N.useState([]),c=N.useRef(null);c.current===null&&s&&(c.current=n??s);const d=N.useRef(!1);N.useEffect(()=>{if(d.current){d.current=!1;return}i({}),o([])},[s]);const u=()=>{const j=new RegExp(yLe.source,"g");let _=0;const S=s.replace(j,A=>{const T=(a[_]||"").trim();return _+=1,T||A});S!==s&&(o(A=>[...A,{html:s,values:a}]),d.current=!0,i({}),t(S))},h=()=>{const j=l[l.length-1];j&&(o(_=>_.slice(0,-1)),d.current=!0,i(j.values),t(j.html))},p=()=>{const j=c.current;!j||j===s||(o([]),d.current=!0,i({}),t(j))},f=l.length>0,g=!!c.current&&c.current!==s,b=e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{type:"button",size:"sm",variant:"outline",onClick:h,disabled:!f,children:[e.jsx(z9,{className:"h-3.5 w-3.5 mr-1"}),"Undo last fill"]}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:p,disabled:!g,children:[e.jsx(Fh,{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(xr,{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."})]}),(f||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?"}),b]})]});const v=r.filter(j=>(a[j.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(Dl,{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(ze,{variant:"secondary",className:"shrink-0",children:[v,"/",r.length," ready"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:r.map(j=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:j.label}),e.jsx(ge,{value:a[j.index]||"",placeholder:j.hint,className:"h-10 text-sm",onChange:_=>i(S=>({...S,[j.index]:_.target.value})),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),u())}})]},j.index))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{type:"button",size:"sm",onClick:u,children:[e.jsx(gL,{className:"h-3.5 w-3.5 mr-1"}),"Apply to email"]}),b]}),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 jR(){var a;const{user:s}=gs(),{data:t,isLoading:n}=lt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,u,h,p;const[i,l]=await Promise.all([q.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),q.from("profiles").select("email, name").eq("id",s.id).maybeSingle()]),o=i.data,c=l.data;return{reply_to_email:((d=o==null?void 0:o.reply_to_email)==null?void 0:d.trim())||((u=c==null?void 0:c.email)==null?void 0:u.trim())||s.email||null,display_name:((h=o==null?void 0:o.display_name)==null?void 0:h.trim())||((p=c==null?void 0:c.name)==null?void 0:p.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:n,settings:t}}function M1e(){const{user:s}=gs();return lt({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,n]=await Promise.all([q.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),q.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]),r=t.data||[],a=r.filter(l=>l.status==="verified"),i=r.filter(l=>l.status==="pending");return{hasVerifiedSes:a.length>0,hasPendingSes:i.length>0,hasAnySender:r.length>0,hasGmail:!!n.data,verifiedEmails:a.map(l=>l.email),pendingEmails:i.map(l=>l.email)}}})}function I1e({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=In();return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{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(Gi,{className:"h-5 w-5"})}),e.jsx(_s,{children:"Verify your sending email first"})]}),e.jsx(Qn,{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(gr,{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(Hs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:i})]},i)),e.jsx("p",{className:"text-xs text-muted-foreground pt-1",children:"Check that inbox (and your spam folder) for an email from Amazon Web Services and click the verification link."})]}):e.jsx("div",{className:"rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground",children:"It only takes a minute — add your email address on the Integrations page, then click the verification link Amazon sends you."}),e.jsxs(Xn,{className:"gap-2 sm:gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Not now"}),e.jsxs(B,{onClick:()=>{t(!1),a("/mission-control/integrations")},children:[e.jsx(tr,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function NR(){const s=fa();return lt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(n)throw n;return t},enabled:!!s})}function XVs(s){return lt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(n)throw n;return t},enabled:!!s})}function vLe(){const s=Gt(),t=fa();return gt({mutationFn:async({name:n,color:r})=>{const{data:a,error:i}=await q.from("contact_custom_tags").insert({owner_user_id:t,name:n.trim(),color:r||"#6366F1"}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]})}})}function JVs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("contact_custom_tags").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function eHs(){const s=Gt();return gt({mutationFn:async({id:t,name:n,color:r})=>{const a={};n!==void 0&&(a.name=n.trim()),r!==void 0&&(a.color=r);const{error:i}=await q.from("contact_custom_tags").update(a).eq("id",t);if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function A_t(){const s=Gt();return gt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await q.from("contact_custom_tag_assignments").insert({contact_id:t,tag_id:n});if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function tHs(){const s=Gt();return gt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await q.from("contact_custom_tag_assignments").delete().eq("contact_id",t).eq("tag_id",n);if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function P1e(){const s=fa();return lt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags(id, name, color)");if(n)throw n;return t},enabled:!!s})}function bLe(){const{user:s}=gs();return lt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function M_t(){const s=Gt(),{user:t}=gs();return gt({mutationFn:async({name:n,filters:r,sort_by:a})=>{const{data:i,error:l}=await q.from("contact_smart_lists").insert({owner_user_id:t.id,name:n,filters:r,sort_by:a}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),Dr({title:"Smart filter saved"})},onError:n=>{Dr({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function I_t(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("contact_smart_lists").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),Dr({title:"Smart filter deleted"})}})}const kZe=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function SZe(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(f=>f[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(" · "),p={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,(f,g)=>p[g]??`{{${g}}}`)}function sHs(s,t,n,r){const a=t.trim()?`
${kZe(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${kZe(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function nHs(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 rHs=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function aHs(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=rHs.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 _Le({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=gs();bh();const{isReady:l,settings:o}=jR(),{data:c}=M1e(),[d,u]=N.useState(!1),h=fa(),{data:p}=lt({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:Fs}=await q.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 Fs}}),[f,g]=N.useState("visual"),[b,v]=N.useState("all"),[j,_]=N.useState(""),[S,A]=N.useState(""),[T,D]=N.useState(""),[L,M]=N.useState(""),[F,z]=N.useState(!0),[V,W]=N.useState([]),[K,Y]=N.useState(null),[ee,ne]=N.useState(new Set),[oe,pe]=N.useState(""),[ce,de]=N.useState(!1),[ie,ye]=N.useState(!1),[_e,Me]=N.useState(!1),[Te,Ce]=N.useState({sent:0,failed:0,total:0,currentName:""}),[Ee,De]=N.useState(!0),[Ie,Fe]=N.useState(!1),[qe,ve]=N.useState([]),[Je,we]=N.useState(!1),[it,Ne]=N.useState(new Set),[He,$e]=N.useState("now"),[Ye,Ke]=N.useState(""),{data:rt=[]}=NR(),{data:tt=[]}=P1e(),{data:at=[]}=bLe(),{data:Ge=[],isLoading:dt}=lt({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const Fs=[];let $n=0;const Cr=1e3;for(;;){const{data:ts,error:Oe}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",h).not("email","is",null).neq("email","").order("first_name").range($n,$n+Cr-1);if(Oe)throw Oe;if(!ts||ts.length===0||(Fs.push(...ts),ts.length{const{data:Fs}=await q.from("ses_suppressed_emails").select("email");return(Fs||[]).map($n=>$n.email.toLowerCase())}}),{data:kt}=lt({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:Fs}=await q.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(Fs!=null&&Fs.brokerage_id))return null;const{data:$n}=await q.from("brokerages").select("name, city, state").eq("id",Fs.brokerage_id).maybeSingle();return $n}}),{data:Qt}=lt({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:Fs}=await q.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",h).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return Fs}}),ns=!!(Qt!=null&&Qt.mls_provider_id),$s=(Qt==null?void 0:Qt.mls_agent_id)||(Qt==null?void 0:Qt.mls_agent_key)||null,{data:Ds=[],isLoading:Dt}=lt({queryKey:["newsletter-agent-listings",h,$s],enabled:!!h&&!!$s&&Je,staleTime:60*1e3,queryFn:async()=>{if(!$s)return[];const{data:Fs}=await q.from("mlsgrid_listings").select("listing_key, address, city, state, list_price, bedrooms, bathrooms_total, living_area, photos, standard_status, modification_timestamp").eq("list_agent_mls_id",$s).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return Fs||[]}}),{data:St=[],isLoading:$t}=lt({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Je,staleTime:60*1e3,queryFn:async()=>{const{data:Fs}=await q.from("listings").select("id, slug, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, created_at").eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]).order("created_at",{ascending:!1}).limit(30),$n=Fs||[];if($n.length===0)return[];const Cr=$n.map(ct=>ct.id),{data:ts}=await q.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",Cr),Oe=new Map,Qe=new Map;for(const ct of ts||[])ct.is_primary&&!Oe.has(ct.listing_id)&&Oe.set(ct.listing_id,ct.photo_url),Qe.has(ct.listing_id)||Qe.set(ct.listing_id,ct.photo_url);return $n.map(ct=>({...ct,_photo:Oe.get(ct.id)||Qe.get(ct.id)||""}))}}),{data:ht=!1}=lt({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:Fs}=await q.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(Fs||0)>0}}),Ut=N.useMemo(()=>{const Fs=new Set(Bt);return Ge.filter($n=>$n.email&&$n.email.includes("@")&&!Fs.has($n.email.toLowerCase()))},[Ge,Bt]),Es=N.useMemo(()=>{if(V.length===0)return null;const Fs=new Set;for(const $n of tt)V.includes($n.tag_id)&&Fs.add($n.contact_id);return Fs},[tt,V]),Xt=N.useMemo(()=>at.find(Fs=>Fs.id===K)||null,[at,K]),Ys=N.useMemo(()=>{var Fs;if(b==="all")return Ut;if(b==="tags")return Es?Ut.filter($n=>Es.has($n.id)):[];if(b==="smartlists"){if(!Xt)return[];const $n=(((Fs=Xt.filters)==null?void 0:Fs.search)||"").toLowerCase().trim();return $n?Ut.filter(Cr=>`${Cr.first_name||""} ${Cr.last_name||""}`.toLowerCase().includes($n)||(Cr.email||"").toLowerCase().includes($n)):Ut}return Ut.filter($n=>ee.has($n.id))},[b,Ut,Es,Xt,ee]),Ss=N.useMemo(()=>{if(!oe.trim())return Ut;const Fs=oe.toLowerCase();return Ut.filter($n=>`${$n.first_name||""} ${$n.last_name||""}`.toLowerCase().includes(Fs))},[Ut,oe]);N.useEffect(()=>{s&&(_(""),A(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),D(`As always, reach out anytime if I can help. Talk soon!`),M(a||""),g("light"),v("all"),W([]),Y(null),ne(new Set),pe(""),de(!1),z(!0),De(!0),ve([]),$e("now"),Ke(""),Ce({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const Bs=l,Us=N.useMemo(()=>YVs(L||a||""),[L,a]),sn=!!(j.trim()&&Bs&&Ys.length>0&&!ie&&Us.length===0),Jn=Fs=>{const $n=L||a,Cr=F&&(p!=null&&p.email_signature)?p.email_signature:null;let ts;return f==="light"?ts=sHs($n,S,T,Cr):ts=Cr?`${$n}
${Cr}
`:$n,Ee&&(ts+=nHs(p??null,kt??null,Fs.email)),SZe(ts,Fs,p??null,(kt==null?void 0:kt.name)??null)},fn=N.useMemo(()=>Jn({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[f,S,T,L,a,F,p,Ee,kt]),Sn=N.useMemo(()=>aHs(j,f==="advanced"||f==="visual"?L:a),[j,f,L,a]),Gn=async()=>{Fe(!0),ve([]);try{const Fs=f==="advanced"||f==="visual"?L:a,{data:$n,error:Cr}=await q.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:Fs,currentSubject:j}});if(Cr)throw Cr;const ts=$n==null?void 0:$n.subjects;if(!Array.isArray(ts)||ts.length===0)throw new Error("No subjects returned");ve(ts)}catch(Fs){const $n=(Fs==null?void 0:Fs.message)||"Failed to generate subjects";$n.includes("credits exhausted")||$n.includes("402")?ae.error("AI credits exhausted. Please add credits to your workspace."):$n.includes("Rate limit")||$n.includes("429")?ae.error("Rate limit hit — try again in a moment."):ae.error($n)}finally{Fe(!1)}},Hr=Fs=>Fs?"$"+Number(Fs).toLocaleString("en-US"):"",pi=()=>{var Qe,ct;if(it.size===0){ae.error("Pick at least one listing first.");return}const Fs=(Qt==null?void 0:Qt.subdomain_slug)||"",$n=Fs?`https://${Fs}.relevelup.com`:"https://relevelup.com",Cr=[];for(const vt of Ds){const It=`mls:${vt.listing_key}`;if(!it.has(It))continue;const qt=Array.isArray(vt.photos)&&vt.photos.length>0?typeof vt.photos[0]=="string"?vt.photos[0]:((Qe=vt.photos[0])==null?void 0:Qe.MediaURL)||((ct=vt.photos[0])==null?void 0:ct.url)||"":"",xs=vt.bedrooms?`${vt.bedrooms} bd`:"",as=vt.bathrooms_total?`${vt.bathrooms_total} ba`:"",Ns=vt.living_area?`${Number(vt.living_area).toLocaleString()} sqft`:"";Cr.push({url:`${$n}/listings/${vt.listing_key}`,photo:qt,price:Hr(vt.list_price),addr:`${vt.address||""}${vt.city?", "+vt.city:""}`,stats:[xs,as,Ns].filter(Boolean).join(" • ")})}for(const vt of St){const It=`ex:${vt.id}`;if(!it.has(It))continue;const qt=vt.bedrooms?`${vt.bedrooms} bd`:"",xs=vt.bathrooms?`${vt.bathrooms} ba`:"",as=vt.square_footage?`${Number(vt.square_footage).toLocaleString()} sqft`:"";Cr.push({url:`https://listings.relevelup.com/${vt.slug||vt.id}`,photo:vt._photo||"",price:Hr(vt.price),addr:`${vt.property_address||""}${vt.city?", "+vt.city:""}`,stats:[qt,xs,as].filter(Boolean).join(" • ")})}const Oe=`

Featured Listings

${Cr.map(vt=>`
${vt.photo?`${vt.addr}`:""}
${vt.price}
${vt.addr}
${vt.stats}
`.trim()).join(` `)}
`.trim();M(vt=>(vt||a||"")+` `+Oe),g("visual"),Ne(new Set),we(!1),ae.success(`Added ${Cr.length} listing${Cr.length===1?"":"s"} to your newsletter.`)},Ms=()=>Jn({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}}"),bi=()=>SZe(j,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},p??null,(kt==null?void 0:kt.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}}"),Rr=()=>{if(Us.length>0){ae.error(`Fill in ${Us.length} template field${Us.length===1?"":"s"} before sending.`);return}if(sn){if(He==="later"){if(!Ye){ae.error("Pick a date and time to schedule.");return}const Fs=new Date(Ye).getTime();if(Number.isNaN(Fs)||Fs{if(!(!sn||!i)){Me(!1),ye(!0),Ce({sent:0,failed:0,total:Ys.length,currentName:"Preparing campaign…"});try{const $n=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Cr=Ms(),ts=bi(),Oe=He==="later",{data:Qe,error:ct}=await q.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:ts,body_html:Cr,from_email:$n,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:Ys.length,status:Oe?"scheduled":"draft",scheduled_at:Oe?new Date(Ye).toISOString():null}).select("id").single();if(ct)throw ct;Ce(It=>({...It,currentName:"Adding recipients…"}));const vt=Ys.map(It=>({campaign_id:Qe.id,contact_id:It.id,email:It.email,name:[It.first_name,It.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let It=0;It({...as,sent:Math.min(It+qt.length,vt.length)}))}if(Oe){const{error:It}=await q.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:Qe.id}});if(It)throw It;ae.success(`Newsletter scheduled for ${new Date(Ye).toLocaleString()}.`)}else{const{error:It}=await q.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:Qe.id}});if(It)throw It;ae.success(`Sending to ${Ys.length} contact${Ys.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(Fs){console.error("Newsletter send failed:",Fs),ae.error(`Failed to send: ${Fs.message||"Unknown error"}`)}finally{ye(!1)}}},lr=Fs=>{ne($n=>{const Cr=new Set($n);return Cr.has(Fs)?Cr.delete(Fs):Cr.add(Fs),Cr})};return e.jsxs(bs,{open:s,onOpenChange:Fs=>!ie&&t(Fs),children:[e.jsxs(vs,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-5 w-5"})," Send Newsletter"]})}),!Bs&&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(Gi,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold text-destructive",children:"Set up Mass Email first"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"You need to verify your sender email before you can send newsletters. It only takes a minute — we'll send a verification email to confirm you own the address."}),e.jsx(B,{size:"sm",className:"mt-3",onClick:()=>{window.open("/mission-control/integrations#mass-email","_blank")},children:"Set up Mass Email →"})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Subject"}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:Gn,disabled:Ie,title:"Generate subject lines with AI",children:[Ie?e.jsx(ss,{className:"h-3 w-3 animate-spin"}):e.jsx(un,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(ge,{value:j,onChange:Fs=>_(Fs.target.value),placeholder:"Newsletter subject"}),qe.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:"}),qe.map((Fs,$n)=>e.jsxs("button",{type:"button",onClick:()=>{_(Fs),ve([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(un,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),Fs]},$n))]}),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}}"})]})]}),Sn.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(bL,{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:Sn.map((Fs,$n)=>e.jsx("li",{children:Fs},$n))})]}),(ns||ht)&&e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsx(zr,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:ns&&ht?"Pick from your live MLS listings or your Listing Exchange listings.":ns?"Pick from your live MLS listings and drop them into the email.":"Pick from your Listing Exchange listings and drop them into the email."})]}),e.jsx(B,{type:"button",size:"sm",variant:"outline",onClick:()=>we(!0),children:"Choose listings"})]}),e.jsx(QVs,{html:L||a||"",originalHtml:a||"",onChange:M}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Editing"}),e.jsxs($r,{value:f,onValueChange:Fs=>g(Fs),children:[e.jsxs(Ur,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Zt,{value:"visual",children:[e.jsx(Rm,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Zt,{value:"light",children:[e.jsx(Nr,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Zt,{value:"advanced",children:[e.jsx(T2,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(ls,{value:"visual",className:"mt-3",children:e.jsx(E_t,{html:L,onChange:M})}),e.jsxs(ls,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Ts,{value:S,onChange:Fs=>A(Fs.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(Ts,{value:T,onChange:Fs=>D(Fs.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(ls,{value:"advanced",className:"mt-3",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Ts,{value:L,onChange:Fs=>M(Fs.target.value),rows:14,className:"font-mono text-xs"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Append my email signature"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:p!=null&&p.email_signature?"Will append the signature from your profile.":"No signature set. Add one in Profile → Email Signature."})]}),e.jsx(vn,{checked:F&&!!(p!=null&&p.email_signature),disabled:!(p!=null&&p.email_signature),onCheckedChange:z})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Include unsubscribe footer"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds your brokerage info and a one-click unsubscribe link. Strongly recommended for deliverability."})]}),e.jsx(vn,{checked:Ee,onCheckedChange:De})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipients"}),e.jsxs($r,{value:b,onValueChange:Fs=>v(Fs),children:[e.jsxs(Ur,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Zt,{value:"all",children:[e.jsx(_n,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Zt,{value:"tags",children:[e.jsx(mh,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Zt,{value:"smartlists",children:[e.jsx(h9,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Zt,{value:"individual",children:[e.jsx(Xi,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(ls,{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:Ut.length})," contact",Ut.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(ls,{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(mi,{className:"h-40 rounded-lg border p-2",children:rt.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No tags yet. Add tags to contacts to use this option."}):rt.map(Fs=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(hi,{checked:V.includes(Fs.id),onCheckedChange:$n=>W(Cr=>$n?[...Cr,Fs.id]:Cr.filter(ts=>ts!==Fs.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:Fs.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:Fs.name})]},Fs.id))})]}),e.jsxs(ls,{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(mi,{className:"h-40 rounded-lg border p-2",children:at.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):at.map(Fs=>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:K===Fs.id,onChange:()=>Y(Fs.id)}),e.jsx("span",{className:"text-sm",children:Fs.name})]},Fs.id))})]}),e.jsxs(ls,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(ge,{placeholder:"Search contacts...",value:oe,onChange:Fs=>pe(Fs.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[ee.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>ne(new Set),children:"Clear"})]}),e.jsxs(mi,{className:"h-48 rounded-lg border p-2",children:[dt&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!dt&&Ss.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),Ss.slice(0,200).map(Fs=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(hi,{checked:ee.has(Fs.id),onCheckedChange:()=>lr(Fs.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[Fs.first_name," ",Fs.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Fs.email})]})]},Fs.id)),Ss.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(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(xr,{className:"h-3 w-3"})," ",Ys.length," recipient",Ys.length===1?"":"s"]}),Bs&&e.jsxs(ze,{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(se,{children:"Preview"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>de(Fs=>!Fs),children:ce?e.jsxs(e.Fragment,{children:[e.jsx(gf,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),ce?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:fn,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)."]})]})]}),ie&&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(ss,{className:"h-4 w-4 animate-spin"}),"Sending to ",Te.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[Te.sent+Te.failed," / ",Te.total]})]}),e.jsx(xi,{value:Te.total?(Te.sent+Te.failed)/Te.total*100:0}),Te.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[Te.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(gr,{className:"h-4 w-4"})," When to send"]}),e.jsxs(db,{value:He,onValueChange:Fs=>$e(Fs),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Fd,{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(Fd,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(cm,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),He==="later"&&e.jsx(ge,{type:"datetime-local",value:Ye,onChange:Fs=>Ke(Fs.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:Us.length>0?`${Us.length} template field${Us.length===1?"":"s"} still need${Us.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(B,{variant:"outline",onClick:()=>t(!1),disabled:ie,children:"Cancel"}),e.jsx(B,{onClick:Rr,disabled:!sn,children:ie?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):He==="later"?e.jsxs(e.Fragment,{children:[e.jsx(cm,{className:"h-4 w-4 mr-1"}),"Schedule for ",Ys.length]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send to ",Ys.length]})})]})]})]})]}),e.jsx(Oo,{open:_e,onOpenChange:Me,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:He==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(Mo,{children:[He==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',j,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[Ys.length," contact",Ys.length===1?"":"s"]}),He==="later"&&Ye?` for ${new Date(Ye).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:er,children:He==="later"?e.jsxs(e.Fragment,{children:[e.jsx(cm,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send to ",Ys.length]})})]})]})}),e.jsx(bs,{open:Je,onOpenChange:we,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(zr,{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."}),(Dt||$t)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(ss,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!Dt&&!$t&&Ds.length===0&&St.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."}),Ds.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:Ds.map(Fs=>{var Oe,Qe;const $n=`mls:${Fs.listing_key}`,Cr=it.has($n),ts=Array.isArray(Fs.photos)&&Fs.photos.length>0?typeof Fs.photos[0]=="string"?Fs.photos[0]:((Oe=Fs.photos[0])==null?void 0:Oe.MediaURL)||((Qe=Fs.photos[0])==null?void 0:Qe.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Ne(ct=>{const vt=new Set(ct);return vt.has($n)?vt.delete($n):vt.size<6?vt.add($n):ae.error("Max 6 listings per newsletter"),vt})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Cr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[ts&&e.jsx("img",{src:ts,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:Fs.list_price?`$${Number(Fs.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:Fs.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[Fs.city,Fs.state?`, ${Fs.state}`:""]})]}),Cr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(xr,{className:"h-4 w-4"})})]},$n)})})]}),St.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:St.map(Fs=>{const $n=`ex:${Fs.id}`,Cr=it.has($n);return e.jsxs("button",{type:"button",onClick:()=>{Ne(ts=>{const Oe=new Set(ts);return Oe.has($n)?Oe.delete($n):Oe.size<6?Oe.add($n):ae.error("Max 6 listings per newsletter"),Oe})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Cr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[Fs._photo&&e.jsx("img",{src:Fs._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:Fs.price?`$${Number(Fs.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:Fs.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[Fs.city,Fs.state?`, ${Fs.state}`:""]})]}),Cr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(xr,{className:"h-4 w-4"})})]},$n)})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>we(!1),children:"Cancel"}),e.jsxs(B,{onClick:pi,disabled:it.size===0,children:["Insert ",it.size>0?it.size:""," listing",it.size===1?"":"s"]})]})]})}),e.jsx(I1e,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function iHs(){const{user:s}=gs(),t=Gt(),[n,r]=N.useState("starters"),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState(null),[u,h]=N.useState(null),{data:p,isLoading:f}=lt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:L,error:M}=await q.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(M)throw M;return L||[]}}),g=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),b=(p==null?void 0:p.filter(L=>L.user_id===(s==null?void 0:s.id)&&!L.is_template))??[],v=(p==null?void 0:p.filter(L=>L.user_id===(s==null?void 0:s.id)&&L.is_template))??[],j=(p==null?void 0:p.filter(L=>L.user_id!==(s==null?void 0:s.id)&&L.is_template&&(L.share_scope==="team"||L.share_scope==="brokerage"||L.share_scope==="global")))??[],_=(p==null?void 0:p.filter(L=>L.share_scope==="global"&&L.is_template))??[],S=n==="starters"?_:n==="mine"?b:n==="templates"?v:j.filter(L=>L.share_scope!=="global"),A=async L=>{if(!s)return;const{error:M}=await q.from("agent_custom_newsletters").insert({user_id:s.id,title:`${L.title} (Copy)`,description:L.description,html_content:L.html_content,is_template:!1,share_scope:"private"});if(M){ae.error(M.message);return}ae.success('Duplicated to "My Newsletters"'),g(),r("mine")},T=async L=>{const{error:M}=await q.from("agent_custom_newsletters").delete().eq("id",L);if(M){ae.error(M.message);return}ae.success("Deleted"),h(null),g()},D=L=>L.share_scope==="global"?e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"}),"Starter"]}):L.share_scope==="brokerage"?e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Ga,{className:"h-3 w-3"}),"Brokerage"]}):L.share_scope==="team"?e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(_n,{className:"h-3 w-3"}),"Team"]}):e.jsxs(ze,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Rc,{className:"h-3 w-3"}),"Private"]});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:n==="starters"?"default":"outline",size:"sm",onClick:()=>r("starters"),className:"gap-1.5",children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"Starter Templates (",_.length,")"]}),e.jsxs(B,{variant:n==="mine"?"default":"outline",size:"sm",onClick:()=>r("mine"),children:["My Newsletters (",b.length,")"]}),e.jsxs(B,{variant:n==="templates"?"default":"outline",size:"sm",onClick:()=>r("templates"),children:["My Templates (",v.length,")"]}),e.jsxs(B,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",j.filter(L=>L.share_scope!=="global").length,")"]})]}),e.jsxs(B,{onClick:()=>{o(null),i(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),f&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((L,M)=>e.jsx(Ws,{className:"h-48 w-full"},M))}),n==="starters"&&!f&&e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm flex items-start gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("span",{children:["Click ",e.jsx("strong",{children:"Use"}),' on any starter to copy it into your "My Newsletters" — then edit, send, or save as your own template.']})]}),!f&&S.length===0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Nr,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),n==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),n==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),n==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),n==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!f&&S.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:S.map(L=>{const M=L.user_id===(s==null?void 0:s.id);return e.jsxs(fe,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[L.thumbnail_url?e.jsx("img",{src:L.thumbnail_url,alt:L.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:`
${L.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[L.is_template&&e.jsx(ze,{className:"bg-primary/90",children:"Template"}),D(L)]})]}),e.jsxs(Ae,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:L.title}),L.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:L.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",ks(new Date(L.updated_at||L.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(B,{size:"sm",onClick:()=>d(L),className:"flex-1 min-w-[80px]",children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),M?e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{o(L),i(!0)},children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(L),children:e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>h(L.id),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>A(L),children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},L.id)})}),e.jsx(WVs,{open:a,onOpenChange:i,initial:l,onSaved:g}),c&&e.jsx(_Le,{open:!!c,onOpenChange:L=>!L&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Oo,{open:!!u,onOpenChange:L=>!L&&h(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this newsletter?"}),e.jsx(Mo,{children:"This cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>u&&T(u),children:"Delete"})]})]})})]})}function oHs(){const s=In(),[t,n]=N.useState(""),[r,a]=N.useState("grid"),[i,l]=N.useState(null),{data:o,isLoading:c}=lt({queryKey:["newsletters"],queryFn:async()=>{const{data:T,error:D}=await q.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(D)throw D;return T}}),{data:d}=lt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:T}=await q.from("newsletter_likes").select("newsletter_id");return T||[]}}),{data:u}=lt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:T}=await q.from("newsletter_comments").select("newsletter_id");return T||[]}}),{data:h}=lt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[T,D,L,M]=await Promise.all([q.from("newsletter_canva_links").select("newsletter_id"),q.from("newsletter_pdfs").select("newsletter_id"),q.from("newsletter_videos").select("newsletter_id"),q.from("newsletter_drive_links").select("newsletter_id")]);return{canva:T.data||[],pdfs:D.data||[],videos:L.data||[],drives:M.data||[]}}}),p=T=>(d==null?void 0:d.filter(D=>D.newsletter_id===T).length)||0,f=T=>(u==null?void 0:u.filter(D=>D.newsletter_id===T).length)||0,g=T=>{var D;return((D=h==null?void 0:h.canva)==null?void 0:D.filter(L=>L.newsletter_id===T).length)||0},b=T=>{var D;return((D=h==null?void 0:h.pdfs)==null?void 0:D.filter(L=>L.newsletter_id===T).length)||0},v=T=>{var D;return((D=h==null?void 0:h.videos)==null?void 0:D.filter(L=>L.newsletter_id===T).length)||0},j=T=>{var D;return((D=h==null?void 0:h.drives)==null?void 0:D.filter(L=>L.newsletter_id===T).length)||0},_=T=>g(T)+b(T)+v(T)+j(T),S=o==null?void 0:o.filter(T=>{var D;return T.title.toLowerCase().includes(t.toLowerCase())||((D=T.description)==null?void 0:D.toLowerCase().includes(t.toLowerCase()))}),A=T=>{s(`/newsletters/${T}`)};return e.jsx(Cs,{title:"Newsletter Content",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Newsletter Content"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Monthly templates, plus newsletters you build yourself"})]}),e.jsxs($r,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"custom",children:"Build & Send"}),e.jsx(Zt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(ls,{value:"custom",className:"mt-2",children:e.jsx(iHs,{})}),e.jsxs(ls,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search newsletters...",value:t,onChange:T=>n(T.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(vf,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Ep,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(S==null?void 0:S.length)||0," item",(S==null?void 0:S.length)!==1?"s":""," found"]}),c&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((T,D)=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-0",children:[e.jsx(Ws,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-full"})]})]})},D))}),!c&&(S==null?void 0:S.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Nr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No newsletters match your search":"No newsletters available yet"}),t&&e.jsx(B,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!c&&S&&S.length>0&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-3",children:S.map(T=>{const D=_(T.id),L=g(T.id),M=b(T.id),F=v(T.id);return r==="grid"?e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(T.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:T.preview_image_url?e.jsx("img",{src:T.preview_image_url,alt:T.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(Nr,{className:"h-16 w-16"})})}),e.jsxs(Ae,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:T.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(yr,{className:"h-3 w-3"}),ks(new Date(T.publish_date),"MMM d, yyyy")]})]}),T.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:T.description.replace(/<[^>]*>/g,"")}),D>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[L>0&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(xl,{className:"h-3 w-3"})," ",L," Template",L>1?"s":""]}),M>0&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Da,{className:"h-3 w-3"})," ",M," PDF",M>1?"s":""]}),F>0&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Al,{className:"h-3 w-3"})," ",F," Video",F>1?"s":""]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground pt-1 border-t border-border/50",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hm,{className:"h-3 w-3"})," ",p(T.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3 w-3"})," ",f(T.id)]})]}),T.html_code&&e.jsxs(B,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:z=>{z.stopPropagation(),l(T)},children:[e.jsx(cr,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},T.id):e.jsx(fe,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(T.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:T.preview_image_url?e.jsx("img",{src:T.preview_image_url,alt:T.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(Nr,{className:"h-10 w-10"})})}),e.jsxs(Ae,{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:T.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(yr,{className:"h-3 w-3"}),ks(new Date(T.publish_date),"MMM d, yyyy")]})]}),T.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:T.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[D>0&&e.jsxs("span",{children:[D," resource",D>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hm,{className:"h-3 w-3"})," ",p(T.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3 w-3"})," ",f(T.id)]})]})]}),T.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:z=>{z.stopPropagation(),l(T)},children:[e.jsx(cr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},T.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(_Le,{open:!!i,onOpenChange:T=>!T&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function lHs({rows:s}){if(!s||s.length===0)return null;const t=s.filter(n=>n.columns.some(r=>r.title||r.description||r.image_url));return t.length===0?null:e.jsx("div",{className:"space-y-6",children:t.map((n,r)=>{const a=n.columns.filter(i=>i.title||i.description||i.image_url);return a.length===0?null:e.jsx("div",{className:"grid gap-4",style:{gridTemplateColumns:`repeat(${a.length}, minmax(0, 1fr))`},children:a.map((i,l)=>e.jsxs(fe,{className:"overflow-hidden border-border/50",children:[i.image_url&&e.jsx("img",{src:i.image_url,alt:i.title||"",className:"w-full h-40 object-cover"}),e.jsxs(Ae,{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 cHs(){const{id:s}=_i(),t=In(),{user:n}=gs(),{toast:r}=Ua(),a=Gt(),{trackEngagement:i}=QD(),[l,o]=N.useState(""),[c,d]=N.useState(!1),{data:u,isLoading:h}=lt({queryKey:["newsletter",s],queryFn:async()=>{const{data:L,error:M}=await q.from("newsletter_content").select("*").eq("id",s).single();if(M)throw M;return L},enabled:!!s});N.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:p}=lt({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return L||[]},enabled:!!s}),{data:f}=lt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return L||[]},enabled:!!s}),{data:g}=lt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return L||[]},enabled:!!s}),{data:b}=lt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return L||[]},enabled:!!s}),{data:v}=lt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_likes").select("*").eq("newsletter_id",s);return L||[]},enabled:!!s}),{data:j}=lt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return L||[]},enabled:!!s}),_=v==null?void 0:v.some(L=>L.user_id===(n==null?void 0:n.id)),S=gt({mutationFn:async()=>{_?await q.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",n==null?void 0:n.id):await q.from("newsletter_likes").insert({newsletter_id:s,user_id:n==null?void 0:n.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),A=gt({mutationFn:async L=>{const{error:M}=await q.from("newsletter_comments").insert({newsletter_id:s,user_id:n==null?void 0:n.id,content:L});if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),r({title:"Comment added"})}}),T=gt({mutationFn:async L=>{const{error:M}=await q.from("newsletter_comments").delete().eq("id",L);if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),D=L=>{if(L.includes("player.mediadelivery.net")||L.includes("iframe.mediadelivery.net")){const M=L.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(M)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${M[1]}/${M[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(L.includes("youtube.com")||L.includes("youtu.be")){const M=L.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(M)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${M[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:L,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Al,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx(Cs,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-32"}),e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-32 w-full"})]})}):u?e.jsx(Cs,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(Wr,{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:ks(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(lHs,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(tR,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs(B,{variant:_?"default":"outline",size:"sm",onClick:()=>S.mutate(),children:[e.jsx(yi,{className:`h-4 w-4 mr-1 ${_?"fill-current":""}`}),(v==null?void 0:v.length)||0," ",(v==null?void 0:v.length)===1?"Like":"Likes"]}),u.html_code&&e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(_Le,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),b&&b.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Ae,{className:"space-y-2",children:b.map(L=>e.jsxs("a",{href:L.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(xl,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:L.title}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},L.id))})]}),p&&p.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Ae,{className:"space-y-2",children:p.map(L=>e.jsxs("a",{href:L.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(tr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:L.title})]},L.id))})]}),f&&f.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Ae,{className:"space-y-2",children:f.map(L=>e.jsxs("a",{href:L.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(Nr,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:L.name}),e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"})]},L.id))})]}),g&&g.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"Videos"})}),e.jsx(Ae,{className:"space-y-6",children:g.map(L=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:L.title}),D(L.video_url)]},L.id))})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-lg",children:["Comments (",(j==null?void 0:j.length)||0,")"]})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ts,{placeholder:"Write a comment...",value:l,onChange:L=>o(L.target.value),className:"flex-1"}),e.jsx(B,{onClick:()=>l.trim()&&A.mutate(l),disabled:!l.trim()||A.isPending,children:e.jsx(cr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:j==null?void 0:j.map(L=>{var M,F,z;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(aa,{className:"h-8 w-8",children:e.jsx(ia,{children:((F=(M=L.profiles)==null?void 0:M.name)==null?void 0:F[0])||"U"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-sm",children:((z=L.profiles)==null?void 0:z.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:ks(new Date(L.created_at),"MMM d, yyyy")}),L.user_id===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>T.mutate(L.id),children:e.jsx(bn,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:L.content})]})]},L.id)})})]})]})]})}):e.jsx(Cs,{title:"Not Found",description:"",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Newsletter not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function dHs({rows:s,onChange:t}){const[n,r]=N.useState(null),[a,i]=N.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=h=>{t(s.filter((p,f)=>f!==h))},c=(h,p,f,g)=>{const b=[...s];b[h]={...b[h],columns:b[h].columns.map((v,j)=>j===p?{...v,[f]:g}:v)},t(b)},d=async(h,p,f)=>{var v;const g=(v=f.target.files)==null?void 0:v[0];if(!g)return;const b=`${h}-${p}`;r(b);try{const j=`content-blocks/${Date.now()}-${g.name}`,{error:_}=await q.storage.from("newsletter-content").upload(j,g);if(!_){const{data:S}=q.storage.from("newsletter-content").getPublicUrl(j);c(h,p,"image_url",S.publicUrl)}}finally{r(null)}},u=(h,p)=>{c(h,p,"image_url","")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(As,{className:"mr-1 h-3 w-3"})," Add Row"]})]}),s.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No content block rows yet. Add a row to create a 3-column layout."}),s.map((h,p)=>e.jsxs(fe,{className:"relative",children:[e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"absolute top-2 right-2 h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>o(p),children:e.jsx(Fn,{className:"h-4 w-4"})}),e.jsxs(Ae,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Uu,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",p+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:h.columns.map((f,g)=>{const b=`${p}-${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]}),f.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:f.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>u(p,g),children:e.jsx(Fn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(ge,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${b}`,onChange:v=>d(p,g,v)}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",disabled:n===b,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${b}`,className:"cursor-pointer",children:n===b?"...":e.jsxs(e.Fragment,{children:[e.jsx(nl,{className:"h-3 w-3 mr-1"})," Upload"]})})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",onClick:()=>i({row:p,col:g}),children:[e.jsx(Wg,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(ge,{placeholder:"Title",value:f.title,onChange:v=>c(p,g,"title",v.target.value),className:"h-8 text-sm"}),e.jsx(Ts,{placeholder:"Description",value:f.description,onChange:v=>c(p,g,"description",v.target.value),className:"text-sm min-h-[60px] resize-none"})]},g)})})]})]},p)),e.jsx(bs,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(vs,{className:"sm:max-w-2xl",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Choose a Graphic"})}),e.jsx(T_t,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function uHs(){const{toast:s}=Ua(),t=Gt(),[n,r]=N.useState(!1),[a,i]=N.useState(null),[l,o]=N.useState({title:"",description:"",publish_date:ks(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=N.useState(null),[u,h]=N.useState(null),[p,f]=N.useState([]),[g,b]=N.useState([]),[v,j]=N.useState([]),[_,S]=N.useState([]),[A,T]=N.useState([]),[D,L]=N.useState(""),[M,F]=N.useState([]),[z,V]=N.useState(!1),{data:W,isLoading:K}=lt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:Ee,error:De}=await q.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(De)throw De;return Ee}}),Y=gt({mutationFn:async Ee=>{const{data:De,error:Ie}=await q.from("newsletter_content").insert({title:Ee.title,description:Ee.description||null,preview_image_url:Ee.preview_image_url,publish_date:Ee.publish_date,is_published:Ee.is_published,content_blocks:Ee.content_blocks,html_code:Ee.html_code}).select().single();if(Ie)throw Ie;return De},onSuccess:async Ee=>{await oe(Ee.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),Ee.is_published&&p_s(Ee.title,Ee.id),de()},onError:Ee=>{s({title:"Error creating newsletter",description:Ee.message,variant:"destructive"})}}),ee=gt({mutationFn:async Ee=>{const{error:De}=await q.from("newsletter_content").update({title:Ee.title,description:Ee.description||null,preview_image_url:Ee.preview_image_url,publish_date:Ee.publish_date,is_published:Ee.is_published,content_blocks:Ee.content_blocks,html_code:Ee.html_code}).eq("id",Ee.id);if(De)throw De;return Ee.id},onSuccess:async Ee=>{await oe(Ee),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),de()},onError:Ee=>{s({title:"Error updating newsletter",description:Ee.message,variant:"destructive"})}}),ne=gt({mutationFn:async Ee=>{const{error:De}=await q.from("newsletter_content").delete().eq("id",Ee);if(De)throw De},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:Ee=>{s({title:"Error deleting newsletter",description:Ee.message,variant:"destructive"})}}),oe=async Ee=>{await q.from("newsletter_drive_links").delete().eq("newsletter_id",Ee),await q.from("newsletter_pdfs").delete().eq("newsletter_id",Ee),await q.from("newsletter_videos").delete().eq("newsletter_id",Ee),await q.from("newsletter_canva_links").delete().eq("newsletter_id",Ee);for(const De of M){const Ie=`${Ee}/${Date.now()}-${De.file.name}`,{error:Fe}=await q.storage.from("newsletter-content").upload(Ie,De.file);if(!Fe){const{data:qe}=q.storage.from("newsletter-content").getPublicUrl(Ie);g.push({name:De.name,file_url:qe.publicUrl,file_size:De.file.size,sort_order:g.length})}}p.length>0&&await q.from("newsletter_drive_links").insert(p.map((De,Ie)=>({newsletter_id:Ee,title:De.title,drive_url:De.drive_url,sort_order:Ie}))),g.length>0&&await q.from("newsletter_pdfs").insert(g.map((De,Ie)=>({newsletter_id:Ee,name:De.name,file_url:De.file_url,file_size:De.file_size||null,sort_order:Ie}))),v.length>0&&await q.from("newsletter_videos").insert(v.map((De,Ie)=>({newsletter_id:Ee,title:De.title,video_url:De.video_url,sort_order:Ie}))),_.length>0&&await q.from("newsletter_canva_links").insert(_.map((De,Ie)=>({newsletter_id:Ee,title:De.title,canva_share_link:De.canva_share_link,sort_order:Ie})))},pe=async Ee=>{i(Ee),o({title:Ee.title,description:Ee.description||"",publish_date:ks(new Date(Ee.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:Ee.is_published}),h(Ee.preview_image_url),T(Ee.content_blocks||[]),L(Ee.html_code||"");const[De,Ie,Fe,qe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",Ee.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",Ee.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",Ee.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",Ee.id).order("sort_order")]);f(De.data||[]),b(Ie.data||[]),j(Fe.data||[]),S(qe.data||[]),F([]),r(!0)},ce=async Ee=>{const[De,Ie,Fe,qe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",Ee.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",Ee.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",Ee.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",Ee.id).order("sort_order")]);i(null),o({title:`${Ee.title} (Copy)`,description:Ee.description||"",publish_date:ks(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(Ee.preview_image_url),T(Ee.content_blocks||[]),L(Ee.html_code||""),f((De.data||[]).map(({id:ve,...Je})=>Je)),b((Ie.data||[]).map(({id:ve,...Je})=>Je)),j((Fe.data||[]).map(({id:ve,...Je})=>Je)),S((qe.data||[]).map(({id:ve,...Je})=>Je)),F([]),r(!0)},de=()=>{r(!1),i(null),o({title:"",description:"",publish_date:ks(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),f([]),b([]),j([]),S([]),T([]),L(""),F([])},ie=async Ee=>{var Ie;const De=(Ie=Ee.target.files)==null?void 0:Ie[0];De&&(d(De),h(URL.createObjectURL(De)))},ye=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}V(!0);let Ee=u;if(c){const De=`previews/${Date.now()}-${c.name}`,{error:Ie}=await q.storage.from("newsletter-content").upload(De,c);if(!Ie){const{data:Fe}=q.storage.from("newsletter-content").getPublicUrl(De);Ee=Fe.publicUrl}}a?ee.mutate({id:a.id,...l,preview_image_url:Ee,content_blocks:A,html_code:D||null}):Y.mutate({...l,preview_image_url:Ee,content_blocks:A,html_code:D||null}),V(!1)},_e=()=>f([...p,{title:"",drive_url:"",sort_order:p.length}]),Me=()=>j([...v,{title:"",video_url:"",sort_order:v.length}]),Te=()=>S([..._,{title:"",canva_share_link:"",sort_order:_.length}]),Ce=Ee=>{const De=Ee.target.files;if(!De)return;const Ie=Array.from(De).map(Fe=>({file:Fe,name:Fe.name.replace(/\.[^/.]+$/,"")}));F([...M,...Ie])};return e.jsx(Cs,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources"}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:(W==null?void 0:W.length)||0})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:(W==null?void 0:W.filter(Ee=>Ee.is_published).length)||0})})]})]}),e.jsxs(bs,{open:n,onOpenChange:Ee=>!Ee&&de(),children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(As,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Title *"}),e.jsx(ge,{value:l.title,onChange:Ee=>o({...l,title:Ee.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Publish Date"}),e.jsx(ge,{type:"datetime-local",value:l.publish_date,onChange:Ee=>o({...l,publish_date:Ee.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Db,{content:l.description,onChange:Ee=>o({...l,description:Ee}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[u&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:u,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute -top-2 -right-2 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>{d(null),h(null)},children:e.jsx(Fn,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(ge,{type:"file",accept:"image/*",onChange:ie,className:"hidden",id:"preview-upload"}),e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{checked:l.is_published,onCheckedChange:Ee=>o({...l,is_published:Ee})}),e.jsx(se,{children:"Published"})]}),e.jsx(dHs,{rows:A,onChange:T}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"HTML Code (for agent send)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:'When provided, agents see a "Send Newsletter" button on this newsletter.'})]}),e.jsx("textarea",{value:D,onChange:Ee=>L(Ee.target.value),rows:10,placeholder:"...",className:"w-full font-mono text-xs rounded-md border border-input bg-background px-3 py-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Supports merge tags: ",e.jsx("code",{children:"{{first_name}}"}),", ",e.jsx("code",{children:"{{last_name}}"}),", ",e.jsx("code",{children:"{{full_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{agent_email}}"}),", ",e.jsx("code",{children:"{{agent_phone}}"}),"."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Te,children:[e.jsx(As,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),_.map((Ee,De)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ge,{placeholder:"Link title",value:Ee.title,onChange:Ie=>{const Fe=[..._];Fe[De].title=Ie.target.value,S(Fe)},className:"w-1/3"}),e.jsx(ge,{placeholder:"Canva share link",value:Ee.canva_share_link,onChange:Ie=>{const Fe=[..._];Fe[De].canva_share_link=Ie.target.value,S(Fe)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>S(_.filter((Ie,Fe)=>Fe!==De)),children:e.jsx(Fn,{className:"h-4 w-4"})})]},De))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:_e,children:[e.jsx(As,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),p.map((Ee,De)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ge,{placeholder:"Link title",value:Ee.title,onChange:Ie=>{const Fe=[...p];Fe[De].title=Ie.target.value,f(Fe)},className:"w-1/3"}),e.jsx(ge,{placeholder:"Google Drive URL",value:Ee.drive_url,onChange:Ie=>{const Fe=[...p];Fe[De].drive_url=Ie.target.value,f(Fe)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>f(p.filter((Ie,Fe)=>Fe!==De)),children:e.jsx(Fn,{className:"h-4 w-4"})})]},De))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(ge,{type:"file",accept:".pdf",multiple:!0,onChange:Ce,className:"hidden",id:"pdf-upload"}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(Sa,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),g.map((Ee,De)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:Ee.name}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>b(g.filter((Ie,Fe)=>Fe!==De)),children:e.jsx(Fn,{className:"h-4 w-4"})})]},`existing-${De}`)),M.map((Ee,De)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ge,{value:Ee.name,onChange:Ie=>{const Fe=[...M];Fe[De].name=Ie.target.value,F(Fe)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>F(M.filter((Ie,Fe)=>Fe!==De)),children:e.jsx(Fn,{className:"h-4 w-4"})})]},`pending-${De}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Me,children:[e.jsx(As,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),v.map((Ee,De)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ge,{placeholder:"Video title",value:Ee.title,onChange:Ie=>{const Fe=[...v];Fe[De].title=Ie.target.value,j(Fe)},className:"w-1/3"}),e.jsx(ge,{placeholder:"Video URL",value:Ee.video_url,onChange:Ie=>{const Fe=[...v];Fe[De].video_url=Ie.target.value,j(Fe)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>j(v.filter((Ie,Fe)=>Fe!==De)),children:e.jsx(Fn,{className:"h-4 w-4"})})]},De))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:de,children:"Cancel"}),e.jsx(B,{onClick:ye,disabled:z||Y.isPending||ee.isPending,children:z?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:K?e.jsx(Gs,{children:e.jsx(ut,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(W==null?void 0:W.length)===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):W==null?void 0:W.map(Ee=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ee.preview_image_url?e.jsx("img",{src:Ee.preview_image_url,alt:Ee.title,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Nr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ee.title}),Ee.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Ee.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(ut,{children:ks(new Date(Ee.publish_date),"MMM d, yyyy")}),e.jsx(ut,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Ee.is_published?"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400":"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"}`,children:Ee.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>pe(Ee),title:"Edit",children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ce(Ee),title:"Duplicate",children:e.jsx(ta,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:()=>{confirm("Are you sure you want to delete this newsletter?")&&ne.mutate(Ee.id)},children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},Ee.id))})]})})})]})})}const hHs=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function mHs(){const s=Gt(),t=N.useRef(null),[n,r]=N.useState(""),[a,i]=N.useState("all"),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:g=[],isLoading:b}=lt({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:V,error:W}=await q.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(W)throw W;return V||[]}}),v=N.useMemo(()=>{const V=new Set(hHs);return g.forEach(W=>V.add(W.category)),Array.from(V).sort()},[g]),j=N.useMemo(()=>{const V=n.trim().toLowerCase();return g.filter(W=>a!=="all"&&W.category!==a?!1:V?W.title.toLowerCase().includes(V)||(W.description||"").toLowerCase().includes(V)||W.tags.some(K=>K.toLowerCase().includes(V)):!0)},[g,n,a]),_=()=>{f({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},S=()=>{_(),d(!0)},A=V=>{o(V),f({title:V.title,description:V.description||"",image_url:V.image_url,category:V.category,tags:V.tags.join(", "),is_active:V.is_active,is_featured:V.is_featured}),d(!0)},T=async V=>{var W;if(!V.type.startsWith("image/")){ae.error("Please choose an image file");return}if(V.size>15*1024*1024){ae.error("Image must be under 15MB");return}h(!0);try{const K=((W=V.name.split(".").pop())==null?void 0:W.toLowerCase())||"png",Y=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${K}`,{error:ee}=await q.storage.from("newsletter-content").upload(Y,V,{cacheControl:"31536000",upsert:!1,contentType:V.type});if(ee)throw ee;const{data:ne}=q.storage.from("newsletter-content").getPublicUrl(Y);f(oe=>({...oe,image_url:ne.publicUrl,title:oe.title||V.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),ae.success("Uploaded")}catch(K){ae.error(K.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},D=gt({mutationFn:async()=>{var K;if(!p.image_url)throw new Error("Please upload an image");if(!p.title.trim())throw new Error("Please add a title");const V=p.tags.split(",").map(Y=>Y.trim()).filter(Boolean),W={title:p.title.trim(),description:p.description.trim()||null,image_url:p.image_url,category:p.category||"General",tags:V,is_active:p.is_active,is_featured:p.is_featured};if(l){const{error:Y}=await q.from("newsletter_graphics").update(W).eq("id",l.id);if(Y)throw Y}else{const{data:Y}=await q.auth.getUser(),{error:ee}=await q.from("newsletter_graphics").insert({...W,created_by:(K=Y.user)==null?void 0:K.id});if(ee)throw ee}},onSuccess:()=>{ae.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),_()},onError:V=>ae.error(V.message||"Save failed")}),L=gt({mutationFn:async V=>{const{error:W}=await q.from("newsletter_graphics").delete().eq("id",V);if(W)throw W},onSuccess:()=>{ae.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:V=>ae.error(V.message||"Delete failed")}),M=async V=>{const{error:W}=await q.from("newsletter_graphics").update({is_active:!V.is_active}).eq("id",V.id);W?ae.error(W.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},F=async V=>{const{error:W}=await q.from("newsletter_graphics").update({is_featured:!V.is_featured}).eq("id",V.id);W?ae.error(W.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},z=V=>{navigator.clipboard.writeText(V),ae.success("URL copied")};return e.jsxs(Cs,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(Vd,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(fe,{children:e.jsxs(Ae,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{value:n,onChange:V=>r(V.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(us,{value:a,onValueChange:i,children:[e.jsx(cs,{className:"w-full md:w-56",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All categories"}),v.map(V=>e.jsx(Ze,{value:V,children:V},V))]})]}),e.jsxs(B,{onClick:S,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(ay,{className:"h-4 w-4"})," Add Graphic"]})]})}),b?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-16 text-center",children:[e.jsx(nl,{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(B,{onClick:S,className:"gap-1.5",children:[e.jsx(ay,{className:"h-4 w-4"})," Upload First Graphic"]})]})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:j.map(V=>e.jsxs(fe,{className:`overflow-hidden group ${V.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:V.image_url,alt:V.title,loading:"lazy",className:"w-full h-full object-cover"}),V.is_featured&&e.jsxs(ze,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(ua,{className:"h-3 w-3 fill-current"})," Featured"]}),!V.is_active&&e.jsx(ze,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Ae,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:V.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:V.category})]}),V.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:V.tags.slice(0,3).map(W=>e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:W},W))}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>A(V),title:"Edit",children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>F(V),title:V.is_featured?"Unfeature":"Feature",children:e.jsx(ua,{className:`h-3.5 w-3.5 ${V.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>z(V.image_url),title:"Copy URL",children:e.jsx(ta,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{checked:V.is_active,onCheckedChange:()=>M(V)}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete "${V.title}"?`)&&L.mutate(V.id)},children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})]})]},V.id))})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:V=>{var K;const W=(K=V.target.files)==null?void 0:K[0];W&&T(W)}}),p.image_url?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border bg-muted/30 mt-1.5",children:[e.jsx("img",{src:p.image_url,alt:"Preview",className:"w-full max-h-64 object-contain"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>f(V=>({...V,image_url:""})),children:e.jsx(Fn,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var V;return(V=t.current)==null?void 0:V.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(ss,{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(Sa,{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(se,{htmlFor:"g-title",children:"Title *"}),e.jsx(ge,{id:"g-title",value:p.title,onChange:V=>f(W=>({...W,title:V.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"g-desc",children:"Description"}),e.jsx(Ts,{id:"g-desc",value:p.description,onChange:V=>f(W=>({...W,description:V.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(se,{children:"Category"}),e.jsxs(us,{value:p.category,onValueChange:V=>f(W=>({...W,category:V})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:v.map(V=>e.jsx(Ze,{value:V,children:V},V))})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(ge,{id:"g-tags",value:p.tags,onChange:V=>f(W=>({...W,tags:V.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(vn,{checked:p.is_featured,onCheckedChange:V=>f(W=>({...W,is_featured:V}))})]}),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(vn,{checked:p.is_active,onCheckedChange:V=>f(W=>({...W,is_active:V}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>D.mutate(),disabled:D.isPending,children:[D.isPending&&e.jsx(ss,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const CZe={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 pHs(){const{user:s}=gs(),{toast:t}=Ua(),n=In(),r=Gt(),[a,i]=N.useState(""),[l,o]=N.useState("popular"),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,b]=N.useState(!1),{data:v=[],isLoading:j}=lt({queryKey:["wishlist-items",l,g],queryFn:async()=>{let D=q.from("wishlist_items").select("*");g&&s&&(D=D.eq("user_id",s.id)),l==="latest"?D=D.order("created_at",{ascending:!1}):l==="popular"?D=D.order("vote_count",{ascending:!1}):l==="trending"&&(D=D.order("vote_count",{ascending:!1}));const{data:L,error:M}=await D;if(M)throw M;const F=[...new Set((L==null?void 0:L.map(ne=>ne.user_id))||[])],{data:z}=await q.from("profiles").select("id, name").in("id",F),V=new Map((z==null?void 0:z.map(ne=>[ne.id,ne]))||[]);let W=[];if(s){const{data:ne}=await q.from("wishlist_votes").select("item_id").eq("user_id",s.id);W=(ne==null?void 0:ne.map(oe=>oe.item_id))||[]}const K=(L==null?void 0:L.map(ne=>ne.id))||[],{data:Y}=await q.from("wishlist_comments").select("item_id").in("item_id",K),ee=new Map;return Y==null||Y.forEach(ne=>{ee.set(ne.item_id,(ee.get(ne.item_id)||0)+1)}),L==null?void 0:L.map(ne=>{const oe=V.get(ne.user_id),pe=(oe==null?void 0:oe.name)||"Unknown";return{...ne,user_name:pe,user_initials:pe.split(" ").map(ce=>ce[0]).join("").toUpperCase().slice(0,2),has_voted:W.includes(ne.id),comment_count:ee.get(ne.id)||0}})}}),_=gt({mutationFn:async({title:D,description:L})=>{const{error:M}=await q.from("wishlist_items").insert({user_id:s.id,title:D,description:L});if(M)throw M},onSuccess:()=>{r.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),h(""),f(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:D=>{t({title:"Error",description:D.message,variant:"destructive"})}}),S=gt({mutationFn:async({itemId:D,hasVoted:L})=>{if(L){const{error:M}=await q.from("wishlist_votes").delete().eq("item_id",D).eq("user_id",s.id);if(M)throw M;return{itemId:D,wasAdded:!1}}else{const{error:M}=await q.from("wishlist_votes").insert({item_id:D,user_id:s.id});if(M)throw M;return{itemId:D,wasAdded:!0}}},onSuccess:async D=>{if(r.invalidateQueries({queryKey:["wishlist-items"]}),D!=null&&D.wasAdded){const L=v.find(F=>F.id===D.itemId),M=((L==null?void 0:L.vote_count)||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:D.itemId,voteCount:M}}).catch(console.error)}},onError:D=>{t({title:"Error",description:D.message,variant:"destructive"})}}),A=v.filter(D=>D.title.toLowerCase().includes(a.toLowerCase())||D.description.toLowerCase().includes(a.toLowerCase())),T=()=>{if(!u.trim()||!p.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}_.mutate({title:u.trim(),description:p.trim()})};return e.jsx(Cs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(bw,{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(bs,{open:c,onOpenChange:d,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(vs,{children:[e.jsx(ws,{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(se,{htmlFor:"title",children:"Title"}),e.jsx(ge,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:D=>h(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:p,onChange:D=>f(D.target.value),rows:4})]}),e.jsx(B,{onClick:T,className:"w-full",disabled:_.isPending,children:_.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ss,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search ideas...",value:a,onChange:D=>i(D.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx($r,{value:l,onValueChange:D=>o(D),children:e.jsxs(Ur,{children:[e.jsx(Zt,{value:"popular",children:"Most Popular"}),e.jsx(Zt,{value:"latest",children:"Latest"}),e.jsx(Zt,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(B,{variant:g?"default":"outline",size:"sm",onClick:()=>b(!g),children:g?"Show All Ideas":"My Ideas"})}),j?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):A.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(bw,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No ideas yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to submit an idea!"}),e.jsxs(B,{onClick:()=>d(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:A.map(D=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${D.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:L=>{L.stopPropagation(),S.mutate({itemId:D.id,hasVoted:D.has_voted||!1})},className:Et("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",D.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(Bu,{className:Et("h-4 w-4",D.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:D.vote_count})]}),e.jsx(aa,{className:"h-10 w-10 bg-primary/20",children:e.jsx(ia,{className:"bg-primary/20 text-primary text-sm font-medium",children:D.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:D.title}),e.jsx(ze,{className:Et("text-xs",CZe[D.status].color),children:CZe[D.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:D.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:D.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(D.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ci,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:D.comment_count})]})]})},D.id))})]})})}const TZe={open:{label:"Open",color:"bg-blue-100 text-blue-800"},under_review:{label:"Under Review",color:"bg-yellow-100 text-yellow-800"},planned:{label:"Planned",color:"bg-purple-100 text-purple-800"},in_progress:{label:"In Progress",color:"bg-orange-100 text-orange-800"},launched:{label:"Launched",color:"bg-green-100 text-green-800"},declined:{label:"Declined",color:"bg-gray-100 text-gray-800"}};function fHs(){const{itemId:s}=_i(),t=In(),{user:n}=gs(),{toast:r}=Ua(),a=Gt(),[i,l]=N.useState(""),{data:o=!1}=lt({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:v,error:j}=await q.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!j&&!!v},enabled:!!n}),{data:c,isLoading:d}=lt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:v,error:j}=await q.from("wishlist_items").select("*").eq("id",s).single();if(j)throw j;const{data:_}=await q.from("profiles").select("name").eq("id",v.user_id).single();let S=!1;if(n){const{data:A}=await q.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();S=!!A}return{...v,user_name:(_==null?void 0:_.name)||"Unknown",user_initials:((_==null?void 0:_.name)||"U").split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),has_voted:S}}}),{data:u=[],isLoading:h}=lt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:v,error:j}=await q.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(j)throw j;const _=[...new Set((v==null?void 0:v.map(T=>T.user_id))||[])],{data:S}=await q.from("profiles").select("id, name").in("id",_),A=new Map((S==null?void 0:S.map(T=>[T.id,T]))||[]);return v==null?void 0:v.map(T=>{const D=A.get(T.user_id),L=(D==null?void 0:D.name)||"Unknown";return{...T,user_name:L,user_initials:L.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2)}})}}),p=gt({mutationFn:async v=>{if(v){const{error:j}=await q.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(j)throw j;return{wasAdded:!1}}else{const{error:j}=await q.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(j)throw j;return{wasAdded:!0}}},onSuccess:async v=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),v!=null&&v.wasAdded&&c){const j=(c.vote_count||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:j}}).catch(console.error)}},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),f=gt({mutationFn:async v=>{const{error:j}=await q.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:v});if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),g=gt({mutationFn:async v=>{const{error:j}=await q.from("wishlist_comments").delete().eq("id",v);if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),b=()=>{i.trim()&&f.mutate(i.trim())};return d?e.jsx(Cs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(Ws,{className:"h-8 w-32 mb-6"}),e.jsx(Ws,{className:"h-48 w-full mb-6"}),e.jsx(Ws,{className:"h-32 w-full"})]})}):c?e.jsx(Cs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Back to Wishlist"]}),e.jsx("div",{className:"bg-card border rounded-lg p-6 mb-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:()=>p.mutate(c.has_voted),className:Et("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(Bu,{className:Et("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(ze,{className:Et("text-xs",TZe[c.status].color),children:TZe[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(aa,{className:"h-6 w-6",children:e.jsx(ia,{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(Pxe,{placeholder:o?"Share your thoughts... Use # to link templates":"Share your thoughts on this idea...",value:i,onChange:l,minHeight:"60px",mentionFormat:"encoded",enableTemplateMentions:o}),e.jsx(B,{onClick:b,disabled:!i.trim()||f.isPending,size:"icon",className:"h-auto",children:f.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(v=>e.jsx(Ws,{className:"h-20 w-full"},v))}):u.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No comments yet. Be the first to share your thoughts!"}):e.jsx("div",{className:"space-y-4",children:u.map(v=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(aa,{className:"h-8 w-8",children:e.jsx(ia,{className:"bg-primary/20 text-primary text-xs",children:v.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium text-sm",children:v.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(v.created_at).toLocaleDateString()})]}),e.jsx(XIe,{content:v.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===v.user_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>g.mutate(v.id),children:e.jsx(bn,{className:"h-4 w-4"})})]},v.id))})]})]})}):e.jsx(Cs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const EZe={open:{label:"Open",color:"bg-blue-100 text-blue-800"},under_review:{label:"Under Review",color:"bg-yellow-100 text-yellow-800"},planned:{label:"Planned",color:"bg-purple-100 text-purple-800"},in_progress:{label:"In Progress",color:"bg-orange-100 text-orange-800"},launched:{label:"Launched",color:"bg-green-100 text-green-800"},declined:{label:"Declined",color:"bg-gray-100 text-gray-800"}},AZe=["open","under_review","planned","in_progress","launched","declined"];function xHs(){const{toast:s}=Ua(),t=In(),n=Gt(),[r,a]=N.useState(""),[i,l]=N.useState("all"),[o,c]=N.useState(!1),[d,u]=N.useState(null),{data:h=[],isLoading:p}=lt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:j,error:_}=await q.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(_)throw _;const S=[...new Set((j==null?void 0:j.map(F=>F.user_id))||[])],{data:A}=await q.from("profiles").select("id, name, email").in("id",S),T=new Map((A==null?void 0:A.map(F=>[F.id,F]))||[]),D=(j==null?void 0:j.map(F=>F.id))||[],{data:L}=await q.from("wishlist_comments").select("item_id").in("item_id",D),M=new Map;return L==null||L.forEach(F=>{M.set(F.item_id,(M.get(F.item_id)||0)+1)}),j==null?void 0:j.map(F=>{const z=T.get(F.user_id);return{...F,user_name:(z==null?void 0:z.name)||"Unknown",user_email:(z==null?void 0:z.email)||"",comment_count:M.get(F.id)||0}})}}),f=gt({mutationFn:async({itemId:j,status:_})=>{const{error:S}=await q.from("wishlist_items").update({status:_}).eq("id",j);if(S)throw S},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:j=>{s({title:"Error",description:j.message,variant:"destructive"})}}),g=gt({mutationFn:async j=>{const{error:_}=await q.from("wishlist_items").delete().eq("id",j);if(_)throw _},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:j=>{s({title:"Error",description:j.message,variant:"destructive"})}}),b=h.filter(j=>{const _=j.title.toLowerCase().includes(r.toLowerCase())||j.description.toLowerCase().includes(r.toLowerCase())||j.user_name.toLowerCase().includes(r.toLowerCase()),S=i==="all"||j.status===i;return _&&S}),v={total:h.length,open:h.filter(j=>j.status==="open").length,inProgress:h.filter(j=>j.status==="in_progress").length,launched:h.filter(j=>j.status==="launched").length,highVotes:h.filter(j=>j.vote_count>=10).length};return e.jsx(Cs,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(Wr,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Wishlist Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Review and manage community ideas"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Ideas"}),e.jsx("p",{className:"text-2xl font-bold",children:v.total})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:v.open})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"In Progress"}),e.jsx("p",{className:"text-2xl font-bold text-orange-600",children:v.inProgress})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Launched"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:v.launched})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"10+ Votes"}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:v.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search ideas, users...",value:r,onChange:j=>a(j.target.value),className:"pl-10"})]}),e.jsxs(us,{value:i,onValueChange:j=>l(j),children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"Filter by status"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),AZe.map(j=>e.jsx(Ze,{value:j,children:EZe[j].label},j))]})]})]}),p?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(j=>e.jsx(Ws,{className:"h-16 w-full"},j))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-[60px]",children:"Votes"}),e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Ct,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(pa,{children:b.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):b.map(j=>e.jsxs(Gs,{className:Et(j.vote_count>=10&&"bg-primary/5"),children:[e.jsx(ut,{children:e.jsx(ze,{variant:j.vote_count>=10?"default":"secondary",children:j.vote_count})}),e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:j.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:j.description})]})}),e.jsx(ut,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:j.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j.user_email})]})}),e.jsx(ut,{className:"hidden sm:table-cell",children:j.comment_count}),e.jsx(ut,{children:e.jsxs(us,{value:j.status,onValueChange:_=>f.mutate({itemId:j.id,status:_}),children:[e.jsx(cs,{className:"w-[140px] h-8",children:e.jsx(hs,{})}),e.jsx(ds,{children:AZe.map(_=>e.jsx(Ze,{value:_,children:EZe[_].label},_))})]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${j.id}`,"_blank"),children:e.jsx(tr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(j.id),c(!0)},children:e.jsx(bn,{className:"h-4 w-4"})})]})})]},j.id))})]})}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsx(ws,{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(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>d&&g.mutate(d),disabled:g.isPending,children:g.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function gHs(){const{user:s}=gs(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,g]=N.useState(""),[b,v]=N.useState(""),[j,_]=N.useState(""),[S,A]=N.useState(""),[T,D]=N.useState(""),[L,M]=N.useState(!1),[F,z]=N.useState(""),[V,W]=N.useState("once"),[K,Y]=N.useState([]),[ee,ne]=N.useState([]),[oe,pe]=N.useState(!1),[ce,de]=N.useState(!1),[ie,ye]=N.useState([]),[_e,Me]=N.useState({total:0,dismissed:0});N.useEffect(()=>{Te()},[]);const Te=async()=>{const{data:at,error:Ge}=await q.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Ge?(ae.error("Failed to fetch briefs"),console.error(Ge)):n(at||[]),a(!1)},Ce=()=>{g(""),v(""),_(""),A(""),D(""),M(!1),z(new Date().toISOString().slice(0,16)),W("once"),Y([]),ne([]),c(null)},Ee=()=>{Ce(),l(!0)},De=async at=>{c(at),g(at.title),v(at.description||""),_(at.video_url||""),A(at.graphic_url||""),D(at.graphic_link_url||""),M(at.is_published),z(at.publish_date.slice(0,16)),W(at.show_frequency);const{data:Ge}=await q.from("levelup_brief_links").select("*").eq("brief_id",at.id).order("sort_order");Y((Ge==null?void 0:Ge.map(Bt=>({title:Bt.title,url:Bt.url})))||[]);const{data:dt}=await q.from("levelup_brief_polls").select("*").eq("brief_id",at.id).order("sort_order");if(dt){const Bt=[];for(const kt of dt){const{data:Qt}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",kt.id).order("sort_order");Bt.push({question:kt.question,poll_type:kt.poll_type,options:(Qt==null?void 0:Qt.map(ns=>ns.option_text))||[]})}ne(Bt)}l(!0)},Ie=async at=>{var dt;const Ge=(dt=at.target.files)==null?void 0:dt[0];if(Ge){pe(!0);try{const Bt=await q.functions.invoke("bunny-upload",{body:{action:"create",title:Ge.name.replace(/\.[^/.]+$/,"")}});if(Bt.error)throw Bt.error;const{videoId:kt,libraryId:Qt}=Bt.data,ns=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:kt}});if(ns.error)throw ns.error;const{uploadUrl:$s,apiKey:Ds}=ns.data,Dt=new XMLHttpRequest;await new Promise(($t,ht)=>{Dt.upload.addEventListener("progress",Ut=>{if(Ut.lengthComputable){const Es=Math.round(Ut.loaded/Ut.total*100);console.log("Upload progress:",Es)}}),Dt.addEventListener("load",()=>{Dt.status>=200&&Dt.status<300?$t():ht(new Error(`Upload failed with status ${Dt.status}`))}),Dt.addEventListener("error",()=>ht(new Error("Upload failed"))),Dt.open("PUT",$s),Dt.setRequestHeader("AccessKey",Ds),Dt.send(Ge)});const St=`https://player.mediadelivery.net/embed/${Qt}/${kt}`;_(St),ae.success("Video uploaded successfully! It may take a few minutes to process.")}catch(Bt){console.error("Upload error:",Bt),ae.error("Failed to upload video")}finally{pe(!1)}}},Fe=async()=>{if(!f.trim()){ae.error("Title is required");return}try{let at;if(o){const{error:Ge}=await q.from("levelup_briefs").update({title:f,description:b||null,video_url:j||null,graphic_url:S||null,graphic_link_url:T||null,is_published:L,publish_date:F,show_frequency:V}).eq("id",o.id);if(Ge)throw Ge;at=o.id,await q.from("levelup_brief_links").delete().eq("brief_id",at);const{data:dt}=await q.from("levelup_brief_polls").select("id").eq("brief_id",at);if(dt)for(const Bt of dt)await q.from("levelup_brief_poll_options").delete().eq("poll_id",Bt.id);await q.from("levelup_brief_polls").delete().eq("brief_id",at)}else{const{data:Ge,error:dt}=await q.from("levelup_briefs").insert({title:f,description:b||null,video_url:j||null,graphic_url:S||null,graphic_link_url:T||null,is_published:L,publish_date:F,show_frequency:V,created_by:s==null?void 0:s.id}).select().single();if(dt)throw dt;at=Ge.id}if(K.length>0){const Ge=K.map((dt,Bt)=>({brief_id:at,title:dt.title,url:dt.url,sort_order:Bt}));await q.from("levelup_brief_links").insert(Ge)}for(let Ge=0;Ge0){const Qt=dt.options.map((ns,$s)=>({poll_id:Bt.id,option_text:ns,sort_order:$s}));await q.from("levelup_brief_poll_options").insert(Qt)}}ae.success(o?"Brief updated":"Brief created"),l(!1),Ce(),Te()}catch(at){console.error("Error saving brief:",at),ae.error("Failed to save brief")}},qe=async at=>{if(confirm("Are you sure you want to delete this brief?"))try{const{error:Ge}=await q.from("levelup_briefs").delete().eq("id",at);if(Ge)throw Ge;ae.success("Brief deleted"),Te()}catch(Ge){console.error("Error deleting brief:",Ge),ae.error("Failed to delete brief")}},ve=async at=>{p(at);const{count:Ge}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",at.id),{count:dt}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",at.id).not("dismissed_at","is",null);Me({total:Ge||0,dismissed:dt||0});const{data:Bt}=await q.from("levelup_brief_polls").select("*").eq("brief_id",at.id).order("sort_order");if(Bt){const kt=[];for(const Qt of Bt){const{data:ns}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",Qt.id).order("sort_order"),{data:$s}=await q.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",Qt.id),Ds=[...new Set(($s==null?void 0:$s.map(Ut=>Ut.user_id))||[])];let Dt={};if(Ds.length>0){const{data:Ut}=await q.from("profiles").select("id, name, email").in("id",Ds);Ut&&Ut.forEach(Es=>{Dt[Es.id]=Es.name||Es.email||"Unknown"})}const St=($s||[]).map(Ut=>({optionId:Ut.option_id,userName:Dt[Ut.user_id]||"Unknown",userId:Ut.user_id})),$t={};let ht=0;ns&&ns.forEach(Ut=>{const Es=($s==null?void 0:$s.filter(Xt=>Xt.option_id===Ut.id).length)||0;$t[Ut.id]=Es,ht+=Es}),kt.push({...Qt,options:ns||[],results:$t,respondents:St,totalResponses:Qt.poll_type==="single"?new Set($s==null?void 0:$s.map(Ut=>Ut.user_id)).size:ht})}ye(kt)}u(!0)},Je=()=>{Y([...K,{title:"",url:""}])},we=(at,Ge,dt)=>{const Bt=[...K];Bt[at][Ge]=dt,Y(Bt)},it=at=>{Y(K.filter((Ge,dt)=>dt!==at))},Ne=()=>{ne([...ee,{question:"",poll_type:"single",options:["",""]}])},He=(at,Ge)=>{const dt=[...ee];dt[at].question=Ge,ne(dt)},$e=(at,Ge)=>{const dt=[...ee];dt[at].poll_type=Ge,ne(dt)},Ye=at=>{const Ge=[...ee];Ge[at].options.push(""),ne(Ge)},Ke=(at,Ge,dt)=>{const Bt=[...ee];Bt[at].options[Ge]=dt,ne(Bt)},rt=(at,Ge)=>{const dt=[...ee];dt[at].options=dt[at].options.filter((Bt,kt)=>kt!==Ge),ne(dt)},tt=at=>{ne(ee.filter((Ge,dt)=>dt!==at))};return e.jsxs(Cs,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(B,{onClick:Ee,children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Frequency"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:r?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(at=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:at.title}),e.jsx(ut,{children:e.jsx(ze,{variant:at.is_published?"default":"secondary",children:at.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"capitalize",children:at.show_frequency.replace("_"," ")}),e.jsx(ut,{children:ks(new Date(at.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ve(at),children:e.jsx(yo,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>De(at),children:e.jsx(Tu,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>qe(at.id),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},at.id))})]})})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs($r,{defaultValue:"content",className:"w-full",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-4",children:[e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"media",children:"Media"}),e.jsx(Zt,{value:"links",children:"Links"}),e.jsx(Zt,{value:"polls",children:"Polls"})]}),e.jsxs(ls,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Title *"}),e.jsx(ge,{value:f,onChange:at=>g(at.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Db,{content:b,onChange:at=>v(at),placeholder:"Brief overview for agents...",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Publish Date"}),e.jsx(ge,{type:"datetime-local",value:F,onChange:at=>z(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Show Frequency"}),e.jsxs(us,{value:V,onValueChange:W,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"once",children:"Once (until dismissed)"}),e.jsx(Ze,{value:"every_login",children:"Every login"}),e.jsx(Ze,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(vn,{checked:L,onCheckedChange:M}),e.jsx(se,{children:"Publish immediately"})]})]}),e.jsxs(ls,{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(se,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ge,{type:"file",accept:"video/*",onChange:Ie,disabled:oe})}),oe&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Or paste embed URL"}),e.jsx(ge,{value:j,onChange:at=>_(at.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),j&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:j,className:"w-full h-full",allow:"autoplay; fullscreen",allowFullScreen:!0})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Graphic / Image (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ge,{type:"file",accept:"image/*",onChange:async at=>{var dt;const Ge=(dt=at.target.files)==null?void 0:dt[0];if(Ge){de(!0);try{const Bt=Ge.name.split(".").pop(),kt=`brief-graphics/${Date.now()}.${Bt}`,{error:Qt}=await q.storage.from("banner-images").upload(kt,Ge,{upsert:!0});if(Qt)throw Qt;const{data:ns}=q.storage.from("banner-images").getPublicUrl(kt);A(ns.publicUrl),ae.success("Image uploaded!")}catch(Bt){console.error(Bt),ae.error("Failed to upload image")}finally{de(!1)}}},disabled:ce})}),ce&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Or paste Image URL"}),e.jsx(ge,{value:S,onChange:at=>A(at.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Click-through Link (optional)"}),e.jsx(ge,{value:T,onChange:at=>D(at.target.value),placeholder:"https://example.com/landing-page"})]}),S&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:S,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(ls,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Quick Links"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Je,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),K.map((at,Ge)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(ge,{value:at.title,onChange:dt=>we(Ge,"title",dt.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(ge,{value:at.url,onChange:dt=>we(Ge,"url",dt.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>it(Ge),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]},Ge)),K.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(ls,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Polls"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Ne,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),ee.map((at,Ge)=>e.jsx(fe,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ge,{value:at.question,onChange:dt=>He(Ge,dt.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(us,{value:at.poll_type,onValueChange:dt=>$e(Ge,dt),children:[e.jsx(cs,{className:"w-32",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"single",children:"Single"}),e.jsx(Ze,{value:"multi",children:"Multi-select"})]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>tt(Ge),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[at.options.map((dt,Bt)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:dt,onChange:kt=>Ke(Ge,Bt,kt.target.value),placeholder:`Option ${Bt+1}`}),at.options.length>2&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>rt(Ge,Bt),children:e.jsx(bn,{className:"h-4 w-4 text-muted-foreground"})})]},Bt)),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>Ye(Ge),children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},Ge)),ee.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls added yet"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:Fe,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(bs,{open:d,onOpenChange:u,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Ae,{children:e.jsx("p",{className:"text-2xl font-bold",children:_e.total})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Ae,{children:e.jsx("p",{className:"text-2xl font-bold",children:_e.dismissed})})]})]}),ie.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),ie.map(at=>e.jsxs(fe,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:at.question}),e.jsx("div",{className:"space-y-2",children:at.options.map(Ge=>{const dt=at.results[Ge.id]||0,Bt=at.totalResponses>0?Math.round(dt/at.totalResponses*100):0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:Ge.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[dt," (",Bt,"%)"]})]}),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:`${Bt}%`}})}),dt>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(at.respondents||[]).filter(kt=>kt.optionId===Ge.id).map((kt,Qt)=>e.jsx(ze,{variant:"secondary",className:"text-xs font-normal",children:kt.userName},Qt))})]},Ge.id)})})]},at.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const yHs=()=>{const{user:s}=gs(),{toast:t}=Ua(),n=Gt(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=N.useState(null),[h,p]=N.useState(""),{data:f=[],isLoading:g}=lt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:T,error:D}=await q.from("additional_services").select("*").order("publish_date",{ascending:!1});if(D)throw D;return T}}),b=gt({mutationFn:async T=>{let D=T.existingImageUrl;if(T.image){const M=T.image.name.split(".").pop(),F=`${Date.now()}-${Math.random().toString(36).substring(7)}.${M}`,{error:z}=await q.storage.from("service-images").upload(F,T.image);if(z)throw z;const{data:V}=q.storage.from("service-images").getPublicUrl(F);D=V.publicUrl}const L={name:T.item.name,description:T.item.description||null,preview_image_url:D,signup_link_url:T.item.signup_link_url,publish_date:T.item.publish_date?new Date(T.item.publish_date).toISOString():new Date().toISOString(),is_published:T.item.is_published,created_by:s==null?void 0:s.id};if(T.itemId){const{error:M}=await q.from("additional_services").update(L).eq("id",T.itemId);if(M)throw M}else{const{error:M}=await q.from("additional_services").insert(L);if(M)throw M}},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:i?"Service updated":"Service created"}),a(!1),j()},onError:T=>{t({title:"Error saving service",description:T.message,variant:"destructive"})}}),v=gt({mutationFn:async T=>{const{error:D}=await q.from("additional_services").delete().eq("id",T);if(D)throw D},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:T=>{t({title:"Error deleting service",description:T.message,variant:"destructive"})}}),j=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),p(""),l(null)},_=T=>{l(T),c({name:T.name,description:T.description||"",signup_link_url:T.signup_link_url,publish_date:T.publish_date?new Date(T.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:T.is_published}),p(T.preview_image_url||""),a(!0)},S=T=>{var L;const D=(L=T.target.files)==null?void 0:L[0];D&&(u(D),p(URL.createObjectURL(D)))},A=T=>{if(T.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}b.mutate({item:o,image:d,existingImageUrl:(i==null?void 0:i.preview_image_url)||null,itemId:i==null?void 0:i.id})};return e.jsx(Cs,{title:"Manage Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(T=>T.is_published).length})})]})]}),e.jsxs(bs,{open:r,onOpenChange:T=>{a(T),T||j()},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:A,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name *"}),e.jsx(ge,{id:"name",value:o.name,onChange:T=>c({...o,name:T.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Db,{content:o.description,onChange:T=>c({...o,description:T}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(ge,{id:"signup_link_url",type:"url",value:o.signup_link_url,onChange:T=>c({...o,signup_link_url:T.target.value}),placeholder:"https://example.com/signup"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ge,{id:"publish_date",type:"date",value:o.publish_date,onChange:T=>c({...o,publish_date:T.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(vn,{id:"is_published",checked:o.is_published,onCheckedChange:T=>c({...o,is_published:T})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),p("")},children:e.jsx(Fn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(nl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(ge,{type:"file",accept:"image/*",onChange:S,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:b.isPending,children:b.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ae,{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"})}):f.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-16",children:"Preview"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Signup Link"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:f.map(T=>e.jsxs(Gs,{children:[e.jsx(ut,{children:T.preview_image_url?e.jsx("img",{src:T.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(nl,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(ut,{className:"font-medium",children:T.name}),e.jsx(ut,{children:e.jsxs("a",{href:T.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(tr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(ut,{children:new Date(T.publish_date).toLocaleDateString()}),e.jsx(ut,{children:e.jsx(ze,{variant:T.is_published?"default":"secondary",children:T.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>_(T),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this service?")&&v.mutate(T.id)},children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},T.id))})]})})})]})})};function vHs(){const{toast:s}=Ua(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});N.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:v,error:j}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(j)throw j;n(v.coupons||[])}catch(v){console.error("Error fetching coupons:",v),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},p=async()=>{if(!d.name){s({title:"Error",description:"Please enter a coupon name",variant:"destructive"});return}if(d.discountType==="percent"&&!d.percentOff){s({title:"Error",description:"Please enter a percent off value",variant:"destructive"});return}if(d.discountType==="amount"&&!d.amountOff){s({title:"Error",description:"Please enter an amount off value",variant:"destructive"});return}if(d.duration==="repeating"&&!d.durationInMonths){s({title:"Error",description:"Please enter duration in months",variant:"destructive"});return}l(!0);try{const v={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?v.percent_off=parseFloat(d.percentOff):(v.amount_off=Math.round(parseFloat(d.amountOff)*100),v.currency="usd"),d.duration==="repeating"&&(v.duration_in_months=parseInt(d.durationInMonths));const{data:j,error:_}=await q.functions.invoke("stripe-manage-coupons",{body:v});if(_)throw _;s({title:"Success",description:"Coupon created successfully"}),c(!1),u({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),h()}catch(v){console.error("Error creating coupon:",v),s({title:"Error",description:v.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},f=async v=>{if(confirm("Are you sure you want to delete this coupon?"))try{const{error:j}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:v}});if(j)throw j;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(j){console.error("Error deleting coupon:",j),s({title:"Error",description:j.message||"Failed to delete coupon",variant:"destructive"})}},g=v=>v.percent_off?`${v.percent_off}% off`:v.amount_off?`$${(v.amount_off/100).toFixed(2)} off`:"N/A",b=v=>{switch(v.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${v.duration_in_months} months`;default:return v.duration}};return e.jsx(Cs,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create New Coupon"}),e.jsx(Qn,{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(se,{children:"Promotion Code (what users will type)"}),e.jsx(ge,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:v=>u({...d,promotionCode:v.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),className:"font-mono uppercase"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Letters and numbers only. This is the code users enter at checkout."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Coupon Name (internal label)"}),e.jsx(ge,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:v=>u({...d,name:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Discount Type"}),e.jsxs(us,{value:d.discountType,onValueChange:v=>{const j=v==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:v,duration:j})},children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(i4,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(Ze,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Zl,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:v=>u({...d,percentOff:v.target.value})}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(ge,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:v=>u({...d,amountOff:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Duration"}),e.jsxs(us,{value:d.duration,onValueChange:v=>u({...d,duration:v}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"once",children:"Once (first payment only)"}),e.jsx(Ze,{value:"repeating",children:"Multiple months"}),e.jsxs(Ze,{value:"forever",disabled:d.discountType==="amount",children:["Forever ",d.discountType==="amount"&&"(% discounts only)"]})]})]}),d.discountType==="amount"&&e.jsx("p",{className:"text-xs text-muted-foreground",children:'Note: "Forever" duration is only available for percentage-based discounts.'})]}),d.duration==="repeating"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Number of Months"}),e.jsx(ge,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:v=>u({...d,durationInMonths:v.target.value})})]}),e.jsx(B,{onClick:p,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Active Coupons"}),e.jsx(Hn,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Ae,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ss,{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(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Promo Code"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Discount"}),e.jsx(Ct,{children:"Duration"}),e.jsx(Ct,{children:"Redemptions"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:t.map(v=>{var j;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-mono font-medium",children:((j=v.promotion_codes)==null?void 0:j.length)>0?v.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(ut,{children:v.name||"-"}),e.jsx(ut,{children:g(v)}),e.jsx(ut,{children:b(v)}),e.jsx(ut,{children:v.times_redeemed}),e.jsx(ut,{children:e.jsx(ze,{variant:v.valid?"default":"secondary",children:v.valid?"Active":"Inactive"})}),e.jsx(ut,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>f(v.id),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})})]},v.id)})})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"How to Use Coupons"})}),e.jsxs(Ae,{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 kNe={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 bHs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),[l,o]=N.useState(null),{data:c,isLoading:d,refetch:u}=lt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:j,error:_}=await q.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(_)throw _;return j}}),{data:h}=lt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:j,error:_}=await q.from("brokerages").select("*").order("name");if(_)throw _;return await Promise.all((j||[]).map(async A=>{const{data:T}=await q.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",A.id),{data:D}=await q.from("user_roles").select("user_id").eq("role","brokerage_manager"),L=(D==null?void 0:D.map(z=>z.user_id))||[],M=(T==null?void 0:T.filter(z=>L.includes(z.id)))||[],F=(T==null?void 0:T.length)||0;return{...A,managers:M,agentCount:F}}))}}),{data:p}=lt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:j,error:_}=await q.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(_)throw _;return j}}),f=j=>{if(j.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(j.brokerage_id&&!j.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(j.is_trial&&j.trial_expires_at)return new Date(j.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(j.subscription_status==="active"||j.subscription_status==="trialing"){const _=kNe[j.subscription_product_id];return{status:(_==null?void 0:_.name)||"Active",badge:j.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return j.subscription_status==="canceled"||j.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},g=c==null?void 0:c.filter(j=>{var S,A;if(!(((S=j.name)==null?void 0:S.toLowerCase().includes(s.toLowerCase()))||((A=j.email)==null?void 0:A.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const T=j.subscription_source||"platform";if(a==="platform"&&T==="local_move_website"||a==="local_move_website"&&T!=="local_move_website")return!1}switch(f(j),n){case"active":return j.subscription_status==="active";case"trialing":return j.subscription_status==="trialing"||j.is_trial&&new Date(j.trial_expires_at)>new Date;case"grandfathered":return j.is_grandfathered;case"brokerage":return j.brokerage_id&&!j.subscription_product_id&&!j.is_grandfathered;case"expired":return j.subscription_status==="canceled"||j.subscription_status==="past_due"||j.is_trial&&new Date(j.trial_expires_at)<=new Date;case"none":return!j.subscription_status||j.subscription_status==="none";default:return!0}}),b={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(j=>j.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(j=>j.subscription_status==="trialing"||j.is_trial&&new Date(j.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(j=>j.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(j=>j.brokerage_id&&!j.subscription_product_id&&!j.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(j=>j.subscription_status==="active"&&j.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(j=>j.subscription_status==="active"&&(j.subscription_product_id==="prod_Tc08MupgoVySDG"||j.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},v=j=>{window.open(`https://dashboard.stripe.com/customers/${j}`,"_blank")};return e.jsx(Cs,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(B,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Refresh"]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_n,{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:b.totalUsers})]})}),e.jsx(fe,{className:"border-green-500/50",children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ff,{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:b.activeSubscriptions})]})}),e.jsx(fe,{className:"border-blue-500/50",children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gr,{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:b.trials})]})}),e.jsx(fe,{className:"border-purple-500/50",children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xf,{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:b.grandfathered})]})}),e.jsx(fe,{className:"border-orange-500/50",children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Members"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-orange-600",children:b.brokerageMembers})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_b,{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:b.individualSubscribers})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Subs"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:b.brokerageSubscribers})]})})]}),e.jsxs($r,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"users",children:"All Users"}),e.jsx(Zt,{value:"brokerages",children:"Brokerages"}),e.jsxs(Zt,{value:"websites",className:"gap-2",children:[e.jsx(lc,{className:"h-4 w-4"}),"Website Subscriptions",p&&p.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1",children:p.length})]})]}),e.jsxs(ls,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name or email...",value:s,onChange:j=>t(j.target.value),className:"pl-9"})]}),e.jsxs(us,{value:a,onValueChange:j=>i(j),children:[e.jsx(cs,{className:"w-[200px]",children:e.jsx(hs,{placeholder:"Source"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Sources"}),e.jsx(Ze,{value:"platform",children:"Platform"}),e.jsx(Ze,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(us,{value:n,onValueChange:j=>r(j),children:[e.jsx(cs,{className:"w-[200px]",children:e.jsx(hs,{placeholder:"Filter by status"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),e.jsx(Ze,{value:"active",children:"Active Subscriptions"}),e.jsx(Ze,{value:"trialing",children:"Trials"}),e.jsx(Ze,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Ze,{value:"brokerage",children:"Brokerage Members"}),e.jsx(Ze,{value:"expired",children:"Expired/Canceled"}),e.jsx(Ze,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"User"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Plan"}),e.jsx(Ct,{children:"Brokerage"}),e.jsx(Ct,{children:"End Date"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:d?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(g==null?void 0:g.length)===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):g==null?void 0:g.map(j=>{var A,T;const _=f(j),S=kNe[j.subscription_product_id];return e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:j.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.email})]})}),e.jsx(ut,{children:e.jsx(ze,{variant:_.variant,children:_.badge})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm",children:j.is_grandfathered?"Legacy Access":j.brokerage_id&&!j.subscription_product_id?"Brokerage Subscription":(S==null?void 0:S.name)||_.status})}),e.jsx(ut,{children:(A=j.brokerages)!=null&&A.name?e.jsx("span",{className:"text-sm",children:j.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ut,{children:j.subscription_end_date?e.jsx("span",{className:"text-sm",children:ks(new Date(j.subscription_end_date),"MMM d, yyyy")}):j.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",ks(new Date(j.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[j.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(j.stripe_customer_id),children:e.jsx(tr,{className:"h-4 w-4"})}),e.jsxs(bs,{children:[e.jsx(Di,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",onClick:()=>o(j),children:"Details"})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Subscription Details"}),e.jsxs(Qn,{children:[j.name," (",j.email,")"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsx(ze,{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:j.is_grandfathered?"Grandfathered (Legacy)":j.brokerage_id&&!j.subscription_product_id?"Brokerage Subscription":(S==null?void 0:S.name)||"None"})]}),j.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((T=j.brokerages)==null?void 0:T.name)||"Unknown"})]}),j.subscription_end_date&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Current Period End"}),e.jsx("p",{className:"font-medium",children:ks(new Date(j.subscription_end_date),"MMMM d, yyyy")})]}),j.trial_expires_at&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trial Expires"}),e.jsx("p",{className:"font-medium",children:ks(new Date(j.trial_expires_at),"MMMM d, yyyy")})]}),j.stripe_customer_id&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Stripe Customer ID"}),e.jsx("p",{className:"font-mono text-sm",children:j.stripe_customer_id})]})]}),j.stripe_customer_id&&e.jsxs(B,{className:"w-full",onClick:()=>v(j.stripe_customer_id),children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},j.id)})})]})})})]}),e.jsx(ls,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(j=>{var S,A;const _=(S=j.managers)==null?void 0:S.some(T=>T.subscription_status==="active"&&(T.subscription_product_id==="prod_Tc08MupgoVySDG"||T.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Ga,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-lg",children:j.name}),e.jsxs(Hn,{children:[j.agentCount," agents"]})]})]}),e.jsx(ze,{variant:_?"default":"outline",children:_?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Ae,{children:((A=j.managers)==null?void 0:A.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),j.managers.map(T=>{const D=kNe[T.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:T.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:T.email})]}),e.jsx("div",{className:"text-right",children:D?e.jsxs("div",{children:[e.jsx(ze,{variant:"default",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:D.price})]}):e.jsx(ze,{variant:"outline",children:"No Subscription"})})]},T.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},j.id)})})}),e.jsx(ls,{value:"websites",className:"space-y-4",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(lc,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Hn,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Ae,{className:"p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Setup Fee"}),e.jsx(Ct,{children:"Monthly"}),e.jsx(Ct,{children:"Next Renewal"}),e.jsx(Ct,{children:"Started"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:p?p.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):p.map(j=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:j.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.agent_email})]})}),e.jsx(ut,{children:e.jsx(ze,{variant:j.status==="active"?"default":j.status==="canceled"?"destructive":"outline",children:j.status})}),e.jsx(ut,{children:j.setup_fee_paid?e.jsxs(ze,{variant:"secondary",children:["Paid · $",(j.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(ze,{variant:"outline",children:"Unpaid"})}),e.jsxs(ut,{className:"font-medium",children:["$",(j.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(ut,{children:j.current_period_end?e.jsx("span",{className:"text-sm",children:ks(new Date(j.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm",children:ks(new Date(j.created_at),"MMM d, yyyy")})}),e.jsx(ut,{className:"text-right",children:j.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(j.stripe_customer_id),children:e.jsx(tr,{className:"h-4 w-4"})})})]},j.id)):e.jsx(Gs,{children:e.jsx(ut,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function _Hs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(""),[l,o]=N.useState("all"),[c,d]=N.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});N.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:g,error:b}=await q.from("referrals").select(` *, referrer_brokerage:brokerages!referrer_brokerage_id(name), referred_brokerage:brokerages!referred_brokerage_id(name), referred_user:profiles!referred_user_id(name, email) `).order("created_at",{ascending:!1});if(b)throw b;t(g||[]);const v=(g==null?void 0:g.filter(S=>S.status==="qualified").length)||0,j=(g==null?void 0:g.filter(S=>S.status==="pending").length)||0,_=(g==null?void 0:g.filter(S=>S.status==="cancelled").length)||0;d({total:(g==null?void 0:g.length)||0,qualified:v,pending:j,cancelled:_,totalDiscounts:v*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 q.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")}},p=s.filter(g=>{var j,_,S,A,T,D;const b=((_=(j=g.referrer_brokerage)==null?void 0:j.name)==null?void 0:_.toLowerCase().includes(a.toLowerCase()))||((A=(S=g.referred_brokerage)==null?void 0:S.name)==null?void 0:A.toLowerCase().includes(a.toLowerCase()))||((D=(T=g.referred_user)==null?void 0:T.email)==null?void 0:D.toLowerCase().includes(a.toLowerCase())),v=l==="all"||g.status===l;return b&&v}),f=g=>{switch(g){case"qualified":return e.jsxs(ze,{className:"bg-green-100 text-green-800",children:[e.jsx(zi,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(ze,{variant:"secondary",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(ze,{variant:"destructive",children:[e.jsx(Gc,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(ze,{children:g})}};return e.jsx(Cs,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(B,{onClick:h,variant:"outline",children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Process Qualifications"]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-4",children:[e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Referrals"})]})]})})}),e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zi,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.qualified}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified"})]})]})})}),e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5 text-amber-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.pending}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending"})]})]})})}),e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gc,{className:"h-5 w-5 text-red-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.cancelled}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cancelled"})]})]})})}),e.jsx(fe,{children:e.jsx(Ae,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zl,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:["$",c.totalDiscounts]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Discounts"})]})]})})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"All Referrals"}),e.jsx(Hn,{children:"View and manage all referral relationships"})]}),e.jsxs(Ae,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by brokerage or email...",value:a,onChange:g=>i(g.target.value),className:"pl-10"})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"Filter by status"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),e.jsx(Ze,{value:"pending",children:"Pending"}),e.jsx(Ze,{value:"qualified",children:"Qualified"}),e.jsx(Ze,{value:"cancelled",children:"Cancelled"})]})]})]}),n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Referrer"}),e.jsx(Ct,{children:"Referred"}),e.jsx(Ct,{children:"Signup Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Qualified Date"}),e.jsx(Ct,{children:"Discount"})]})}),e.jsx(pa,{children:p.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):p.map(g=>{var b,v,j,_;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:((b=g.referrer_brokerage)==null?void 0:b.name)||"Unknown"}),e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{children:((v=g.referred_brokerage)==null?void 0:v.name)||((j=g.referred_user)==null?void 0:j.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(_=g.referred_user)==null?void 0:_.email})]})}),e.jsx(ut,{children:ks(new Date(g.signup_date),"MMM d, yyyy")}),e.jsx(ut,{children:f(g.status)}),e.jsx(ut,{children:g.qualified_date?ks(new Date(g.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(ut,{children:g.discount_applied?e.jsx(ze,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},g.id)})})]})]})]})]})})}const SNe=[{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"}],wHs=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function jHs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});N.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:_,error:S}=await q.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(S)throw S;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)},p=_=>{o(_),d({title:_.title,description:_.description||"",action_type:_.action_type,target_role:_.target_role,is_active:_.is_active}),i(!0)},f=async()=>{if(!c.title.trim()){ae.error("Title is required");return}try{if(l){const{error:_}=await q.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(_)throw _;ae.success("Checklist item updated")}else{const _=s.filter(A=>A.target_role===c.target_role).reduce((A,T)=>Math.max(A,T.sort_order),-1),{error:S}=await q.from("onboarding_checklist_items").insert({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active,sort_order:_+1});if(S)throw S;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(confirm("Are you sure you want to delete this checklist item?"))try{const{error:S}=await q.from("onboarding_checklist_items").delete().eq("id",_);if(S)throw S;ae.success("Checklist item deleted"),u()}catch(S){console.error("Error deleting checklist item:",S),ae.error("Failed to delete checklist item")}},b=async _=>{try{const{error:S}=await q.from("onboarding_checklist_items").update({is_active:!_.is_active}).eq("id",_.id);if(S)throw S;ae.success(_.is_active?"Item deactivated":"Item activated"),u()}catch(S){console.error("Error toggling item:",S),ae.error("Failed to update item")}},v=s.filter(_=>_.target_role==="brokerage_manager"),j=s.filter(_=>_.target_role==="agent");return e.jsxs(Cs,{title:"Onboarding Checklist",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),e.jsxs(B,{onClick:h,className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Ae,{children:v.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-12",children:"#"}),e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Action Type"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:v.map((_,S)=>{var A;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"text-muted-foreground",children:S+1}),e.jsx(ut,{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(ut,{children:e.jsx(ze,{variant:"outline",children:((A=SNe.find(T=>T.value===_.action_type))==null?void 0:A.label)||_.action_type})}),e.jsx(ut,{children:e.jsx(vn,{checked:_.is_active,onCheckedChange:()=>b(_)})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(_),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(_.id),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},_.id)})})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Ae,{children:j.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-12",children:"#"}),e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Action Type"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:j.map((_,S)=>{var A;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"text-muted-foreground",children:S+1}),e.jsx(ut,{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(ut,{children:e.jsx(ze,{variant:"outline",children:((A=SNe.find(T=>T.value===_.action_type))==null?void 0:A.label)||_.action_type})}),e.jsx(ut,{children:e.jsx(vn,{checked:_.is_active,onCheckedChange:()=>b(_)})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(_),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(_.id),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},_.id)})})]})})]})]}),e.jsx(bs,{open:a,onOpenChange:i,children:e.jsxs(vs,{children:[e.jsx(ws,{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(se,{htmlFor:"title",children:"Title *"}),e.jsx(ge,{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(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{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(se,{children:"Target Role"}),e.jsxs(us,{value:c.target_role,onValueChange:_=>d({...c,target_role:_}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:wHs.map(_=>e.jsx(Ze,{value:_.value,children:_.label},_.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Action Type"}),e.jsxs(us,{value:c.action_type,onValueChange:_=>d({...c,action_type:_}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:SNe.map(_=>e.jsx(Ze,{value:_.value,children:_.label},_.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{id:"is_active",checked:c.is_active,onCheckedChange:_=>d({...c,is_active:_})}),e.jsx(se,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{onClick:f,children:l?"Save Changes":"Create Item"})]})]})})]})}function NHs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("name"),[l,o]=N.useState("asc"),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,b]=N.useState(""),{data:v}=lt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:z,error:V}=await q.from("brokerages").select("id, name").order("name");if(V)throw V;return z}}),j=async z=>{let W=[],K=0,Y=!0;for(;Y;){const{data:ee,error:ne}=await z(K,K+1e3-1);if(ne)throw ne;ee&&ee.length>0?(W=[...W,...ee],K+=1e3,Y=ee.length===1e3):Y=!1}return W},{data:_,isLoading:S}=lt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const z=await j((De,Ie)=>q.from("profiles").select("id, name, email, brokerage_id, created_at").range(De,Ie)),{data:V}=await q.from("brokerages").select("id, name"),W=new Map((V==null?void 0:V.map(De=>[De.id,De.name]))||[]),[{data:K},{data:Y},{data:ee},{data:ne},{data:oe},{data:pe},{data:ce}]=await Promise.all([q.rpc("get_admin_contact_counts"),q.rpc("get_admin_video_counts"),q.rpc("get_admin_popby_counts"),q.rpc("get_admin_listing_counts"),q.rpc("get_admin_deal_counts"),q.rpc("get_admin_portal_counts"),q.rpc("get_admin_sendable_card_counts")]),de=new Map;K==null||K.forEach(De=>de.set(De.owner_user_id,De.contact_count));const ie=new Map;Y==null||Y.forEach(De=>ie.set(De.owner_user_id,De.video_count));const ye=new Map;ee==null||ee.forEach(De=>ye.set(De.owner_user_id,De.popby_count));const _e=new Map;ne==null||ne.forEach(De=>_e.set(De.agent_id,De.listing_count));const Me=new Map;oe==null||oe.forEach(De=>Me.set(De.owner_user_id,De.deal_count));const Te=new Map;pe==null||pe.forEach(De=>Te.set(De.owner_user_id,{total:De.portal_count,active:De.active_portal_count}));const Ce=new Map;return ce==null||ce.forEach(De=>Ce.set(De.owner_user_id,{total:De.card_count,sent:De.sent_card_count,views:De.total_card_views})),z.map(De=>{const Ie=Te.get(De.id),Fe=Ce.get(De.id);return{id:De.id,name:De.name||"Unknown",email:De.email||"",brokerage_id:De.brokerage_id,brokerage_name:De.brokerage_id&&W.get(De.brokerage_id)||null,contact_count:de.get(De.id)||0,video_count:ie.get(De.id)||0,popby_count:ye.get(De.id)||0,listing_count:_e.get(De.id)||0,deal_count:Me.get(De.id)||0,portal_count:(Ie==null?void 0:Ie.total)||0,active_portal_count:(Ie==null?void 0:Ie.active)||0,card_count:(Fe==null?void 0:Fe.total)||0,sent_card_count:(Fe==null?void 0:Fe.sent)||0,total_card_views:(Fe==null?void 0:Fe.views)||0,created_at:De.created_at}})}}),A=N.useMemo(()=>{if(!_)return[];let z=_.filter(V=>{const W=s.toLowerCase(),K=!s||V.name.toLowerCase().includes(W)||V.email.toLowerCase().includes(W),Y=n==="all"||n==="none"&&!V.brokerage_id||V.brokerage_id===n,ee=parseInt(c)||0,ne=parseInt(u)||0,oe=parseInt(p)||0,pe=parseInt(g)||0,ce=V.contact_count>=ee&&V.video_count>=ne&&V.popby_count>=oe&&V.listing_count>=pe;return K&&Y&&ce});return z.sort((V,W)=>{let K=0;return a==="name"?K=V.name.localeCompare(W.name):K=V[a]-W[a],l==="asc"?K:-K}),z},[_,s,n,a,l,c,u,p,g]),T=z=>{a===z?o(l==="asc"?"desc":"asc"):(i(z),o("desc"))},D=()=>{const z=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],V=A.map(ne=>[ne.name,ne.email,ne.brokerage_name||"None",ne.contact_count,ne.video_count,ne.popby_count,ne.listing_count,ne.deal_count,`${ne.portal_count} (${ne.active_portal_count})`,ne.card_count,ne.sent_card_count,ne.total_card_views]),W=[z.join(","),...V.map(ne=>ne.map(oe=>`"${oe}"`).join(","))].join(` `),K=new Blob([W],{type:"text/csv"}),Y=URL.createObjectURL(K),ee=document.createElement("a");ee.href=Y,ee.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,ee.click(),URL.revokeObjectURL(Y)},L=N.useMemo(()=>A.length?A.reduce((z,V)=>({contacts:z.contacts+V.contact_count,videos:z.videos+V.video_count,popbys:z.popbys+V.popby_count,listings:z.listings+V.listing_count,deals:z.deals+V.deal_count,portals:z.portals+V.portal_count,activePortals:z.activePortals+V.active_portal_count,cards:z.cards+V.card_count,sentCards:z.sentCards+V.sent_card_count,cardViews:z.cardViews+V.total_card_views}),{contacts:0,videos:0,popbys:0,listings:0,deals:0,portals:0,activePortals:0,cards:0,sentCards:0,cardViews:0}):{contacts:0,videos:0,popbys:0,listings:0,deals:0,portals:0,activePortals:0,cards:0,sentCards:0,cardViews:0},[A]),M=N.useMemo(()=>A.length?{portals:A.filter(z=>z.portal_count>0).length,cards:A.filter(z=>z.card_count>0).length}:{portals:0,cards:0},[A]),F=({field:z,children:V})=>e.jsx(Ct,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>T(z),children:e.jsxs("div",{className:"flex items-center gap-1",children:[V,e.jsx(sm,{className:`h-3 w-3 ${a===z?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(Kw,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(fe,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(gw,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Ae,{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:M.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:L.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:L.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(fe,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Hs,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Ae,{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:M.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:L.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:L.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:L.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(Hn,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:D,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Ae,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name or email...",value:s,onChange:z=>t(z.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(us,{value:n,onValueChange:r,children:[e.jsxs(cs,{children:[e.jsx(Ga,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(hs,{placeholder:"Brokerage"})]}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Brokerages"}),e.jsx(Ze,{value:"none",children:"No Brokerage"}),v==null?void 0:v.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))]})]})}),e.jsx("div",{children:e.jsx(ge,{type:"number",placeholder:"Min contacts",value:c,onChange:z=>d(z.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(ge,{type:"number",placeholder:"Min videos",value:u,onChange:z=>h(z.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(ge,{type:"number",placeholder:"Min popbys",value:p,onChange:z=>f(z.target.value),min:"0"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-8 text-sm",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:A.length}),e.jsx("div",{className:"text-muted-foreground",children:"Users"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:L.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:L.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:L.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:L.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:L.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:L.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:L.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),S?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(F,{field:"name",children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Brokerage"}),e.jsx(F,{field:"contact_count",children:"Contacts"}),e.jsx(F,{field:"video_count",children:"Videos"}),e.jsx(F,{field:"popby_count",children:"Popbys"}),e.jsx(F,{field:"listing_count",children:"Listings"}),e.jsx(F,{field:"deal_count",children:"Deals"}),e.jsx(F,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gw,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(F,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hs,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(pa,{children:A.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):A.map(z=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:z.name}),e.jsx(ut,{className:"text-muted-foreground",children:z.email}),e.jsx(ut,{children:z.brokerage_name?e.jsx(ze,{variant:"secondary",children:z.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.contact_count>0?"default":"outline",children:z.contact_count})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.video_count>0?"default":"outline",children:z.video_count})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.popby_count>0?"default":"outline",children:z.popby_count})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.listing_count>0?"default":"outline",children:z.listing_count})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.deal_count>0?"default":"outline",children:z.deal_count})}),e.jsx(ut,{children:z.portal_count>0?e.jsxs(Ac,{children:[e.jsx(Mc,{children:e.jsxs(ze,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[z.portal_count,z.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",z.active_portal_count," active)"]})]})}),e.jsxs(yc,{children:[e.jsxs("p",{children:[z.portal_count," total portals"]}),e.jsxs("p",{children:[z.active_portal_count," currently active"]})]})]}):e.jsx(ze,{variant:"outline",children:"0"})}),e.jsx(ut,{children:z.card_count>0?e.jsxs(Ac,{children:[e.jsx(Mc,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ze,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:z.card_count}),z.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(cr,{className:"h-3 w-3"}),z.sent_card_count]}),z.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(Ir,{className:"h-3 w-3"}),z.total_card_views]})]})}),e.jsxs(yc,{children:[e.jsxs("p",{children:[z.card_count," cards created"]}),e.jsxs("p",{children:[z.sent_card_count," sent"]}),e.jsxs("p",{children:[z.total_card_views," total views"]})]})]}):e.jsx(ze,{variant:"outline",children:"0"})})]},z.id))})]})})]})]})]})})}function kHs(){Ua(),Gt();const[s,t]=N.useState("user-analytics"),{data:n}=lt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:f,error:g}=await q.from("feature_flags").select("*").order("key");if(g)throw g;return f}}),{data:r,isLoading:a}=lt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:f,error:g}=await q.from("relationship_types").select("*").order("sort_order");if(g)throw g;return f}}),{data:i,isLoading:l}=lt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:f,error:g}=await q.from("action_types").select("*").order("sort_order");if(g)throw g;return f}}),{data:o,isLoading:c}=lt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:f,error:g}=await q.from("action_scripts").select("*, action_type:action_types(*)");if(g)throw g;return f}}),{data:d,isLoading:u}=lt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:f,error:g}=await q.from("touchpoint_plans").select("*").order("name");if(g)throw g;return f}}),{data:h,isLoading:p}=lt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:f,error:g}=await q.from("popby_items").select("*").is("owner_user_id",null).order("name");if(g)throw g;return f}});return e.jsx(Cs,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs($r,{value:s,onValueChange:t,children:[e.jsxs(Ur,{className:"grid w-full grid-cols-9",children:[e.jsxs(Zt,{value:"user-analytics",className:"gap-2",children:[e.jsx(yo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Zt,{value:"relationship-types",className:"gap-2",children:[e.jsx(_n,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Zt,{value:"action-types",className:"gap-2",children:[e.jsx(Pr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Zt,{value:"scripts",className:"gap-2",children:[e.jsx(Nr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Zt,{value:"video-scripts",className:"gap-2",children:[e.jsx(Ph,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Zt,{value:"plans",className:"gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Zt,{value:"popbys",className:"gap-2",children:[e.jsx(Bi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Zt,{value:"settings",className:"gap-2",children:[e.jsx(Vo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Zt,{value:"feature-flags",className:"gap-2",children:[e.jsx(Y2,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(ls,{value:"user-analytics",className:"mt-6",children:e.jsx(NHs,{})}),e.jsx(ls,{value:"relationship-types",className:"mt-6",children:e.jsx(SHs,{types:r||[],isLoading:a})}),e.jsx(ls,{value:"action-types",className:"mt-6",children:e.jsx(CHs,{types:i||[],isLoading:l})}),e.jsx(ls,{value:"scripts",className:"mt-6",children:e.jsx(THs,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(ls,{value:"video-scripts",className:"mt-6",children:e.jsx(IHs,{})}),e.jsx(ls,{value:"plans",className:"mt-6",children:e.jsx(EHs,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(ls,{value:"popbys",className:"mt-6",children:e.jsx(MHs,{items:h||[],isLoading:p})}),e.jsx(ls,{value:"settings",className:"mt-6",children:e.jsx(PHs,{})}),e.jsx(ls,{value:"feature-flags",className:"mt-6",children:e.jsx(AHs,{flags:n||[]})})]})]})})}function SHs({types:s,isLoading:t}){const{toast:n}=Ua(),r=Gt(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=gt({mutationFn:async u=>{if(u.id){const{error:h}=await q.from("relationship_types").update({name:u.name,description:u.description,icon:u.icon}).eq("id",u.id);if(h)throw h}else{const{error:h}=await q.from("relationship_types").insert([{name:u.name,description:u.description,icon:u.icon,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await q.from("relationship_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Relationship Types"}),e.jsx(Hn,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Ae,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-12"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(pa,{children:s.map(u=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsx(Uu,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(ut,{className:"font-medium",children:u.name}),e.jsx(ut,{className:"text-muted-foreground",children:u.description}),e.jsx(ut,{children:e.jsx(vn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(ut,{children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(ja,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(ws,{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(se,{htmlFor:"name",children:"Name"}),e.jsx(ge,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"icon",children:"Icon"}),e.jsx(ge,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function CHs({types:s,isLoading:t}){const{toast:n}=Ua(),r=Gt(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=gt({mutationFn:async u=>{if(u.id){const{error:h}=await q.from("action_types").update({name:u.name,description:u.description,icon:u.icon,color:u.color}).eq("id",u.id);if(h)throw h}else{const{error:h}=await q.from("action_types").insert([{name:u.name,description:u.description,icon:u.icon,color:u.color,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await q.from("action_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Action Types"}),e.jsx(Hn,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Ae,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{children:"Color"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(pa,{children:s.map(u=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:u.name}),e.jsx(ut,{className:"text-muted-foreground",children:u.description}),e.jsx(ut,{children:u.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:u.color}})}),e.jsx(ut,{children:e.jsx(vn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(ut,{children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(ja,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(ws,{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(se,{htmlFor:"name",children:"Name"}),e.jsx(ge,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"icon",children:"Icon"}),e.jsx(ge,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"color",children:"Color"}),e.jsx(ge,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function THs({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=Ua(),a=Gt(),[i,l]=N.useState(null),[o,c]=N.useState(!1),d=gt({mutationFn:async h=>{if(h.id){const{error:p}=await q.from("action_scripts").update({title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:h.active}).eq("id",h.id);if(p)throw p}else{const{error:p}=await q.from("action_scripts").insert([{title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:!0}]);if(p)throw p}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),u=gt({mutationFn:async h=>{const{error:p}=await q.from("action_scripts").delete().eq("id",h);if(p)throw p},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),r({title:"Deleted successfully"})}});return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Script Library"}),e.jsx(Hn,{children:"Create and manage scripts for each action type"})]}),e.jsxs(B,{onClick:()=>{l(null),c(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Ae,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Action Type"}),e.jsx(Ct,{children:"Tone"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(pa,{children:s.map(h=>{var p;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:h.title}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",children:((p=h.action_type)==null?void 0:p.name)||"Unknown"})}),e.jsx(ut,{className:"text-muted-foreground",children:h.tone}),e.jsx(ut,{children:e.jsx(ze,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(ut,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{l(h),c(!0)},children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsxs(_s,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const p=new FormData(h.currentTarget);d.mutate({id:i==null?void 0:i.id,title:p.get("title"),action_type_id:p.get("action_type_id"),tone:p.get("tone"),script_body:p.get("script_body"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(ge,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(us,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select action type"})}),e.jsx(ds,{children:t.map(h=>e.jsx(Ze,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(ge,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ts,{id:"script_body",name:"script_body",defaultValue:i==null?void 0:i.script_body,rows:8,required:!0,placeholder:`Use {{FirstName}}, {{LastName}}, and {{AgentName}} as placeholders. Example: Hey {{FirstName}}, it's {{AgentName}}. I was thinking about you and wanted to check in...`})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function EHs({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=Ua(),i=Gt(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(!1),[g,b]=N.useState(null),[v,j]=N.useState(null),{data:_}=lt({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:F,error:z}=await q.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(z)throw z;return F},enabled:!!u}),S=gt({mutationFn:async F=>{if(F.id){const{error:z}=await q.from("touchpoint_plans").update({name:F.name,description:F.description,active:F.active}).eq("id",F.id);if(z)throw z}else{const{error:z}=await q.from("touchpoint_plans").insert([{name:F.name,description:F.description,active:!0}]);if(z)throw z}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:F=>{a({title:"Error",description:F.message,variant:"destructive"})}}),A=gt({mutationFn:async F=>{if(F.id){const{error:z}=await q.from("touchpoint_plan_items").update({action_type_id:F.action_type_id,default_script_id:F.default_script_id,notes:F.notes}).eq("id",F.id);if(z)throw z}else{const{error:z}=await q.from("touchpoint_plan_items").insert([{plan_id:F.plan_id,month_number:F.month_number,action_type_id:F.action_type_id,default_script_id:F.default_script_id,notes:F.notes}]);if(z)throw z}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),T=gt({mutationFn:async F=>{const{error:z}=await q.from("touchpoint_plan_items").delete().eq("id",F);if(z)throw z},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),D=gt({mutationFn:async F=>{const{data:z,error:V}=await q.from("action_scripts").insert([{...F,active:!0}]).select().single();if(V)throw V;return z},onSuccess:async F=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),g&&await A.mutateAsync({id:g.itemId,plan_id:u,month_number:g.month,action_type_id:g.actionTypeId,default_script_id:F.id}),f(!1),b(null),a({title:"Script created and assigned"})},onError:F=>{a({title:"Error",description:F.message,variant:"destructive"})}}),L=(F,z,V)=>{b({month:F,actionTypeId:z,itemId:V}),f(!0)},M=F=>n.find(z=>z.id===F);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Touchpoint Plans"}),e.jsx(Hn,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(B,{onClick:()=>{o(null),d(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Ae,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(F=>e.jsxs(fe,{className:`cursor-pointer transition-colors ${u===F.id?"border-primary":""}`,onClick:()=>h(F.id),children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Pt,{className:"text-base",children:F.name}),e.jsx(B,{variant:"ghost",size:"icon",onClick:z=>{z.stopPropagation(),o(F),d(!0)},children:e.jsx(ja,{className:"h-4 w-4"})})]})}),e.jsxs(Ae,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:F.description}),e.jsx(ze,{variant:F.active?"default":"secondary",className:"mt-2",children:F.active?"Active":"Inactive"})]})]},F.id))})})]}),u&&e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Plan Schedule"}),e.jsx(Hn,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Ae,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(F,z)=>z+1).map(F=>{const z=_==null?void 0:_.find(K=>K.month_number===F),V=z!=null&&z.default_script_id?M(z.default_script_id):null,W=n.filter(K=>K.action_type_id===(z==null?void 0:z.action_type_id)&&K.active);return e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"w-20 font-medium text-sm",children:["Month ",F]}),e.jsxs(us,{value:(z==null?void 0:z.action_type_id)||"none",onValueChange:K=>{K==="none"&&z?T.mutate(z.id):K!=="none"&&A.mutate({id:z==null?void 0:z.id,plan_id:u,month_number:F,action_type_id:K,default_script_id:null})},children:[e.jsx(cs,{className:"w-40",children:e.jsx(hs,{placeholder:"No action"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No action"}),t.filter(K=>K.active).map(K=>e.jsx(Ze,{value:K.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[K.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:K.color}}),K.name]})},K.id))]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs(us,{value:z.default_script_id||"none",onValueChange:K=>{j(null),A.mutate({id:z.id,default_script_id:K==="none"?null:K})},children:[e.jsx(cs,{className:"w-56",children:e.jsx(hs,{placeholder:"Select script"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No default script"}),W.map(K=>e.jsxs(Ze,{value:K.id,children:[K.title," ",K.tone&&`(${K.tone})`]},K.id))]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>L(F,z.action_type_id,z.id),children:[e.jsx(As,{className:"h-3 w-3 mr-1"}),"New Script"]}),V&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>j((v==null?void 0:v.id)===V.id?null:V),children:(v==null?void 0:v.id)===V.id?"Hide":"Preview"})]})]}),v&&(z==null?void 0:z.default_script_id)===v.id&&e.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ze,{variant:"outline",children:v.title}),v.tone&&e.jsx(ze,{variant:"secondary",children:v.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:v.script_body})]})]},F)})})})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:F=>{F.preventDefault();const z=new FormData(F.currentTarget);S.mutate({id:l==null?void 0:l.id,name:z.get("name"),description:z.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ge,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:S.isPending,children:[S.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(bs,{open:p,onOpenChange:f,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create New Script"}),e.jsxs(Qn,{children:["Create a script for Month ",g==null?void 0:g.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:F=>{F.preventDefault();const z=new FormData(F.currentTarget);D.mutate({title:z.get("title"),action_type_id:g.actionTypeId,tone:z.get("tone"),script_body:z.get("script_body")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_title",children:"Title"}),e.jsx(ge,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_tone",children:"Tone"}),e.jsx(ge,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ts,{id:"script_body",name:"script_body",rows:6,required:!0,placeholder:"Hey {{FirstName}}, it's {{AgentName}}. I was thinking about you and wanted to check in..."})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:D.isPending,children:[D.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function AHs({flags:s}){const{toast:t}=Ua(),n=Gt(),r=async(a,i)=>{const{error:l}=await q.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(n.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Feature Flags"}),e.jsx(Hn,{children:"Control which features are enabled for members"})]}),e.jsx(Ae,{children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Flag"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Notes"}),e.jsx(Ct,{children:"Last Updated"})]})}),e.jsx(pa,{children:s.map(a=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-mono text-sm",children:a.key}),e.jsx(ut,{children:e.jsx(vn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(ut,{children:e.jsx(ge,{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(ut,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function MHs({items:s,isLoading:t}){const{toast:n}=Ua(),r=Gt(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=gt({mutationFn:async h=>{if(h.id){const{error:p}=await q.from("popby_items").update({name:h.name,description:h.description}).eq("id",h.id);if(p)throw p}else{const{error:p}=await q.from("popby_items").insert([{name:h.name,description:h.description,owner_user_id:null}]);if(p)throw p}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:h=>{n({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await q.from("popby_items").update({is_active:!h.is_active}).eq("id",h.id),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]})},u=async h=>{await q.from("popby_items").delete().eq("id",h),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),n({title:"Deleted successfully"})};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Popby Ideas"}),e.jsx(Hn,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Ae,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ss,{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(Bi,{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(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(pa,{children:s.map(h=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:h.name}),e.jsx(ut,{className:"text-muted-foreground",children:h.description}),e.jsx(ut,{children:e.jsx(vn,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const p=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:p.get("name"),description:p.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ge,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function IHs(){var f;const{toast:s}=Ua(),t=Gt(),[n,r]=N.useState(null),[a,i]=N.useState(!1),{data:l,isLoading:o}=lt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:g,error:b}=await q.from("video_script_categories").select("*").order("sort_order");if(b)throw b;return g}}),{data:c,isLoading:d}=lt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:g,error:b}=await q.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(b)throw b;return g}}),u=gt({mutationFn:async g=>{var b,v;if(g.id){const{error:j}=await q.from("video_scripts").update({title:g.title,script_text:g.script_text,category_id:g.category_id,tags:((b=g.tags)==null?void 0:b.split(",").map(_=>_.trim()).filter(Boolean))||[]}).eq("id",g.id);if(j)throw j}else{const{error:j}=await q.from("video_scripts").insert([{title:g.title,script_text:g.script_text,category_id:g.category_id||null,tags:((v=g.tags)==null?void 0:v.split(",").map(_=>_.trim()).filter(Boolean))||[]}]);if(j)throw j}},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 q.from("video_scripts").update({is_active:!g.is_active}).eq("id",g.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},p=async g=>{confirm("Delete this video script?")&&(await q.from("video_scripts").delete().eq("id",g),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Video Scripts"}),e.jsx(Hn,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(B,{onClick:()=>{r(null),i(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Ae,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Category"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(pa,{children:c==null?void 0:c.map(g=>{var b;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:g.title}),e.jsx(ut,{className:"text-muted-foreground",children:((b=g.category)==null?void 0:b.name)||"Uncategorized"}),e.jsx(ut,{children:e.jsx(vn,{checked:g.is_active,onCheckedChange:()=>h(g)})}),e.jsxs(ut,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{r(g),i(!0)},children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(g.id),children:e.jsx(bn,{className:"h-4 w-4"})})]})]},g.id)})})]})}),e.jsx(bs,{open:a,onOpenChange:i,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsxs(_s,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault();const b=new FormData(g.currentTarget);u.mutate({id:n==null?void 0:n.id,title:b.get("title"),script_text:b.get("script_text"),category_id:b.get("category_id")||null,tags:b.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(ge,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"category_id",children:"Category"}),e.jsxs(us,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select category"})}),e.jsx(ds,{children:l==null?void 0:l.map(g=>e.jsx(Ze,{value:g.id,children:g.name},g.id))})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Ts,{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(se,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(ge,{id:"tags",name:"tags",defaultValue:((f=n==null?void 0:n.tags)==null?void 0:f.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:u.isPending,children:[u.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function PHs(){const{toast:s}=Ua(),[t,n]=N.useState(""),[r,a]=N.useState(!0),[i,l]=N.useState(!1);N.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();d!=null&&d.value&&n(d.value)}catch(d){console.error("Error fetching settings:",d)}a(!1)})()},[]);const o=async()=>{l(!0);try{await q.from("settings").upsert({key:"mapbox_public_token",value:t.trim()}),s({title:"Mapbox token saved!"})}catch{s({title:"Error saving token",variant:"destructive"})}l(!1)};return r?e.jsx(fe,{children:e.jsx(Ae,{className:"flex justify-center py-8",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(Ca,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Hn,{children:"Configure the map feature for popbys"})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(ge,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>n(c.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",e.jsx("a",{href:"https://mapbox.com/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"mapbox.com"}),". This token will be used by all agents for the popby map feature."]})]}),e.jsxs(B,{onClick:o,disabled:i,children:[i&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(ze,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const LHs=()=>{const[s,t]=N.useState(""),[n,r]=N.useState("grid"),a=In(),{data:i=[],isLoading:l}=lt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await q.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var u;return c.name.toLowerCase().includes(s.toLowerCase())||((u=c.description)==null?void 0:u.toLowerCase().includes(s.toLowerCase()))});return e.jsx(Cs,{title:"Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Additional Services"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Explore our additional services and offerings"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search services...",value:s,onChange:c=>t(c.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[s&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>r("grid"),className:"rounded-full",children:e.jsx(vf,{className:"h-4 w-4"})}),e.jsx(B,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(Ep,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," service",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(4)].map((c,d)=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"})]})},d))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:s?"No services match your search":"No additional services available yet"}),s&&e.jsx(B,{variant:"outline",onClick:()=>t(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(c=>e.jsxs(fe,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>a(`/additional-services/${c.id}`),children:[e.jsx("div",{className:`relative overflow-hidden bg-muted ${n==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:c.preview_image_url?e.jsx("img",{src:c.preview_image_url,alt:c.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(un,{className:"h-8 w-8"})})}),e.jsxs(Ae,{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:tB(c.description)})]})]},c.id))})]})})},DHs=()=>{const{serviceId:s}=_i(),t=In(),{data:n,isLoading:r}=lt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await q.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return r?e.jsx(Cs,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(Ws,{className:"h-8 w-48"}),e.jsx(Ws,{className:"h-64 w-full rounded-lg"}),e.jsx(Ws,{className:"h-24 w-full"})]})}):n?e.jsx(Cs,{title:n.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(fe,{className:"overflow-hidden",children:e.jsx("div",{className:"relative bg-muted",children:n.preview_image_url?e.jsx("img",{src:n.preview_image_url,alt:n.name,className:"w-full h-auto max-h-[500px] object-contain mx-auto"}):e.jsx("div",{className:"w-full h-64 flex items-center justify-center text-muted-foreground",children:e.jsx(un,{className:"h-16 w-16"})})})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:n.name}),e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(yr,{className:"h-4 w-4 mr-1"}),"Published ",ks(new Date(n.publish_date),"MMMM d, yyyy")]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:n.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs(B,{size:"lg",className:"gap-2",onClick:()=>window.open(n.signup_link_url,"_blank"),children:[e.jsx(tr,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(Cs,{title:"Not Found",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center py-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground mb-4",children:"Service Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"The service you're looking for doesn't exist or has been removed."}),e.jsxs(B,{onClick:()=>t("/additional-services"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},OF=[{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 RHs(){const[s,t]=N.useState(OF[0].id),n=OF.find(r=>r.id===s)||OF[0];return e.jsx(Cs,{title:"AI Toolkit",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(ZS,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"AI Toolkit"}),e.jsx("p",{className:"text-muted-foreground",children:"Powerful AI tools to boost your real estate business"})]})]}),e.jsx("div",{className:"md:hidden",children:e.jsxs(us,{value:s,onValueChange:t,children:[e.jsx(cs,{className:"w-full",children:e.jsx(hs,{placeholder:"Select a tool"})}),e.jsx(ds,{children:OF.map(r=>e.jsx(Ze,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx($r,{value:s,onValueChange:t,className:"w-full",children:e.jsx(Ur,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:OF.map(r=>e.jsx(Zt,{value:r.id,className:"flex-1 min-w-[150px] text-xs lg:text-sm whitespace-normal h-auto py-2",children:r.name},r.id))})})}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-full max-w-[700px]",dangerouslySetInnerHTML:{__html:n.iframe}})})]})})}function OHs({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 pG({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:Et("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(ga,{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 FHs({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 p=new Date().getHours(),f=p<12?"Good morning":p<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:[f,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(un,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(OHs,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(pG,{icon:e.jsx(wc,{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(Vo,{className:"h-3.5 w-3.5"})})}),e.jsx(pG,{icon:e.jsx(_c,{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(pG,{icon:e.jsx(gr,{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(pG,{icon:e.jsx(_n,{className:"h-3.5 w-3.5"}),label:"Your sphere",value:String(c),hint:"People in your database",onClick:h})]})]})}const MZe="agent-os-onboarding-completed",fG=[{icon:nx,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:ph,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:_n,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:Tl,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:Bi,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:yo,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"]}],zHs=()=>{const[s,t]=N.useState(!1),[n,r]=N.useState(0),[a,i]=N.useState(!1);N.useEffect(()=>{if(!localStorage.getItem(MZe)){const g=setTimeout(()=>t(!0),500);return()=>clearTimeout(g)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(MZe,"true"),t(!1)},d=fG[n],u=d.icon,h=n===fG.length-1,p=f=>{f||c(),t(f)};return e.jsx(bs,{open:s,onOpenChange:p,children:e.jsxs(vs,{className:"sm:max-w-lg overflow-hidden p-0 gap-0",children:[e.jsxs("div",{className:`relative bg-gradient-to-br ${d.bgGradient} p-8 pb-12 transition-all duration-500`,children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx("div",{className:"absolute -top-4 -right-4 w-32 h-32 bg-white/10 rounded-full blur-2xl animate-pulse"}),e.jsx("div",{className:"absolute -bottom-8 -left-8 w-40 h-40 bg-white/10 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl"})]}),e.jsxs("div",{className:`relative mx-auto flex h-20 w-20 items-center justify-center transition-all duration-300 ${a?"scale-75 opacity-0":"scale-100 opacity-100"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-white/20 rounded-2xl blur-xl"}),e.jsx("div",{className:"relative flex h-20 w-20 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm border border-white/30 shadow-2xl",children:e.jsx(u,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),n===0&&e.jsxs("div",{className:"absolute top-4 right-4 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm border border-white/30 text-white text-xs font-medium flex items-center gap-1.5",children:[e.jsx(un,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(ws,{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(Qn,{className:`text-base pt-2 transition-all duration-300 delay-75 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.description})]}),d.highlights&&e.jsx("div",{className:`space-y-2.5 py-4 transition-all duration-300 delay-100 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.highlights.map((f,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(Lr,{className:"h-3.5 w-3.5 text-white"})}),e.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-foreground transition-colors",children:f})]},g))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:fG.map((f,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}=gs();return lt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(n)throw n;return t},enabled:!!s})},$Hs=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Ul(new Date,r);await q.from("contact_snoozes").delete().eq("contact_id",n);const{error:i}=await q.from("contact_snoozes").insert({contact_id:n,owner_user_id:t.id,snoozed_until:a.toISOString()});if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),Dr({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{Dr({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},UHs=()=>{const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("contact_snoozes").delete().eq("contact_id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),Dr({title:"Snooze cancelled"})},onError:t=>{Dr({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},qHs=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function L1e({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=N.useState(null),l=$Hs(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>ks(Ul(new Date,d),"MMM d, yyyy");return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Qn,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:qHs.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Et("w-full flex items-center justify-between p-3 rounded-lg border transition-colors",a===d.days?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"),children:[e.jsx("span",{className:"font-medium",children:d.label}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(yr,{className:"h-3.5 w-3.5"}),"Until ",c(d.days)]})]},d.days))}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const VHs={Crown:xf,FileText:Nr,Users:_n,Globe:lc,Star:ua,Phone:Pr,MessageSquare:Ci,PenTool:a4,Video:vr,Gift:Bi};function HHs({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=In(),[c,d]=N.useState("name"),[u,h]=N.useState("asc"),[p,f]=N.useState(null),[g,b]=N.useState(""),v=T=>{c===T?h(D=>D==="asc"?"desc":"asc"):(d(T),h("asc"))},j=N.useMemo(()=>[...s].sort((T,D)=>{var M,F;let L=0;switch(c){case"name":{const z=`${T.contact.first_name} ${T.contact.last_name||""}`.toLowerCase(),V=`${D.contact.first_name} ${D.contact.last_name||""}`.toLowerCase();L=z.localeCompare(V);break}case"relationship_type":L=(T.relationshipTypeName||"").localeCompare(D.relationshipTypeName||"");break;case"action_type":L=(((M=T.actionType)==null?void 0:M.name)||"").localeCompare(((F=D.actionType)==null?void 0:F.name)||"");break;case"last_touch":L=(T.monthNumber||0)-(D.monthNumber||0);break}return u==="asc"?L:-L}),[s,c,u]),_=T=>VHs[T||"Phone"]||Pr,S=({field:T,children:D})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>v(T),children:[D,c===T?u==="asc"?e.jsx(Bu,{className:"ml-2 h-4 w-4"}):e.jsx(om,{className:"ml-2 h-4 w-4"}):e.jsx(sm,{className:"ml-2 h-4 w-4 opacity-50"})]}),A=(T,D,L)=>{f(T),b(`${D} ${L||""}`.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(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{className:"bg-muted/50",children:[e.jsx(Ct,{className:"w-[180px]",children:e.jsx(S,{field:"name",children:"Contact"})}),e.jsx(Ct,{className:"w-[130px]",children:e.jsx(S,{field:"relationship_type",children:"Type"})}),e.jsx(Ct,{className:"w-[120px]",children:e.jsx(S,{field:"action_type",children:"Action"})}),e.jsx(Ct,{className:"w-[130px]",children:"Phone"}),e.jsx(Ct,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(pa,{children:j.map((T,D)=>{var W,K,Y,ee,ne,oe;const L=T.isSpecialDate,M=T.specialDateType,F=L?M==="birthday"?hu:zr:_(((W=T.actionType)==null?void 0:W.icon)||null),z=T.contact.phone,V=T.contact.email;return e.jsxs(Gs,{className:Et("hover:bg-muted/50 transition-colors",L&&M==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",L&&M==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(ut,{className:"font-medium",children:e.jsx("div",{children:e.jsxs("button",{onClick:()=>o(`/mission-control/contacts/${T.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[T.contact.first_name," ",T.contact.last_name]})})}),e.jsx(ut,{children:T.relationshipTypeName?e.jsx(ze,{variant:"secondary",className:"text-xs",children:T.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ut,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:L?e.jsx(ze,{className:Et("gap-1",M==="birthday"&&"bg-pink-500 hover:bg-pink-600",M==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:M==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(hu,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(zr,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(F,{className:"h-3 w-3"}),(K=T.actionType)==null?void 0:K.name]})})}),e.jsx(ut,{children:z?e.jsx("span",{className:"text-sm font-mono",children:T.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[z&&e.jsx("a",{href:`tel:${T.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(Pr,{className:"h-3.5 w-3.5"})}),z&&e.jsx("a",{href:a(T.contact.phone,(Y=T.script)==null?void 0:Y.script_body,T.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(Ci,{className:"h-3.5 w-3.5"})}),V&&(l?e.jsx("button",{onClick:()=>l({id:T.contact.id,first_name:T.contact.first_name,last_name:T.contact.last_name,email:T.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(Hs,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(T.contact.email,(ee=T.script)==null?void 0:ee.script_body,(ne=T.script)==null?void 0:ne.email_subject,(oe=T.actionType)==null?void 0:oe.name,T.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(Hs,{className:"h-3.5 w-3.5"})})),L&&e.jsxs("button",{onClick:()=>{const pe=`${T.contact.first_name}${T.contact.last_name?" "+T.contact.last_name:""}`,ce=M==="birthday"?"birthday":"home_anniversary",de=new URLSearchParams({cardType:ce,contactId:T.contact.id,name:pe,...T.contact.address?{address:T.contact.address}:{},...M==="anniversary"&&T.contact.home_anniversary?{date:T.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${de.toString()}`)},className:Et("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",M==="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 ${M==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(Hs,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>A(T.contact.id,T.contact.first_name,T.contact.last_name),title:"Snooze",children:e.jsx(_f,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var pe;return t(T.contact.id,T.actionType.id,(pe=T.script)==null?void 0:pe.id)},disabled:r,children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${T.contact.id}-${D}`)})})]})}),e.jsx(L1e,{open:!!p,onOpenChange:T=>!T&&f(null),contactId:p||"",contactName:g})]})}function GHs({onSelect:s}){const{user:t}=gs(),[n,r]=N.useState("root"),[a,i]=N.useState(null),{data:l=[],isLoading:o}=lt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:j,error:_}=await q.from("email_template_categories").select("*").order("sort_order");if(_)throw _;return j}}),{data:c=[],isLoading:d}=lt({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:j,error:_}=await q.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(_)throw _;return j}}),{data:u=[],isLoading:h}=lt({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:j,error:_}=await q.from("campaign_templates").select("id,name,subject,body_html,is_shared,user_id,updated_at").or(`user_id.eq.${t.id},is_shared.eq.true`).order("updated_at",{ascending:!1});if(_)throw _;return j}}),p=u.filter(j=>j.user_id===(t==null?void 0:t.id)&&!j.is_shared),f=u.filter(j=>j.is_shared),g=l.find(j=>j.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(ss,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const b=j=>{s({title:j.name,subject:j.subject,body:j.body_html})};if(n==="root")return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Your templates"}),e.jsxs("button",{onClick:()=>r("my"),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(Xi,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"My Saved Templates"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.length," template",p.length===1?"":"s"," you've created"]})]})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0"})]}),e.jsxs("button",{onClick:()=>r("shared"),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-400 flex items-center justify-center",children:e.jsx(lc,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Shared Library"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.length," team template",f.length===1?"":"s"]})]})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0"})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Quick scripts by category"}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-1 pr-1",children:l.map(j=>e.jsxs("button",{onClick:()=>{i(j.id),r("category")},className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:j.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:j.name}),j.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:j.description})]})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},j.id))})]})]});const v=e.jsxs("button",{onClick:()=>{r("root"),i(null)},className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(fl,{className:"h-3.5 w-3.5"}),"Back"]});return n==="my"?e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Xi,{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(ss,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):p.length===0?e.jsxs("div",{className:"text-center py-6 space-y-2",children:[e.jsx(un,{className:"h-6 w-6 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You haven't created any templates yet."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Create beautiful templates in ",e.jsx("span",{className:"font-medium",children:"Email Templates"})," in the sidebar — they'll appear here."]})]}):e.jsx(mi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:p.map(j=>e.jsxs("button",{onClick:()=>b(j),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:j.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:j.subject||"(no subject)"})]},j.id))})})]}):n==="shared"?e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(lc,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(ss,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(mi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:f.map(j=>e.jsxs("button",{onClick:()=>b(j),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:j.name}),e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:"Shared"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:j.subject||"(no subject)"})]},j.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children: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(ss,{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(mi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(j=>e.jsxs("button",{onClick:()=>s(j),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm",children:j.title}),j.tone&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:j.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:j.subject})]},j.id))})})]})}function D1e(){const{user:s}=gs(),t=Gt(),{data:n,isLoading:r}=lt({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:u}=await q.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),a=gt({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:u,error:h}=await q.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ae.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?ae.error("That slug is already taken. Try another."):ae.error("Failed to create page")}}),i=gt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page");const{error:u}=await q.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",n.id);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ae.success("Page updated!")},onError:()=>ae.error("Failed to update page")}),{data:l=[],isLoading:o}=lt({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:u}=await q.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),c=gt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page. Create your Connect page first.");const{data:u,error:h}=await q.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:n.id}).select("token").single();if(h)throw h;return`${window.location.origin}/connect/${n.slug}?t=${u.token}`}});return{intakePage:n,isLoading:r,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function P_t({value:s,onChange:t,userId:n,placeholder:r}){const[a,i]=N.useState(!1),[l,o]=N.useState([]),[c,d]=N.useState(!1),[u,h]=N.useState(0),p=N.useRef(null),f=N.useRef(null);N.useEffect(()=>{const b=v=>{p.current&&!p.current.contains(v.target)&&i(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]),N.useEffect(()=>{f.current&&clearTimeout(f.current);const b=s.trim();if(!n||b.length<1||b.includes("@")&&b.indexOf("@")>0&&/\S+@\S+\.\S+/.test(b)){o([]);return}return f.current=setTimeout(async()=>{d(!0);const v=`%${b}%`,j=q,{data:_,error:S}=await j.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n).not("email","is",null).or(`first_name.ilike.${v},last_name.ilike.${v},email.ilike.${v}`).order("first_name",{ascending:!0}).limit(8);d(!1),!S&&_&&(o(_),h(0),i(_.length>0))},180),()=>{f.current&&clearTimeout(f.current)}},[s,n]);const g=b=>{b.email&&(t(b.email),i(!1))};return e.jsxs("div",{ref:p,className:"relative",children:[e.jsx(ge,{id:"gmail-to",value:s,onChange:b=>t(b.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:b=>{!a||l.length===0||(b.key==="ArrowDown"?(b.preventDefault(),h(v=>Math.min(v+1,l.length-1))):b.key==="ArrowUp"?(b.preventDefault(),h(v=>Math.max(v-1,0))):b.key==="Enter"?(b.preventDefault(),g(l[u])):b.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(ss,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((b,v)=>{const j=[b.first_name,b.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(v),onClick:()=>g(b),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${v===u?"bg-accent":"bg-popover"}`,children:[e.jsx(Xi,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:j}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:b.email})]})]},b.id)})})]})}function WHs(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 CNe=25*1024*1024,IZe=Math.floor(6.5*1024*1024),KHs=750*1024,d2=50,YHs=["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 xG(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function ZHs(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 QHs(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function u2(s,t){const n=QHs(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 Ty({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=gs(),h=Gt(),{isReady:p,settings:f}=jR(),{data:g}=M1e(),[b,v]=N.useState(!1),{intakePage:j}=D1e(),_=j?`https://contacts.relevelup.com/${j.slug}`:null,S=!!r&&r.length>0,A=p,T=S?r:n?[n]:[],D=T[0],L=S?Math.ceil(T.length/d2):1,M=S&&T.length>d2,[F,z]=N.useState((D==null?void 0:D.email)||""),[V,W]=N.useState(a),[K,Y]=N.useState(i),[ee,ne]=N.useState(!1),[oe,pe]=N.useState(!1),[ce,de]=N.useState([]),ie=N.useRef(new Map),[ye,_e]=N.useState(a),[Me,Te]=N.useState(i),[Ce,Ee]=N.useState("composing"),[De,Ie]=N.useState(0),[Fe,qe]=N.useState(0),[ve,Je]=N.useState(0),[we,it]=N.useState(0),Ne=N.useRef(!1),[He,$e]=N.useState(null);N.useEffect(()=>{if(s){const Ut=/<[a-z][\s\S]*>/i.test(i),Es=Ut?WHs(i):i;at.current=Ut?{plain:Es,html:i}:null,z((D==null?void 0:D.email)||""),_e(a),Te(Es),W(u2(a,D||{first_name:""})),Y(u2(Es,D||{first_name:""})),pe(!a&&!i),de([]),ie.current=new Map,Ee("composing"),Ie(0),qe(0),Je(0),it(0),Ne.current=!1,$e(null)}},[s,D,a,i]);const Ye=async Ut=>{const Es=Ut.target.files;if(!Es)return;const Xt=ce.reduce((Bs,Us)=>Bs+Us.size,0),Ys=[];let Ss=Xt;for(const Bs of Array.from(Es)){if(!YHs.includes(Bs.type)){ae.error(`${Bs.name}: Unsupported file type`);continue}if(Ss+Bs.size>CNe){ae.error(`Total attachments exceed ${xG(CNe)} limit`);break}try{const Us=await ZHs(Bs);Ys.push({name:Bs.name,type:Bs.type,size:Bs.size,data:Us}),Ss+=Bs.size}catch{ae.error(`Failed to read ${Bs.name}`)}}de(Bs=>[...Bs,...Ys]),Ut.target.value=""},Ke=Ut=>{const Es=ce[Ut];Es&&ie.current.delete(`${Es.name}::${Es.size}`),de(Xt=>Xt.filter((Ys,Ss)=>Ss!==Ut))},rt=async()=>{if(ce.length===0||!u)return{inline:[],paths:[]};const Ut=[],Es=[];for(const Xt of ce){const Ys=`${Xt.name}::${Xt.size}`,Ss=ie.current.get(Ys);if(Ss){Es.push(Ss);continue}if(Xt.size<=KHs){Ut.push(Xt);continue}const Bs=Xt.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Us=`${u.id}/${Date.now()}-${Bs}`,sn=atob(Xt.data),Jn=new Uint8Array(sn.length);for(let Sn=0;Sn{if(!/<[a-z][\s\S]*>/i.test(Ut)||typeof window>"u")return Ut;const Es=Ut.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*[^>]*>/gi,` `).replace(/<\s*li\b[^>]*>/gi,"• ").replace(/<\s*(p|div|h[1-6]|tr)\b[^>]*>/gi,""),Xt=document.createElement("div");return Xt.innerHTML=Es,(Xt.textContent||Xt.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},at=N.useRef(null),Ge=Ut=>{const Es=/<[a-z][\s\S]*>/i.test(Ut.body),Xt=Es?tt(Ut.body):Ut.body;at.current=Es?{plain:Xt,html:Ut.body}:null,_e(Ut.subject),Te(Xt),W(u2(Ut.subject,D||{first_name:""})),Y(u2(Xt,D||{first_name:""})),pe(!1)},dt=Ut=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(Ut)?Ut:Ut.split(/\n\n+/).map(Es=>`

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

`).join(""),Bt=(Ut,Es)=>{const Xt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let Ys=Ut.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(Bs,Us,sn,Jn,fn)=>{if(!Jn||/^(mailto:|tel:|#)/i.test(Jn)||Jn.includes("/bulk-email-track")||Jn.includes("/ses-campaign-track"))return Bs;const Sn=`${Xt}?s=${Es}&t=click&u=${encodeURIComponent(Jn)}`;return``});const Ss=``;return/<\/body>/i.test(Ys)?Ys=Ys.replace(/<\/body>/i,`${Ss}`):Ys=`${Ys}${Ss}`,Ys},kt=async Ut=>{if(!(Ut!=null&&Ut.email))return ae.error("Please enter a recipient email"),!1;const Es=Ut||{first_name:""},Xt=u2(ye,Es),Ys=at.current,Ss=Ys&&Me===Ys.plain,Bs=u2(Ss?Ys.html:Me,Es);let Us=Ss?Bs:dt(Bs);const sn=u&&Ut.id?crypto.randomUUID():null;sn&&(Us=Bt(Us,sn));try{if(u&&Ut.email){const Sn=new Date(Date.now()-6e5).toISOString(),{data:Gn}=await q.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",Ut.email).eq("subject",Xt).gte("sent_at",Sn).limit(1);if(Gn&&Gn.length>0)return console.log(`Skipping duplicate send to ${Ut.email} (same subject within 10 min)`),ae.info(`Skipped ${Ut.first_name||Ut.email} — already sent this in the last 10 min`),!0}const{inline:Jn,paths:fn}=await rt();if(A){const Sn=(f==null?void 0:f.display_name)||"ReLevelUp",Gn=`${Sn.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Hr=`${Sn} <${Gn}>`;let pi=fn[0];if(!pi&&Jn.length>0&&u){const Rr=Jn[0],er=Rr.name.replace(/[^a-zA-Z0-9._-]/g,"_"),lr=`${u.id}/${Date.now()}-${er}`,Fs=atob(Rr.data),$n=new Uint8Array(Fs.length);for(let ts=0;ts({name:Hr,type:pi,data:Ms})),attachment_paths:fn}});if(Gn)throw Gn;if(!(Sn!=null&&Sn.success))throw new Error((Sn==null?void 0:Sn.error)||"Failed to send")}if(u&&Ut.id&&sn&&(await q.from("bulk_email_sends").insert({id:sn,user_id:u.id,contact_id:Ut.id,contact_email:Ut.email,subject:Xt,source:c||(A?"ses_bulk":"sphere_gaps")}),d))try{await q.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:Ut.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Xt}`,completed_at:new Date().toISOString()})}catch(Sn){console.warn("touch log insert failed",Sn)}return!0}catch(Jn){return console.error("Send error:",Jn),ae.error("Failed to send to "+Ut.first_name+": "+(Jn instanceof Error?Jn.message:"Unknown error")),!1}},Qt=()=>{const Ut=De*d2;return T.slice(Ut,Ut+d2)},ns=async()=>{if(!V||!K){ae.error("Please fill in subject and message");return}const Ut=Qt();ne(!0),Ee("sending");let Es=0,Xt=0;for(let Ss=0;SssetTimeout(Us,150));qe(Ss=>Ss+Es),Je(Ss=>Ss+Xt),ne(!1),h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),De>=L-1||Ne.current?Ee("all_done"):Ee("batch_complete")},$s=async()=>{if(!V||!K){ae.error("Please fill in subject and message");return}if(A&&g&&!g.hasVerifiedSes&&!g.hasGmail){v(!0);return}if(!S){const Ut=D||{id:"",first_name:"",last_name:"",email:F.trim()};if(!Ut.email){ae.error("Please enter a recipient email");return}ne(!0);try{await kt(Ut)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),ae.success("Email sent successfully!"),t(!1),o==null||o())}finally{ne(!1)}return}await ns()},Ds=async()=>{Ie(Ut=>Ut+1),it(0),await new Promise(Ut=>setTimeout(Ut,50)),await ns()};N.useEffect(()=>{},[De]);const Dt=()=>{if(ee){Ne.current=!0;return}t(!1),o==null||o()},St=De*d2,$t=Math.min(St+d2,T.length),ht=S&&T.length>0?Math.round((Fe+ve)/T.length*100):0;return e.jsxs(bs,{open:s,onOpenChange:Dt,children:[e.jsxs(vs,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:`h-5 w-5 ${A?"text-orange-500":"text-red-500"}`}),S?`Send to ${T.length} Contacts`:"Compose Email"]}),A?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",f==null?void 0:f.reply_to_email,")"]}):l?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:l})]}):null,S&&Ce==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[T.length," contacts"]}),". You'll review each personalized email before sending."]})]}),Ce==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(ss,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",De+1," of ",L,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[we," of ",Qt().length," in this batch"]})]}),e.jsx(xi,{value:we/Qt().length*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Fe+ve," / ",T.length]}),e.jsxs("span",{children:[Fe," sent • ",ve," failed"]})]}),e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Ne.current=!0},children:"Stop Sending"})]}),Ce==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(xr,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Batch ",De+1," Complete!"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Fe," sent, ",ve," failed so far"]})]}),e.jsx(xi,{value:ht,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[T.length-Fe-ve," contacts remaining (",L-De-1," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:Dt,children:"Done for Now"}),e.jsxs(B,{className:"flex-1 gap-2",onClick:Ds,children:[e.jsx(cr,{className:"h-4 w-4"}),"Send Next ",Math.min(d2,T.length-$t)," Contacts"]})]})]}),Ce==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(xr,{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:[Fe," emails sent successfully",ve>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",ve," failed"]})]})]}),e.jsx(B,{className:"w-full",onClick:Dt,children:"Close"})]}),Ce==="composing"&&e.jsxs("div",{className:"space-y-4",children:[oe?e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/30 max-h-[50vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(Nr,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>pe(!1),className:"h-7 px-2 text-xs",children:[e.jsx(Fn,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(GHs,{onSelect:Ge})]}):e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>pe(!0),children:[e.jsx(Nr,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(cl,{}),!S&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"gmail-to",children:"To"}),e.jsx(P_t,{value:F,onChange:z,userId:u==null?void 0:u.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(ge,{id:"gmail-subject",value:V,onChange:Ut=>{W(Ut.target.value),_e(Ut.target.value)},placeholder:"Enter subject..."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(ze,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{Y(Ut=>Ut+"{{first_name}}"),Te(Ut=>Ut+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(ze,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{Y(Ut=>Ut+"{{last_name}}"),Te(Ut=>Ut+"{{last_name}}")},children:"{{last_name}}"}),_&&e.jsx(ze,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const Ut=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${_} `;Y(Es=>Es+Ut),Te(Es=>Es+Ut)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),e.jsx(Ts,{id:"gmail-body",value:K,onChange:Ut=>{Y(Ut.target.value),Te(Ut.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),S&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}"," to personalize. You'll preview each recipient's email in the next step."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var Ut;return(Ut=document.getElementById("gmail-attachments"))==null?void 0:Ut.click()},disabled:ee,children:[e.jsx(r4,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",xG(CNe)," 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:Ye})]}),ce.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ce.map((Ut,Es)=>e.jsxs(ze,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(r4,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:Ut.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",xG(Ut.size),")"]}),e.jsx("button",{type:"button",onClick:()=>Ke(Es),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(Fn,{className:"h-3 w-3"})})]},Es))}),A&&ce.some(Ut=>Ut.size>IZe)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",xG(IZe)," will be sent as secure download links."]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),S?e.jsxs(B,{onClick:()=>{$e(T[0]||null),Ee("reviewing")},disabled:!V||!K,className:"gap-2",children:["Review Emails",e.jsx(za,{className:"h-4 w-4"})]}):e.jsxs(B,{onClick:$s,disabled:ee||!V||!K||!F.trim(),className:"gap-2",children:[ee?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),ee?"Sending...":"Send Email"]})]})]}),Ce==="reviewing"&&S&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-primary bg-primary/10 rounded-md px-2.5 py-1.5",children:["✉️ Click any recipient below to preview the ",e.jsx("span",{className:"font-semibold",children:"exact personalized email"})," they will receive."]}),M&&e.jsxs("p",{className:"text-xs text-amber-600 bg-amber-500/10 rounded-md px-2.5 py-1.5",children:["📦 ",T.length," contacts will be sent in ",L," batches of up to ",d2,". You'll confirm before each batch."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{children:["Recipients (",T.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:T.map(Ut=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(He==null?void 0:He.id)===Ut.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>$e(Ut),children:[Ut.first_name," ",Ut.last_name," — ",Ut.email]},Ut.id))})]}),He&&e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/30 space-y-2 animate-in fade-in slide-in-from-top-1",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("p",{className:"text-xs font-semibold text-primary flex items-center gap-1.5",children:[e.jsx(Hs,{className:"h-3.5 w-3.5"}),"Preview for ",He.first_name," ",He.last_name]})}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"To:"})," ",He.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",u2(ye,He)]})]}),e.jsx(cl,{}),e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:u2(Me,He)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>{Ee("composing"),$e(null)},children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(B,{onClick:$s,disabled:ee,className:"gap-2",children:[ee?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),M?`Send First ${d2}`:`Send to ${T.length}`]})]})]})]}),e.jsx(I1e,{open:b,onOpenChange:v,hasPending:!!(g!=null&&g.hasPendingSes),pendingEmails:g==null?void 0:g.pendingEmails})]})}function XHs(){const s=In(),{data:t}=lx(),{data:n}=XD(),r=gU(),{isGmailConnected:a,gmailEmail:i}=bh(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(new Set),p=Sf(new Date),f=Ul(p,30),g=T=>{if(!T)return null;const D=T.split(/[-/T]/);if(D.length<3)return null;const L=parseInt(D[1],10)-1,M=parseInt(D[2],10);return isNaN(L)||isNaN(M)?null:new Date(p.getFullYear(),L,M)},b=N.useMemo(()=>{if(!t)return[];const T=[];for(const D of t){if(D.birthday){const L=g(D.birthday);L&&(Rl(L,p)||Uv(L,p)&&jb(L,f))&&T.push({contact:D,type:"birthday",date:L,daysUntil:Wx(L,p),dateStr:D.birthday})}if(D.home_anniversary){const L=g(D.home_anniversary);L&&(Rl(L,p)||Uv(L,p)&&jb(L,f))&&T.push({contact:D,type:"anniversary",date:L,daysUntil:Wx(L,p),dateStr:D.home_anniversary})}if(D.wedding_anniversary){const L=g(D.wedding_anniversary);L&&(Rl(L,p)||Uv(L,p)&&jb(L,f))&&T.push({contact:D,type:"wedding_anniversary",date:L,daysUntil:Wx(L,p),dateStr:D.wedding_anniversary})}}return T.sort((D,L)=>D.daysUntil-L.daysUntil),T},[t]),v=T=>T==="birthday"?"Birthday":T==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",j=async T=>{const D=(n==null?void 0:n.find(L=>L.name==="Call"))||(n==null?void 0:n[0]);if(D)try{await r.mutateAsync({contactId:T.contact.id,actionTypeId:D.id,notes:`${v(T.type)} outreach`}),h(L=>new Set(L).add(`${T.contact.id}-${T.type}`)),Dr({title:"Touch logged!",description:`Logged outreach for ${T.contact.first_name}`})}catch{Dr({title:"Error",description:"Failed to log touch",variant:"destructive"})}},_=T=>{const D=`${T.contact.first_name}${T.contact.last_name?" "+T.contact.last_name:""}`,L=T.type==="birthday"?"birthday":T.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",M=new URLSearchParams({cardType:L,contactId:T.contact.id,name:D,...T.contact.address?{address:T.contact.address}:{},...(T.type==="anniversary"||T.type==="wedding_anniversary")&&T.dateStr?{date:T.dateStr}:{}});s(`/mission-control/card-studio?${M.toString()}`)},S=T=>T===0?"Today!":T===1?"Tomorrow":`${T} days`,A=T=>T===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":T<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":T<=7?"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/30":"bg-muted text-muted-foreground border-border";return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Tl,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(ze,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[b.length," event",b.length!==1?"s":""]})]})}),e.jsxs(Ae,{className:"space-y-2",children:[b.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(hu,{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."})]}),b.map((T,D)=>{var z,V;const L=`${T.contact.id}-${T.type}`,M=u.has(L),F=`${((z=T.contact.first_name)==null?void 0:z[0])||""}${((V=T.contact.last_name)==null?void 0:V[0])||""}`.toUpperCase();return e.jsxs("div",{className:Et("p-3 rounded-lg border transition-colors",T.daysUntil===0&&T.type==="birthday"?"bg-pink-500/10 border-pink-500/30 dark:bg-pink-900/20 dark:border-pink-800/40":T.daysUntil===0&&(T.type==="anniversary"||T.type==="wedding_anniversary")?"bg-blue-500/10 border-blue-500/30 dark:bg-blue-900/20 dark:border-blue-800/40":T.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(aa,{className:Et("h-10 w-10",T.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(ia,{className:Et("text-xs font-medium",T.type==="birthday"?"bg-pink-100 text-pink-700 dark:bg-pink-900/40 dark:text-pink-300":"bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300"),children:F})}),e.jsx("span",{className:"absolute -bottom-1.5 -right-1.5 text-base leading-none drop-shadow-sm",children:T.type==="birthday"?"🎂":T.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:[T.contact.first_name," ",T.contact.last_name||""]}),e.jsx(ze,{variant:"outline",className:Et("text-[10px] shrink-0 whitespace-nowrap",A(T.daysUntil)),children:S(T.daysUntil)})]}),e.jsxs("div",{className:Et("text-xs flex items-center gap-1.5 mt-0.5",T.type==="birthday"?"text-pink-600/80 dark:text-pink-400/80":"text-blue-600/80 dark:text-blue-400/80"),children:[T.type==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(hu,{className:"h-3 w-3"})," Birthday"]}):T.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(yi,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(zr,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:ks(T.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[T.contact.phone&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${T.contact.phone}`,children:e.jsx(Pr,{className:"h-3.5 w-3.5"})})}),T.contact.phone&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${T.contact.phone}`,children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})}),T.contact.email&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:T.contact.id,first_name:T.contact.first_name,last_name:T.contact.last_name,email:T.contact.email}),d(!0)):window.location.href=`mailto:${T.contact.email}`},children:e.jsx(Hs,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Record video",onClick:()=>s(`/mission-control/video/record?contactId=${T.contact.id}`),children:e.jsx(vr,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("h-7 px-2 gap-1 text-xs",T.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 ${T.type==="birthday"?"birthday":"anniversary"} card`,onClick:()=>_(T),children:[e.jsx(un,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(B,{variant:"ghost",size:"icon",className:Et("h-7 w-7",M&&"text-green-600"),title:"Log a touch",disabled:M||r.isPending,onClick:()=>j(T),children:e.jsx(xr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${T.contact.id}`),children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})]})]},`${L}-${D}`)})]})]}),a&&l&&e.jsx(Ty,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function JHs(s){const[t,n]=N.useState([]),[r,a]=N.useState(!1),{data:i,isLoading:l}=lt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await q.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await q.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!u)return[];const h=u.map(g=>g.contact_id).filter(Boolean);let p={};if(h.length>0){const{data:g}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(g||[]).forEach(b=>{p[b.id]=b})}const f=u.map(g=>g.auth_user_id).filter(Boolean);if(f.length>0){const{data:g}=await q.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",f);(g||[]).forEach(b=>{const v=u.find(j=>j.auth_user_id===b.user_id);v&&!v.contact_id&&b.contact_id&&(v.contact_id=b.contact_id),v&&!p[v.contact_id||""]&&b.name&&(p[v.contact_id||v.auth_user_id||""]={first_name:b.name.split(" ")[0],last_name:b.name.split(" ").slice(1).join(" ")||null,email:null,phone:b.phone})})}return u.map(g=>{var b,v;return{...g,contact_name:p[g.contact_id||g.auth_user_id||""]?`${p[g.contact_id||g.auth_user_id||""].first_name} ${p[g.contact_id||g.auth_user_id||""].last_name||""}`.trim():null,contact_email:((b=p[g.contact_id||g.auth_user_id||""])==null?void 0:b.email)||null,contact_phone:((v=p[g.contact_id||g.auth_user_id||""])==null?void 0:v.phone)||null}})},enabled:!!s,refetchInterval:6e4});N.useEffect(()=>{if(!s)return;const u=q.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},h=>{h.eventType==="INSERT"?n(p=>p.find(g=>g.id===h.new.id)?p:[h.new,...p]):h.eventType==="UPDATE"?n(p=>p.map(f=>f.id===h.new.id?{...f,...h.new}:f)):h.eventType==="DELETE"&&n(p=>p.filter(f=>f.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{q.removeChannel(u)}},[s]);const o=r&&t.length>0?eGs([...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 eGs(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const tGs={property_view:{label:"Viewed",icon:Ir,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:Fo,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:yi,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function sGs(){const{user:s}=gs(),t=In(),{isGmailConnected:n,gmailEmail:r}=bh(),{leadSite:a}=Pp(),{count:i}=JHs(a==null?void 0:a.id),[l,o]=N.useState(!1),[c,d]=N.useState(null),{data:u,isLoading:h}=lt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:j,error:_}=await q.rpc("get_lead_site_activity",{_user_id:s.id});if(_)throw _;return j},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const p=(u.activities||[]).filter(j=>j.visitor_name&&j.visitor_name!=="Site Visitor"),f=p.filter(j=>j.activity_type==="new_lead"),g=(u.activities||[]).filter(j=>j.activity_type==="property_view").length,b=(u.activities||[]).filter(j=>j.activity_type==="saved_listing").length,v=j=>{if(j.visitor_email)if(n){const _=(j.visitor_name||"").split(" ");d({id:j.contact_id||"",first_name:_[0]||"",last_name:_.slice(1).join(" ")||null,email:j.visitor_email}),o(!0)}else window.location.href=`mailto:${j.visitor_email}`};return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 bg-primary/10 rounded-lg",children:e.jsx(lc,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Website Activity"}),i>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 text-[11px] font-semibold",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"})]}),i," Live"]})]})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(za,{className:"h-4 w-4"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-emerald-500/5 border border-emerald-200 dark:border-emerald-800",children:[e.jsx(Fo,{className:"h-4 w-4 text-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-emerald-600 dark:text-emerald-400",children:f.length}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"New Leads"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-blue-500/5 border border-blue-200 dark:border-blue-800",children:[e.jsx(Ir,{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(yi,{className:"h-4 w-4 text-rose-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-rose-600 dark:text-rose-400",children:b}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saved"})]})]})]}),p.length>0?e.jsxs("div",{className:"space-y-2",children:[p.slice(0,5).map((j,_)=>{const S=tGs[j.activity_type],A=S.icon,T=Go(new Date(j.occurred_at),{addSuffix:!0});return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:shadow-sm transition-shadow",children:[e.jsx("div",{className:`p-1.5 rounded-md ${S.bgColor}`,children:e.jsx(A,{className:`h-3.5 w-3.5 ${S.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{className:"font-medium text-sm text-primary hover:underline text-left truncate block",onClick:()=>{j.contact_id&&t(`/mission-control/contacts/${j.contact_id}`)},children:j.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:S.label}),j.mls_number&&e.jsxs("span",{children:["· MLS# ",j.mls_number]}),j.lead_type&&e.jsxs("span",{children:["· ",j.lead_type]}),e.jsxs("span",{children:["· ",T]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[j.visitor_email&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>v(j),children:e.jsx(Hs,{className:"h-3.5 w-3.5"})}),j.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${j.visitor_phone}`,children:e.jsx(Pr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${j.visitor_phone}`,children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})]}),j.contact_id&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${j.contact_id}`),children:e.jsx(ga,{className:"h-3.5 w-3.5"})})]})]},`${j.activity_type}-${j.occurred_at}-${_}`)}),p.length>5&&e.jsxs(B,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",p.length-5," more activities",e.jsx(za,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6 text-center",children:[e.jsx(am,{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(B,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(za,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(Ty,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const PZe={Crown:xf,FileText:Nr,Users:_n,Globe:lc,Star:ua,Phone:Pr,MessageSquare:Ci,PenTool:a4,Video:vr,Gift:Bi},nGs={"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 rGs(){var Bt,kt,Qt,ns,$s,Ds;const s=In(),{user:t}=gs(),{data:n}=Cy(),{data:r}=npt(),{data:a}=lx(),{data:i}=XD(),{data:l}=lpt(),o=xrs(),c=j6e(),d=prs(90),u=gU(),[h,p]=N.useState(null),[f,g]=N.useState(null),[b,v]=N.useState(!1),[j,_]=N.useState(""),[S,A]=N.useState(!1),[T,D]=N.useState(""),[L,M]=N.useState(Dfe()),[F,z]=N.useState("cards"),[V,W]=N.useState(!1),[K,Y]=N.useState(null),[ee,ne]=N.useState(null),[oe,pe]=N.useState(""),{isGmailConnected:ce,gmailEmail:de}=bh(),ie=()=>{const Dt=parseInt(T,10);if(isNaN(Dt)||Dt<1){Dr({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}M(Dt),opt(Dt),A(!1),Dr({title:"Goal updated",description:`Weekly touch goal set to ${Dt}`})},ye=()=>{D(L.toString()),A(!0)};N.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:St}=await q.from("profiles").select("name").eq("id",t.id).single();St!=null&&St.name&&_(St.name.split(" ")[0])})()},[t==null?void 0:t.id]),N.useEffect(()=>{o.mutate()},[]);const _e=Sf(new Date),Me=Ul(_e,7),Te=Dt=>{if(!Dt)return null;const St=Dt.split(/[-/T]/);if(St.length<3)return null;const $t=parseInt(St[1],10)-1,ht=parseInt(St[2],10);return isNaN($t)||isNaN(ht)?null:new Date(_e.getFullYear(),$t,ht)},Ce=(a==null?void 0:a.filter(Dt=>{const St=Te(Dt.birthday),$t=Te(Dt.home_anniversary);return St&&Rl(St,_e)||$t&&Rl($t,_e)}))||[],Ee=(a==null?void 0:a.filter(Dt=>{if(!Dt.birthday&&!Dt.home_anniversary)return!1;const St=$t=>{if(!$t)return!1;const ht=Te($t);return ht?Uv(ht,_e)&&jb(ht,Me):!1};return St(Dt.birthday)||St(Dt.home_anniversary)}).slice(0,5))||[],De=[],Ie=(i==null?void 0:i.find(Dt=>Dt.name==="Call"))||(i==null?void 0:i[0]);for(const Dt of Ce){const St=Te(Dt.birthday),$t=Te(Dt.home_anniversary),ht=St&&Rl(St,_e),Ut=$t&&Rl($t,_e);ht&&De.push({contact:Dt,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:((Qt=(kt=(Bt=Dt.tags)==null?void 0:Bt[0])==null?void 0:kt.relationship_type)==null?void 0:Qt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Ut&&De.push({contact:Dt,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:((Ds=($s=(ns=Dt.tags)==null?void 0:ns[0])==null?void 0:$s.relationship_type)==null?void 0:Ds.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const qe=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((Dt,St)=>{var ht,Ut,Es;const $t=i==null?void 0:i[St%((i==null?void 0:i.length)||1)];return $t?{contact:Dt,actionType:$t,planName:"Quick Touch",relationshipTypeName:((Es=(Ut=(ht=Dt.tags)==null?void 0:ht[0])==null?void 0:Ut.relationship_type)==null?void 0:Es.name)||"",monthNumber:0}:null}).filter(Boolean))||[],ve=[...De,...qe],{data:Je}=JD(7),we=(Je||[]).filter(Dt=>Rl(new Date(Dt.completed_at),_e)).length,it=we+ve.length,Ne=(a==null?void 0:a.length)??0,He=De.length>0?`${De.length} celebration${De.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.`:Ee.length>0?`${Ee.length} milestone${Ee.length===1?"":"s"} coming up this week — get ahead of them.`:"Consistency beats intensity. A few real conversations today is a win.",$e=async(Dt,St,$t)=>{await u.mutateAsync({contactId:Dt,actionTypeId:St,scriptUsedId:$t}),v(!1),g(null)},Ye=Dt=>{Dt.script?(g(Dt),v(!0)):$e(Dt.contact.id,Dt.actionType.id)},Ke=Dt=>PZe[Dt||"Phone"]||Pr,rt=Dt=>PZe[Dt||"Users"]||_n,tt=(Dt,St)=>Dt.replace(/\{\{FirstName\}\}/g,St.first_name).replace(/\{\{LastName\}\}/g,St.last_name||"").replace(/\{\{AgentName\}\}/g,j||"there"),at=(Dt,St)=>({Call:`Thinking of you, ${St}!`,Text:`Quick hello, ${St}`,Email:`Checking in, ${St}`,"Handwritten Note":`A note for ${St}`,Video:`Video message for ${St}`,Gift:`Something special for you, ${St}`})[Dt]||`Hello ${St}!`,Ge=(Dt,St,$t)=>{const ht=`sms:${Dt}`;if(St&&$t){const Ut=tt(St,$t);return`${ht}?body=${encodeURIComponent(Ut)}`}return ht},dt=(Dt,St,$t,ht,Ut)=>{const Es=`mailto:${Dt}`,Xt=[];if(Ut){const Ys=$t||at(ht||"Email",Ut.first_name);if(Xt.push(`subject=${encodeURIComponent(Ys)}`),St){const Ss=tt(St,Ut);Xt.push(`body=${encodeURIComponent(Ss)}`)}}return Xt.length>0?`${Es}?${Xt.join("&")}`:Es};return e.jsxs(e.Fragment,{children:[e.jsxs(Cs,{title:"Mission Control",description:"Your relationship-first contact system",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex 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(B,{size:"sm",onClick:()=>s("/mission-control/video/record"),className:"gap-1.5 bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(Ph,{className:"h-4 w-4"}),"Quick Video"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/contacts"),className:"gap-1.5",children:[e.jsx(_n,{className:"h-4 w-4"}),"Contacts"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(vr,{className:"h-4 w-4"}),"Library"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/plans"),className:"gap-1.5",children:[e.jsx(Vo,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(FHs,{agentName:j,todayDone:we,todayTotal:it,focusLine:He,weekDone:c.actionsThisWeek,weekGoal:L,streak:c.streak,staleCount:d.count,sphereCount:Ne,onEditGoal:ye,onStaleClick:()=>s("/mission-control/contacts?filter=not-touched-90"),onSphereClick:()=>s("/mission-control/contacts")}),e.jsx(sGs,{}),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(ga,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n==null?void 0:n.filter(Dt=>Dt.active).map(Dt=>{const St=rt(Dt.icon),$t=(r==null?void 0:r[Dt.id])||0,ht=h===Dt.id,Ut=nGs[Dt.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{ht?(p(null),s("/mission-control/contacts")):(p(Dt.id),s(`/mission-control/contacts?type=${Dt.id}`))},className:` inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-all ${ht?Ut:"bg-card hover:bg-accent"} `,children:[e.jsx(St,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-medium",children:Dt.name}),e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[11px] tabular-nums ${ht?"bg-black/15":"bg-muted text-muted-foreground"}`,children:$t})]},Dt.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(ze,{variant:"outline",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"}),"Plan-based"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 border rounded-lg p-0.5",children:[e.jsx(B,{variant:F==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>z("cards"),title:"Card view",children:e.jsx(vf,{className:"h-4 w-4"})}),e.jsx(B,{variant:F==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>z("table"),title:"Table view",children:e.jsx(Ep,{className:"h-4 w-4"})})]})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-4",children:ve.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."}),e.jsx(B,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):F==="table"?e.jsx(HHs,{actions:ve,onMarkComplete:$e,onViewScript:Ye,isLoading:u.isPending,buildSmsLink:Ge,buildEmailLink:dt,onGmailCompose:ce?Dt=>{Y(Dt),W(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[ve.map((Dt,St)=>{var Bs,Us,sn,Jn,fn,Sn,Gn;const $t=Dt.isSpecialDate,ht=Dt.specialDateType,Ut=$t?ht==="birthday"?hu:zr:Ke(((Bs=Dt.actionType)==null?void 0:Bs.icon)||null),Es=Dt.contact.phone,Xt=Dt.contact.email,Ys=$t?ht==="birthday"?"#EC4899":"#8B5CF6":((Us=Dt.actionType)==null?void 0:Us.color)||"#3B82F6",Ss=$t?ht==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(sn=Dt.actionType)==null?void 0:sn.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${$t?"ring-2 ring-offset-2":""}`,style:$t?{"--tw-ring-color":Ys}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:Ys},children:[e.jsx(Ut,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Ss})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${Dt.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[Dt.contact.first_name," ",Dt.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[Es&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${Dt.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(Pr,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:Ge(Dt.contact.phone,(Jn=Dt.script)==null?void 0:Jn.script_body,Dt.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(Ci,{className:"h-3 w-3"}),"Text"]})]}),Xt&&(ce?e.jsxs("button",{onClick:()=>{Y({id:Dt.contact.id,first_name:Dt.contact.first_name,last_name:Dt.contact.last_name,email:Dt.contact.email}),W(!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(Hs,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:dt(Dt.contact.email,(fn=Dt.script)==null?void 0:fn.script_body,(Sn=Dt.script)==null?void 0:Sn.email_subject,(Gn=Dt.actionType)==null?void 0:Gn.name,Dt.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(Hs,{className:"h-3 w-3"}),"Email"]}))]}),$t&&e.jsxs("button",{onClick:()=>{const Hr=`${Dt.contact.first_name}${Dt.contact.last_name?" "+Dt.contact.last_name:""}`,pi=ht==="birthday"?"birthday":"home_anniversary",Ms=new URLSearchParams({cardType:pi,contactId:Dt.contact.id,name:Hr,...Dt.contact.address?{address:Dt.contact.address}:{},...ht==="anniversary"&&Dt.contact.home_anniversary?{date:Dt.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${Ms.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(Hs,{className:"h-3 w-3"}),"Send ",ht==="birthday"?"Birthday":"Anniversary"," Card"]}),!Es&&!Xt&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[Dt.relationshipTypeName&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:Dt.relationshipTypeName}),Dt.monthNumber>0&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:["Month ",Dt.monthNumber]})]}),Dt.script&&e.jsx(B,{size:"sm",variant:"outline",className:"w-full",onClick:()=>Ye(Dt),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{ne(Dt.contact.id),pe(`${Dt.contact.first_name} ${Dt.contact.last_name||""}`.trim())},children:[e.jsx(_f,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(B,{size:"sm",className:"flex-1",onClick:()=>{var Hr;return $e(Dt.contact.id,Dt.actionType.id,(Hr=Dt.script)==null?void 0:Hr.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},Dt.contact.id+St)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"h-full w-full",children:[e.jsx(Xf,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(cc,{children:e.jsx(Xr,{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(_c,{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 ",L," touches"]})]}),e.jsx(xi,{value:Math.min(c.actionsThisWeek/L*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>=L?"Goal hit for the week — anything else is bonus.":`${L-c.actionsThisWeek} more to hit your goal.`})]}),e.jsx(bs,{open:S,onOpenChange:A,children:e.jsxs(vs,{className:"sm:max-w-[360px]",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Set Weekly Goal"}),e.jsx(Qn,{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(se,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(ge,{id:"weekly-goal-ic",type:"number",min:"1",value:T,onChange:Dt=>D(Dt.target.value),placeholder:"20",onKeyDown:Dt=>{Dt.key==="Enter"&&ie()}})]}),e.jsx(B,{onClick:ie,className:"w-full",children:"Save Goal"})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(wpt,{}),e.jsx(XHs,{})]})]}),e.jsx(bs,{open:b,onOpenChange:v,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{className:"flex items-center gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:f.actionType.color||"#3B82F6"}}),f.actionType.name," Script"]})})}),f&&f.script&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["For: ",e.jsxs("span",{className:"font-medium text-foreground",children:[f.contact.first_name," ",f.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:tt(f.script.script_body,f.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>v(!1),children:"Close"}),e.jsx(B,{className:"flex-1",onClick:()=>{var Dt;return $e(f.contact.id,f.actionType.id,(Dt=f.script)==null?void 0:Dt.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(zHs,{})]}),ce&&K&&e.jsx(Ty,{open:V,onOpenChange:W,contact:K,gmailEmail:de}),e.jsx(L1e,{open:!!ee,onOpenChange:Dt=>!Dt&&ne(null),contactId:ee||"",contactName:oe})]})}const aGs=[{value:"bidirectional",label:"Two-Way",icon:sm,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:Bu,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:om,tooltip:"Only pull BoldTrail → Agent OS"}];function nTe({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($L,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:aGs.map(a=>e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsxs(XA,{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(yc,{children:a.tooltip})]},a.value))})]})}function LZe(){const s=Gt(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,g]=N.useState(0),b=N.useRef(!1),{data:v}=lt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:F,error:z}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(z)throw z;return F}}),j=(v==null?void 0:v.sync_direction)||"bidirectional",_=d??j,S=gt({mutationFn:async()=>{const{data:F,error:z}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(z)throw z;if(F!=null&&F.error)throw new Error(F.error);return F},onSuccess:F=>{u(null),a(F),n(!0)},onError:F=>{ae.error(F.message||"Failed to generate sync preview")}}),A=gt({mutationFn:async()=>{b.current=!1,p("Initializing sync..."),g(5);const{data:F,error:z}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:_}});if(z)throw z;if(F!=null&&F.error)throw new Error(F.error);const V=F;let W=V.sync_log_id,K=V.next_phase,Y=V.next_offset,ee=V.push_total||0,ne=V.pull_total||0,oe=V.update_total||0,pe=0,ce=0,de=0;for(;K!=="finalize"&&!b.current;){const _e=ee+ne+oe;K==="fetch_bt"?p("Fetching BoldTrail contacts..."):K==="analyze"?(p("Analyzing contacts..."),g(15)):K==="push"?(p(`Pushing contacts to BoldTrail... (${pe}/${ee})`),g(_e>0?pe/_e*90:0)):K==="pull"?(p(`Pulling contacts from BoldTrail... (${ce}/${ne})`),g(_e>0?(ee+ce)/_e*90:0)):K==="update"&&(p(`Updating existing contacts... (${de}/${oe})`),g(_e>0?(ee+ne+de)/_e*90:0));const{data:Me,error:Te}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:K,offset:Y,sync_log_id:W,sync_direction:_}});if(Te)throw Te;if(Me!=null&&Me.error)throw new Error(Me.error);const Ce=Me;pe+=Ce.chunk_pushed||0,ce+=Ce.chunk_pulled||0,de+=Ce.chunk_updated||0,Ce.push_total!==void 0&&(ee=Ce.push_total||0),Ce.pull_total!==void 0&&(ne=Ce.pull_total||0),Ce.update_total!==void 0&&(oe=Ce.update_total||0),Ce.progress&&p(Ce.progress),K=Ce.next_phase,Y=Ce.next_offset}p("Finalizing sync..."),g(95);const{data:ie,error:ye}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:W,sync_direction:_}});if(ye)throw ye;return g(100),ie},onSuccess:F=>{p(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 z=[`Pushed ${F.contacts_pushed||0}`,`pulled ${F.contacts_pulled||0}`,`updated ${F.contacts_updated||0}`,`skipped ${F.contacts_skipped||0} duplicates`];ae.success(`Sync complete! ${z.join(", ")}.`)},onError:F=>{p(null),g(0),ae.error(F.message||"Sync failed")}});if(!(v!=null&&v.connected))return null;const T=_==="pull_only"?0:(r==null?void 0:r.to_push)??0,D=_==="push_only"?0:(r==null?void 0:r.to_pull)??0,L=(r==null?void 0:r.to_update)??0,M=T>0||D>0||L>0;return e.jsxs(e.Fragment,{children:[e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",onClick:()=>S.mutate(),disabled:S.isPending,className:"shrink-0",children:S.isPending?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(sm,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(yc,{children:"Sync with BoldTrail"})]}),e.jsx(bs,{open:t,onOpenChange:F=>{A.isPending||n(F)},children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(sm,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Qn,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(nTe,{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:T}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Bu,{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:D}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(om,{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:L}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(yL,{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(_n,{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"]}),L>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(yL,{className:"h-3 w-3 inline mr-1"}),L," contacts have missing fields that will be filled from the other system"]}),T>0&&e.jsxs(uy,{open:i,onOpenChange:l,children:[e.jsx(hy,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bu,{className:"h-3 w-3 text-emerald-600"}),T," contacts to push to BoldTrail"]}),e.jsx(io,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(my,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.push_preview.map((F,z)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:F.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:F.email})]},z)),r.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_push-20," more"]})]})})]}),D>0&&e.jsxs(uy,{open:o,onOpenChange:c,children:[e.jsx(hy,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(om,{className:"h-3 w-3 text-blue-600"}),D," contacts to pull from BoldTrail"]}),e.jsx(io,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(my,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((F,z)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:F.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:F.email})]},z)),r.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_pull-20," more"]})]})})]}),!M&&!A.isPending&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer or update."}),A.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(xi,{value:f||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:h||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),disabled:A.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>A.mutate(),disabled:A.isPending||!M,className:"gap-2",children:[A.isPending?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(sm,{className:"h-4 w-4"}),A.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const iGs=()=>{const{user:s}=gs();return lt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("popby_items").select("*").or(`owner_user_id.is.null,owner_user_id.eq.${s==null?void 0:s.id}`).eq("is_active",!0).order("name");if(n)throw n;return t},enabled:!!s})},R1e=s=>{const{user:t}=gs();return lt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let n=q.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(s){const i=new Date;i.setDate(i.getDate()-s),n=n.gte("completed_at",i.toISOString())}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})},wLe=()=>{const{user:s}=gs();return lt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("relationship_type_popby_defaults").select("*");if(n)throw n;return t},enabled:!!s})},L_t=()=>{const{user:s}=gs();return lt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_popby_settings").select("*");if(n)throw n;return t},enabled:!!s})},oGs=()=>{const{data:s}=lx();Cy();const{data:t}=R1e(),{data:n}=L_t(),{data:r}=wLe(),a=new Map;t==null||t.forEach(d=>{const u=a.get(d.contact_id);(!u||new Date(d.completed_at)>new Date(u))&&a.set(d.contact_id,d.completed_at)});const i=new Map;r==null||r.forEach(d=>i.set(d.relationship_type_id,d.frequency_days));const l=new Map;n==null||n.filter(d=>d.is_active).forEach(d=>{l.set(d.contact_id,d.frequency_days)});const o=Sf(new Date);return(s||[]).map(d=>{let u=90;if(l.has(d.id))u=l.get(d.id);else if(d.tags&&d.tags.length>0){const b=d.tags.map(v=>i.get(v.relationship_type_id)).filter(v=>v!==void 0);b.length>0&&(u=Math.min(...b))}const h=a.get(d.id)||null,p=h?Yv(o,Sf(new Date(h))):null,f=p===null||p>=u,g=f&&p!==null?p-u:0;return{...d,lastPopby:h,daysSinceLastPopby:p,frequencyDays:u,isDue:f,daysOverdue:g}}).sort((d,u)=>u.daysOverdue-d.daysOverdue)},D_t=()=>oGs().filter(t=>t.isDue),lGs=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{const{error:r}=await q.from("popby_items").insert({...n,owner_user_id:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),Dr({title:"Popby item created!"})},onError:n=>{Dr({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},cGs=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{const r=new Date().toISOString(),{error:a}=await q.from("popby_logs").insert({...n,owner_user_id:t==null?void 0:t.id,completed_at:r});if(a)throw a;try{const{data:i}=await q.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await q.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id:n.contact_id,action_type_id:i.id,notes:n.notes??"Pop-by logged",completed_at:r})}catch(i){console.error("Failed to log corresponding touch for popby",i)}},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-logs"]}),s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),Dr({title:"Popby logged!"})},onError:n=>{Dr({title:"Error logging popby",description:n.message,variant:"destructive"})}})},dGs=()=>{const s=Gt(),{user:t}=gs();return gt({mutationFn:async n=>{const{error:r}=await q.from("relationship_type_popby_defaults").upsert({...n,owner_user_id:t==null?void 0:t.id},{onConflict:"relationship_type_id,owner_user_id"});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),Dr({title:"Frequency updated!"})},onError:n=>{Dr({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},uGs=()=>{const{data:s}=R1e(30),t=D_t(),n=new Date;n.setDate(n.getDate()-7);const r=(s==null?void 0:s.filter(i=>new Date(i.completed_at)>=n).length)||0,a=(s==null?void 0:s.length)||0;return{thisWeekCount:r,thisMonthCount:a,dueCount:t.length}};function hGs(){const{user:s}=gs();return lt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function R_t(s){const{data:t}=hGs(),{data:n}=L_t(),{data:r}=wLe(),{data:a}=BHs();return N.useMemo(()=>{const i=a==null?void 0:a.find(v=>v.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=Sf(new Date);if(l&&!jb(l,o))return{nextTouchDate:l,daysUntil:Yv(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(v=>v.contact_id===s.id))||[]).sort((v,j)=>new Date(j.completed_at).getTime()-new Date(v.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const p=n==null?void 0:n.find(v=>v.contact_id===s.id&&v.is_active);if(p)h=p.frequency_days;else if(s.tags&&s.tags.length>0){const v=s.tags.map(j=>{const _=r==null?void 0:r.find(S=>S.relationship_type_id===j.relationship_type_id);return _==null?void 0:_.frequency_days}).filter(j=>j!==void 0);v.length>0&&(h=Math.min(...v))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:h,lastTouchDate:null,snoozedUntil:null};const f=Ul(Sf(u),h),g=Yv(f,o);let b;return g<0?b="overdue":g<=7?b="due-soon":b="on-track",{nextTouchDate:f,daysUntil:g,status:b,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function Bge({contact:s}){const t=R_t(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:Gi,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:gr,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:xr,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:_f,text:`Snoozed until ${ks(t.snoozedUntil,"MMM d")}`,className:"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"};case"never-touched":return{variant:"outline",icon:yr,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs(ze,{variant:r.variant,className:Et("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function mGs({contact:s,onLogTouch:t,onSnooze:n}){const r=R_t(s),a=UHs(),[i,l]=N.useState(!1),o=()=>{switch(r.status){case"overdue":return"text-destructive";case"due-soon":return"text-amber-600 dark:text-amber-400";case"on-track":return"text-emerald-600 dark:text-emerald-400";case"snoozed":return"text-slate-600 dark:text-slate-400";case"never-touched":return"text-muted-foreground"}},c=()=>{switch(r.status){case"overdue":return e.jsx(Gi,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(gr,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(xr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(_f,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(yr,{className:"h-5 w-5 text-muted-foreground"})}},d=()=>{switch(r.status){case"overdue":return`${Math.abs(r.daysUntil)} days overdue`;case"due-soon":return r.daysUntil===0?"Due today!":`Due in ${r.daysUntil} days`;case"on-track":return`On track - ${r.daysUntil} days remaining`;case"snoozed":return`Snoozed for ${r.daysUntil} more days`;case"never-touched":return"No touches logged yet"}},u=async()=>{await a.mutateAsync(s.id)};return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Ae,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:Et("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:"})," ",ks(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:"})," ",ks(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:"})," ",ks(r.lastTouchDate,"MMM d, yyyy")]}),r.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",r.frequencyDays," days"]}),r.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx(Fn,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx(B,{size:"sm",className:"flex-1",onClick:t,children:"Log Touch"})]}),r.status!=="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(_f,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(r.status==="overdue"||r.status==="due-soon"||r.status==="never-touched")&&t&&e.jsx(B,{size:"sm",className:"flex-1",variant:r.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(L1e,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const TNe=768;function kR(){const[s,t]=N.useState(void 0);return N.useEffect(()=>{const n=window.matchMedia(`(max-width: ${TNe-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function pGs(){const{user:s}=gs(),{hasLeadSite:t,leadSite:n}=Pp(),{data:r,isLoading:a}=lt({queryKey:["website-active-contacts",s==null?void 0:s.id,n==null?void 0:n.id],queryFn:async()=>{if(!n)return new Set;const{data:i}=await q.from("lead_site_visitors").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),{data:l}=await q.from("lead_site_consumer_profiles").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),o=new Set;return(i||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),(l||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),o},enabled:!!s&&t,staleTime:5*60*1e3});return{activeContactIds:r??new Set,hasLeadSite:t,isLoading:a}}const fGs={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"}},xGs={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 rTe({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=fGs[s.status],l=xGs[r],o=e.jsxs("div",{className:Et("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Et("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return n?e.jsx(Kw,{children:e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:o}),e.jsx(yc,{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:Et("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(xi,{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 gGs=[{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}],gG=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]},yGs=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=gs(),{toast:i}=Ua(),l=N.useRef(null),[o,c]=N.useState("upload"),[d,u]=N.useState([]),[h,p]=N.useState([]),[f,g]=N.useState({}),[b,v]=N.useState([]),[j,_]=N.useState([]),[S,A]=N.useState([]),[T,D]=N.useState(""),[L,M]=N.useState(!1),[F,z]=N.useState([]),[V,W]=N.useState(!1),[K,Y]=N.useState(null);N.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Fe}=await q.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");_(Fe||[])})()},[s,a==null?void 0:a.id]);const ee=Fe=>{A(qe=>qe.includes(Fe)?qe.filter(ve=>ve!==Fe):[...qe,Fe])},ne=async()=>{const Fe=T.trim();if(!(!Fe||!(a!=null&&a.id))){M(!0);try{const{data:qe,error:ve}=await q.from("contact_custom_tags").insert({owner_user_id:a.id,name:Fe}).select("id, name, color").single();if(ve)throw ve;qe&&(_(Je=>[...Je,qe].sort((we,it)=>we.name.localeCompare(it.name))),A(Je=>[...Je,qe.id]),D(""))}catch(qe){i({title:"Could not create tag",description:qe.message||"Try a different name.",variant:"destructive"})}finally{M(!1)}}},oe=()=>{c("upload"),u([]),p([]),g({}),v([]),A([]),D(""),z([]),Y(null),l.current&&(l.current.value="")},pe=()=>{oe(),t(!1)},ce=Fe=>{const qe=Fe.split(` `).map(He=>He.trim()).filter(He=>He);if(qe.length===0)return{headers:[],data:[]};const ve=He=>{const $e=[];let Ye="",Ke=!1;for(let rt=0;rt0&&(Je[0]=Je[0].replace(/^\uFEFF/,""));const we=new Map,it=Je.map((He,$e)=>{let Ye=(He||"").trim();Ye||(Ye=`Column ${$e+1}`);const Ke=we.get(Ye)||0;return we.set(Ye,Ke+1),Ke===0?Ye:`${Ye} (${Ke+1})`}),Ne=qe.slice(1).map(ve);return{headers:it,data:Ne}},de=Fe=>{var Je;const qe=(Je=Fe.target.files)==null?void 0:Je[0];if(!qe)return;const ve=new FileReader;ve.onload=we=>{var Ye;const it=(Ye=we.target)==null?void 0:Ye.result,{headers:Ne,data:He}=ce(it);if(Ne.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(Ne),p(He);const $e={};Ne.forEach(Ke=>{const rt=Ke.toLowerCase().replace(/[_\s-]/g,"");rt.includes("firstname")||rt==="first"?$e.first_name=Ke:rt.includes("lastname")||rt==="last"?$e.last_name=Ke:rt.includes("spouse")&&rt.includes("email")?$e.spouse_email=Ke:rt.includes("spouse")||rt.includes("partner")?$e.spouse_name=Ke:rt.includes("email")?$e.email=Ke:rt.includes("phone")||rt.includes("mobile")||rt.includes("cell")?$e.phone=Ke:rt.includes("address")||rt.includes("street")?$e.address=Ke:rt==="city"?$e.city=Ke:rt==="state"||rt==="province"?$e.state=Ke:rt==="zip"||rt==="zipcode"||rt==="postalcode"?$e.zip=Ke:rt.includes("company")||rt.includes("organization")||rt.includes("business")?$e.company_name=Ke:rt.includes("jobtitle")||rt.includes("title")&&!rt.includes("spouse")?$e.job_title=Ke:rt.includes("birthday")||rt.includes("dob")||rt.includes("birthdate")?$e.birthday=Ke:rt.includes("anniversary")||rt.includes("homeanniversary")?$e.home_anniversary=Ke:(rt.includes("notes")||rt.includes("comment"))&&($e.notes=Ke)}),g($e),c("mapping")},ve.readAsText(qe)},ie=(Fe,qe)=>{g(ve=>{if(qe==="none"){const{[Fe]:Je,...we}=ve;return we}return{...ve,[Fe]:qe}})},ye=Fe=>{v(qe=>qe.includes(Fe)?qe.filter(ve=>ve!==Fe):[...qe,Fe])},_e=async()=>{if(!(a!=null&&a.id))return;const{data:Fe}=await q.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),qe=new Set((Fe||[]).filter(we=>we.email).map(we=>we.email.toLowerCase())),ve=new Set((Fe||[]).filter(we=>we.phone).map(we=>we.phone.replace(/[^0-9]/g,""))),Je=h.map(we=>{const it=rt=>{const tt=f[rt];if(!tt)return"";const at=d.indexOf(tt);return at>=0?(we[at]||"").trim():""},Ne=it("first_name"),He=it("email"),$e=it("phone"),Ye=Ne.length>0,Ke=!!(He&&qe.has(He.toLowerCase())||$e&&ve.has($e.replace(/[^0-9]/g,"")));return{first_name:Ne,last_name:it("last_name"),email:He,phone:$e,address:it("address"),city:it("city"),state:it("state"),zip:it("zip"),spouse_name:it("spouse_name"),spouse_email:it("spouse_email"),company_name:it("company_name"),job_title:it("job_title"),birthday:it("birthday"),home_anniversary:it("home_anniversary"),notes:it("notes"),isValid:Ye,isDuplicate:Ke,error:Ye?void 0:"First name is required"}});z(Je),c("preview")},Me=Fe=>{const qe=Fe.trim().split(/\s+/);return{first_name:qe[0],last_name:qe.length>1?qe.slice(1).join(" "):null}},Te=async()=>{if(!(a!=null&&a.id))return;const Fe=F.filter(we=>we.isValid);if(Fe.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}W(!0);let qe=0,ve=0,Je=0;try{for(const we of Fe)try{let it=null;if(we.email){const{data:$e}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",we.email).maybeSingle();it=$e}if(!it&&we.phone){const $e=we.phone.replace(/[^0-9]/g,""),{data:Ye}=await q.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Ye){const Ke=Ye.find(rt=>rt.phone&&rt.phone.replace(/[^0-9]/g,"")===$e);Ke&&(it={id:Ke.id})}}const Ne={owner_user_id:a.id,first_name:we.first_name,last_name:we.last_name||null,email:we.email||null,phone:we.phone||null,address:we.address||null,city:we.city||null,state:we.state||null,zip:we.zip||null,spouse_name:we.spouse_name||null,spouse_email:we.spouse_email||null,company_name:we.company_name||null,job_title:we.job_title||null,birthday:gG(we.birthday),home_anniversary:gG(we.home_anniversary),notes:we.notes||null};let He=null;if(it){const{data:$e}=await q.from("innercircle_contacts").select("*").eq("id",it.id).single();if($e){const Ye={},Ke=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const rt of Ke){const tt=$e[rt],at=Ne[rt];(!tt||tt==="")&&at&&(Ye[rt]=at)}Object.keys(Ye).length>0&&await q.from("innercircle_contacts").update(Ye).eq("id",it.id)}He=it.id,ve++}else{const{data:$e,error:Ye}=await q.from("innercircle_contacts").insert(Ne).select("id").single();Ye?(console.error("Insert error for contact:",we.first_name,Ye),Je++):$e?(He=$e.id,b.length>0&&await q.from("innercircle_contact_tags").insert(b.map(Ke=>({contact_id:$e.id,relationship_type_id:Ke}))),qe++):Je++}if(He&&S.length>0&&await q.from("contact_custom_tag_assignments").upsert(S.map($e=>({contact_id:He,tag_id:$e})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),He&&we.spouse_name){const $e=Me(we.spouse_name);let Ye=null;if(we.spouse_email){const{data:rt}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",we.spouse_email).maybeSingle();Ye=rt}if(!Ye){const{data:rt}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",$e.first_name).eq("last_name",$e.last_name||we.last_name||"").maybeSingle();Ye=rt}let Ke=null;if(Ye){Ke=Ye.id;const rt=gG(we.home_anniversary);rt&&await q.from("innercircle_contacts").update({home_anniversary:rt}).eq("id",Ye.id).is("home_anniversary",null)}else{const{data:rt}=await q.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:$e.first_name,last_name:$e.last_name||we.last_name||null,email:we.spouse_email||null,address:we.address||null,city:we.city||null,state:we.state||null,zip:we.zip||null,home_anniversary:gG(we.home_anniversary),spouse_name:`${we.first_name}${we.last_name?" "+we.last_name:""}`,spouse_email:we.email||null,notes:`Spouse of ${we.first_name} ${we.last_name||""} (imported via CSV)`.trim()}).select("id").single();rt&&(Ke=rt.id,qe++)}Ke&&(await q.from("innercircle_contacts").update({spouse_contact_id:Ke}).eq("id",He),await q.from("innercircle_contacts").update({spouse_contact_id:He}).eq("id",Ke))}}catch(it){console.error("Error importing contact:",it),Je++}Y({created:qe,updated:ve,failed:Je}),c("result"),(qe>0||ve>0)&&r(),i({title:"Import Complete",description:`${qe} created, ${ve} updated${Je>0?`, ${Je} failed`:""}.`})}catch(we){console.error("Import error:",we),i({title:"Import Failed",description:we.message||"Failed to import contacts",variant:"destructive"})}finally{W(!1)}},Ce=F.filter(Fe=>Fe.isValid).length,Ee=F.filter(Fe=>!Fe.isValid).length,De=F.filter(Fe=>Fe.isValid&&Fe.isDuplicate).length,Ie=Ce-De;return e.jsx(bs,{open:s,onOpenChange:pe,children:e.jsxs(vs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(yw,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Qn,{children:"Upload a CSV file with your contacts. You can map columns and select relationship types."})]}),o==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:de,className:"hidden"}),e.jsx(Sa,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(B,{onClick:()=>{var Fe;return(Fe=l.current)==null?void 0:Fe.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Supported Fields:"}),e.jsx("p",{className:"text-muted-foreground text-xs mb-3",children:"First Name, Last Name, Email, Phone, Street Address, City, State, Zip, Spouse Name, Spouse Email, Company, Job Title, Birthday, Home Anniversary, Notes"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{const Fe=`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`,qe=new Blob([Fe],{type:"text/csv"}),ve=URL.createObjectURL(qe),Je=document.createElement("a");Je.href=ve,Je.download="contact_import_template.csv",Je.click(),URL.revokeObjectURL(ve)},children:[e.jsx(Da,{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(se,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:gGs.map(Fe=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(se,{className:"w-40 text-sm",children:[Fe.label,Fe.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(us,{value:f[Fe.key]||"none",onValueChange:qe=>ie(Fe.key,qe),children:[e.jsx(cs,{className:"w-48",children:e.jsx(hs,{placeholder:"Select column..."})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"-- Not mapped --"}),d.map(qe=>e.jsx(Ze,{value:qe,children:qe},qe))]})]})]},Fe.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(Fe=>e.jsx(ze,{variant:b.includes(Fe.id)?"default":"outline",className:"cursor-pointer",onClick:()=>ye(Fe.id),children:Fe.name},Fe.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-base font-medium",children:"Apply Tags to All Imported Contacts (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every contact in this CSV — both newly created and merged duplicates — will receive the selected tags."}),j.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(Fe=>{const qe=S.includes(Fe.id);return e.jsxs(ze,{variant:qe?"default":"outline",className:"cursor-pointer gap-1",style:qe&&Fe.color?{backgroundColor:Fe.color,borderColor:Fe.color}:void 0,onClick:()=>ee(Fe.id),children:[Fe.name,qe&&e.jsx(Fn,{className:"h-3 w-3"})]},Fe.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:T,onChange:Fe=>D(Fe.target.value),onKeyDown:Fe=>{Fe.key==="Enter"&&(Fe.preventDefault(),ne())},className:"max-w-xs"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ne,disabled:!T.trim()||L,children:[L?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(As,{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(xr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Ie," new"]})]}),De>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Gi,{className:"h-4 w-4"}),e.jsxs("span",{children:[De," existing (will merge gaps)"]})]}),Ee>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Gi,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ee," invalid"]})]})]}),De>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(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{className:"bg-muted/30",children:[e.jsx(Ct,{children:"First Name"}),e.jsx(Ct,{children:"Last Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Phone"}),e.jsx(Ct,{children:"Status"})]})}),e.jsx(pa,{children:F.slice(0,100).map((Fe,qe)=>e.jsxs(Gs,{children:[e.jsx(ut,{children:Fe.first_name}),e.jsx(ut,{children:Fe.last_name}),e.jsx(ut,{children:Fe.email}),e.jsx(ut,{children:Fe.phone}),e.jsx(ut,{children:Fe.isValid?Fe.isDuplicate?e.jsx(ze,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(ze,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(ze,{variant:"destructive",children:Fe.error||"Invalid"})})]},qe))})]}),F.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",F.length," contacts"]})]})]}),o==="result"&&K&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(xr,{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:[K.created," created, ",K.updated," merged"]}),K.failed>0&&e.jsxs("p",{className:"text-destructive",children:[K.failed," failed to import"]})]}),e.jsxs(Xn,{children:[o==="upload"&&e.jsx(B,{variant:"outline",onClick:pe,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:oe,children:"Back"}),e.jsx(B,{onClick:_e,disabled:!f.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(B,{onClick:Te,disabled:V||Ce===0,children:V?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${Ce} Contact${Ce!==1?"s":""}`})]}),o==="result"&&e.jsx(B,{onClick:pe,children:"Done"})]})]})})};function vGs(){return"contacts"in navigator&&"ContactsManager"in window}function bGs(s){const t=[],n=s.split("BEGIN:VCARD").filter(r=>r.trim());for(const r of n){const a=r.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const u of a){const h=u.replace(/^\s+/,"");if(h.startsWith("N:")||h.startsWith("N;")){const f=h.substring(h.indexOf(":")+1).split(";");l=(f[0]||"").trim(),i=(f[1]||"").trim()}if((h.startsWith("FN:")||h.startsWith("FN;"))&&!i){const f=h.substring(h.indexOf(":")+1).trim().split(" ");i=f[0]||"",l=f.slice(1).join(" ")}(h.startsWith("EMAIL")||h.match(/^item\d+\.EMAIL/i))&&!o&&(o=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("TEL")||h.match(/^item\d+\.TEL/i))&&!c&&(c=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("ADR")||h.match(/^item\d+\.ADR/i))&&!d&&(d=h.substring(h.indexOf(":")+1).split(";").map(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 _Gs({open:s,onOpenChange:t,onComplete:n}){gs();const{data:r}=lx(),a=Gye(),i=N.useRef(null),[l,o]=N.useState("choose"),[c,d]=N.useState([]),[u,h]=N.useState(new Set),[p,f]=N.useState(0),[g,b]=N.useState(0),v=vGs(),j=N.useCallback(z=>{if(!r)return z;const V=new Set(r.filter(K=>K.email).map(K=>K.email.toLowerCase())),W=new Set(r.filter(K=>K.phone).map(K=>K.phone.replace(/\D/g,"")));return z.map(K=>{var ne,oe;const Y=(ne=K.email)==null?void 0:ne.toLowerCase(),ee=(oe=K.phone)==null?void 0:oe.replace(/\D/g,"");return Y&&V.has(Y)?{...K,isDuplicate:!0,duplicateField:"email"}:ee&&ee.length>=7&&W.has(ee)?{...K,isDuplicate:!0,duplicateField:"phone"}:K})},[r]),_=async()=>{try{const z=["name","email","tel","address"],V=await navigator.contacts.select(z,{multiple:!0});if(!V||V.length===0)return;const W=V.map(ee=>{var pe,ce,de,ie;const oe=(((pe=ee.name)==null?void 0:pe[0])||"").split(" ");return{first_name:oe[0]||"",last_name:oe.slice(1).join(" "),email:((ce=ee.email)==null?void 0:ce[0])||"",phone:((de=ee.tel)==null?void 0:de[0])||"",address:(ie=ee.address)!=null&&ie[0]?[ee.address[0].streetAddress,ee.address[0].city,ee.address[0].region,ee.address[0].postalCode].filter(Boolean).join(", "):""}}),K=j(W);d(K);const Y=new Set;K.forEach((ee,ne)=>{ee.isDuplicate||Y.add(ne)}),h(Y),o("preview")}catch(z){console.error("Contact Picker error:",z),Dr({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},S=z=>{var K;const V=(K=z.target.files)==null?void 0:K[0];if(!V)return;const W=new FileReader;W.onload=Y=>{var ce;const ee=(ce=Y.target)==null?void 0:ce.result,ne=bGs(ee);if(ne.length===0){Dr({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const oe=j(ne);d(oe);const pe=new Set;oe.forEach((de,ie)=>{de.isDuplicate||pe.add(ie)}),h(pe),o("preview")},W.readAsText(V),i.current&&(i.current.value="")},A=async()=>{const z=c.filter((W,K)=>u.has(K));if(z.length===0)return;o("importing");let V=0;for(const W of z)try{await a.mutateAsync({first_name:W.first_name,last_name:W.last_name||void 0,email:W.email||void 0,phone:W.phone||void 0,address:W.address||void 0}),V++,b(Math.round(V/z.length*100))}catch(K){console.error(`Failed to import ${W.first_name} ${W.last_name}:`,K)}f(V),o("done")},T=z=>{h(V=>{const W=new Set(V);return W.has(z)?W.delete(z):W.add(z),W})},D=()=>{u.size===c.length?h(new Set):h(new Set(c.map((z,V)=>V)))},L=z=>{z||(o("choose"),d([]),h(new Set),f(0),b(0),l==="done"&&n()),t(z)},M=c.filter(z=>z.isDuplicate).length,F=u.size;return e.jsx(bs,{open:s,onOpenChange:L,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(rg,{className:"h-5 w-5 text-primary"}),l==="choose"&&"Import Phone Contacts",l==="preview"&&"Select Contacts to Import",l==="importing"&&"Importing Contacts...",l==="done"&&"Import Complete"]}),l==="choose"&&e.jsx(Qn,{children:"Add contacts from your phone directly into Agent OS."})]}),l==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[v&&e.jsxs(B,{onClick:_,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(rg,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Select from Phone"}),e.jsx("div",{className:"text-xs opacity-80",children:"Pick contacts directly from your device"})]})]}),e.jsxs("div",{className:"relative",children:[v&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),v&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs(B,{variant:v?"outline":"default",onClick:()=>{var z;return(z=i.current)==null?void 0:z.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(Sa,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Upload Contact File"}),e.jsx("div",{className:"text-xs opacity-80",children:v?"Import a .vcf file exported from your Contacts app":"Export contacts from your phone as a .vcf file, then upload here"})]})]}),e.jsx("input",{ref:i,type:"file",accept:".vcf,.vcard",onChange:S,className:"hidden"}),!v&&e.jsxs("div",{className:"rounded-lg bg-muted p-3 text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{className:"font-medium",children:"How to export contacts:"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"iPhone:"}),e.jsx("p",{className:"text-xs",children:'Open Contacts → select contacts → Share → choose "Export vCard"'})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"Android:"}),e.jsx("p",{className:"text-xs",children:"Open Contacts → Menu → Export → save as .vcf file"})]})]})]}),l==="preview"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{children:[c.length," contact",c.length!==1?"s":""," found",M>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",M," already exist)"]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:D,children:u.size===c.length?"Deselect All":"Select All"})]}),e.jsx(mi,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map((z,V)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${z.isDuplicate?"opacity-60":""}`,onClick:()=>T(V),children:[e.jsx(hi,{checked:u.has(V),onCheckedChange:()=>T(V),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[z.first_name," ",z.last_name]}),z.isDuplicate&&e.jsxs(ze,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",z.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[z.phone&&e.jsx("div",{children:z.phone}),z.email&&e.jsx("div",{className:"truncate",children:z.email})]})]})]},V))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o("choose"),children:"Back"}),e.jsxs(B,{onClick:A,disabled:F===0,children:["Import ",F," Contact",F!==1?"s":""]})]})]}),l==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(ss,{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:[g,"% 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:`${g}%`}})})]}),l==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-500/10 flex items-center justify-center",children:e.jsx(Lr,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[p," contact",p!==1?"s":""," imported!"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Your contacts are now in Agent OS and ready for touchpoint plans."})]}),e.jsx(B,{onClick:()=>L(!1),className:"mt-2",children:"Done"})]})]})})}function wGs(s){return lt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function jGs(){const{user:s}=gs();return lt({queryKey:["video-share-stats",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await q.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(n)throw n;const r=t;return{totalSent:r.length,totalOpened:r.filter(a=>a.opened_at).length,totalClicked:r.filter(a=>a.clicked_at).length,totalWatched:r.filter(a=>a.watched_at).length,openRate:r.length>0?Math.round(r.filter(a=>a.opened_at).length/r.length*100):0,clickRate:r.length>0?Math.round(r.filter(a=>a.clicked_at).length/r.length*100):0,watchRate:r.length>0?Math.round(r.filter(a=>a.watched_at).length/r.length*100):0}},enabled:!!(s!=null&&s.id)})}function NGs(){const{user:s}=gs();return lt({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("video_share_recipients").select(` *, agent_videos!inner(id, title, thumbnail_url, share_token, duration_seconds) `).eq("owner_user_id",s.id).order("sent_at",{ascending:!1}).limit(200);if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function O_t(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("video_share_recipients").insert([{video_id:n.video_id,owner_user_id:s.id,recipient_email:n.recipient_email,recipient_name:n.recipient_name||null,contact_id:n.contact_id||null,sent_via:n.sent_via||"gmail",share_token:"placeholder"}]).select().single();if(a)throw a;return r},onSuccess:n=>{t.invalidateQueries({queryKey:["video-share-recipients",n.video_id]}),t.invalidateQueries({queryKey:["video-share-stats"]}),t.invalidateQueries({queryKey:["video-share-history"]})}})}function F_t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function z_t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const kGs=100;function SGs({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=In(),o=fa(),c=O_t(),[d,u]=N.useState([]),[h,p]=N.useState(!1),[f,g]=N.useState(""),[b,v]=N.useState(null),[j,_]=N.useState(""),[S,A]=N.useState(""),[T,D]=N.useState(!1),[L,M]=N.useState({done:0,total:0,failed:0}),F=n.filter(oe=>!!oe.email),z=n.length-F.length,V=F.length>kGs;N.useEffect(()=>{s&&(v(null),g(""),M({done:0,total:0,failed:0}))},[s]),N.useEffect(()=>{!s||!o||(p(!0),q.from("agent_videos").select("id, title, share_token, thumbnail_url, playback_url, duration_seconds, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:oe})=>{u(oe||[]),p(!1)}))},[s,o]),N.useEffect(()=>{if(!b)return;const oe=b.title||"a quick video";_(`I recorded a video for you — ${oe}`),A("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[b]);const W=d.filter(oe=>!f||(oe.title||"").toLowerCase().includes(f.toLowerCase())),K=(oe,pe)=>{if(!b)return"";const ce=b.share_token?`https://video.relevelup.com/share/video/${b.share_token}`:"",de=b.share_token?`https://video.relevelup.com/thumb/${b.share_token}`:b.thumbnail_url||"",ie=b.title||"Video Message",_e=S.replace(/\{\{first_name\}\}/gi,oe).split(/\n\n+/).map(Ce=>`

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

`).join(""),Me=pe?z_t(pe):ce,Te=pe?``:"";return`
`},Y=async()=>{if(!b)return;D(!0),M({done:0,total:F.length,failed:0});let oe=0,pe=0;for(const ce of F)try{let de;try{de=(await c.mutateAsync({video_id:b.id,recipient_email:ce.email,recipient_name:`${ce.first_name} ${ce.last_name||""}`.trim(),contact_id:ce.id,sent_via:"gmail"})).share_token}catch(Te){console.warn("Tracking record failed for",ce.email,Te)}const ie=K(ce.first_name,de),ye=j.replace(/\{\{first_name\}\}/gi,ce.first_name),{data:_e,error:Me}=await q.functions.invoke("gmail-send",{body:{to:ce.email,subject:ye,body:ie,contactId:ce.id}});if(Me||!(_e!=null&&_e.success))throw new Error((_e==null?void 0:_e.error)||(Me==null?void 0:Me.message)||"Send failed");oe+=1}catch(de){console.error("Failed to send to",ce.email,de),pe+=1}finally{M({done:oe+pe,total:F.length,failed:pe}),await new Promise(de=>setTimeout(de,250))}D(!1),pe===0?ae.success(`Video sent to ${oe} ${oe===1?"contact":"contacts"}!`):ae.warning(`Sent to ${oe}, ${pe} failed. Check console for details.`),t(!1),i==null||i()},ee=()=>{if(!b)return;const oe=K("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:F.map(pe=>({email:pe.email,name:`${pe.first_name} ${pe.last_name||""}`.trim()})),initialSubject:j,initialBodyHtml:oe}}),t(!1)},ne=!!b&&!!j.trim()&&F.length>0&&(V?a:r);return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-5 w-5 text-primary"}),"Send Video to ",F.length," ",F.length===1?"Contact":"Contacts"]}),e.jsxs(Qn,{children:[V?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(qd,{className:"h-3.5 w-3.5"}),F.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Hs,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),z>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",z," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[V&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Gi,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{children:["Mass Email is not set up yet. Verify a sender address in Integrations → Mass Email before sending to ",F.length," recipients."]})]}),!V&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Gi,{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(se,{children:"Choose a video"}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(As,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search your video library...",value:f,onChange:oe=>g(oe.target.value),className:"pl-10"})]}),e.jsx("div",{className:"max-h-[220px] overflow-y-auto space-y-2 border rounded-md p-2",children:h?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{className:"h-14 w-full"}),e.jsx(Ws,{className:"h-14 w-full"})]}):W.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."}):W.map(oe=>{const pe=(b==null?void 0:b.id)===oe.id;return e.jsxs("button",{type:"button",onClick:()=>v(oe),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${pe?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"}`,children:[e.jsxs("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden relative",children:[oe.thumbnail_url?e.jsx("img",{src:oe.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(Ph,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20",children:e.jsx(Al,{className:"h-4 w-4 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:oe.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[oe.duration_seconds?`${Math.round(oe.duration_seconds)}s`:"",oe.created_at?` · ${new Date(oe.created_at).toLocaleDateString()}`:""]})]})]},oe.id)})})]}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(ge,{id:"bulk-video-subject",value:j,onChange:oe=>_(oe.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Ts,{id:"bulk-video-message",value:S,onChange:oe=>A(oe.target.value),rows:4,className:"resize-y"})]}),T&&L.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",L.done," / ",L.total,L.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",L.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:T,children:"Cancel"}),V?e.jsxs(B,{onClick:ee,disabled:!ne,className:"gap-2",children:[e.jsx(qd,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(B,{onClick:Y,disabled:!ne||T,className:"gap-2",children:[T?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),T?"Sending…":`Send to ${F.length}`]})]})]})]})})}function O1e(){const s=fa();return lt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaigns").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("is_starter",{ascending:!1}).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function CGs(s){return lt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function TGs(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description??null,category:n.category??"nurture",icon:n.icon??"🌱",cover_color:n.cover_color??"from-emerald-500 to-teal-600",goal:n.goal??null,is_active:!1}).select().single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function B_t(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("drip_campaigns").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["drip-campaigns"]}),s.invalidateQueries({queryKey:["drip-campaign",n.id]})}})}function EGs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("drip_campaigns").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function $_t(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const[{data:r,error:a},{data:i,error:l}]=await Promise.all([q.from("drip_campaigns").select("*").eq("id",n).single(),q.from("drip_campaign_steps").select("*").eq("campaign_id",n).order("step_order")]);if(a)throw a;if(l)throw l;const{data:o,error:c}=await q.from("drip_campaigns").insert({owner_user_id:s,name:r.name,description:r.description,category:r.category,icon:r.icon,cover_color:r.cover_color,goal:r.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(h=>({campaign_id:o.id,step_order:h.step_order,channel:h.channel,subject:h.subject,body:h.body,video_url:h.video_url,delay_type:h.delay_type,delay_days:h.delay_days,delay_hours:h.delay_hours,anchor_field:h.anchor_field,anchor_offset_days:h.anchor_offset_days,send_window_start:h.send_window_start,send_window_end:h.send_window_end})),{error:u}=await q.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function U_t(s){return lt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function AGs(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("drip_campaign_steps").insert({campaign_id:t.campaign_id,step_order:t.step_order,channel:t.channel??"email",subject:t.subject??"",body:t.body??"",video_url:t.video_url??null,delay_type:t.delay_type??"relative",delay_days:t.delay_days??0,delay_hours:t.delay_hours??0,anchor_field:t.anchor_field??null,anchor_offset_days:t.anchor_offset_days??0}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["drip-campaign-steps",n.campaign_id]})})}function MGs(){const s=Gt();return gt({mutationFn:async({id:t,campaign_id:n,...r})=>{const{data:a,error:i}=await q.from("drip_campaign_steps").update(r).eq("id",t).select().single();if(i)throw i;return{data:a,campaign_id:n}},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t.campaign_id]})})}function IGs(){const s=Gt();return gt({mutationFn:async({id:t,campaign_id:n})=>{const{error:r}=await q.from("drip_campaign_steps").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function PGs(s){return lt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function LGs(s){return lt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:n}=await q.from("drip_campaign_enrollments").select("id",{count:"exact",head:!0}).eq("campaign_id",s).eq("status","active");if(n)throw n;return t??0},enabled:!!s,staleTime:3e4})}function q_t(){const s=Gt();return gt({mutationFn:async({campaignId:t,contactIds:n})=>{const{data:r,error:a}=await q.functions.invoke("enroll-contacts-in-campaign",{body:{campaign_id:t,contact_ids:n}});if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}function DGs(){const s=Gt();return gt({mutationFn:async({id:t,status:n})=>{const r={status:n};n==="paused"&&(r.paused_at=new Date().toISOString()),n==="exited"&&(r.exited_at=new Date().toISOString(),r.exit_reason="manual");const{data:a,error:i}=await q.from("drip_campaign_enrollments").update(r).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}const RGs=[{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"}],F1e={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"},OGs={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 o6({userId:s,onSelect:t,onSelectVideo:n,triggerLabel:r="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=N.useState(!1),[d,u]=N.useState([]),[h,p]=N.useState(!1),[f,g]=N.useState("");N.useEffect(()=>{!o||!s||(p(!0),q.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:v})=>{u(v||[]),p(!1)}))},[o,s]);const b=d.filter(v=>!f||(v.title||v.recipient_name||"").toLowerCase().includes(f.toLowerCase()));return e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(Ph,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(vs,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(ws,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search videos...",value:f,onChange:v=>g(v.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:h?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{className:"h-16 w-full"}),e.jsx(Ws,{className:"h-16 w-full"})]}):b.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"}):b.map(v=>e.jsxs("button",{onClick:()=>{t(v.playback_url||""),n==null||n(v),c(!1)},className:"w-full flex items-center gap-3 p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-accent/50 transition-colors text-left",children:[e.jsx("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden",children:v.thumbnail_url?e.jsx("img",{src:v.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:j=>{const _=j.currentTarget.parentElement;if(_){j.currentTarget.remove();const S=document.createElement("span");S.innerHTML="🎬",S.className="text-lg",_.appendChild(S)}}}):e.jsx(vr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.title||v.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.duration_seconds?`${Math.round(v.duration_seconds)}s`:"",v.created_at?` · ${new Date(v.created_at).toLocaleDateString()}`:""]})]})]},v.id))})]})]})}function FGs(){return lt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await q.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function zGs(s){return lt({queryKey:["video-scripts",s],queryFn:async()=>{let t=q.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:n,error:r}=await t;if(r)throw r;return n}})}function BGs(){const{user:s}=gs();return lt({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",s.id).order("title");if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function $Gs(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("user_video_scripts").insert([{owner_user_id:s.id,source_script_id:n.id,category_id:n.category_id,title:n.title,script_text:n.script_text,tags:n.tags,is_custom:!1}]).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["user-video-scripts"]})}})}function UGs(s){const{user:t}=gs();return lt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let n=q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",t.id).order("created_at",{ascending:!1});n=n.eq("is_deleted",!1);const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!(t!=null&&t.id)})}function qGs(s){return lt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function PN(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("agent_videos").insert([{owner_user_id:s.id,contact_id:n.contact_id,bunny_video_id:n.bunny_video_id,playback_url:n.playback_url,thumbnail_url:n.thumbnail_url,preview_url:n.preview_url,duration_seconds:n.duration_seconds,file_size_mb:n.file_size_mb||0,title:n.title,notes:n.notes,task_id:n.task_id,status:n.status||"processing",touch_type:n.touch_type||"video",page_template:"default",category:n.category||"general"}]).select("*, share_token").single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function VGs(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("agent_videos").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["agent-video",t.id]})}})}function HGs(){const s=Gt();return gt({mutationFn:async({id:t,bunnyVideoId:n,hardDelete:r=!1})=>{if(console.log("Deleting video:",{id:t,bunnyVideoId:n,hardDelete:r}),n){console.log("Calling bunny-upload delete for videoId:",n);const{data:a,error:i}=await q.functions.invoke("bunny-upload",{body:{action:"delete",videoId:n,isAgentVideo:!0}});i?console.error("Failed to delete from Bunny:",i):console.log("Bunny delete response:",a)}else console.warn("No bunnyVideoId provided, skipping Bunny.net deletion");if(r){console.log("Hard deleting from database:",t);const{error:a}=await q.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await q.from("agent_videos").update({is_deleted:!0}).eq("id",t);if(a)throw a}console.log("Video deletion complete")},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["storage-usage"]})}})}function z1e(){const{user:s}=gs();return lt({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await q.from("agent_storage_usage").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t||{user_id:s.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(s!=null&&s.id)})}function V_t(){const{data:s,isLoading:t}=z1e(),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 l6(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(n)throw n;return t}async function c6(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}async function Uw(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}function GGs(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async({contactId:n,videoId:r,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await q.from("action_types").select("id").eq("name","Video").single();if(!i)throw new Error("Video action type not found");const{data:l,error:o}=await q.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id:n,action_type_id:i.id,notes:a||`Quick Video Touch - Video ID: ${r}`}]).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts"]})}})}function H_t({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=lx(),{data:a}=z1e(),i=PN(),l=N.useRef(null),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(""),[b,v]=N.useState(!1),[j,_]=N.useState(0),[S,A]=N.useState("idle"),T=(a==null?void 0:a.total_storage_mb)||0,L=((a==null?void 0:a.max_storage_mb)||1024)-T,M=W=>{var ee;const K=(ee=W.target.files)==null?void 0:ee[0];if(!K)return;if(!K.type.startsWith("video/")){ae.error("Please select a video file");return}const Y=K.size/(1024*1024);if(Y>500){ae.error("Video file must be less than 500MB");return}if(Y>L){ae.error(`Not enough storage. You have ${L.toFixed(1)} MB remaining.`);return}c(K),d||u(K.name.replace(/\.[^/.]+$/,""))},F=async()=>{if(!o){ae.error("Please select a video file");return}v(!0),_(0),A("creating");try{const{data:W,error:K}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(K)throw new Error(K.message);const{videoId:Y,libraryId:ee}=W;A("uploading");const{data:ne,error:oe}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Y,isAgentVideo:!0}});if(oe)throw new Error(oe.message);await new Promise((de,ie)=>{const ye=new XMLHttpRequest;ye.upload.addEventListener("progress",_e=>{if(_e.lengthComputable){const Me=Math.round(_e.loaded/_e.total*100);_(Me)}}),ye.addEventListener("load",()=>{ye.status>=200&&ye.status<300?de():ie(new Error(`Upload failed with status ${ye.status}`))}),ye.addEventListener("error",()=>ie(new Error("Upload failed"))),ye.open("PUT",ne.uploadUrl),ye.setRequestHeader("AccessKey",ne.apiKey),ye.send(o)}),A("processing");const pe=o.size/(1024*1024),ce=`https://iframe.mediadelivery.net/embed/${ee}/${Y}`;await i.mutateAsync({bunny_video_id:Y,playback_url:ce,file_size_mb:pe,title:d||o.name,notes:h||void 0,contact_id:f||void 0,status:"processing",touch_type:"video_upload"}),ae.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(ce),z()}catch(W){console.error("Upload error:",W),ae.error(W instanceof Error?W.message:"Failed to upload video")}finally{v(!1),A("idle")}},z=()=>{b||(c(null),u(""),p(""),g(""),_(0),A("idle"),t(!1))},V=()=>{switch(S){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${j}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(bs,{open:s,onOpenChange:z,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Upload Video"}),e.jsx(Qn,{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(se,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(vr,{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"]})]}),!b&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:W=>{W.stopPropagation(),c(null)},children:e.jsx(Fn,{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 W;return(W=l.current)==null?void 0:W.click()},children:[e.jsx(Sa,{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:M,disabled:b})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(ge,{id:"title",value:d,onChange:W=>u(W.target.value),placeholder:"Enter video title",disabled:b})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Associate with Contact (optional)"}),e.jsxs(us,{value:f||"__none__",onValueChange:W=>g(W==="__none__"?"":W),disabled:b,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select a contact"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"__none__",children:"No contact"}),r==null?void 0:r.map(W=>e.jsxs(Ze,{value:W.id,children:[W.first_name," ",W.last_name||""]},W.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Ts,{id:"notes",value:h,onChange:W=>p(W.target.value),placeholder:"Add any notes about this video",rows:2,disabled:b})]}),b&&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(ss,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:V()})]}),e.jsx(xi,{value:S==="uploading"?j:S==="processing"?100:10})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:z,disabled:b,children:"Cancel"}),e.jsx(B,{onClick:F,disabled:!o||b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const WGs=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],KGs={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},DZe=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=>KGs[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function G_t({open:s,onOpenChange:t,campaignId:n}){const[r,a]=N.useState(n??null),[i,l]=N.useState("details");N.useEffect(()=>{a(n??null),l("details")},[n,s]);const o=r,c=!!o,{data:d}=CGs(o||void 0),{data:u,isLoading:h}=U_t(o||void 0),p=TGs(),f=B_t(),g=AGs(),[b,v]=N.useState(""),[j,_]=N.useState(""),[S,A]=N.useState("nurture"),[T,D]=N.useState("🌱"),[L,M]=N.useState("");N.useEffect(()=>{d?(v(d.name),_(d.description||""),A(d.category),D(d.icon),M(d.goal||"")):c||(v(""),_(""),A("nurture"),D("🌱"),M(""))},[d,c,s]);const F=OGs[S],z=async()=>{if(!b.trim()){ae.error("Give your campaign a name");return}try{if(c&&o)await f.mutateAsync({id:o,name:b,description:j,category:S,icon:T,goal:L,cover_color:F}),ae.success("Campaign updated");else{const W=await p.mutateAsync({name:b,description:j,category:S,icon:T,goal:L,cover_color:F});return ae.success("Campaign created — now add your first step!"),a(W.id),l("steps"),W}}catch(W){ae.error(W.message||"Failed to save")}},V=async()=>{if(!o){ae.error("Save the campaign first, then add steps");return}const W=((u==null?void 0:u.length)||0)+1;try{await g.mutateAsync({campaign_id:o,step_order:W,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:W===1?0:2,delay_hours:0})}catch{ae.error("Failed to add step")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${F} p-5 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:T}),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(Qn,{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($r,{value:i,onValueChange:W=>l(W),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(Ur,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Zt,{value:"details",children:"Details"}),e.jsxs(Zt,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(ls,{value:"details",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(mi,{className:"h-full",children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Campaign Name *"}),e.jsx(ge,{value:b,onChange:W=>v(W.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Description"}),e.jsx(Ts,{value:j,onChange:W=>_(W.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Goal (optional)"}),e.jsx(ge,{value:L,onChange:W=>M(W.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(se,{className:"text-xs",children:"Category"}),e.jsxs(us,{value:S,onValueChange:W=>A(W),children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(ds,{children:Object.entries(F1e).map(([W,K])=>e.jsx(Ze,{value:W,children:K},W))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:WGs.map(W=>e.jsx("button",{type:"button",onClick:()=>D(W),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${T===W?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:W},W))})]})]}),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(ls,{value:"steps",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(mi,{className:"h-full",children:e.jsx("div",{className:"p-5 space-y-3",children:h?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!u||u.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No steps yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build your sequence — each step waits for its delay, then sends."}),e.jsxs(B,{size:"sm",onClick:V,disabled:g.isPending,children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((W,K)=>e.jsx(YGs,{step:W,index:K,totalSteps:u.length},W.id)),e.jsxs(B,{variant:"outline",size:"sm",onClick:V,disabled:g.isPending,className:"w-full",children:[g.isPending?e.jsx(ss,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(As,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(Xn,{className:"border-t p-4 shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(B,{onClick:z,disabled:p.isPending||f.isPending,children:[(p.isPending||f.isPending)&&e.jsx(ss,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function YGs({step:s,index:t,totalSteps:n}){const r=MGs(),a=IGs(),i=fa(),[l,o]=N.useState(!1),[c,d]=N.useState(()=>({...s,body:DZe(s.body)})),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,b]=N.useState(""),[v,j]=N.useState(!1);N.useEffect(()=>{d({...s,body:DZe(s.body)})},[s]);const _=JSON.stringify(c)!==JSON.stringify(s),S=async()=>{h(!0);try{await r.mutateAsync({id:s.id,campaign_id:s.campaign_id,channel:c.channel,subject:c.subject,body:c.body,video_url:c.video_url,delay_type:c.delay_type,delay_days:c.delay_days,delay_hours:c.delay_hours,anchor_field:c.anchor_field,anchor_offset_days:c.anchor_offset_days}),ae.success(`Step ${t+1} saved`)}catch{ae.error("Failed to save step")}finally{h(!1)}},A=async()=>{if(confirm(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),ae.success("Step deleted")}catch{ae.error("Failed to delete")}},T=L=>{d({...c,body:c.body+L})},D=()=>{if(c.delay_type==="calendar_anchor"){const M=c.anchor_field==="birthday"?"birthday":"home anniversary",F=c.anchor_offset_days||0;return F===0?`On their ${M}`:F<0?`${Math.abs(F)}d before ${M}`:`${F}d after ${M}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const L=[];return c.delay_days&&L.push(`${c.delay_days}d`),c.delay_hours&&L.push(`${c.delay_hours}h`),t===0?`After ${L.join(" ")||"0"}`:`+${L.join(" ")||"0"}`};return e.jsxs("div",{className:"border rounded-lg bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 hover:bg-muted/30 cursor-pointer",onClick:()=>o(!l),children:[e.jsx("div",{className:"h-7 w-7 shrink-0 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:t+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[c.delay_type==="calendar_anchor"?e.jsx(yr,{className:"h-3 w-3"}):e.jsx(gr,{className:"h-3 w-3"}),e.jsx("span",{children:D()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(Hs,{className:"h-3 w-3"}):e.jsx(Ci,{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(sx,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(io,{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(se,{className:"text-xs",children:"Channel"}),e.jsxs(us,{value:c.channel,onValueChange:L=>d({...c,channel:L}),children:[e.jsx(cs,{className:"mt-1 h-9",children:e.jsx(hs,{})}),e.jsx(ds,{children:e.jsx(Ze,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Timing Type"}),e.jsxs(us,{value:c.delay_type,onValueChange:L=>d({...c,delay_type:L}),children:[e.jsx(cs,{className:"mt-1 h-9",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"relative",children:"⏱ Relative delay"}),e.jsx(Ze,{value:"calendar_anchor",children:"📅 Calendar date"})]})]})]})]}),c.delay_type==="relative"?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Days delay"}),e.jsx(ge,{type:"number",min:0,value:c.delay_days,onChange:L=>d({...c,delay_days:parseInt(L.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Hours delay"}),e.jsx(ge,{type:"number",min:0,max:23,value:c.delay_hours,onChange:L=>d({...c,delay_hours:parseInt(L.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(se,{className:"text-xs",children:"Anchor"}),e.jsxs(us,{value:c.anchor_field||"birthday",onValueChange:L=>d({...c,anchor_field:L}),children:[e.jsx(cs,{className:"mt-1 h-9",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"birthday",children:"🎂 Birthday"}),e.jsx(Ze,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(ge,{type:"number",value:c.anchor_offset_days||0,onChange:L=>d({...c,anchor_offset_days:parseInt(L.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject Line"}),e.jsx(ge,{value:c.subject,onChange:L=>d({...c,subject:L.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(se,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(Ts,{value:c.body,onChange:L=>d({...c,body:L.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:"}),RGs.map(L=>e.jsx("button",{type:"button",onClick:()=>T(L.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:L.label},L.key))]})]}),e.jsxs("div",{children:[e.jsx(se,{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(vr,{className:"h-3 w-3 inline mr-1 text-primary"}),c.video_url.length>50?c.video_url.slice(0,50)+"...":c.video_url]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>d({...c,video_url:null}),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 flex-wrap",children:[e.jsx(o6,{userId:i||void 0,onSelect:L=>d({...c,video_url:L}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>j(!0),children:[e.jsx(Sa,{className:"h-3 w-3"})," Upload"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{b(""),f(!0)},children:[e.jsx(tl,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(H_t,{open:v,onOpenChange:j,onUploadComplete:L=>d({...c,video_url:L})}),e.jsx(bs,{open:p,onOpenChange:f,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add video URL"}),e.jsx(Qn,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(ge,{value:g,onChange:L=>b(L.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:L=>{L.key==="Enter"&&g.trim()&&(d({...c,video_url:g.trim()}),f(!1))}}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{disabled:!g.trim(),onClick:()=>{d({...c,video_url:g.trim()}),f(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:A,className:"text-destructive hover:text-destructive",children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs(B,{size:"sm",onClick:S,disabled:!_||u,children:[u&&e.jsx(ss,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]})]})}function ZGs({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=O1e(),l=q_t(),[o,c]=N.useState(""),[d,u]=N.useState(null),[h,p]=N.useState(!1),f=(a||[]).filter(v=>!v.is_starter),g=f.filter(v=>v.name.toLowerCase().includes(o.toLowerCase())||(v.description||"").toLowerCase().includes(o.toLowerCase())),b=async()=>{if(d)try{const v=await l.mutateAsync({campaignId:d,contactIds:n}),j=[`${v.enrolled} enrolled`];v.skipped>0&&j.push(`${v.skipped} skipped`),v.errors>0&&j.push(`${v.errors} errors`),ae.success(j.join(" · ")),t(!1),u(null),r==null||r()}catch(v){ae.error(v.message||"Failed to enroll contacts")}};return e.jsxs(bs,{open:s,onOpenChange:t,children:[e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Qn,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search campaigns...",value:o,onChange:v=>c(v.target.value),className:"pl-9 h-9"})]}),e.jsx(mi,{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:f.length===0?e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No campaigns yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build a custom drip campaign to nurture these contacts on autopilot."}),e.jsxs(B,{size:"sm",onClick:()=>p(!0),children:[e.jsx(As,{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(v=>e.jsxs("button",{onClick:()=>u(v.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===v.id?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("div",{className:`shrink-0 h-9 w-9 rounded-lg bg-gradient-to-br ${v.cover_color} flex items-center justify-center text-lg`,children:v.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),v.is_active&&e.jsx(ze,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:v.description})]}),d===v.id&&e.jsx(Lr,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},v.id))})})]}),e.jsxs(Xn,{className:"gap-2 sm:gap-2",children:[f.length>0&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>p(!0),className:"mr-auto text-xs",children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:b,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(ss,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(G_t,{open:h,onOpenChange:p})]})}function QGs({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=In(),{data:c}=Cy(),d=w6e(),u=Gt(),{isGmailConnected:h}=bh(),{isReady:p}=jR(),{data:f}=NR(),g=vLe(),b=A_t(),[v,j]=N.useState(!1),[_,S]=N.useState(!1),[A,T]=N.useState(!1),[D,L]=N.useState(!1),[M,F]=N.useState(!1),[z,V]=N.useState(""),W=s.size;if(W===0)return null;const K=async de=>{j(!0);try{const ye=Array.from(s).map(Me=>({contact_id:Me,relationship_type_id:de})),{error:_e}=await q.from("innercircle_contact_tags").upsert(ye,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(_e)throw _e;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Dr({title:`Assigned type to ${W} contacts`}),n()}catch(ie){Dr({title:"Error assigning type",description:ie.message,variant:"destructive"})}finally{j(!1)}},Y=async de=>{j(!0);try{const ie=Array.from(s);for(const ye of ie)try{await b.mutateAsync({contactId:ye,tagId:de})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),Dr({title:`Tagged ${W} contacts`}),F(!1),V("")}catch(ie){Dr({title:"Error adding tags",description:ie.message,variant:"destructive"})}finally{j(!1)}},ee=async()=>{if(z.trim()){j(!0);try{const de=await g.mutateAsync({name:z.trim()});await Y(de.id)}catch(de){Dr({title:"Error creating tag",description:de.message,variant:"destructive"}),j(!1)}}},ne=(f==null?void 0:f.filter(de=>de.name.toLowerCase().includes(z.toLowerCase())))||[],oe=f==null?void 0:f.find(de=>de.name.toLowerCase()===z.trim().toLowerCase()),pe=()=>{const de=t.filter(Ee=>s.has(Ee.id)),ie=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],ye=de.map(Ee=>{var De;return[Ee.first_name,Ee.last_name||"",Ee.email||"",Ee.phone||"",Ee.address||"",Ee.birthday||"",Ee.home_anniversary||"",Ee.notes||"",((De=Ee.tags)==null?void 0:De.map(Ie=>{var Fe;return(Fe=Ie.relationship_type)==null?void 0:Fe.name}).join("; "))||""]}),_e=[ie.join(","),...ye.map(Ee=>Ee.map(De=>`"${(De||"").replace(/"/g,'""')}"`).join(","))].join(` `),Me=new Blob([_e],{type:"text/csv"}),Te=URL.createObjectURL(Me),Ce=document.createElement("a");Ce.href=Te,Ce.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Ce.click(),URL.revokeObjectURL(Te),Dr({title:`Exported ${W} contacts`})},ce=async()=>{if(confirm(`Are you sure you want to delete ${W} contacts? This cannot be undone.`)){j(!0);try{const de=Array.from(s);for(const ie of de)await d.mutateAsync(ie);n()}catch(de){Dr({title:"Error deleting contacts",description:de.message,variant:"destructive"})}finally{j(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[e.jsxs(ze,{variant:"secondary",className:"font-semibold",children:[W," selected"]}),e.jsxs(us,{onValueChange:K,disabled:v,children:[e.jsx(cs,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(mh,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(ds,{children:c==null?void 0:c.filter(de=>de.active).map(de=>e.jsx(Ze,{value:de.id,children:de.name},de.id))})]}),e.jsxs(Wo,{open:M,onOpenChange:F,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",disabled:v,children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(zo,{className:"w-56 p-2",align:"start",children:[e.jsx(ge,{placeholder:"Search or create tag...",value:z,onChange:de=>V(de.target.value),onKeyDown:de=>{de.key==="Enter"&&z.trim()&&!oe?(de.preventDefault(),ee()):de.key==="Enter"&&oe&&(de.preventDefault(),Y(oe.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[ne.map(de=>e.jsxs("button",{onClick:()=>Y(de.id),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:de.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:de.name})]},de.id)),z.trim()&&!oe&&e.jsxs("button",{onClick:ee,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(As,{className:"h-3.5 w-3.5"}),'Create "',z.trim(),'"']}),ne.length===0&&!z.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),h&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>S(!0),disabled:v,children:[e.jsx(Hs,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),p&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{const de=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${de}`)},disabled:v,children:[e.jsx(qd,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>T(!0),disabled:v,children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>L(!0),disabled:v,children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&r&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>r(Array.from(s)),disabled:v,children:[e.jsx(pb,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:v,children:[e.jsx(pw,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:pe,disabled:v,children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ce,disabled:v,className:"text-destructive hover:text-destructive",children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:n,className:"ml-auto",children:[e.jsx(Fn,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(ZGs,{open:D,onOpenChange:L,contactIds:Array.from(s),onSuccess:n}),e.jsx(Ty,{open:_,onOpenChange:S,bulkContacts:Array.from(s).map(de=>{const ie=t.find(ye=>ye.id===de);return ie?{id:ie.id,first_name:ie.first_name,last_name:ie.last_name,email:ie.email||""}:null}).filter(de=>de!==null&&de.email!==""),onSendComplete:()=>{S(!1),n()}}),e.jsx(SGs,{open:A,onOpenChange:T,contacts:Array.from(s).map(de=>t.find(ie=>ie.id===de)).filter(de=>!!de).map(de=>({id:de.id,first_name:de.first_name,last_name:de.last_name,email:de.email})),isGmailConnected:!!h,isMassEmailReady:!!p,onSendComplete:()=>{T(!1),n()}})]})}function RZe({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=In(),{isReady:d}=jR(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(Xf,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(Xr,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(Pr,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(Xr,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(vr,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(Xr,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(Xr,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(Xr,{onClick:()=>r(s.id,u),children:[e.jsx(_f,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(Xr,{onClick:()=>a(s.id),children:[e.jsx(pb,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(Xr,{onClick:()=>l(s.id),children:[e.jsx(pw,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(Xr,{onClick:()=>t(s),children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Xr,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function OZe({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=bLe(),a=M_t(),i=I_t(),[l,o]=N.useState(!1),[c,d]=N.useState(""),u=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all"||s.behavior&&Object.values(s.behavior).some(p=>p!==void 0&&p!==!1),h=async()=>{c.trim()&&(await a.mutateAsync({name:c.trim(),filters:s,sort_by:t}),d(""),o(!1))};return e.jsxs(e.Fragment,{children:[e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Fv,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx(ze,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(io,{className:"h-3.5 w-3.5"})]})}),e.jsxs(cc,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(p=>e.jsxs(Xr,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>n(p.filters,p.sort_by),children:p.name}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:f=>{f.stopPropagation(),i.mutate(p.id)},children:e.jsx(bn,{className:"h-3 w-3 text-destructive"})})]},p.id)),e.jsx(Qg,{})]}):e.jsx(Xr,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(Xr,{onClick:()=>o(!0),children:[e.jsx(tL,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ge,{placeholder:"e.g. Buyers in 40205",value:c,onChange:p=>d(p.target.value),onKeyDown:p=>p.key==="Enter"&&h(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{onClick:h,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}const $ge=[{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"}],W_t=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],XGs=[{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 JGs({open:s,onOpenChange:t,hasLeadSite:n,behavior:r,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o}){const[c,d]=N.useState(r),[u,h]=N.useState(n?"behavior":"contact"),{data:p}=KM();N.useEffect(()=>{s&&d(r)},[s,r]);const f=b=>d(v=>({...v,...b})),g=Object.entries(c).filter(([,b])=>b!==void 0&&b!==!1&&b!=="").length;return e.jsx(ug,{open:s,onOpenChange:t,children:e.jsxs(ox,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(r0,{children:[e.jsxs(a0,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(lU,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs($r,{value:u,onValueChange:b=>h(b),className:"mt-4",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-3",children:[e.jsxs(Zt,{value:"contact",className:"gap-1.5",children:[e.jsx(_n,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(Zt,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(am,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(Zt,{value:"engagement",children:"Engagement"})]}),e.jsxs(ls,{value:"contact",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact Type"}),e.jsxs(us,{value:i,onValueChange:l,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"All types"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),o==null?void 0:o.map(b=>e.jsx(Ze,{value:b.id,children:b.name},b.id))]})]})]}),e.jsxs(h2,{title:"Contact Info Present",children:[e.jsx(Gf,{label:"Has email",checked:c.hasEmail===!0,onChange:b=>f({hasEmail:b||void 0})}),e.jsx(Gf,{label:"Has phone",checked:c.hasPhone===!0,onChange:b=>f({hasPhone:b||void 0})}),e.jsx(Gf,{label:"Has address",checked:c.hasAddress===!0,onChange:b=>f({hasAddress:b||void 0})}),e.jsx(Gf,{label:"Has birthday",checked:c.hasBirthday===!0,onChange:b=>f({hasBirthday:b||void 0})}),e.jsx(Gf,{label:"Has spouse",checked:c.hasSpouse===!0,onChange:b=>f({hasSpouse:b||void 0})}),e.jsx(Gf,{label:"Has company / job",checked:c.hasCompany===!0,onChange:b=>f({hasCompany:b||void 0})}),e.jsx(Gf,{label:"Has notes",checked:c.hasNotes===!0,onChange:b=>f({hasNotes:b||void 0})})]}),e.jsxs(h2,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(ENe,{label:"City",value:c.city||"",onChange:b=>f({city:b||void 0}),placeholder:"Any city"}),e.jsx(ENe,{label:"State",value:c.state||"",onChange:b=>f({state:b||void 0}),placeholder:"Any state"})]}),e.jsx(ENe,{label:"ZIP / Postal",value:c.zip||"",onChange:b=>f({zip:b||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(h2,{title:"Important Dates",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Birthday month"}),e.jsxs(us,{value:c.birthdayMonth?String(c.birthdayMonth):"all",onValueChange:b=>f({birthdayMonth:b==="all"?void 0:Number(b)}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Any month"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"Any month"}),$ge.map(b=>e.jsx(Ze,{value:String(b.value),children:b.label},b.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(us,{value:c.anniversaryField||"home_anniversary",onValueChange:b=>f({anniversaryField:b}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Field"})}),e.jsx(ds,{children:W_t.map(b=>e.jsx(Ze,{value:b.value,children:b.label},b.value))})]}),e.jsxs(us,{value:c.anniversaryMonth?String(c.anniversaryMonth):"all",onValueChange:b=>f({anniversaryMonth:b==="all"?void 0:Number(b)}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Any month"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"Any month"}),$ge.map(b=>e.jsx(Ze,{value:String(b.value),children:b.label},b.value))]})]})]})]})]}),e.jsx(h2,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(FZe,{label:"From",value:c.dateAddedFrom,onChange:b=>f({dateAddedFrom:b||void 0})}),e.jsx(FZe,{label:"To",value:c.dateAddedTo,onChange:b=>f({dateAddedTo:b||void 0})})]})}),e.jsx(h2,{title:"Lead Source",children:e.jsxs(us,{value:c.leadSourceId||"all",onValueChange:b=>f({leadSourceId:b==="all"?void 0:b}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"All sources"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All sources"}),e.jsx(Ze,{value:"none",children:"No source"}),p==null?void 0:p.map(b=>e.jsx(Ze,{value:b.id,children:b.name},b.id))]})]})})]}),e.jsx(ls,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(h2,{title:"Last Active On Site",children:[e.jsx(db,{value:c.lastActive||"",onValueChange:b=>f({lastActive:b||void 0}),className:"grid grid-cols-2 gap-2",children:XGs.map(b=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(Fd,{value:b.value}),e.jsx("span",{className:"text-sm",children:b.label})]},b.value))}),c.lastActive&&e.jsx(B,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>f({lastActive:void 0}),children:"Clear"})]}),e.jsxs(h2,{title:"Registration",children:[e.jsx(Gf,{label:"Registered on lead site",checked:c.registered==="yes",onChange:b=>f({registered:b?"yes":void 0})}),e.jsx(Gf,{label:"Anonymous visitors only",checked:c.registered==="no",onChange:b=>f({registered:b?"no":void 0})})]}),e.jsxs(h2,{title:"Property Activity",children:[e.jsx(Gf,{label:"Viewed any listing",checked:c.viewedListing==="any",onChange:b=>f({viewedListing:b?"any":void 0})}),e.jsx(Gf,{label:"Hot buyer — 3+ views in last 7 days",checked:c.viewedListing==="multiple7d",onChange:b=>f({viewedListing:b?"multiple7d":void 0})}),e.jsx(Gf,{label:"Saved a property",checked:!!c.savedProperty,onChange:b=>f({savedProperty:b||void 0})}),e.jsx(Gf,{label:"Has an active saved search / alert",checked:!!c.hasSavedSearch,onChange:b=>f({hasSavedSearch:b||void 0})})]}),e.jsxs(h2,{title:"Requests",children:[e.jsx(Gf,{label:"Requested a showing / asked a question",checked:!!c.requestedShowing,onChange:b=>f({requestedShowing:b||void 0})}),e.jsx(Gf,{label:"Requested a home valuation",checked:!!c.requestedValuation,onChange:b=>f({requestedValuation:b||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(ls,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(Gf,{label:"Any website activity",checked:!!c.websiteActiveOnly,onChange:b=>f({websiteActiveOnly:b||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(Pdt,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx(B,{variant:"ghost",onClick:()=>d({}),disabled:g===0,children:"Clear behavior filters"}),e.jsx(B,{onClick:()=>{a(c),t(!1)},children:"Apply"})]})]})})}function h2({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function Gf({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(vn,{checked:t,onCheckedChange:n})]})}function ENe({label:s,value:t,onChange:n,placeholder:r}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{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(Fn,{className:"h-3 w-3"})})]})]})}function FZe({label:s,value:t,onChange:n}){const[r,a]=N.useState(!1),i=t?Lu(t):void 0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs(Wo,{open:r,onOpenChange:a,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal h-8",!i&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-3.5 w-3.5"}),i?ks(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:i,onSelect:l=>{n(l?ks(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function eWs({behavior:s,onRemove:t,onClearAll:n}){const r=tWs(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 tWs(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=$ge.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=$ge.find(i=>i.value===s.anniversaryMonth),a=((n=W_t.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 ${ks(Lu(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${ks(Lu(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}async function BI(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 FF(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function sWs(){const{user:s}=gs(),{leadSite:t,hasLeadSite:n}=Pp(),{data:r,isLoading:a}=lt({queryKey:["contact-behavior-summary",s==null?void 0:s.id,t==null?void 0:t.id],queryFn:async()=>{const i=new Map;if(!t)return i;const l=(j,_)=>{const S=i.get(j)||FF();i.set(j,{...S,..._})},o=await BI((j,_)=>q.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(j,_)),c=new Map,d=new Map;o.forEach(j=>{if(!j.contact_id)return;c.set(j.id,j.contact_id),j.email&&d.set(j.email.toLowerCase(),j.contact_id);const _=i.get(j.contact_id);(!_||!_.lastActiveAt||j.last_seen_at>_.lastActiveAt)&&l(j.contact_id,{lastActiveAt:j.last_seen_at})});const u=await BI((j,_)=>q.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(j,_)),h=new Map;u.forEach(j=>{j.contact_id&&(h.set(j.user_id,j.contact_id),l(j.contact_id,{registered:!0}))});const p=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await BI((j,_)=>q.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(j,_))).forEach(j=>{const _=j.visitor_id?c.get(j.visitor_id):null;if(!_)return;const S=i.get(_)||FF();S.propertyViewCount+=1,j.viewed_at>=p&&(S.propertyViewCount7d+=1),i.set(_,S)}),(await BI((j,_)=>q.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(j,_))).forEach(j=>{const _=h.get(j.user_id);if(!_)return;const S=i.get(_)||FF();S.savedListingCount+=1,i.set(_,S)}),(await BI((j,_)=>q.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(j,_))).forEach(j=>{const _=h.get(j.user_id);if(!_)return;const S=i.get(_)||FF();S.activeSavedSearchCount+=1,i.set(_,S)}),(await BI((j,_)=>q.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(j,_))).forEach(j=>{if(!j.email)return;const _=d.get(j.email.toLowerCase());if(!_)return;const S=i.get(_)||FF(),A=(j.lead_type||"").toLowerCase();(A.includes("showing")||A.includes("question")||A==="contact")&&(S.showingRequests+=1),(A.includes("valuation")||A.includes("cma")||A.includes("home_value"))&&(S.valuationRequests+=1),i.set(_,S)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const K_t="innercircle_geocode_cache_v1";function nWs(){try{return JSON.parse(localStorage.getItem(K_t)||"{}")}catch{return{}}}function rWs(s){try{localStorage.setItem(K_t,JSON.stringify(s))}catch{}}function aWs(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 iWs({open:s,onOpenChange:t,contacts:n,onCitySelect:r}){const a=N.useRef(null),i=N.useRef(null),[l,o]=N.useState(""),[c,d]=N.useState(!0),[u,h]=N.useState([]),[p,f]=N.useState({done:0,total:0}),[g,b]=N.useState(!1),[v,j]=N.useState("heat");N.useEffect(()=>{if(!s)return;let S=!1;return(async()=>{d(!0);const{data:A}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();S||(o((A==null?void 0:A.value)||""),d(!1))})(),()=>{S=!0}},[s]),N.useEffect(()=>{if(!s||!l)return;let S=!1;return(async()=>{const T=nWs(),D=n.map(Y=>({c:Y,addr:aWs(Y)})).filter(Y=>Y.addr),L=[],M=[];for(const{c:Y,addr:ee}of D){const ne=T[ee];ne!==null&&(ne?L.push({id:Y.id,name:`${Y.first_name||""} ${Y.last_name||""}`.trim(),city:Y.city||null,state:Y.state||null,zip:Y.zip||Y.zip_code||null,lat:ne.lat,lng:ne.lng}):M.push({c:Y,addr:ee}))}if(S||h(L),f({done:L.length,total:D.length}),M.length===0)return;b(!0);const F=6;let z=0;const V={...T},W=[...L],K=async()=>{var Y;for(;z{S=!0}},[s,l,n]);const _=N.useMemo(()=>{const S=new Map;for(const A of n){const T=(A.city||"").trim();if(!T)continue;const D=(A.state||"").trim()||null,L=`${T.toLowerCase()}|${D||""}`,M=S.get(L);M?M.count++:S.set(L,{city:T,state:D,count:1})}return Array.from(S.values()).sort((A,T)=>T.count-A.count)},[n]);return N.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return ml.accessToken=l,i.current=new ml.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new ml.NavigationControl,"top-right"),()=>{var S;(S=i.current)==null||S.remove(),i.current=null}},[s,l]),N.useEffect(()=>{const S=i.current;if(!S||u.length===0)return;const A=()=>{const D={type:"FeatureCollection",features:u.map(M=>({type:"Feature",properties:{id:M.id,name:M.name},geometry:{type:"Point",coordinates:[M.lng,M.lat]}}))},L=S.getSource("contacts-src");if(L?L.setData(D):(S.addSource("contacts-src",{type:"geojson",data:D}),S.addLayer({id:"contacts-heat",type:"heatmap",source:"contacts-src",maxzoom:15,paint:{"heatmap-weight":1,"heatmap-intensity":["interpolate",["linear"],["zoom"],0,1,15,3],"heatmap-color":["interpolate",["linear"],["heatmap-density"],0,"rgba(64,110,113,0)",.2,"rgba(64,110,113,0.4)",.4,"rgba(56,189,248,0.6)",.6,"rgba(250,204,21,0.7)",.8,"rgba(249,115,22,0.85)",1,"rgba(220,38,38,1)"],"heatmap-radius":["interpolate",["linear"],["zoom"],0,12,9,30,15,60],"heatmap-opacity":["interpolate",["linear"],["zoom"],13,1,15,.6]}}),S.addLayer({id:"contacts-points",type:"circle",source:"contacts-src",paint:{"circle-radius":["interpolate",["linear"],["zoom"],0,4,8,5,16,9],"circle-color":"#406E71","circle-stroke-color":"#ffffff","circle-stroke-width":1.5,"circle-opacity":.9}}),S.on("click","contacts-points",M=>{var V;const F=(V=M.features)==null?void 0:V[0];if(!F)return;const z=F.geometry.coordinates.slice();new ml.Popup({offset:12}).setLngLat(z).setHTML(`
${F.properties.name||"Contact"}
`).addTo(S)}),S.on("mouseenter","contacts-points",()=>{S.getCanvas().style.cursor="pointer"}),S.on("mouseleave","contacts-points",()=>{S.getCanvas().style.cursor=""})),S.getLayer("contacts-heat")&&S.setLayoutProperty("contacts-heat","visibility",v==="heat"?"visible":"none"),S.getLayer("contacts-points")&&(S.setPaintProperty("contacts-points","circle-opacity",v==="points"?.9:0),S.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!S._fitDone){const M=new ml.LngLatBounds;u.forEach(F=>M.extend([F.lng,F.lat]));try{S.fitBounds(M,{padding:60,maxZoom:11,duration:600}),S._fitDone=!0}catch{}}};S.isStyleLoaded()?A():S.once("load",A)},[u,v]),e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(ws,{className:"p-4 pb-2 border-b",children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(_c,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(ze,{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(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):l?e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),e.jsxs("div",{className:"absolute top-3 left-3 flex flex-col gap-2 z-10",children:[e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border p-1 flex",children:[e.jsxs(B,{size:"sm",variant:v==="heat"?"default":"ghost",onClick:()=>j("heat"),className:"h-8",children:[e.jsx(_c,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(B,{size:"sm",variant:v==="points"?"default":"ghost",onClick:()=>j("points"),className:"h-8",children:[e.jsx(u9,{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(ss,{className:"h-3 w-3 animate-spin"}),"Mapping ",p.done," / ",p.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(Gi,{className:"h-10 w-10 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Mapbox token is not set. Contact your administrator."})]})]})}),e.jsxs("div",{className:"w-full md:w-72 border-t md:border-t-0 md:border-l flex flex-col bg-muted/30 min-h-[200px]",children:[e.jsxs("div",{className:"p-3 border-b bg-background",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(Ca,{className:"h-4 w-4 text-primary"}),"Top Cities"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Tap a city to filter your contacts"})]}),e.jsx(mi,{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((S,A)=>{var L;const T=((L=_[0])==null?void 0:L.count)||1,D=S.count/T*100;return e.jsx(fe,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(S.city,S.state),t(!1)},children:e.jsxs(Ae,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${D}%`}}),e.jsxs("div",{className:"relative flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[S.city,S.state?`, ${S.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:A===0?"🔥 Hottest market":`Rank #${A+1}`})]}),e.jsx(ze,{variant:"secondary",className:"shrink-0",children:S.count})]})]})},`${S.city}-${S.state}-${A}`)})]})})]})]})]})})}function RE(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 zZe({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=In(),c=ANe(s,"birthday",7),d=ANe(t,"anniversary",7),u=ANe(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(p,f,g)=>{g.stopPropagation();const b=new URLSearchParams;a&&b.set("contactId",a),i&&b.set("name",i),l&&b.set("address",l),(p==="home_anniversary"||p==="wedding_anniversary")&&f&&b.set("date",f),b.set("cardType",p),o(`/mission-control/card-studio?${b.toString()}`)};return e.jsxs("div",{className:Et("flex flex-wrap gap-1",r),children:[c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(ze,{variant:"secondary",className:Et("text-[10px] gap-0.5 font-medium",c.daysUntil===0?"bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-400 animate-pulse":"bg-pink-50 text-pink-600 dark:bg-pink-900/20 dark:text-pink-400"),children:c.label}),a&&e.jsxs("button",{onClick:p=>h("birthday",s,p),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-pink-500/15 text-pink-600 dark:text-pink-400 hover:bg-pink-500/25 transition-colors",title:"Send a birthday card",children:[e.jsx(Hs,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(ze,{variant:"secondary",className:Et("text-[10px] gap-0.5 font-medium",d.daysUntil===0?"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 animate-pulse":"bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400"),children:d.label}),a&&e.jsxs("button",{onClick:p=>h("home_anniversary",t,p),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-blue-500/15 text-blue-600 dark:text-blue-400 hover:bg-blue-500/25 transition-colors",title:"Send an anniversary card",children:[e.jsx(Hs,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(ze,{variant:"secondary",className:Et("text-[10px] gap-0.5 font-medium",u.daysUntil===0?"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400 animate-pulse":"bg-rose-50 text-rose-600 dark:bg-rose-900/20 dark:text-rose-400"),children:["💍 ",u.label.replace(/^[^\w]+/,"")]}),a&&e.jsxs("button",{onClick:p=>h("wedding_anniversary",n||null,p),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-rose-500/15 text-rose-600 dark:text-rose-400 hover:bg-rose-500/25 transition-colors",title:"Send a wedding anniversary card",children:[e.jsx(Hs,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function aTe({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(ze,{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 BZe({count:s,className:t}){return!s||s<=0?null:e.jsxs(ze,{variant:"outline",className:Et("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(qA,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function oWs(){const s=fa();return lt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("contact_id, status").eq("owner_user_id",s).eq("status","active");if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&(r[a.contact_id]=(r[a.contact_id]||0)+1)}),r},enabled:!!s,staleTime:6e4})}function lWs(){const s=fa();return lt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:n}=await q.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})}function cWs({contactId:s,compact:t=!1}){const{data:n}=NR(),{data:r}=XVs(s),a=vLe(),i=A_t(),l=tHs(),[o,c]=N.useState(!1),[d,u]=N.useState(""),h=N.useRef(null),p=new Set((r==null?void 0:r.map(j=>j.tag_id))||[]),f=(n==null?void 0:n.filter(j=>j.name.toLowerCase().includes(d.toLowerCase())))||[],g=n==null?void 0:n.find(j=>j.name.toLowerCase()===d.trim().toLowerCase()),b=async j=>{p.has(j.id)?await l.mutateAsync({contactId:s,tagId:j.id}):await i.mutateAsync({contactId:s,tagId:j.id})},v=async()=>{if(!(!d.trim()||g))try{const j=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:j.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(j=>{var _,S,A;return e.jsxs(ze,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((_=j.tag)==null?void 0:_.color)||"#6366F1",color:((S=j.tag)==null?void 0:S.color)||"#6366F1"},children:[e.jsx(mh,{className:"h-2.5 w-2.5"}),(A=j.tag)==null?void 0:A.name,e.jsx("button",{onClick:T=>{T.stopPropagation(),l.mutate({contactId:s,tagId:j.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(Fn,{className:"h-2.5 w-2.5"})})]},j.id)}),e.jsxs(Wo,{open:o,onOpenChange:c,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:j=>j.stopPropagation(),children:[e.jsx(As,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(zo,{className:"w-56 p-2",align:"start",onClick:j=>j.stopPropagation(),children:[e.jsx(ge,{ref:h,placeholder:"Search or create tag...",value:d,onChange:j=>u(j.target.value),onKeyDown:j=>{j.key==="Enter"&&d.trim()&&!g?(j.preventDefault(),v()):j.key==="Enter"&&g&&!p.has(g.id)&&(j.preventDefault(),b(g))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[f.map(j=>e.jsxs("button",{onClick:()=>b(j),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:j.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:j.name}),p.has(j.id)&&e.jsx(Lr,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},j.id)),d.trim()&&!g&&e.jsxs("button",{onClick:v,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(As,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),f.length===0&&!d.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create your first tag"})]})]})]})]})}function $Ze({contactId:s,tags:t}){return!t||t.length===0?null:e.jsx(e.Fragment,{children:t.map(n=>{var r,a,i;return e.jsx(ze,{variant:"outline",className:"text-[10px] gap-0.5",style:{borderColor:((r=n.tag)==null?void 0:r.color)||"#6366F1",color:((a=n.tag)==null?void 0:a.color)||"#6366F1"},children:(i=n.tag)==null?void 0:i.name},n.tag_id)})})}const yG=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function dWs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=NR(),a=vLe(),i=eHs(),l=JVs(),[o,c]=N.useState(""),[d,u]=N.useState(yG[0]),[h,p]=N.useState(null),[f,g]=N.useState(""),[b,v]=N.useState(""),j=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(yG[0]),Dr({title:"Tag created"})}catch(T){Dr({title:"Error",description:T.message,variant:"destructive"})}},_=async T=>{if(f.trim())try{await i.mutateAsync({id:T,name:f.trim(),color:b}),p(null),Dr({title:"Tag updated"})}catch(D){Dr({title:"Error",description:D.message,variant:"destructive"})}},S=async(T,D)=>{if(confirm(`Delete tag "${D}"? It will be removed from all contacts.`))try{await l.mutateAsync(T),Dr({title:"Tag deleted"})}catch(L){Dr({title:"Error",description:L.message,variant:"destructive"})}},A=T=>{p(T.id),g(T.name),v(T.color)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{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(ge,{placeholder:"New tag name...",value:o,onChange:T=>c(T.target.value),onKeyDown:T=>T.key==="Enter"&&j(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:j,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:yG.map(T=>e.jsx("button",{onClick:()=>u(T),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===T?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:T}},T))})]}),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(T=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:h===T.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:yG.map(D=>e.jsx("button",{onClick:()=>v(D),className:`h-5 w-5 rounded-full border-2 ${b===D?"border-foreground":"border-transparent"}`,style:{backgroundColor:D}},D))}),e.jsx(ge,{value:f,onChange:D=>g(D.target.value),onKeyDown:D=>D.key==="Enter"&&_(T.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>_(T.id),children:e.jsx(Lr,{className:"h-4 w-4 text-primary"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>p(null),children:e.jsx(Fn,{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:T.color}}),e.jsx("span",{className:"flex-1 text-sm",children:T.name}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>A(T),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>S(T.id,T.name),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})},T.id))]})]})})}function uWs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=KM(),a=k6e(),i=Xrs(),l=Jrs(),[o,c]=N.useState(""),[d,u]=N.useState(null),[h,p]=N.useState(""),f=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(j){ae.error(j.message||"Failed to add lead source")}},g=async j=>{if(h.trim())try{await i.mutateAsync({id:j,name:h.trim()}),u(null)}catch(_){ae.error(_.message||"Failed to update")}},b=async(j,_)=>{if(confirm(`Remove lead source "${_}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(j)}catch(S){ae.error(S.message||"Failed to remove")}},v=j=>{u(j.id),p(j.name)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{placeholder:"New lead source name...",value:o,onChange:j=>c(j.target.value),onKeyDown:j=>j.key==="Enter"&&f(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:f,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[360px] overflow-y-auto",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(n==null?void 0:n.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No lead sources yet. Create one above!"}),n==null?void 0:n.map(j=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===j.id?e.jsxs(e.Fragment,{children:[e.jsx(ge,{value:h,onChange:_=>p(_.target.value),onKeyDown:_=>_.key==="Enter"&&g(j.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>g(j.id),children:e.jsx(Lr,{className:"h-4 w-4 text-primary"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(null),children:e.jsx(Fn,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:j.name}),j.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>v(j),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>b(j.id,j.name),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]}),!j.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},j.id))]})]})})}function Y_t({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=KM(),a=k6e(),[i,l]=N.useState(!1),[o,c]=N.useState(""),d=async()=>{if(o.trim())try{const u=await a.mutateAsync(o.trim());u&&(t(u.id),c(""),l(!1))}catch{}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(cs,{className:"flex-1",children:e.jsx(hs,{placeholder:"Select lead source"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(Ze,{value:u.id,children:u.name},u.id))]})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx(Fn,{className:"h-4 w-4"}):e.jsx(As,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{placeholder:"New lead source name...",value:o,onChange:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())},className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function iTe({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=In(),c=fa(),[d,u]=N.useState(!1),[h,p]=N.useState(""),{data:f}=lt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:b,error:v}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(v)throw v;return b},enabled:!!t}),{data:g}=lt({queryKey:["spouse-search",c,s,h],queryFn:async()=>{let b=q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("owner_user_id",c).is("synced_source",null).neq("id",s).order("first_name").limit(20);if(h.trim()){const _=h.replace(/[,()%]/g," ").trim();_&&(b=b.or(`first_name.ilike.%${_}%,last_name.ilike.%${_}%,email.ilike.%${_}%,phone.ilike.%${_}%`))}const{data:v,error:j}=await b;if(j)throw j;return v},enabled:d&&!!c});if(t&&f){const b=`${f.first_name} ${f.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{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(Xi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${f.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:b}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[f.phone,f.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(VA,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${f.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(za,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(n||r)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{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(Xi,{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(Wo,{open:d,onOpenChange:u,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(El,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(zo,{className:"w-72 p-2",align:"end",children:e.jsx(UZe,{search:h,setSearch:p,results:g,onSelect:b=>{a(b),u(!1),p("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(Wo,{open:d,onOpenChange:u,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(El,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(zo,{className:"w-72 p-2",align:"start",children:e.jsx(UZe,{search:h,setSearch:p,results:g,onSelect:b=>{a(b),u(!1),p("")}})})]})]}):null}function UZe({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(_r,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ge,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(mi,{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 vG=new Map;async function hWs(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 mWs(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(vG.has(r))return vG.get(r)??null;try{const i=`https://gravatar.com/avatar/${await hWs(n)}?s=${t}&d=404`;return vG.set(r,i),i}catch{return vG.set(r,null),null}}function pWs(s,t=256){const[n,r]=N.useState(null);return N.useEffect(()=>{let a=!0;if(!s){r(null);return}return mWs(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function jLe({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=pWs(n?null:r,Math.max(64,a*2)),[u,h]=N.useState(!1);N.useEffect(()=>h(!1),[d]);const p=n||(u?null:d);return e.jsx("div",{className:Et("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:p?e.jsx("img",{src:p,alt:`${s??""} ${t??""}`.trim()||"Contact photo",className:"h-full w-full object-cover",loading:"lazy",onError:()=>h(!0)}):e.jsx("span",{children:o})})}const fWs=5*1024*1024;function Z_t({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=N.useRef(null),o=Gt(),[c,d]=N.useState(!1),u=()=>{o.invalidateQueries({queryKey:["innercircle-contacts"]}),o.invalidateQueries({queryKey:["innercircle-contact"]}),o.invalidateQueries({queryKey:["contact",s]})},h=async g=>{const{error:b}=await q.from("innercircle_contacts").update({avatar_url:g}).eq("id",s);if(b)throw b;u()},p=async g=>{var b;if(!g.type.startsWith("image/")){Dr({title:"Please choose an image file",variant:"destructive"});return}if(g.size>fWs){Dr({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:v}=await q.auth.getUser(),j=(b=v.user)==null?void 0:b.id,_=(g.name.split(".").pop()||"jpg").toLowerCase(),S=`contacts/${j}/${s}-${Date.now()}.${_}`,{error:A}=await q.storage.from("avatars").upload(S,g,{upsert:!0,contentType:g.type});if(A)throw A;const{data:T}=q.storage.from("avatars").getPublicUrl(S);await h(T.publicUrl),Dr({title:"Photo updated"})}catch(v){Dr({title:"Upload failed",description:v.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},f=async()=>{d(!0);try{await h(null),Dr({title:"Photo removed"})}catch(g){Dr({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(jLe,{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(ss,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(pf,{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(ss,{className:"h-5 w-5 text-background animate-spin"})})]}),r&&e.jsxs(B,{variant:"ghost",size:"sm",className:"text-muted-foreground gap-1.5",onClick:f,disabled:c,children:[e.jsx(bn,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:g=>{var v;const b=(v=g.target.files)==null?void 0:v[0];b&&p(b)}})]})}const xWs={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},gWs={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 Q_t({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:Et("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:xWs[t]})]}),e.jsx("span",{className:Et("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",gWs[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}function yWs(s,t){const n=[];if(s.daysSinceTouch===null?n.push({id:"first-touch",label:"Reach out for the first time",detail:"This contact has no logged touches yet. A single call or note starts the clock.",points:40,action:"touch"}):s.daysSinceTouch>14&&n.push({id:"recent-touch",label:"Log a touch this week",detail:`It has been ${s.daysSinceTouch} days. Touching base within 14 days earns full recency credit.`,points:Math.max(0,40-s.breakdown.recency),action:"touch"}),s.touchCountLast12Months<12){const r=12-s.touchCountLast12Months;n.push({id:"cadence",label:`Build to 12 touches a year (${r} to go)`,detail:"Monthly contact is the cadence that turns a name in your database into repeat and referral business.",points:Math.max(0,30-s.breakdown.touchpoints),action:"touch"})}return(!t.birthday||!t.home_anniversary)&&n.push({id:"dates",label:"Add their key dates",detail:!t.birthday&&!t.home_anniversary?"No birthday or home anniversary on file. Add them and the Life Event Autopilot will reach out for you.":t.birthday?"No home anniversary on file. Add it to unlock the anniversary campaign.":"No birthday on file. Add it so the birthday campaign can run automatically.",points:0,action:"edit"}),(!t.email||!t.phone)&&n.push({id:"contact-info",label:t.email?"Add a phone number":"Add an email address",detail:"Missing contact info blocks automated campaigns and quick touches.",points:0,action:"edit"}),s.hasTransaction||n.push({id:"transaction",label:"Link a past transaction",detail:"If you have closed a deal with them, connecting it adds real weight to the relationship.",points:20,action:"edit"}),n.slice(0,4)}function vWs({score:s,contact:t,onEdit:n,onLogTouch:r}){const a=yWs(s,t);return a.length===0?e.jsxs("div",{className:"mt-3 flex items-start gap-2 rounded-xl bg-emerald-500/10 px-3 py-2.5",children:[e.jsx(Lr,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This relationship is in great shape. Keep the cadence going and the score stays high."})]}):e.jsxs("div",{className:"mt-3 border-t pt-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1.5",children:[e.jsx(bw,{className:"h-3.5 w-3.5 text-amber-500"}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"How to raise this score"})]}),e.jsx("ul",{className:"space-y-2",children:a.map(i=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-primary/60"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:i.label}),i.points>0&&e.jsxs("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-semibold text-primary",children:["+",i.points]})]}),e.jsx("p",{className:"mt-0.5 text-xs leading-snug text-muted-foreground",children:i.detail}),i.action==="edit"&&n&&e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0 text-xs",onClick:n,children:"Update contact"}),i.action==="touch"&&r&&e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0 text-xs",onClick:r,children:"Log a touch"})]})]},i.id))})]})}const bWs={warm:"Strong",cooling:"Cooling off","at-risk":"Needs attention"};function _Ws({contact:s,deal:t,open:n,onOpenChange:r,onEdit:a,index:i,total:l,onPrev:o,onNext:c}){var L;const d=In(),{data:u}=XD(),h=gU(),[p,f]=N.useState(null),[g,b]=N.useState(!1),{gmailEmail:v}=bh(),j=s==null?void 0:s.spouse_contact_id,{data:_}=lt({queryKey:["innercircle-contact-spouse",j],queryFn:async()=>{const{data:M,error:F}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday, avatar_url").eq("id",j).maybeSingle();if(F)throw F;return M},enabled:!!j&&n});if(!s)return null;const S=async M=>{f(M);try{await h.mutateAsync({contactId:s.id,actionTypeId:M})}finally{f(null)}},A=`${s.first_name||""} ${s.last_name||""}`.trim();A.split(" ").filter(Boolean).map(M=>M[0]).join("").toUpperCase().slice(0,2);const T=[s.city,s.state].filter(Boolean).join(", "),D=s.relationshipScore;return e.jsxs(ug,{open:n,onOpenChange:r,children:[e.jsxs(ox,{side:"right",className:"w-full sm:max-w-md overflow-y-auto p-0",children:[(o||c)&&e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between gap-2 border-b bg-background/95 px-5 py-2 backdrop-blur",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 px-2",onClick:o,disabled:!o,children:[e.jsx(fl,{className:"h-4 w-4"}),"Prev"]}),typeof i=="number"&&typeof l=="number"&&e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:[i+1," of ",l," on this page"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 px-2",onClick:c,disabled:!c,children:["Next",e.jsx(ga,{className:"h-4 w-4"})]})]}),e.jsxs("div",{className:"p-5 space-y-5",children:[e.jsxs(r0,{className:"space-y-0 text-left",children:[e.jsx(a0,{className:"sr-only",children:A}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Z_t,{contactId:s.id,firstName:s.first_name,lastName:s.last_name,avatarUrl:s.avatar_url,email:s.email,size:56}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h2",{className:"text-lg font-bold leading-tight truncate",children:A}),e.jsxs("div",{className:"mt-1.5 space-y-1 text-sm text-muted-foreground",children:[s.email&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Hs,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pr,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:s.phone})]}),T&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ca,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:T})]})]})]})]})]}),e.jsxs("div",{className:"rounded-2xl border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Relationship Health"}),e.jsx("p",{className:"text-base font-semibold",children:bWs[D.status]??D.status}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:D.lastTouchDate?`Last touch ${ks(new Date(D.lastTouchDate),"MMM d, yyyy")}`:"Never contacted"})]}),e.jsx(Q_t,{score:D.score,status:D.status,size:64})]}),e.jsx(vWs,{score:D,contact:s,onEdit:a?()=>a(s):void 0})]}),e.jsxs("div",{className:"rounded-2xl border p-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Suggested Next Action"}),e.jsx(Bge,{contact:s})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",disabled:!s.email,onClick:()=>b(!0),children:[e.jsx(Hs,{className:"h-4 w-4"})," Email"]}),e.jsx(B,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,disabled:!s.phone,children:e.jsxs("a",{href:s.phone?`sms:${s.phone}`:void 0,children:[e.jsx(Ci,{className:"h-4 w-4"})," Text"]})}),e.jsx(B,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,disabled:!s.phone,children:e.jsxs("a",{href:s.phone?`tel:${s.phone}`:void 0,children:[e.jsx(Pr,{className:"h-4 w-4"})," Call"]})})]}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{variant:"secondary",className:"w-full gap-1.5",disabled:!!p,children:[p?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(xr,{className:"h-4 w-4"}),"Log a touch"]})}),e.jsxs(cc,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(I4,{children:"What did you do?"}),u==null?void 0:u.map(M=>e.jsx(Xr,{onClick:()=>S(M.id),children:M.name},M.id))]})]}),(t||s.tags&&s.tags.length>0)&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(aTe,{deal:t}),(L=s.tags)==null?void 0:L.map(M=>{var F;return e.jsx(ze,{variant:"secondary",className:"text-xs",children:(F=M.relationship_type)==null?void 0:F.name},M.id)})]}),(_||s.spouse_name)&&e.jsxs("div",{className:"rounded-2xl border p-4",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3 flex items-center gap-1.5",children:[e.jsx(_n,{className:"h-3.5 w-3.5"})," Spouse / Partner"]}),_?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jLe,{firstName:_.first_name,lastName:_.last_name,avatarUrl:_.avatar_url,email:_.email,size:40}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("button",{className:"font-medium hover:underline truncate block text-left",onClick:()=>d(`/mission-control/contacts/${_.id}`),children:`${_.first_name||""} ${_.last_name||""}`.trim()}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:[_.phone,_.email].filter(Boolean).join(" · ")||"No contact info"})]}),e.jsx(B,{variant:"ghost",size:"icon","aria-label":"Open spouse record",onClick:()=>d(`/mission-control/contacts/${_.id}`),children:e.jsx(tr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(yi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{children:s.spouse_name}),s.spouse_email&&e.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["· ",s.spouse_email]})]}),(s.spouse_birthday||(_==null?void 0:_.birthday))&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(hu,{className:"h-3.5 w-3.5"}),"Spouse birthday · ",ks(ll(s.spouse_birthday||_.birthday),"MMM d, yyyy")]})]}),(s.birthday||s.home_anniversary||s.created_at)&&e.jsxs("div",{className:"rounded-2xl border p-4 space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Key Dates"}),s.birthday&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(yr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Birthday · ",ks(ll(s.birthday),"MMM d, yyyy")]}),s.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(zr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Home anniversary · ",ks(ll(s.home_anniversary),"MMM d, yyyy")]}),s.created_at&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),"Added ",ks(new Date(s.created_at),"MMM d, yyyy")]})]}),s.notes&&e.jsxs("div",{className:"rounded-2xl border p-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",children:s.notes})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs(B,{className:"flex-1 gap-1.5",onClick:()=>d(`/mission-control/contacts/${s.id}`),children:[e.jsx(tr,{className:"h-4 w-4"}),"Open full record"]}),a&&e.jsx(B,{variant:"outline",size:"icon",onClick:()=>a(s),"aria-label":"Edit contact",children:e.jsx(ja,{className:"h-4 w-4"})})]})]})]}),s.email&&e.jsx(Ty,{open:g,onOpenChange:b,contact:{id:s.id,first_name:s.first_name,last_name:s.last_name,email:s.email},gmailEmail:v})]})}function wWs({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(Ac,{children:[e.jsx(Mc,{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(_n,{className:"h-3 w-3"})})}),e.jsx(yc,{children:r})]})}function X_t(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 qZe(s){if(!s)return null;const t=ll(s);if(!t)return null;const n=new Date;n.setHours(0,0,0,0);const r=new Date(n.getFullYear(),t.getMonth(),t.getDate());return rs.relationshipScore.status==="at-risk"},{key:"never-contacted",title:"Never Contacted",icon:Fo,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:gr,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:Mv,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:hu,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:zr,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:Vm,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:lc,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:un,color:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"missing-info",title:"Missing Info",icon:Dl,color:"text-slate-600 dark:text-slate-400",match:s=>X_t(s)}];function jWs({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}=bLe(),p=M_t(),f=I_t(),[g,b]=N.useState(!1),[v,j]=N.useState(""),_=N.useMemo(()=>{const D={"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 D;for(const L of s){const M={hasDeal:!!(t&&t[L.id]),daysToBirthday:qZe(L.birthday),daysToAnniv:qZe(L.home_anniversary)};for(const F of VZe)F.key!=="website-active"&&F.match(L,M)&&D[F.key]++}return D},[s,t,n]),S=!!l.search||!!l.type&&l.type!=="all"||!!l.status&&l.status!=="all"||!!l.behavior&&Object.values(l.behavior).some(D=>D!==void 0&&D!==!1),A=async()=>{v.trim()&&(await p.mutateAsync({name:v.trim(),filters:l,sort_by:o}),j(""),b(!1))},T="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:Et(T,!a&&!c?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx(_n,{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(D=>{const L=c===D.id;return e.jsxs("div",{className:Et(T,"group pr-1",L?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx("button",{type:"button",onClick:()=>d(D.id,D.filters,D.sort_by),children:D.name}),e.jsx("button",{type:"button","aria-label":`Delete view ${D.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:()=>{f.mutate(D.id),L&&u()},children:e.jsx(Fn,{className:"h-3 w-3"})})]},D.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),VZe.map(D=>{const L=D.icon,M=_[D.key],F=a===D.key;return e.jsxs("button",{type:"button",onClick:()=>i(F?null:D.key),"aria-pressed":F,className:Et(T,F?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!F&&M===0&&"opacity-55"),children:[e.jsx(L,{className:Et("h-3.5 w-3.5",F?"":D.color)}),D.title,e.jsx("span",{className:"tabular-nums opacity-70",children:M.toLocaleString()})]},D.key)}),e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 text-xs shrink-0",disabled:!S,onClick:()=>b(!0),children:[e.jsx(tL,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(bs,{open:g,onOpenChange:b,children:e.jsxs(vs,{className:"sm:max-w-sm",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Save this view"}),e.jsx(Qn,{children:"Your current search, filters, and sorting are saved as a one-click chip."})]}),e.jsx(ge,{autoFocus:!0,placeholder:"e.g. Past clients cooling off",value:v,onChange:D=>j(D.target.value),onKeyDown:D=>D.key==="Enter"&&A()}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(B,{onClick:A,disabled:!v.trim()||p.isPending,children:"Save view"})]})]})})]})}const HZe=[{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"}],MNe={relationship:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},GZe="innercircle:contact-columns:v1";function NWs(){const[s,t]=N.useState(()=>{try{const a=localStorage.getItem(GZe);if(a)return{...MNe,...JSON.parse(a)}}catch{}return MNe});N.useEffect(()=>{try{localStorage.setItem(GZe,JSON.stringify(s))}catch{}},[s]);const n=N.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=N.useCallback(()=>t(MNe),[]);return{columns:s,toggle:n,reset:r}}function kWs({columns:s,onToggle:t,onReset:n}){const r=HZe.filter(a=>s[a.key]).length;return e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(Yk,{className:"h-3.5 w-3.5"}),"Columns",e.jsx(ze,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r})]})}),e.jsxs(zo,{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(Fh,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:HZe.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(hi,{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 SWs(){var Tr;const s=In(),[t,n]=yl(),{user:r}=gs(),a=kR(),i=Gt(),{columns:l,toggle:o,reset:c}=NWs(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:p,isLoading:f}=Yye(),{activeContactIds:g,hasLeadSite:b}=pGs(),{data:v}=oWs(),{data:j}=Cy(),{data:_}=lWs(),{data:S}=NR(),{data:A}=P1e(),[T,D]=N.useState(new Set),[L,M]=N.useState("any"),F=Gye(),z=_6e(),V=w6e(),W=rpt(),[K,Y]=N.useState(""),[ee,ne]=N.useState(!1),[oe,pe]=N.useState(d||"all"),[ce,de]=N.useState(u||"all"),[ie,ye]=N.useState("date-added"),[_e,Me]=N.useState("all"),[Te,Ce]=N.useState({}),Ee=N.useMemo(()=>Object.values(Te).filter(Ot=>Ot!==void 0&&Ot!==!1&&Ot!=="").length,[Te]),[De,Ie]=N.useState(!1),{behaviorMap:Fe,hasLeadSite:qe}=sWs(),[ve,Je]=N.useState(h),[we,it]=N.useState(null),[Ne,He]=N.useState(!1),[$e,Ye]=N.useState(!1),[Ke,rt]=N.useState(null),[tt,at]=N.useState(""),[Ge,dt]=N.useState(new Set),[Bt,kt]=N.useState(!1),[Qt,ns]=N.useState(null),$s=Math.max(1,parseInt(t.get("page")||"1",10)||1),[Ds,Dt]=N.useState($s),St=N.useCallback(Ot=>{Dt(wn=>{const kr=typeof Ot=="function"?Ot(wn):Ot;return n(dr=>{const Jr=new URLSearchParams(dr);return kr<=1?Jr.delete("page"):Jr.set("page",String(kr)),Jr},{replace:!0}),kr})},[]),[$t,ht]=N.useState(50),[Ut,Es]=N.useState("my"),[Xt,Ys]=N.useState(!1),[Ss,Bs]=N.useState(!1),{data:Us}=Xv(),{addToLeadPond:sn}=cyt(Us==null?void 0:Us.teamId),Jn=!!((Tr=Us==null?void 0:Us.team)!=null&&Tr.lead_pond_enabled&&(Us!=null&&Us.teamId)),fn=!!(Us!=null&&Us.teamId),[Sn,Gn]=N.useState([]),[Hr,pi]=N.useState(!1),Ms=Ot=>{Gn([Ot]),pi(!0)},bi=Ot=>{Gn(Ot),pi(!0)},Rr=Ot=>{Us!=null&&Us.teamId&&sn.mutate({contact_id:Ot,team_id:Us.teamId})},er=Ot=>{Us!=null&&Us.teamId&&Ot.forEach(wn=>{sn.mutate({contact_id:wn,team_id:Us.teamId})})},lr=N.useCallback(Ot=>{kt(!1),dt(wn=>{const kr=new Set(wn);return kr.has(Ot)?kr.delete(Ot):kr.add(Ot),kr})},[]);N.useEffect(()=>{if(!(r!=null&&r.id))return;const Ot=q.channel(`innercircle_contacts_inserts_${r.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${r.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{q.removeChannel(Ot)}},[i,r==null?void 0:r.id]),N.useEffect(()=>{u&&de(u)},[u]);const[Fs,$n]=N.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]});N.useEffect(()=>{h&&Je(!0)},[h]),N.useEffect(()=>{var Ot;we&&$n({first_name:we.first_name||"",last_name:we.last_name||"",email:we.email||"",phone:we.phone||"",address:we.address||"",city:we.city||"",state:we.state||"",zip_code:we.zip_code||"",birthday:we.birthday||"",home_anniversary:we.home_anniversary||"",spouse_name:we.spouse_name||"",spouse_email:we.spouse_email||"",lead_source_id:we.lead_source_id||"",notes:we.notes||"",tagIds:((Ot=we.tags)==null?void 0:Ot.map(wn=>wn.relationship_type_id))||[]})},[we]);const Cr=N.useMemo(()=>{const Ot=new Set;return S==null||S.forEach(wn=>{(wn.name==="Recruits"||wn.name==="Brokerage Agents")&&Ot.add(wn.id)}),Ot},[S]),ts=N.useMemo(()=>Array.from(T).some(Ot=>Cr.has(Ot)),[T,Cr]),Oe=N.useMemo(()=>{const Ot={};return(p||[]).forEach(wn=>{Ot[wn.id]=`${wn.first_name||""} ${wn.last_name||""}`.trim()}),Ot},[p]),Qe=N.useMemo(()=>{if(!p)return[];let Ot=p.filter(dr=>{var da,jn,Aa,Yi,Bo,rl,po,zc,Sd,fm,Cd;if(!ts&&dr.synced_source)return!1;const Jr=K===""||`${dr.first_name} ${dr.last_name}`.toLowerCase().includes(K.toLowerCase())||((da=dr.email)==null?void 0:da.toLowerCase().includes(K.toLowerCase()))||((jn=dr.phone)==null?void 0:jn.includes(K))||((Aa=dr.city)==null?void 0:Aa.toLowerCase().includes(K.toLowerCase()))||((Yi=dr.state)==null?void 0:Yi.toLowerCase().includes(K.toLowerCase()))||((Bo=dr.address)==null?void 0:Bo.toLowerCase().includes(K.toLowerCase()))||((rl=dr.zip_code)==null?void 0:rl.toLowerCase().includes(K.toLowerCase())),jr=oe==="all"||((po=dr.tags)==null?void 0:po.some(Hd=>Hd.relationship_type_id===oe)),qn=T.size===0||(()=>{const Hd=(A==null?void 0:A.filter(uc=>uc.contact_id===dr.id).map(uc=>uc.tag_id))||[];return L==="any"?Hd.some(uc=>T.has(uc)):Array.from(T).every(uc=>Hd.includes(uc))})(),wi=!!((zc=dr.address)!=null&&zc.trim()||(Sd=dr.city)!=null&&Sd.trim()||(fm=dr.state)!=null&&fm.trim()||(Cd=dr.zip_code)!=null&&Cd.trim()),Oi=_e==="all"||_e==="has-address"&&wi||_e==="no-address"&&!wi,ea=dr,ya=Te,Mi=(ya.hasEmail===void 0||!!ea.email===ya.hasEmail)&&(ya.hasPhone===void 0||!!ea.phone===ya.hasPhone)&&(ya.hasAddress===void 0||wi===ya.hasAddress)&&(ya.hasBirthday===void 0||!!ea.birthday===ya.hasBirthday)&&(ya.hasSpouse===void 0||!!(ea.spouse_name||ea.spouse_contact_id||ea.spouse_email)===ya.hasSpouse)&&(ya.hasCompany===void 0||!!(ea.company_name||ea.job_title)===ya.hasCompany)&&(ya.hasNotes===void 0||!!(ea.notes&&ea.notes.trim())===ya.hasNotes)&&(!ya.city||(ea.city||"").toLowerCase().includes(ya.city.toLowerCase()))&&(!ya.state||(ea.state||"").toLowerCase().includes(ya.state.toLowerCase()))&&(!ya.zip||((ea.zip||"")+(ea.zip_code||"")).toLowerCase().includes(ya.zip.toLowerCase()))&&(!ya.birthdayMonth||!!ea.birthday&&ll(ea.birthday).getMonth()+1===ya.birthdayMonth)&&(!ya.anniversaryMonth||((ya.anniversaryField||"home_anniversary")==="home_anniversary"?!!ea.home_anniversary&&ll(ea.home_anniversary).getMonth()+1===ya.anniversaryMonth:!!ea.wedding_anniversary&&ll(ea.wedding_anniversary).getMonth()+1===ya.anniversaryMonth))&&(!ya.dateAddedFrom||!!ea.created_at&&ea.created_at.slice(0,10)>=ya.dateAddedFrom)&&(!ya.dateAddedTo||!!ea.created_at&&ea.created_at.slice(0,10)<=ya.dateAddedTo)&&(!ya.leadSourceId||ea.lead_source_id===ya.leadSourceId||!ea.lead_source_id&&ya.leadSourceId==="none");return Jr&&jr&&qn&&Oi&&Mi});ce==="not-touched-90"?Ot=Ot.filter(dr=>{const Jr=dr.relationshipScore.daysSinceTouch;return Jr===null||Jr>90}):ce==="at-risk"?Ot=Ot.filter(dr=>dr.relationshipScore.status==="at-risk"):ce==="cooling"?Ot=Ot.filter(dr=>dr.relationshipScore.status==="cooling"):ce==="warm"?Ot=Ot.filter(dr=>dr.relationshipScore.status==="warm"):ce==="has-deal"?Ot=Ot.filter(dr=>_&&_[dr.id]):ce==="no-deal"?Ot=Ot.filter(dr=>!_||!_[dr.id]):ce==="open-house"?Ot=Ot.filter(dr=>{var jr;return(((jr=dr.lead_source_ref)==null?void 0:jr.name)||dr.lead_source)==="Open House"}):ce==="website-active"?Ot=Ot.filter(dr=>g.has(dr.id)):ce==="never-contacted"?Ot=Ot.filter(dr=>dr.relationshipScore.daysSinceTouch===null):ce==="vips"?Ot=Ot.filter(dr=>dr.relationshipScore.score>=80):ce==="missing-info"?Ot=Ot.filter(dr=>X_t(dr)):ce==="birthdays-soon"?Ot=Ot.filter(dr=>{const Jr=RE(dr.birthday);return Jr!==null&&Jr<=30}):ce==="anniversary-soon"?Ot=Ot.filter(dr=>{const Jr=RE(dr.home_anniversary);return Jr!==null&&Jr<=30}):ce==="in-drip"?Ot=Ot.filter(dr=>((v==null?void 0:v[dr.id])??0)>0):ce==="not-in-drip"&&(Ot=Ot.filter(dr=>((v==null?void 0:v[dr.id])??0)===0));const wn=Te;if(wn.lastActive||wn.registered||wn.viewedListing||wn.savedProperty||wn.hasSavedSearch||wn.requestedShowing||wn.requestedValuation||wn.websiteActiveOnly){const dr=Date.now(),Jr={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};Ot=Ot.filter(jr=>{const qn=Fe.get(jr.id);if(wn.lastActive==="never"){if(qn!=null&&qn.lastActiveAt)return!1}else if(wn.lastActive){const wi=dr-Jr[wn.lastActive];if(!(qn!=null&&qn.lastActiveAt)||new Date(qn.lastActiveAt).getTime()0)||wn.viewedListing==="multiple7d"&&!(qn&&qn.propertyViewCount7d>=3)||wn.savedProperty&&!(qn&&qn.savedListingCount>0)||wn.hasSavedSearch&&!(qn&&qn.activeSavedSearchCount>0)||wn.requestedShowing&&!(qn&&qn.showingRequests>0)||wn.requestedValuation&&!(qn&&qn.valuationRequests>0)||wn.websiteActiveOnly&&!g.has(jr.id))})}return Ot=[...Ot].sort((dr,Jr)=>{switch(ie){case"important-dates":{const jr=RE(dr.birthday),qn=RE(Jr.birthday),wi=RE(dr.home_anniversary),Oi=RE(Jr.home_anniversary),ea=[jr,wi].filter(Mi=>Mi!==null).sort((Mi,da)=>(Mi??1/0)-(da??1/0))[0]??1/0,ya=[qn,Oi].filter(Mi=>Mi!==null).sort((Mi,da)=>(Mi??1/0)-(da??1/0))[0]??1/0;return ea-ya}case"last-touched":{const jr=dr.relationshipScore.lastTouchDate,qn=Jr.relationshipScore.lastTouchDate;return!jr&&!qn?0:jr?qn?new Date(jr).getTime()-new Date(qn).getTime():1:-1}case"next-touch":{const jr=dr.relationshipScore.daysSinceTouch,qn=Jr.relationshipScore.daysSinceTouch;return jr===null&&qn===null?0:jr===null?-1:qn===null?1:qn-jr}case"score":return dr.relationshipScore.score-Jr.relationshipScore.score;case"date-added":{const jr=dr.created_at,qn=Jr.created_at;return!jr&&!qn?0:jr?qn?new Date(qn).getTime()-new Date(jr).getTime():-1:1}case"last-name":{const jr=(dr.last_name||"").toLowerCase(),qn=(Jr.last_name||"").toLowerCase();if(jr!==qn)return jr.localeCompare(qn);const wi=(dr.first_name||"").toLowerCase(),Oi=(Jr.first_name||"").toLowerCase();return wi.localeCompare(Oi)}case"name":default:{const jr=`${dr.first_name||""} ${dr.last_name||""}`.toLowerCase(),qn=`${Jr.first_name||""} ${Jr.last_name||""}`.toLowerCase();return jr.localeCompare(qn)}}}),Ot},[p,K,oe,T,L,ce,ie,_,A,g,v,_e,Te,Fe,ts]),ct=Qe.length,vt=Math.max(1,Math.ceil(ct/$t)),It=Math.min(Ds,vt),qt=N.useMemo(()=>{const Ot=(It-1)*$t;return Qe.slice(Ot,Ot+$t)},[Qe,It,$t]),xs=N.useRef(!1);N.useEffect(()=>{if(!xs.current){xs.current=!0;return}St(1)},[K,oe,T,L,ce,ie,_e,Te]);const as=N.useCallback(()=>{kt(!1),dt(Ot=>Ot.size>0?new Set:new Set(qt.map(wn=>wn.id)))},[qt]),Ns=N.useCallback(()=>{kt(!0),dt(new Set(Qe.map(Ot=>Ot.id)))},[Qe]),[ln,Ks]=N.useState(null),Un=N.useCallback((Ot,wn)=>{Y(Ot.search||""),pe(Ot.type||"all"),de(Ot.status||"all"),Ce(Ot.behavior||{}),ye(wn||"name")},[]),br=()=>{$n({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},Ar=async Ot=>{Ot.preventDefault();const wn={...Fs,lead_source_id:Fs.lead_source_id||null};we?(await z.mutateAsync({id:we.id,...wn}),it(null)):(await F.mutateAsync(wn),Je(!1)),br()},sr=async Ot=>{confirm("Are you sure you want to delete this contact?")&&await V.mutateAsync(Ot)};return e.jsx(Cs,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Contacts"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),Us&&e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsx("button",{onClick:()=>Es("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Ut==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Contacts"}),(Us.team.contact_visibility==="full_team"||Us.team.contact_visibility==="leader_only"&&Us.role==="team_leader")&&e.jsxs("button",{onClick:()=>Es("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${Ut==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(_n,{className:"h-3.5 w-3.5"}),"Team"]}),Us.team.lead_pond_enabled&&e.jsxs("button",{onClick:()=>Es("lead-pond"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${Ut==="lead-pond"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(pb,{className:"h-3.5 w-3.5"}),"Lead Pond"]})]})]}),e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(fl,{className:"h-4 w-4 mr-1"}),"Back"]})}),Ut==="team"?e.jsx(JIe,{}):Ut==="lead-pond"&&Us?e.jsx(ePe,{teamId:Us.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(jWs,{contacts:p,contactDealsMap:_,websiteActiveIds:g,totalCount:(p||[]).length,activeViewId:ln,currentFilters:{search:K,type:oe,status:ce,behavior:Te},currentSortBy:ie,onApplyView:(Ot,wn,kr)=>{Ks(Ot),Un(wn,kr),St(1)},onClearAll:()=>{Ks(null),Un({search:"",type:"all",status:"all",behavior:{}},"name"),St(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"}[ce]??null,onSelectSegment:Ot=>{const kr=Ot?{"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"}[Ot]:"all";de(kr),St(1)}}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs("div",{className:"p-3 sm:p-4 bg-background",children:[e.jsxs("div",{className:"sm:hidden space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search contacts...",value:K,onChange:Ot=>Y(Ot.target.value),className:"pl-9 h-10 rounded-xl bg-muted/40"})]}),e.jsxs(ug,{children:[e.jsx(oU,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl relative shrink-0","aria-label":"Filters",children:[e.jsx(c4,{className:"h-4 w-4"}),(()=>{const Ot=(oe!=="all"?1:0)+(ce!=="all"?1:0)+(_e!=="all"?1:0)+T.size+Ee;return Ot>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:Ot}):null})()]})}),e.jsxs(ox,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(r0,{className:"text-left",children:e.jsx(a0,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(us,{value:oe,onValueChange:pe,children:[e.jsx(cs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(hs,{placeholder:"All Types"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),j==null?void 0:j.filter(Ot=>Ot.active).map(Ot=>e.jsx(Ze,{value:Ot.id,children:Ot.name},Ot.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(us,{value:ce,onValueChange:de,children:[e.jsx(cs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(hs,{placeholder:"All Status"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Status"}),e.jsx(Ze,{value:"warm",children:"🟢 Warm"}),e.jsx(Ze,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Ze,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Ze,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Ze,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Ze,{value:"open-house",children:"🏠 Open House"}),b&&e.jsx(Ze,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Ze,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Ze,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(us,{value:_e,onValueChange:Ot=>Me(Ot),children:[e.jsx(cs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(hs,{placeholder:"All Addresses"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Addresses"}),e.jsx(Ze,{value:"has-address",children:"Has Address"}),e.jsx(Ze,{value:"no-address",children:"No Address"})]})]})]}),S&&S.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{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:()=>M("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${L==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>M("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${L==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(Ot=>{const wn=T.has(Ot.id);return e.jsxs("button",{onClick:()=>{D(kr=>{const dr=new Set(kr);return dr.has(Ot.id)?dr.delete(Ot.id):dr.add(Ot.id),dr})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${wn?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:Ot.color}}),Ot.name]},Ot.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(us,{value:ie,onValueChange:ye,children:[e.jsx(cs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"name",children:"Name (A-Z)"}),e.jsx(Ze,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(Ze,{value:"important-dates",children:"Important Dates"}),e.jsx(Ze,{value:"last-touched",children:"Last Touched"}),e.jsx(Ze,{value:"next-touch",children:"Next Touch Due"}),e.jsx(Ze,{value:"score",children:"Relationship Score"}),e.jsx(Ze,{value:"date-added",children:"Date Added"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs(B,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Ie(!0),children:[e.jsx(un,{className:"h-4 w-4"})," Advanced"]}),e.jsxs(B,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Ys(!0),children:[e.jsx(mh,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(OZe,{currentFilters:{search:K,type:oe,status:ce,behavior:Te},currentSortBy:ie,onApplySmartList:Un})}),e.jsx(B,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{pe("all"),de("all"),Me("all"),D(new Set),Ce({})},children:"Clear all filters"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{onClick:()=>Je(!0),className:"h-11 rounded-xl",children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Add Contact"]}),e.jsxs(B,{onClick:()=>ne(!0),className:"h-11 rounded-xl bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white border-0",children:[e.jsx(_c,{className:"h-4 w-4 mr-1.5"})," Heat Map"]})]}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full h-10 rounded-xl gap-2",children:[e.jsx(Sa,{className:"h-4 w-4"})," Import & Sync"]})}),e.jsxs(cc,{align:"center",className:"w-[calc(100vw-2rem)] max-w-sm",children:[e.jsxs(Xr,{onClick:()=>He(!0),children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(Xr,{onClick:()=>Ye(!0),children:[e.jsx(rg,{className:"h-4 w-4 mr-2"})," Import from Phone"]}),e.jsx("div",{className:"px-1 py-1 [&_button]:w-full [&_button]:justify-start [&_button]:h-9",children:e.jsx(LZe,{})})]})]})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[280px]",children:[e.jsx(_r,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name, email, or phone...",value:K,onChange:Ot=>Y(Ot.target.value),className:"pl-10 h-10 rounded-xl bg-muted/40 border-border focus-visible:ring-primary/20"})]}),e.jsxs("div",{className:"inline-flex items-center gap-1 p-1 bg-muted rounded-xl border border-border",children:[e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold rounded-lg bg-background shadow-sm text-foreground",children:[e.jsx(_n,{className:"h-3.5 w-3.5"}),"Grid"]}),e.jsxs("button",{type:"button",onClick:()=>ne(!0),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg text-muted-foreground hover:text-foreground hover:bg-background/60 transition-colors",children:[e.jsx(_c,{className:"h-3.5 w-3.5 text-orange-600"}),"Heat Map"]})]}),e.jsxs("div",{className:"inline-flex rounded-xl overflow-hidden shadow-sm",children:[e.jsxs(B,{onClick:()=>Je(!0),className:"rounded-none rounded-l-xl h-10 px-4 gap-2 shadow-none",children:[e.jsx(As,{className:"h-4 w-4"}),"Add Contact"]}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{className:"rounded-none rounded-r-xl h-10 px-2.5 border-l border-primary-foreground/20 shadow-none","aria-label":"More import options",children:e.jsx(ga,{className:"h-4 w-4 rotate-90"})})}),e.jsxs(cc,{align:"end",children:[e.jsxs(Xr,{onClick:()=>He(!0),children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Import CSV"]}),e.jsxs(Xr,{onClick:()=>Ye(!0),children:[e.jsx(rg,{className:"h-4 w-4 mr-2"}),"Import from Phone"]})]})]})]}),e.jsx(LZe,{}),e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(zv,{className:"h-4 w-4"})})}),e.jsxs(zo,{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(Ot=>e.jsx("button",{onClick:()=>ye(Ot.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${ie===Ot.v?"bg-accent font-medium text-primary":""}`,children:Ot.l},Ot.v))]})]})]})]}),e.jsxs("div",{className:"hidden sm:flex px-3 sm:px-4 py-3 bg-muted/40 border-t flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(us,{value:oe,onValueChange:pe,children:[e.jsx(cs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(hs,{placeholder:"All Types"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),j==null?void 0:j.filter(Ot=>Ot.active).map(Ot=>e.jsx(Ze,{value:Ot.id,children:Ot.name},Ot.id))]})]}),e.jsxs(us,{value:ce,onValueChange:de,children:[e.jsx(cs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(hs,{placeholder:"All Status"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Status"}),e.jsx(Ze,{value:"warm",children:"🟢 Warm"}),e.jsx(Ze,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Ze,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Ze,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Ze,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Ze,{value:"open-house",children:"🏠 Open House"}),b&&e.jsx(Ze,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Ze,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Ze,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(us,{value:_e,onValueChange:Ot=>Me(Ot),children:[e.jsx(cs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(hs,{placeholder:"All Addresses"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Addresses"}),e.jsx(Ze,{value:"has-address",children:"Has Address"}),e.jsx(Ze,{value:"no-address",children:"No Address"})]})]}),S&&S.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(Wo,{children:[e.jsx(Ko,{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(mh,{className:"h-3.5 w-3.5"}),T.size===0?"Filter by Tags":`${T.size} tag${T.size>1?"s":""}`]})}),e.jsx(zo,{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:()=>M("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${L==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>M("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${L==="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:S.map(Ot=>{const wn=T.has(Ot.id);return e.jsxs("button",{onClick:()=>{D(kr=>{const dr=new Set(kr);return dr.has(Ot.id)?dr.delete(Ot.id):dr.add(Ot.id),dr})},className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx(hi,{checked:wn,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:Ot.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:Ot.name})]},Ot.id)})}),T.size>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>D(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(jc,{children:[e.jsx(Nc,{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(Vo,{className:"h-3.5 w-3.5"})})}),e.jsxs(cc,{align:"end",children:[e.jsxs(Xr,{onClick:()=>Ys(!0),children:[e.jsx(mh,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(Xr,{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(OZe,{currentFilters:{search:K,type:oe,status:ce,behavior:Te},currentSortBy:ie,onApplySmartList:Un}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 h-8 rounded-lg border-[#2a4c64]/20 text-[#2a4c64] hover:bg-[#2a4c64]/5 hover:text-[#2a4c64]",onClick:()=>Ie(!0),children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"Advanced Filters",Ee>0&&e.jsx(ze,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Ee})]}),e.jsx(kWs,{columns:l,onToggle:o,onReset:c})]})]}),Ee>0&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx(eWs,{behavior:Te,onRemove:Ot=>Ce(wn=>{const kr={...wn};return delete kr[Ot],kr}),onClearAll:()=>Ce({})})})]}),e.jsx(JGs,{open:De,onOpenChange:Ie,hasLeadSite:qe||b,behavior:Te,onApply:Ce,selectedType:oe,onSelectedTypeChange:pe,relationshipTypes:j}),e.jsx(QGs,{selectedIds:Ge,contacts:Qe,onClearSelection:()=>{dt(new Set),kt(!1)},showLeadPondAction:Jn,onSendToLeadPond:er,showTransferAction:fn,onTransfer:bi}),Ge.size>0&&Ge.size===qt.length&&!Bt&&ct>$t&&e.jsxs("div",{className:"flex items-center justify-center gap-2 p-2 bg-primary/5 border border-primary/20 rounded-lg text-sm",children:[e.jsxs("span",{children:["All ",qt.length," contacts on this page are selected."]}),e.jsxs(B,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:Ns,children:["Select all ",ct.toLocaleString()," matching contacts"]})]}),Bt&&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 ",ct.toLocaleString()," matching contacts are selected.",e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{dt(new Set),kt(!1)},children:"Clear selection"})]}),ct>$t&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-2 py-1",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Showing ",(It-1)*$t+1,"–",Math.min(It*$t,ct)," of ",ct.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",disabled:It<=1,onClick:()=>St(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:It<=1,onClick:()=>St(Ot=>Ot-1),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",It," of ",vt]}),e.jsx(B,{variant:"outline",size:"sm",disabled:It>=vt,onClick:()=>St(Ot=>Ot+1),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:It>=vt,onClick:()=>St(vt),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:f?e.jsx(fe,{className:"p-6 text-center text-muted-foreground",children:"Loading contacts..."}):Qe.length===0?e.jsx(fe,{className:"p-6 text-center text-muted-foreground",children:K||oe!=="all"||ce!=="all"||_e!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"}):qt.map(Ot=>{var kr,dr,Jr;const{relationshipScore:wn}=Ot;return e.jsx(fe,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>{const jr=new URLSearchParams;K&&jr.set("search",K),oe!=="all"&&jr.set("type",oe),ce!=="all"&&jr.set("filter",ce),T.size>0&&(jr.set("tags",Array.from(T).join(",")),jr.set("tagMode",L));const qn=jr.toString();s(`/mission-control/contacts/${Ot.id}${qn?`?${qn}`:""}`)},children:e.jsx(Ae,{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:[Ot.first_name," ",Ot.last_name]}),e.jsx(BZe,{count:(v==null?void 0:v[Ot.id])??0}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[Ot.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Hs,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:Ot.email})]}),Ot.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Pr,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Ot.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(rTe,{score:wn,size:"sm"}),e.jsx(Bge,{contact:Ot}),(((kr=Ot.lead_source_ref)==null?void 0:kr.name)||Ot.lead_source)&&e.jsx(ze,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((dr=Ot.lead_source_ref)==null?void 0:dr.name)||Ot.lead_source}),(Jr=Ot.tags)==null?void 0:Jr.map(jr=>{var qn;return e.jsx(ze,{variant:"secondary",className:"text-xs",children:(qn=jr.relationship_type)==null?void 0:qn.name},jr.id)}),e.jsx($Ze,{contactId:Ot.id,tags:A==null?void 0:A.filter(jr=>jr.contact_id===Ot.id)}),e.jsx(aTe,{deal:_==null?void 0:_[Ot.id]})]}),e.jsx(zZe,{birthday:Ot.birthday,homeAnniversary:Ot.home_anniversary,weddingAnniversary:Ot.wedding_anniversary,className:"mb-2",contactId:Ot.id,contactName:`${Ot.first_name}${Ot.last_name?" "+Ot.last_name:""}`,contactAddress:[Ot.address,Ot.city,Ot.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[wn.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),ks(new Date(wn.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),Ot.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),ks(ll(Ot.birthday),"MMM d")]}),Ot.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(zr,{className:"h-3 w-3"}),ks(ll(Ot.home_anniversary),"MMM d")]}),Ot.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(As,{className:"h-3 w-3"}),"Added ",ks(new Date(Ot.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:jr=>jr.stopPropagation(),children:e.jsx(RZe,{contact:Ot,onEdit:it,onDelete:sr,onSnooze:(jr,qn)=>{rt(jr),at(qn)},showLeadPondAction:Jn,onSendToLeadPond:Rr,showTransferAction:fn,onTransfer:Ms})})]})})},Ot.id)})}):e.jsx(fe,{children:e.jsx(Ae,{className:"p-0 overflow-x-auto",children:e.jsxs(ha,{className:"min-w-[800px]",children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-[40px]",children:e.jsx(hi,{checked:qt.length>0&&qt.every(Ot=>Ge.has(Ot.id)),onCheckedChange:()=>as()})}),e.jsx(Ct,{children:e.jsxs("button",{onClick:()=>ye(Ot=>Ot==="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",ie==="name"&&e.jsx(ga,{className:"h-3 w-3 rotate-90 text-primary"}),ie==="last-name"&&e.jsx(ga,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Ct,{children:"Relationship"}),l.stage&&e.jsx(Ct,{children:"Stage"}),l.leadSource&&e.jsx(Ct,{children:"Lead Source"}),l.tags&&e.jsx(Ct,{children:"Tags"}),l.lastTouch&&e.jsx(Ct,{children:"Last Touch"}),l.nextAction&&e.jsx(Ct,{children:"Next Action"}),l.dealValue&&e.jsx(Ct,{title:"Total value of deals linked to this contact in your pipeline",children:"Pipeline Value"}),l.email&&e.jsx(Ct,{children:"Email"}),l.phone&&e.jsx(Ct,{children:"Phone"}),l.address&&e.jsx(Ct,{children:"Address"}),l.birthday&&e.jsx(Ct,{children:"Birthday"}),e.jsx(Ct,{className:"w-[50px]"})]})}),e.jsx(pa,{children:f?e.jsx(Gs,{children:e.jsx(ut,{colSpan:3+Object.values(l).filter(Boolean).length,className:"text-center py-8",children:"Loading contacts..."})}):Qe.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:3+Object.values(l).filter(Boolean).length,className:"text-center py-8 text-muted-foreground",children:K||oe!=="all"||ce!=="all"||_e!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"})}):qt.map(Ot=>{var dr;const{relationshipScore:wn}=Ot,kr=_==null?void 0:_[Ot.id];return e.jsxs(Gs,{className:`cursor-pointer hover:bg-accent/50 ${Ge.has(Ot.id)?"bg-accent/30":""}`,onClick:()=>ns(Ot),children:[e.jsx(ut,{onClick:Jr=>Jr.stopPropagation(),children:e.jsx(hi,{checked:Ge.has(Ot.id),onCheckedChange:()=>lr(Ot.id)})}),e.jsx(ut,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jLe,{firstName:Ot.first_name,lastName:Ot.last_name,avatarUrl:Ot.avatar_url,email:Ot.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:[Ot.first_name," ",Ot.last_name]}),e.jsx(wWs,{linked:!!Ot.spouse_contact_id||!!Ot.spouse_name,spouseName:Ot.spouse_contact_id&&Oe[Ot.spouse_contact_id]||Ot.spouse_name||null}),e.jsx(BZe,{count:(v==null?void 0:v[Ot.id])??0})]}),Ot.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ot.email}),Ot.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Ot.phone})]})]})}),l.relationship&&e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(Q_t,{score:wn.score,status:wn.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:wn.status==="warm"?"Strong":wn.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:wn.daysSinceTouch===null?"Never contacted":wn.daysSinceTouch===0?"Touched today":`${wn.daysSinceTouch}d since touch`})]})]})}),l.stage&&e.jsx(ut,{children:e.jsx(aTe,{deal:kr})}),l.leadSource&&e.jsx(ut,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((dr=Ot.lead_source_ref)==null?void 0:dr.name)||Ot.lead_source||"—"}),l.tags&&e.jsx(ut,{children:e.jsx("div",{className:"flex flex-wrap items-center gap-1 max-w-[220px]",children:e.jsx($Ze,{contactId:Ot.id,tags:A==null?void 0:A.filter(Jr=>Jr.contact_id===Ot.id)})})}),l.lastTouch&&e.jsx(ut,{children:wn.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),ks(new Date(wn.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-xs italic text-muted-foreground",children:"No activity"})}),l.nextAction&&e.jsx(ut,{children:e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(Bge,{contact:Ot}),e.jsx(zZe,{birthday:Ot.birthday,homeAnniversary:Ot.home_anniversary,weddingAnniversary:Ot.wedding_anniversary,contactId:Ot.id,contactName:`${Ot.first_name}${Ot.last_name?" "+Ot.last_name:""}`,contactAddress:[Ot.address,Ot.city,Ot.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(ut,{children:(()=>{const Jr=(kr==null?void 0:kr.sale_price)??(kr==null?void 0:kr.expected_price);return Jr?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:gc(Number(Jr))}),(kr==null?void 0:kr.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(kr.deal_type).replace(/_/g," ")})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})})()}),l.email&&e.jsx(ut,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:Ot.email||"—"}),l.phone&&e.jsx(ut,{className:"text-sm text-muted-foreground whitespace-nowrap",children:Ot.phone||"—"}),l.address&&e.jsx(ut,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[Ot.address,Ot.city,Ot.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(ut,{className:"text-sm text-muted-foreground whitespace-nowrap",children:Ot.birthday?(()=>{const[Jr,jr,qn]=String(Ot.birthday).split(/[-/T]/).map(Number);return jr&&qn?`${jr}/${qn}${Jr&&Jr>1900?`/${Jr}`:""}`:"—"})():"—"}),e.jsx(ut,{onClick:Jr=>Jr.stopPropagation(),children:e.jsx(RZe,{contact:Ot,onEdit:it,onDelete:sr,onSnooze:(Jr,jr)=>{rt(Jr),at(jr)},showLeadPondAction:Jn,onSendToLeadPond:Rr,showTransferAction:fn,onTransfer:Ms})})]},Ot.id)})})]})})}),e.jsx(_Ws,{contact:Qt,deal:Qt?_==null?void 0:_[Qt.id]:void 0,open:!!Qt,onOpenChange:Ot=>{Ot||ns(null)},onEdit:Ot=>{ns(null),it(Ot)},index:Qt?qt.findIndex(Ot=>Ot.id===Qt.id):void 0,total:qt.length,onPrev:(()=>{if(!Qt)return;const Ot=qt.findIndex(wn=>wn.id===Qt.id);return Ot>0?()=>ns(qt[Ot-1]):void 0})(),onNext:(()=>{if(!Qt)return;const Ot=qt.findIndex(wn=>wn.id===Qt.id);return Ot>=0&&Otns(qt[Ot+1]):void 0})()}),ct>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 ",(It-1)*$t+1,"–",Math.min(It*$t,ct)," of ",ct.toLocaleString()," contacts"]}),e.jsxs(us,{value:String($t),onValueChange:Ot=>{ht(Number(Ot)),St(1)},children:[e.jsx(cs,{className:"w-[80px] h-8",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"50",children:"50"}),e.jsx(Ze,{value:"100",children:"100"}),e.jsx(Ze,{value:"250",children:"250"})]})]}),e.jsx("span",{className:"text-xs",children:"per page"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",disabled:It<=1,onClick:()=>St(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:It<=1,onClick:()=>St(Ot=>Ot-1),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",It," of ",vt]}),e.jsx(B,{variant:"outline",size:"sm",disabled:It>=vt,onClick:()=>St(Ot=>Ot+1),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:It>=vt,onClick:()=>St(vt),children:"Last"})]})]}),e.jsx(bs,{open:ve||!!we,onOpenChange:Ot=>{Ot||(Je(!1),it(null),br())},children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:we?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:Ar,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"first_name",children:"First Name *"}),e.jsx(ge,{id:"first_name",value:Fs.first_name,onChange:Ot=>$n({...Fs,first_name:Ot.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"last_name",children:"Last Name"}),e.jsx(ge,{id:"last_name",value:Fs.last_name,onChange:Ot=>$n({...Fs,last_name:Ot.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ge,{id:"email",type:"email",value:Fs.email,onChange:Ot=>$n({...Fs,email:Ot.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone"}),e.jsx(ge,{id:"phone",value:Fs.phone,onChange:Ot=>$n({...Fs,phone:Ot.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"address",children:"Address"}),e.jsx(ge,{id:"address",value:Fs.address,onChange:Ot=>$n({...Fs,address:Ot.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(ge,{id:"city",value:Fs.city,onChange:Ot=>$n({...Fs,city:Ot.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ge,{id:"state",value:Fs.state,onChange:Ot=>$n({...Fs,state:Ot.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"zip_code",children:"Zip"}),e.jsx(ge,{id:"zip_code",value:Fs.zip_code,onChange:Ot=>$n({...Fs,zip_code:Ot.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"birthday",children:"Birthday"}),e.jsx(ge,{id:"birthday",type:"date",value:Fs.birthday,onChange:Ot=>$n({...Fs,birthday:Ot.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(ge,{id:"home_anniversary",type:"date",value:Fs.home_anniversary,onChange:Ot=>$n({...Fs,home_anniversary:Ot.target.value})})]})]}),we&&e.jsx(iTe,{contactId:we.id,currentSpouseContactId:(we==null?void 0:we.spouse_contact_id)||null,currentSpouseName:(we==null?void 0:we.spouse_name)||null,currentSpouseEmail:(we==null?void 0:we.spouse_email)||null,onLink:Ot=>W.mutate({contactId:we.id,spouseContactId:Ot}),onUnlink:()=>W.mutate({contactId:we.id,spouseContactId:null}),isEditing:!0}),e.jsx(Y_t,{value:Fs.lead_source_id,onChange:Ot=>$n({...Fs,lead_source_id:Ot})}),e.jsxs("div",{children:[e.jsx(se,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:j==null?void 0:j.filter(Ot=>Ot.active).map(Ot=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(hi,{checked:Fs.tagIds.includes(Ot.id),onCheckedChange:wn=>{$n(wn?{...Fs,tagIds:[...Fs.tagIds,Ot.id]}:{...Fs,tagIds:Fs.tagIds.filter(kr=>kr!==Ot.id)})}}),e.jsx("span",{className:"text-sm",children:Ot.name})]},Ot.id))})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Ts,{id:"notes",value:Fs.notes,onChange:Ot=>$n({...Fs,notes:Ot.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{Je(!1),it(null),br()},children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:F.isPending||z.isPending,children:[we?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(yGs,{open:Ne,onOpenChange:He,relationshipTypes:(j==null?void 0:j.filter(Ot=>Ot.active))||[],onSuccess:()=>{He(!1)}}),e.jsx(_Gs,{open:$e,onOpenChange:Ye,onComplete:()=>Ye(!1)}),e.jsx(L1e,{open:!!Ke,onOpenChange:Ot=>{Ot||rt(null)},contactId:Ke||"",contactName:tt}),e.jsx(dWs,{open:Xt,onOpenChange:Ys}),e.jsx(uWs,{open:Ss,onOpenChange:Bs}),e.jsx(iWs,{open:ee,onOpenChange:ne,contacts:p||[],onCitySelect:Ot=>{Y(Ot),St(1)}}),e.jsx(dyt,{open:Hr,onOpenChange:pi,contactIds:Sn,contactNames:Sn.map(Ot=>{const wn=Qe.find(kr=>kr.id===Ot);return wn?`${wn.first_name} ${wn.last_name||""}`.trim():""}),onComplete:()=>{Gn([]),dt(new Set),kt(!1)}})]})]})})}const CWs="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function TWs({open:s,onOpenChange:t,contact:n}){var W;const{user:r}=gs(),a=In(),i=Gt(),{intakePage:l,isLoading:o}=D1e(),{isGmailConnected:c,gmailEmail:d}=bh(),u=gU(),{data:h}=lt({queryKey:["profile-for-invite",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&s,queryFn:async()=>{const{data:K}=await q.from("profiles").select("name, email, avatar_url").eq("id",r.id).maybeSingle();return K}}),p=(h==null?void 0:h.name)||((W=r==null?void 0:r.email)==null?void 0:W.split("@")[0])||"Your Agent",f=p.split(" ")[0],g=l?`https://contacts.relevelup.com/${l.slug}`:"",b=N.useMemo(()=>`Hi ${n.first_name}, I'm updating my contact list and want to make sure I have your latest info — the best phone, email, address, and a couple of dates I love to remember (like your birthday and home anniversary). It only takes about a minute, and it helps me stay in touch the right way. Thanks so much!`,[n.first_name]),[v,j]=N.useState("gmail"),[_,S]=N.useState(""),[A,T]=N.useState(""),[D,L]=N.useState(!1);N.useEffect(()=>{s&&(S(`Quick favor, ${n.first_name} — can you update your info?`),T(b),j(c?"gmail":"system"))},[s,b,n.first_name,c]);const M=N.useMemo(()=>A.split(/\n\n+/).map(K=>`

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

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

A note from ${p}

${M}

Update Your Info

Takes about a minute — promise

Share My Info →

${g}

Sent with care by ${p}

Powered by ReLevelUp

`,z=async()=>{if(!l){ae.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!_.trim()||!A.trim()){ae.error("Subject and message are required");return}L(!0);const K=F();try{if(v==="gmail"&&c){const{data:Y,error:ee}=await q.functions.invoke("gmail-send",{body:{to:n.email,subject:_,body:K,contactId:n.id}});if(ee)throw ee;if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Failed to send")}else{const{data:Y,error:ee}=await q.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:_,htmlBody:K,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:p}});if(ee)throw ee;if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Failed to send")}try{await u.mutateAsync({contactId:n.id,actionTypeId:CWs,notes:`Sent Connect Page invite — Subject: "${_}"`})}catch(Y){console.warn("Failed to log activity:",Y)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),ae.success("Connect Page invite sent!"),t(!1)}catch(Y){console.error("Send error:",Y),ae.error(Y instanceof Error?Y.message:"Failed to send invite")}finally{L(!1)}},V=F();return e.jsx(bs,{open:s,onOpenChange:K=>!D&&t(K),children:e.jsxs(vs,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Send Connect Page Invite"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ask ",e.jsxs("span",{className:"font-medium",children:[n.first_name," ",n.last_name||""]})," to share their latest contact info — takes them about a minute."]})]}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx($r,{value:v,onValueChange:K=>j(K),className:"mt-1.5",children:e.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"gmail",disabled:!c,children:[e.jsx(Hs,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Zt,{value:"system",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"}),"System Email"]})]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:v==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(h==null?void 0:h.email)||(r==null?void 0:r.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(ge,{id:"invite-subject",value:_,onChange:K=>S(K.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Ts,{id:"invite-message",value:A,onChange:K=>T(K.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(se,{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(tr,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden bg-muted/30",children:e.jsx("iframe",{srcDoc:V,title:"Email preview",sandbox:"",className:"w-full h-[420px] bg-background"})})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:D,children:"Cancel"}),e.jsx(B,{onClick:z,disabled:D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(Gi,{className:"h-10 w-10 text-amber-500 mx-auto"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"You haven't set up a Connect Page yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create yours in one click — it only takes a moment."})]}),e.jsxs(B,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(El,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function EWs(){const{user:s}=gs();return lt({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function AWs(s){return lt({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:n}=await q.from("cmas").select("*").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function MWs(s){return lt({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:n}=await q.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function J_t(){const s=Gt(),{user:t}=gs(),{leadSite:n}=Pp();return gt({mutationFn:async r=>{const{data:a,error:i}=await q.from("cmas").insert({agent_id:t.id,lead_site_id:(n==null?void 0:n.id)??null,contact_id:r.contactId??null,deal_id:r.dealId??null,buyer_mode:!!r.buyerMode,title:r.title??r.subject.address,subject:r.subject,settings:{sqftPct:.2,monthsBack:6,statuses:["Active","Pending","Closed"]}}).select("*").single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function IWs(){const s=Gt();return gt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await q.from("cmas").update(n).eq("id",t).select("*").single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cma",n.id]}),s.invalidateQueries({queryKey:["cmas"]})}})}function PWs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function LWs(){const{leadSite:s}=Pp();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function DWs(){const{leadSite:s}=Pp();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function RWs(){const s=Gt();return gt({mutationFn:async({cmaId:t,comps:n})=>{if(await q.from("cma_comps").delete().eq("cma_id",t),!n.length)return;const r=n.map((i,l)=>({cma_id:t,mls_number:i.mlsNumber??null,source_provider:i.source_provider??null,selected:i.selected!==!1,manual:!!i.manual,score:i.score??null,position:l,snapshot:i})),{error:a}=await q.from("cma_comps").insert(r);if(a)throw a},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["cma-comps",n.cmaId]})})}function WZe(s,t){const n=t.filter(h=>{var p,f;return h.selected!==!1&&(((p=h.snapshot)==null?void 0:p.sqft)||h.sqft)&&(((f=h.snapshot)==null?void 0:f.price)||h.price)});if(!n.length||!s.sqft)return{low:null,likely:null,high:null,ppsf:null};const r=n.map(h=>{const p=h.snapshot||h;return(p.soldPrice||p.price)/p.sqft}).filter(h=>Number.isFinite(h)&&h>0).sort((h,p)=>h-p);if(!r.length)return{low:null,likely:null,high:null,ppsf:null};const a=r[Math.floor(r.length/2)],i=r.reduce((h,p)=>h+p,0)/r.length,l=r.reduce((h,p)=>h+(p-i)**2,0)/r.length,o=Math.sqrt(l),c=Math.round(a*s.sqft),d=Math.round((a-o)*s.sqft),u=Math.round((a+o)*s.sqft);return{low:d,likely:c,high:u,ppsf:Math.round(a)}}function OWs(s){return lt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function FWs(s){return lt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function NLe(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("client_portals").insert({deal_id:n.deal_id,owner_user_id:s,slug:"",is_enabled:n.is_enabled??!0,visibility:n.visibility||"private",require_onboarding:n.require_onboarding??!0,allow_spouse:n.allow_spouse??!1,client_name:n.client_name||null,client_email:n.client_email||null,client_phone:n.client_phone||null,invite_method:n.invite_method||"email"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["client-portal",r.deal_id]})}})}function SR(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("client_portals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function ewt(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("client_portals").update({archived_at:new Date().toISOString(),is_enabled:!1}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function twt(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("client_portals").update({archived_at:null}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function swt(){const s=Gt();return gt({mutationFn:async({id:t,dealId:n})=>{await q.from("portal_updates").delete().eq("portal_id",t);const{error:r}=await q.from("client_portals").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function zWs(s){return lt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function nwt(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("portal_updates").insert({portal_id:t.portal_id,title:t.title,content:t.content||null,video_url:t.video_url||null,is_stage_change:t.is_stage_change||!1}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-updates",n.portal_id]})}})}function BWs(){const s=fa();return lt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",s).eq("is_active",!0).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function $Ws(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("portal_custom_questions").insert({owner_user_id:s,question_text:n.question_text,field_type:n.field_type,options:n.options||[],is_required:n.is_required||!1,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function UWs(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("portal_custom_questions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function qWs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function Ew(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function VWs({contactId:s}){const t=In(),n=Gt(),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(null),b=SR(),v=nwt(),{data:j,isLoading:_}=lt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:M,error:F}=await q.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(F)throw F;if(!M||M.length===0)return[];const z=M.map(K=>K.id),{data:V,error:W}=await q.from("client_portals").select("*").in("deal_id",z).is("archived_at",null);if(W)throw W;return(V||[]).map(K=>({...K,deal:M.find(Y=>Y.id===K.deal_id)}))},enabled:!!s}),S=(j==null?void 0:j.map(M=>M.id))||[],{data:A}=lt({queryKey:["contact-portal-updates",S],queryFn:async()=>{if(S.length===0)return{};const{data:M,error:F}=await q.from("portal_updates").select("*").in("portal_id",S).order("created_at",{ascending:!1});if(F)throw F;const z={};return(M||[]).forEach(V=>{z[V.portal_id]||(z[V.portal_id]=V)}),z},enabled:S.length>0}),T=M=>{navigator.clipboard.writeText(Ew(M)),a(M),ae.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},D=async M=>{d.trim()&&(await v.mutateAsync({portal_id:M,title:d,content:h||void 0}),c(!1),u(""),p(""),n.invalidateQueries({queryKey:["contact-portal-updates"]}),ae.success("Portal update posted!"))},L=async()=>{f&&(await b.mutateAsync({id:f.id,welcome_message:f.welcome_message,next_step_text:f.next_step_text,is_enabled:f.is_enabled,show_post_close_tips:f.show_post_close_tips,review_url:f.review_url}),l(!1),g(null),n.invalidateQueries({queryKey:["contact-portals",s]}),ae.success("Portal settings updated!"))};return _||!j||j.length===0?null:e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(lc,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Ae,{className:"space-y-3",children:j.map(M=>{var W,K,Y;const F=((W=M.stage_mapping)==null?void 0:W.length)>0?M.stage_mapping:Dye(((K=M.deal)==null?void 0:K.deal_type)||"buyer"),z=F==null?void 0:F[M.current_stage_index??0],V=A==null?void 0:A[M.id];return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:((Y=M.deal)==null?void 0:Y.deal_name)||"Portal"}),z&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",z.label||z.name]})]}),e.jsx(ze,{variant:M.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:M.is_enabled?"Active":"Disabled"})]}),V&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:V.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:ks(new Date(V.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>T(M.slug),children:[r===M.slug?e.jsx(Lr,{className:"h-3 w-3 mr-1"}):e.jsx(ta,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(Ew(M.slug),"_blank"),children:[e.jsx(tr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(Ci,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ge,{value:d,onChange:ee=>u(ee.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Details (optional)"}),e.jsx(Ts,{value:h,onChange:ee=>p(ee.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(B,{onClick:()=>D(M.id),disabled:!d.trim()||v.isPending,className:"w-full",children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{g({...M}),l(!0)},children:[e.jsx(Vo,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Portal Settings"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Portal Enabled"}),e.jsx(vn,{checked:f.is_enabled,onCheckedChange:ee=>g({...f,is_enabled:ee})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Welcome Message"}),e.jsx(Ts,{value:f.welcome_message||"",onChange:ee=>g({...f,welcome_message:ee.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Next Step"}),e.jsx(ge,{value:f.next_step_text||"",onChange:ee=>g({...f,next_step_text:ee.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review URL"}),e.jsx(ge,{value:f.review_url||"",onChange:ee=>g({...f,review_url:ee.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Show Post-Close Tips"}),e.jsx(vn,{checked:f.show_post_close_tips,onCheckedChange:ee=>g({...f,show_post_close_tips:ee})})]}),e.jsx(cl,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:L,disabled:b.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${M.deal_id}`),children:[e.jsx(za,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),j.length>1&&e.jsx(cl,{})]},M.id)})})]})}function HWs({contactId:s}){const{data:t}=lt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await q.from("lead_sites").select("id, subdomain_slug").eq("is_active",!0);if(o)throw o;return new Map((l||[]).map(c=>[c.id,c.subdomain_slug]))},staleTime:6e5}),n=t&&t.size>0,{data:r,isLoading:a}=lt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await q.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!n});if(!n||a||!r||r.length===0)return null;const i=l=>{const o=t==null?void 0:t.get(l.lead_site_id);return o?`https://${o}.thelocalmove.com/listing/${l.mls_number}`:null};return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{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(Ir,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(ze,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(Ae,{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(zr,{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(gr,{className:"h-3 w-3"}),e.jsx("span",{title:ks(new Date(l.viewed_at),"PPp"),children:Go(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}const GWs=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function KZe({value:s,onChange:t,onAdd:n,suggestions:r,placeholder:a,icon:i}){const[l,o]=N.useState(!1),c=N.useRef(null),d=N.useRef(null);N.useEffect(()=>{const h=p=>{d.current&&!d.current.contains(p.target)&&c.current&&!c.current.contains(p.target)&&o(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const u=r.filter(h=>h.toLowerCase().includes(s.toLowerCase()));return e.jsxs("div",{className:"relative flex-1",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ge,{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(io,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>n(s),children:e.jsx(As,{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(Ca,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function WWs({contactId:s,contactName:t}){var ie,ye,_e;const{user:n}=gs(),r=fa(),{hasLeadSite:a}=Pp(),i=Gt(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(!1),[g,b]=N.useState(""),[v,j]=N.useState(null),[_,S]=N.useState(!1),[A,T]=N.useState(!1),{data:D}=lt({queryKey:["agent-lead-site-config",r],queryFn:async()=>{const{data:Me,error:Te}=await q.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(Te||!Me)return{cities:[],zipCodes:[]};const Ce=Me.theme_config||{},Ee=Array.isArray(Ce.searchCities)?Ce.searchCities:[];Me.mls_market_area&&!Ee.includes(Me.mls_market_area)&&Ee.unshift(Me.mls_market_area);const De=Array.isArray(Ce.searchZipCodes)?Ce.searchZipCodes:[];return{cities:Ee,zipCodes:De}},enabled:!!r}),{data:L,isLoading:M}=lt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:Me,error:Te}=await q.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(Te)throw Te;return Me},enabled:!!s&&!!n}),[F,z]=N.useState({}),V=()=>{z({is_active:(L==null?void 0:L.is_active)??!0,min_price:(L==null?void 0:L.min_price)??null,max_price:(L==null?void 0:L.max_price)??null,min_beds:(L==null?void 0:L.min_beds)??null,min_baths:(L==null?void 0:L.min_baths)??null,min_sqft:(L==null?void 0:L.min_sqft)??null,max_sqft:(L==null?void 0:L.max_sqft)??null,cities:(L==null?void 0:L.cities)??[],zip_codes:(L==null?void 0:L.zip_codes)??[],property_types:(L==null?void 0:L.property_types)??[],frequency:(L==null?void 0:L.frequency)??"daily"}),o(!0)},W=gt({mutationFn:async()=>{const Me={contact_id:s,owner_user_id:r,is_active:F.is_active??!0,min_price:F.min_price||null,max_price:F.max_price||null,min_beds:F.min_beds||null,min_baths:F.min_baths||null,min_sqft:F.min_sqft||null,max_sqft:F.max_sqft||null,cities:F.cities||[],zip_codes:F.zip_codes||[],property_types:F.property_types||[],frequency:F.frequency||"daily"};if(L!=null&&L.id){const{error:Te}=await q.from("contact_property_alerts").update(Me).eq("id",L.id);if(Te)throw Te}else{const{error:Te}=await q.from("contact_property_alerts").insert(Me);if(Te)throw Te}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ae.success("Property alert saved!")},onError:Me=>{ae.error(Me.message||"Failed to save alert")}}),K=gt({mutationFn:async()=>{if(!(L!=null&&L.id))return;const{error:Me}=await q.from("contact_property_alerts").delete().eq("id",L.id);if(Me)throw Me},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ae.success("Property alert removed")}}),Y=Me=>{var Ce;const Te=Me.trim();Te&&!((Ce=F.cities)!=null&&Ce.includes(Te))&&z(Ee=>({...Ee,cities:[...Ee.cities||[],Te]})),d("")},ee=Me=>{var Ce;const Te=Me.trim();Te&&!((Ce=F.zip_codes)!=null&&Ce.includes(Te))&&z(Ee=>({...Ee,zip_codes:[...Ee.zip_codes||[],Te]})),h("")},ne=Me=>{z(Te=>{const Ce=Te.property_types||[];return{...Te,property_types:Ce.includes(Me)?Ce.filter(Ee=>Ee!==Me):[...Ce,Me]}})},oe=async()=>{if(L!=null&&L.id){S(!0),f(!0),b(""),j(null);try{const{data:Me,error:Te}=await q.functions.invoke("process-property-alerts",{body:{alert_id:L.id,mode:"preview"}});if(Te)throw Te;Me!=null&&Me.html?(b(Me.html),j({count:Me.listings_count||0,recipient:Me.recipient,subject:Me.subject})):j({count:0,message:(Me==null?void 0:Me.message)||"No matching listings found right now."})}catch(Me){ae.error(Me.message||"Failed to generate preview"),f(!1)}finally{S(!1)}}},pe=async()=>{if(L!=null&&L.id&&confirm(`Send property alert email to ${t} now?`)){T(!0);try{const{data:Me,error:Te}=await q.functions.invoke("process-property-alerts",{body:{alert_id:L.id,mode:"send"}});if(Te)throw Te;Me!=null&&Me.sent_count?(ae.success(`Sent ${Me.sent_count} ${Me.sent_count===1?"listing":"listings"} to ${Me.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):ae.info((Me==null?void 0:Me.message)||"No new matching listings to send right now.")}catch(Me){ae.error(Me.message||"Failed to send alert")}finally{T(!1)}}};if(!a||M)return null;if(L&&!l)return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${L.is_active?"bg-green-500/10":"bg-muted"}`,children:L.is_active?e.jsx(lm,{className:"h-4 w-4 text-green-600"}):e.jsx(fw,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs(ze,{variant:L.is_active?"default":"secondary",className:"text-xs ml-auto",children:[L.is_active?"Active":"Paused"," · ",L.frequency]})]})}),e.jsxs(Ae,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[L.min_price||L.max_price?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Zl,{className:"h-3 w-3"}),L.min_price?`$${(L.min_price/1e3).toFixed(0)}k`:"$0"," - ",L.max_price?`$${(L.max_price/1e3).toFixed(0)}k`:"Any"]}):null,L.min_beds?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(G2,{className:"h-3 w-3"}),L.min_beds,"+ beds"]}):null,L.min_baths?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Tp,{className:"h-3 w-3"}),L.min_baths,"+ baths"]}):null,(ie=L.cities)==null?void 0:ie.map(Me=>e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),Me]},Me)),(ye=L.zip_codes)==null?void 0:ye.map(Me=>e.jsx(ze,{variant:"outline",children:Me},Me)),(_e=L.property_types)==null?void 0:_e.map(Me=>e.jsx(ze,{variant:"outline",children:Me},Me))]}),L.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(L.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:oe,disabled:_,children:[_?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ir,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs(B,{size:"sm",onClick:pe,disabled:A||!L.is_active,title:L.is_active?"Send this alert email now":"Activate alert to send",children:[A?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send Now"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:V,children:"Manage Alert"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>K.mutate(),disabled:K.isPending,children:[K.isPending?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Fn,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(bs,{open:p,onOpenChange:f,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Property Alert Email Preview"}),(v==null?void 0:v.subject)&&e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 pt-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"To:"})," ",v.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",v.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",v.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:_?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(ss,{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:(v==null?void 0:v.message)||"No matching listings found right now."})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(!1),children:"Close"}),g&&e.jsxs(B,{onClick:()=>{f(!1),pe()},disabled:A||!L.is_active,children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]});const ce=((D==null?void 0:D.cities)||[]).filter(Me=>{var Te;return!((Te=F.cities)!=null&&Te.includes(Me))}),de=((D==null?void 0:D.zipCodes)||[]).filter(Me=>{var Te;return!((Te=F.zip_codes)!=null&&Te.includes(Me))});return l?e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(lm,{className:"h-4 w-4 text-primary"}),L?"Edit":"Setup"," Property Alert for ",t]})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Alert Active"}),e.jsx(vn,{checked:F.is_active??!0,onCheckedChange:Me=>z(Te=>({...Te,is_active:Me}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Zl,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ge,{type:"number",placeholder:"Min price",value:F.min_price??"",onChange:Me=>z(Te=>({...Te,min_price:Me.target.value?Number(Me.target.value):null}))}),e.jsx(ge,{type:"number",placeholder:"Max price",value:F.max_price??"",onChange:Me=>z(Te=>({...Te,max_price:Me.target.value?Number(Me.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(G2,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(us,{value:F.min_beds?String(F.min_beds):"any",onValueChange:Me=>z(Te=>({...Te,min_beds:Me==="any"?null:Number(Me)})),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Any"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"any",children:"Any"}),[1,2,3,4,5].map(Me=>e.jsxs(Ze,{value:String(Me),children:[Me,"+"]},Me))]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Tp,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(us,{value:F.min_baths?String(F.min_baths):"any",onValueChange:Me=>z(Te=>({...Te,min_baths:Me==="any"?null:Number(Me)})),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Any"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(Me=>e.jsxs(Ze,{value:String(Me),children:[Me,"+"]},Me))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(eN,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ge,{type:"number",placeholder:"Min sqft",value:F.min_sqft??"",onChange:Me=>z(Te=>({...Te,min_sqft:Me.target.value?Number(Me.target.value):null}))}),e.jsx(ge,{type:"number",placeholder:"Max sqft",value:F.max_sqft??"",onChange:Me=>z(Te=>({...Te,max_sqft:Me.target.value?Number(Me.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(KZe,{value:c,onChange:d,onAdd:Y,suggestions:ce,placeholder:"Type to search cities..."}),F.cities&&F.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:F.cities.map(Me=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[Me,e.jsx("button",{onClick:()=>z(Te=>{var Ce;return{...Te,cities:(Ce=Te.cities)==null?void 0:Ce.filter(Ee=>Ee!==Me)}}),children:e.jsx(Fn,{className:"h-3 w-3"})})]},Me))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(KZe,{value:u,onChange:h,onAdd:ee,suggestions:de,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),F.zip_codes&&F.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:F.zip_codes.map(Me=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[Me,e.jsx("button",{onClick:()=>z(Te=>{var Ce;return{...Te,zip_codes:(Ce=Te.zip_codes)==null?void 0:Ce.filter(Ee=>Ee!==Me)}}),children:e.jsx(Fn,{className:"h-3 w-3"})})]},Me))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(zr,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:GWs.map(Me=>{var Te;return e.jsx(ze,{variant:(Te=F.property_types)!=null&&Te.includes(Me)?"default":"outline",className:"cursor-pointer",onClick:()=>ne(Me),children:Me},Me)})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-1.5",children:"Frequency"}),e.jsxs(us,{value:F.frequency||"daily",onValueChange:Me=>z(Te=>({...Te,frequency:Me})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"daily",children:"Daily"}),e.jsx(Ze,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>W.mutate(),disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),L&&e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>K.mutate(),disabled:K.isPending,children:e.jsx(Fn,{className:"h-4 w-4"})})]})]})]}):e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ae,{className:"p-4",children:e.jsxs("button",{onClick:V,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(lm,{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 KWs({contactId:s,contactName:t}){var ne;const{user:n}=gs(),r=fa(),{hasLeadSite:a}=Pp(),i=Gt(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState([]),[p,f]=N.useState(!1),[g,b]=N.useState(!1),[v,j]=N.useState(!1),[_,S]=N.useState(""),A=N.useRef(null),T=N.useRef(null),{data:D}=lt({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:oe,error:pe}=await q.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(pe||!oe)return[];const ce=oe.theme_config||{},de=Array.isArray(ce.searchCities)?ce.searchCities:[];return oe.mls_market_area&&!de.includes(oe.mls_market_area)&&de.unshift(oe.mls_market_area),de},enabled:!!r}),{data:L,isLoading:M}=lt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:oe,error:pe}=await q.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(pe)throw pe;return oe},enabled:!!s&&!!n});N.useEffect(()=>{const oe=pe=>{T.current&&!T.current.contains(pe.target)&&A.current&&!A.current.contains(pe.target)&&b(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[]);const F=()=>{f((L==null?void 0:L.market_report_enabled)??!1),h((L==null?void 0:L.market_report_cities)??[]),o(!0)},z=oe=>{const pe=(oe||c).trim();pe&&!u.includes(pe)&&h([...u,pe]),d(""),b(!1)},V=(D||[]).filter(oe=>!u.includes(oe)&&oe.toLowerCase().includes(c.toLowerCase())),W=gt({mutationFn:async()=>{const{data:oe,error:pe}=await q.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(L==null?void 0:L.market_report_cities)??[]}});if(pe)throw new Error(pe.message||"Failed to generate preview");if(oe&&!oe.ok&&oe.error)throw new Error(oe.error);return oe},onSuccess:oe=>{S(oe.html),j(!0)},onError:oe=>{ae.error(oe.message||"Failed to generate preview")}}),K=gt({mutationFn:async()=>{const{data:oe,error:pe}=await q.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(L==null?void 0:L.market_report_cities)??[],contactIds:[s]}});if(pe)throw new Error(pe.message||"Failed to send report");if(oe&&!oe.ok&&oe.error)throw new Error(oe.error);return oe},onSuccess:()=>{ae.success(`Market report sent to ${t}!`)},onError:oe=>{ae.error(oe.message||"Failed to send report")}}),Y=gt({mutationFn:async()=>{const{error:oe}=await q.from("innercircle_contacts").update({market_report_enabled:p,market_report_cities:u}).eq("id",s);if(oe)throw oe},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),ae.success(p?"Monthly market report enabled!":"Market report disabled")},onError:oe=>{ae.error(oe.message||"Failed to save")}}),ee=gt({mutationFn:async()=>{const{error:oe}=await q.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(oe)throw oe},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),f(!1),h([]),ae.success("Market report removed")},onError:oe=>{ae.error(oe.message||"Failed to remove market report")}});return!a||M?null:L!=null&&L.market_report_enabled&&!l?e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{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(yo,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(ze,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Ae,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((ne=L.market_report_cities)==null?void 0:ne.length)>0?L.market_report_cities.map(oe=>e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),oe]},oe)):e.jsx("span",{className:"text-muted-foreground",children:"Using default market area"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t," receives a branded market report on the 1st of each month."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>W.mutate(),disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ir,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>K.mutate(),disabled:K.isPending,className:"flex-1",children:[K.isPending?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:F,className:"flex-1",children:"Manage"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>ee.mutate(),disabled:ee.isPending,className:"flex-1",children:[ee.isPending?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Fn,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(bs,{open:v,onOpenChange:j,children:e.jsxs(vs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(yo,{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(B,{onClick:()=>{j(!1),K.mutate()},disabled:K.isPending,className:"flex-1",children:[K.isPending?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(B,{variant:"outline",onClick:()=>j(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(yo,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Send Monthly Report"}),e.jsx(vn,{checked:p,onCheckedChange:f})]}),p&&e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"})," Report Cities"]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select cities from your website's configured areas."}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ge,{ref:A,value:c,onChange:oe=>{d(oe.target.value),b(!0)},onFocus:()=>b(!0),placeholder:"Type to search cities...",onKeyDown:oe=>{oe.key==="Enter"&&(oe.preventDefault(),V.length>0?z(V[0]):z())}}),e.jsx(io,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>z(),children:e.jsx(As,{className:"h-4 w-4"})})]}),g&&V.length>0&&e.jsx("div",{ref:T,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:V.map(oe=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>z(oe),children:[e.jsx(Ca,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),oe]},oe))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(oe=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[oe,e.jsx("button",{onClick:()=>h(u.filter(pe=>pe!==oe)),children:e.jsx(Fn,{className:"h-3 w-3"})})]},oe))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>Y.mutate(),disabled:Y.isPending,className:"flex-1",children:[Y.isPending?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ae,{className:"p-4",children:e.jsxs("button",{onClick:F,className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed border-primary/30 hover:bg-primary/5 transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(yo,{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 YWs(s){return lt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("id, campaign_id, current_step, status, next_send_at, enrolled_at, completed_at, exited_at, exit_reason").eq("contact_id",s).order("enrolled_at",{ascending:!1});if(n)throw console.error("[ContactDripActivity] enrollments error",n),n;const r=(t||[]).map(c=>c.id),a=Array.from(new Set((t||[]).map(c=>c.campaign_id)));let i=new Map;if(a.length>0){const{data:c}=await q.from("drip_campaigns").select("id, name, description, is_active").in("id",a);(c||[]).forEach(d=>i.set(d.id,d))}const l=(t||[]).map(c=>({...c,campaign:i.get(c.campaign_id)||null}));let o=[];if(r.length>0){const{data:c,error:d}=await q.from("drip_campaign_step_log").select("id, enrollment_id, campaign_id, step_order, channel, recipient_email, subject, status, error_message, sent_at").in("enrollment_id",r).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(u=>{var h;return{...u,campaign:{name:((h=i.get(u.campaign_id))==null?void 0:h.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function ZWs(s){switch(s){case"active":return e.jsx(ze,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(ze,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(ze,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(ze,{variant:"outline",children:"Exited"});default:return e.jsx(ze,{variant:"outline",children:s})}}function YZe(s){return s==="sent"?e.jsx(xr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(Dl,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(_f,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(gr,{className:"h-4 w-4 text-muted-foreground"})}function QWs({contactId:s}){const t=In(),{data:n,isLoading:r}=YWs(s),[a,i]=N.useState(null);if(r)return null;const l=(n==null?void 0:n.enrollments)||[],o=(n==null?void 0:n.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2 text-base",children:[e.jsx(qA,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Ae,{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(qA,{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"}),ZWs(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: ",Go(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",Go(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",Go(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]},c.id)})]}),o.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Send History (",o.length,")"]}),e.jsxs("div",{className:"space-y-1",children:[o.slice(0,8).map(c=>{var d,u;return e.jsxs(bs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(Di,{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:YZe(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(Ci,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(Hs,{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"," · ",ks(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(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[YZe(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:ks(new Date(c.sent_at),"MMM d, yyyy h:mm a")})]}),c.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-2 text-destructive text-xs",children:c.error_message})]})]})]},c.id)}),o.length>8&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}function rwt({contactId:s}={}){const{user:t}=gs();return lt({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const n=t.id;let r=q.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",n).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1}).limit(1e3);s&&(r=r.eq("contact_id",s));let a=q.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source, opened_at, clicked_at").eq("user_id",n).order("sent_at",{ascending:!1}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await q.from("email_campaigns").select("id, subject").eq("user_id",n),l=(i.data||[]).map(b=>b.id),o=new Map((i.data||[]).map(b=>[b.id,b.subject]));let c=[];if(l.length>0){let b=q.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",l).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1}).limit(1e3);s&&(b=b.eq("contact_id",s)),c=(await b).data||[]}const[d,u]=await Promise.all([r,a]),h=(d.data||[]).map(b=>({id:`g-${b.id}`,channel:b.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:b.subject,to_email:b.to_email,contact_id:b.contact_id,sent_at:b.sent_at,source:b.source})),p=(u.data||[]).map(b=>({id:`b-${b.id}`,channel:"Mass Email",subject:b.subject,to_email:b.contact_email,contact_id:b.contact_id,sent_at:b.sent_at,source:b.source,opened_at:b.opened_at,clicked_at:b.clicked_at})),f=c.map(b=>({id:`c-${b.id}`,channel:"Campaign",subject:o.get(b.campaign_id)||"(campaign)",to_email:b.email,contact_id:b.contact_id,sent_at:b.sent_at,source:null,campaign_id:b.campaign_id,opened_at:b.opened_at,clicked_at:b.clicked_at})),g=[...h,...p,...f];return g.sort((b,v)=>b.sent_at0&&e.jsx(ze,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Ae,{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(Hs,{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(ze,{variant:"outline",className:`text-xs ${XWs[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ks(new Date(l.sent_at),"MMM d, yyyy h:mm a")})]}),e.jsx("p",{className:"text-sm font-medium truncate",children:l.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["to ",l.to_email]})]})},l.id))}),t.length>5&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>a(!r),children:r?"Show less":`Show all ${t.length}`}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx(Ln,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function eKs({videoId:s}){var l;const{data:t,isLoading:n,error:r}=qGs(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"w-full aspect-video rounded-lg"}),e.jsx(Ws,{className:"h-4 w-1/3"})]});if(r||!t||t.is_deleted)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Dl,{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 tKs({contactId:s}){const t=In(),[n,r]=N.useState(!1),{data:a,isLoading:i}=lt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:p}=await q.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(p)throw p;return h},enabled:!!s}),l=async(h,p)=>{const f=p==="done"?"todo":"done";await q.from("deal_tasks").update({status:f,completed_at:f==="done"?new Date().toISOString():null}).eq("id",h),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=lt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:p}=await q.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(p)throw p;return h},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(h=>h.status!=="done"))||[],u=(a==null?void 0:a.filter(h=>h.status==="done"))||[];return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>r(!0),children:e.jsx(As,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Ae,{className:"space-y-1",children:i?e.jsx(Ws,{className:"h-8 w-full"}):d.length===0&&u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tasks yet"}):e.jsxs(e.Fragment,{children:[d.map(h=>e.jsxs("button",{onClick:async()=>{await l(h.id,h.status),o()},className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted/50 transition-colors group",children:[e.jsx("div",{className:"h-4 w-4 rounded-full border-2 border-muted-foreground/30 shrink-0 group-hover:border-primary"}),e.jsxs("span",{className:"text-sm flex-1 truncate",children:[c[h.priority]," ",h.title]}),h.due_date&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:ks(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(sKs,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function sKs({contactId:s,open:t,onOpenChange:n}){const[r,a]=N.useState(""),[i,l]=N.useState("medium"),[o,c]=N.useState(),{data:d}=lt({queryKey:["session"],queryFn:async()=>{const{data:h}=await q.auth.getSession();return h.session}}),u=async()=>{var p;if(!r.trim()||!((p=d==null?void 0:d.user)!=null&&p.id))return;const{error:h}=await q.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:r.trim(),priority:i,status:"todo",due_date:o?ks(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(bs,{open:t,onOpenChange:n,children:e.jsxs(vs,{className:"sm:max-w-[400px]",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ge,{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(se,{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(se,{children:"Due Date"}),e.jsx(ge,{type:"date",value:o?ks(o,"yyyy-MM-dd"):"",onChange:h=>c(h.target.value?new Date(h.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{onClick:u,disabled:!r.trim(),children:"Create Task"})]})]})]})})}function nKs({contactId:s}){const t=In(),{data:n,isLoading:r}=lt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await q.from("deal_pipeline").select(` id, deal_name, deal_type, expected_price, property_address, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).eq("contact_id",s).order("updated_at",{ascending:!1});if(i)throw i;return a},enabled:!!s});return r||!n||n.length===0?null:e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(Vm,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Ae,{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(ze,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(ze,{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(za,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function rKs(){var St,$t,ht,Ut,Es;const{contactId:s}=_i(),t=In(),[n]=yl(),r=n.get("search")||"",a=n.get("type")||"all",i=n.get("status")||n.get("filter")||"all",l=n.get("tags")||"",o=n.get("tagMode")==="all"?"all":"any",c=N.useMemo(()=>new Set(l.split(",").map(Xt=>Xt.trim()).filter(Boolean)),[l]),{data:d,isLoading:u}=nrs(s||""),{data:h}=Cy(),{data:p}=XD(),{data:f}=JD(3650),{data:g}=R1e(365),{data:b}=OWs(s),{contactsWithScores:v}=Yye(),{data:j}=P1e(),_=_6e(),S=w6e(),A=gU(),T=rpt(),[D,L]=N.useState(!1),[M,F]=N.useState({}),[z,V]=N.useState(!1),[W,K]=N.useState(null),[Y,ee]=N.useState(""),[ne,oe]=N.useState(void 0),[pe,ce]=N.useState(""),[de,ie]=N.useState(null),[ye,_e]=N.useState(!1),[Me,Te]=N.useState(null),[Ce,Ee]=N.useState(!1),{isGmailConnected:De,gmailEmail:Ie}=bh(),{isReady:Fe}=jR(),qe=Fe||De,ve=J_t(),[Je,we]=N.useState(!1),{data:it}=lt({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:Xt}}=await q.auth.getUser();if(!Xt)return!1;const{data:Ys}=await q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",Xt.id);return(Ys||[]).some(Ss=>Ss.is_active&&Ss.mls_provider_id&&!Ss.no_mls_mode)}}),Ne=async()=>{var Us,sn,Jn,fn;if(!d)return;const Xt=(Us=d.address)==null?void 0:Us.trim(),Ys=(sn=d.city)==null?void 0:sn.trim(),Ss=(Jn=d.state)==null?void 0:Jn.trim().toUpperCase(),Bs=((fn=d.zip_code)==null?void 0:fn.trim())||"";if(!Xt||!Ys||!Ss){ae.error("Add a full address (street, city, state) before creating a CMA.");return}try{we(!0);const Sn=await ve.mutateAsync({subject:{address:Xt,city:Ys,state:Ss,zip:Bs},contactId:d.id,title:`${d.first_name||""} ${d.last_name||""}`.trim()+" — "+Xt});t(`/mission-control/cma/${Sn.id}`)}catch(Sn){ae.error("Could not create CMA: "+((Sn==null?void 0:Sn.message)||"unknown error"))}finally{we(!1)}},{data:He}=lt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:Xt,error:Ys}=await q.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(Ys)throw Ys;return Xt},enabled:!!s}),$e=Xt=>{if(!Xt)return null;const Ys=Xt.match(/Video ID:\s*([a-f0-9-]+)/i);return Ys?Ys[1]:null},Ye=N.useMemo(()=>{if(!v)return[];const Xt=new Map;if(c.size>0&&j)for(const Ss of j)Xt.has(Ss.contact_id)||Xt.set(Ss.contact_id,new Set),Xt.get(Ss.contact_id).add(Ss.tag_id);let Ys=v.filter(Ss=>{var Jn,fn,Sn;const Bs=r===""||`${Ss.first_name} ${Ss.last_name}`.toLowerCase().includes(r.toLowerCase())||((Jn=Ss.email)==null?void 0:Jn.toLowerCase().includes(r.toLowerCase()))||((fn=Ss.phone)==null?void 0:fn.includes(r)),Us=a==="all"||((Sn=Ss.tags)==null?void 0:Sn.some(Gn=>Gn.relationship_type_id===a));let sn=!0;if(c.size>0){const Gn=Xt.get(Ss.id)||new Set;o==="all"?sn=Array.from(c).every(Hr=>Gn.has(Hr)):sn=Array.from(c).some(Hr=>Gn.has(Hr))}return Bs&&Us&&sn});return i==="not-touched-90"?Ys=Ys.filter(Ss=>{const Bs=Ss.relationshipScore.daysSinceTouch;return Bs===null||Bs>90}):i==="at-risk"?Ys=Ys.filter(Ss=>Ss.relationshipScore.status==="at-risk"):i==="cooling"?Ys=Ys.filter(Ss=>Ss.relationshipScore.status==="cooling"):i==="warm"&&(Ys=Ys.filter(Ss=>Ss.relationshipScore.status==="warm")),Ys.map(Ss=>Ss.id)},[v,r,a,i,c,o,j]),Ke=Ye.indexOf(s||""),rt=Ke>0?Ye[Ke-1]:null,tt=Ke1&&Ke!==-1,Ge=Xt=>{const Ys=new URLSearchParams;r&&Ys.set("search",r),a!=="all"&&Ys.set("type",a),i!=="all"&&Ys.set("status",i),c.size>0&&(Ys.set("tags",Array.from(c).join(",")),Ys.set("tagMode",o));const Ss=Ys.toString();return`/mission-control/contacts/${Xt}${Ss?`?${Ss}`:""}`},dt=N.useMemo(()=>{const Xt=((f==null?void 0:f.filter(Ss=>Ss.contact_id===s))||[]).map(Ss=>{var Jn,fn,Sn;const Bs=$e(Ss.notes);let Us=((Jn=Ss.action_type)==null?void 0:Jn.name)||"Touch",sn=Ss.notes;if(Us==="Other"&&((fn=Ss.notes)!=null&&fn.startsWith("["))){const Gn=Ss.notes.indexOf("]");Gn>0&&(Us=Ss.notes.substring(1,Gn),sn=Ss.notes.substring(Gn+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:Ss.id,type:"touch",completed_at:Ss.completed_at,name:Us,color:((Sn=Ss.action_type)==null?void 0:Sn.color)||"#3B82F6",notes:sn,videoId:Bs}}),Ys=((g==null?void 0:g.filter(Ss=>Ss.contact_id===s))||[]).map(Ss=>({id:Ss.id,type:"popby",completed_at:Ss.completed_at,name:"Pop-by",color:"#F97316",notes:Ss.notes,videoId:null}));return[...Xt,...Ys].sort((Ss,Bs)=>new Date(Bs.completed_at).getTime()-new Date(Ss.completed_at).getTime())},[f,g,s]),Bt=()=>{var Xt;d&&(F({first_name:d.first_name||"",last_name:d.last_name||"",email:d.email||"",phone:d.phone||"",address:d.address||"",city:d.city||"",state:d.state||"",zip_code:d.zip_code||"",birthday:d.birthday||"",home_anniversary:d.home_anniversary||"",wedding_anniversary:d.wedding_anniversary||"",spouse_birthday:d.spouse_birthday||"",spouse_name:d.spouse_name||"",spouse_email:d.spouse_email||"",company_name:d.company_name||"",job_title:d.job_title||"",lead_source_id:d.lead_source_id||"",notes:d.notes||"",tagIds:((Xt=d.tags)==null?void 0:Xt.map(Ys=>Ys.relationship_type_id))||[]}),L(!0))},kt=async()=>{await _.mutateAsync({id:s,...M,lead_source_id:M.lead_source_id||null}),L(!1)},Qt=async()=>{confirm("Are you sure you want to delete this contact?")&&(await S.mutateAsync(s),t("/mission-control/contacts"))},$s=((St=p==null?void 0:p.find(Xt=>Xt.id===W))==null?void 0:St.name)==="Other",Ds=async()=>{if(!W||$s&&!pe.trim())return;const Xt=ne?new Date(ne.getFullYear(),ne.getMonth(),ne.getDate(),12,0,0).toISOString():void 0,Ys=$s?`[${pe.trim()}]${Y?" — "+Y:""}`:Y;await A.mutateAsync({contactId:s,actionTypeId:W,notes:Ys,completedAt:Xt}),V(!1),K(null),ee(""),oe(void 0),ce("")},Dt=(Xt,Ys)=>{qe&&d?(Te({email:Xt,name:Ys||`${d.first_name} ${d.last_name||""}`.trim()}),_e(!0)):window.location.href=`mailto:${Xt}`};return u?e.jsx(Cs,{title:"Contact Details",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):d?e.jsxs(e.Fragment,{children:[e.jsx(Cs,{title:`${d.first_name} ${d.last_name||""}`,description:"Contact details and activity",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{window.history.length>1?t(-1):t("/mission-control/contacts")},children:[e.jsx(fl,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),at&&e.jsxs("div",{className:"flex items-center gap-1 ml-2 border-l pl-2",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>rt&&t(Ge(rt)),disabled:!rt,className:"px-2",children:[e.jsx(fl,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only sm:not-sr-only sm:ml-1",children:"Prev"})]}),e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[Ke+1," of ",Ye.length]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>tt&&t(Ge(tt)),disabled:!tt,className:"px-2",children:[e.jsx("span",{className:"sr-only sm:not-sr-only sm:mr-1",children:"Next"}),e.jsx(ga,{className:"h-4 w-4"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end flex-wrap",children:[d.phone&&e.jsxs(B,{variant:"outline",onClick:()=>window.location.href=`sms:${d.phone}`,className:"border-blue-500/30 text-blue-600 hover:bg-blue-500/10",children:[e.jsx(Ci,{className:"h-4 w-4 mr-1"}),"Text"]}),d.email&&e.jsxs(B,{variant:"outline",onClick:()=>Dt(d.email,`${d.first_name} ${d.last_name||""}`.trim()),children:[e.jsx(Hs,{className:"h-4 w-4 mr-1"}),"Email"]}),d.email&&e.jsxs(B,{variant:"outline",onClick:()=>Ee(!0),className:"border-primary/40 text-primary hover:bg-primary/10",children:[e.jsx(un,{className:"h-4 w-4 mr-1"}),"Send Connect Page"]}),e.jsxs(B,{variant:"default",onClick:()=>t(`/mission-control/video/record?contact_id=${s}`),className:"bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(vr,{className:"h-4 w-4 mr-1"}),"Quick Video Touch"]}),e.jsxs(bs,{open:z,onOpenChange:V,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Log Action"]})}),e.jsxs(vs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Action Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:p==null?void 0:p.filter(Xt=>Xt.active).map(Xt=>e.jsxs("button",{onClick:()=>K(Xt.id),className:` p-3 rounded-lg border text-left transition-all ${W===Xt.id?"border-primary bg-primary/10":"hover:bg-accent"} `,children:[e.jsx("div",{className:"font-medium",children:Xt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Xt.description})]},Xt.id))}),$s&&e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(ge,{id:"custom-action-name",value:pe,onChange:Xt=>ce(Xt.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date (optional — backdate if needed)"}),e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal mt-2",!ne&&"text-muted-foreground"),children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),ne?ks(ne,"PPP"):"Today (default)"]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:ne,onSelect:oe,disabled:Xt=>Xt>new Date,initialFocus:!0,className:Et("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(Ts,{id:"action-notes",value:Y,onChange:Xt=>ee(Xt.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(B,{onClick:Ds,disabled:!W||$s&&!pe.trim()||A.isPending,className:"w-full",children:[e.jsx(Lr,{className:"h-4 w-4 mr-1"}),"Complete Action"]})]})]})]}),e.jsxs(B,{variant:"outline",onClick:Bt,children:[e.jsx(Tu,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:Qt,children:e.jsx(bn,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"bg-card border rounded-lg p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsx(Z_t,{contactId:d.id,firstName:d.first_name,lastName:d.last_name,avatarUrl:d.avatar_url,email:d.email,size:88}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold",children:[d.first_name," ",d.last_name||""]}),((($t=d.lead_source_ref)==null?void 0:$t.name)||d.lead_source)&&e.jsx(ze,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((ht=d.lead_source_ref)==null?void 0:ht.name)||d.lead_source})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-muted-foreground",children:[d.email&&e.jsxs("button",{onClick:()=>Dt(d.email),className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(Hs,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:d.email})]}),d.phone&&e.jsxs("a",{href:`tel:${d.phone}`,className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(Pr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:d.phone})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Bge,{contact:d}),(Ut=d.tags)==null?void 0:Ut.map(Xt=>{const Ys=h==null?void 0:h.find(Ss=>Ss.id===Xt.relationship_type_id);return Ys?e.jsx(ze,{variant:"secondary",className:"text-xs",children:Ys.name},Xt.id):null})]}),e.jsx("div",{className:"mt-2",children:e.jsx(cWs,{contactId:s})})]})}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"md:col-span-2",children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Contact Information"})}),e.jsx(Ae,{children:D?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"first_name",children:"First Name"}),e.jsx(ge,{id:"first_name",value:M.first_name,onChange:Xt=>F({...M,first_name:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"last_name",children:"Last Name"}),e.jsx(ge,{id:"last_name",value:M.last_name,onChange:Xt=>F({...M,last_name:Xt.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ge,{id:"email",type:"email",value:M.email,onChange:Xt=>F({...M,email:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone"}),e.jsx(ge,{id:"phone",value:M.phone,onChange:Xt=>F({...M,phone:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"address",children:"Street Address"}),e.jsx(ge,{id:"address",value:M.address,onChange:Xt=>F({...M,address:Xt.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(ge,{id:"city",value:M.city,onChange:Xt=>F({...M,city:Xt.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ge,{id:"state",value:M.state,onChange:Xt=>F({...M,state:Xt.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(ge,{id:"zip_code",value:M.zip_code,onChange:Xt=>F({...M,zip_code:Xt.target.value}),placeholder:"12345"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"birthday",children:"Birthday"}),e.jsx(ge,{id:"birthday",type:"date",value:M.birthday,onChange:Xt=>F({...M,birthday:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(ge,{id:"home_anniversary",type:"date",value:M.home_anniversary,onChange:Xt=>F({...M,home_anniversary:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(ge,{id:"wedding_anniversary",type:"date",value:M.wedding_anniversary||"",onChange:Xt=>F({...M,wedding_anniversary:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(ge,{id:"spouse_birthday",type:"date",value:M.spouse_birthday,onChange:Xt=>F({...M,spouse_birthday:Xt.target.value})})]})]}),e.jsx(cl,{}),e.jsx(iTe,{contactId:s,currentSpouseContactId:(d==null?void 0:d.spouse_contact_id)||null,currentSpouseName:(d==null?void 0:d.spouse_name)||null,currentSpouseEmail:(d==null?void 0:d.spouse_email)||null,onLink:Xt=>T.mutate({contactId:s,spouseContactId:Xt}),onUnlink:()=>T.mutate({contactId:s,spouseContactId:null}),isEditing:!0}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"company_name",children:"Company"}),e.jsx(ge,{id:"company_name",value:M.company_name,onChange:Xt=>F({...M,company_name:Xt.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"job_title",children:"Job Title"}),e.jsx(ge,{id:"job_title",value:M.job_title,onChange:Xt=>F({...M,job_title:Xt.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(Y_t,{value:M.lead_source_id||"",onChange:Xt=>F({...M,lead_source_id:Xt})}),e.jsxs("div",{children:[e.jsx(se,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:h==null?void 0:h.filter(Xt=>Xt.active).map(Xt=>{var Ys;return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(hi,{checked:(Ys=M.tagIds)==null?void 0:Ys.includes(Xt.id),onCheckedChange:Ss=>{var Bs;F(Ss?{...M,tagIds:[...M.tagIds||[],Xt.id]}:{...M,tagIds:(Bs=M.tagIds)==null?void 0:Bs.filter(Us=>Us!==Xt.id)})}}),e.jsx("span",{className:"text-sm",children:Xt.name})]},Xt.id)})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Ts,{id:"notes",value:M.notes,onChange:Xt=>F({...M,notes:Xt.target.value}),rows:4})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:kt,disabled:_.isPending,children:"Save Changes"}),e.jsx(B,{variant:"outline",onClick:()=>L(!1),children:"Cancel"})]})]}):e.jsxs("div",{className:"space-y-4",children:[dt.length>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Last Contacted:"})," ",ks(new Date(dt[0].completed_at),"MMM d, yyyy")," ","(",dt[0].name,")"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:gap-6 gap-2",children:[d.email&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Hs,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("button",{onClick:()=>Dt(d.email),className:"text-primary hover:underline truncate text-left",children:d.email})]}),d.phone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("a",{href:`tel:${d.phone}`,className:"text-primary hover:underline",children:d.phone}),e.jsx("button",{onClick:()=>window.location.href=`sms:${d.phone}`,className:"h-6 px-2 rounded-full bg-blue-500/10 text-blue-600 text-xs font-medium hover:bg-blue-500/20 transition-colors",children:"Text"})]})]}),(d.address||d.city||d.state||d.zip_code)&&e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ca,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[d.address&&e.jsx("span",{children:d.address}),(d.city||d.state||d.zip_code)&&e.jsxs("span",{className:"text-muted-foreground",children:[[d.city,d.state].filter(Boolean).join(", "),d.zip_code&&` ${d.zip_code}`]})]})]}),it&&d.address&&d.city&&d.state&&e.jsxs(B,{size:"sm",variant:"outline",onClick:Ne,disabled:Je,children:[Je?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(xw,{className:"h-4 w-4 mr-1"}),"Create CMA"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[d.birthday&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Birthday: ",ks(ll(d.birthday),ll(d.birthday).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Home Anniversary: ",ks(ll(d.home_anniversary),ll(d.home_anniversary).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.spouse_birthday&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Spouse Birthday: ",ks(ll(d.spouse_birthday),ll(d.spouse_birthday).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.wedding_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Wedding Anniversary: ",ks(ll(d.wedding_anniversary),ll(d.wedding_anniversary).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.created_at&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(As,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Date Added: ",ks(new Date(d.created_at),"MMMM d, yyyy")]})]})]}),e.jsx(cl,{}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(iTe,{contactId:s,currentSpouseContactId:(d==null?void 0:d.spouse_contact_id)||null,currentSpouseName:d.spouse_name||null,currentSpouseEmail:d.spouse_email||null,onLink:Xt=>T.mutate({contactId:s,spouseContactId:Xt}),onUnlink:()=>T.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),(d.company_name||d.job_title)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:d.job_title&&d.company_name?`${d.job_title} at ${d.company_name}`:d.job_title||d.company_name})]})]}),e.jsx(cl,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(Es=d.tags)!=null&&Es.length?d.tags.map(Xt=>{var Ys;return e.jsx(ze,{variant:"secondary",children:(Ys=Xt.relationship_type)==null?void 0:Ys.name},Xt.id)}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No relationship types assigned"})})]}),d.notes&&e.jsxs(e.Fragment,{children:[e.jsx(cl,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:d.notes})]})]})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(mGs,{contact:d,onLogTouch:()=>V(!0)}),e.jsx(nKs,{contactId:s}),e.jsx(VWs,{contactId:s}),e.jsx(HWs,{contactId:s}),e.jsx(WWs,{contactId:s,contactName:d.first_name}),e.jsx(KWs,{contactId:s,contactName:d.first_name}),e.jsx(tKs,{contactId:s}),e.jsx(QWs,{contactId:s}),e.jsx(JWs,{contactId:s}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Activity Log"})}),e.jsx(Ae,{children:dt.length>0?e.jsx("div",{className:"space-y-4",children:dt.map(Xt=>{var Ys;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[e.jsx("div",{className:"h-8 w-8 rounded-full flex items-center justify-center text-white text-xs",style:{backgroundColor:Xt.color},children:Xt.type==="popby"?e.jsx(Bi,{className:"h-4 w-4"}):(Ys=Xt.name)==null?void 0:Ys.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:Xt.name}),Xt.videoId&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>ie(Xt.videoId),children:[e.jsx(Al,{className:"h-3 w-3 mr-1"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ks(new Date(Xt.completed_at),"MMM d, yyyy h:mm a")}),Xt.notes&&!Xt.videoId&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Xt.notes})]})]},Xt.id)})}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"})})]}),b&&b.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(Ci,{className:"h-5 w-5 text-primary"}),"Video Replies"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"space-y-4",children:b.map(Xt=>{var Ys,Ss;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[(Ys=Xt.video)!=null&&Ys.thumbnail_url?e.jsx("img",{src:Xt.video.thumbnail_url,alt:Xt.video.title||"Video",className:"h-12 w-16 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>ie(Xt.video_id)}):e.jsx("div",{className:"h-12 w-16 bg-muted rounded flex items-center justify-center cursor-pointer hover:bg-muted/80 transition-colors",onClick:()=>ie(Xt.video_id),children:e.jsx(vr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:["Replied to: ",((Ss=Xt.video)==null?void 0:Ss.title)||"Untitled Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs flex-shrink-0",onClick:()=>ie(Xt.video_id),children:[e.jsx(Al,{className:"h-3 w-3 mr-1"}),"Watch"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ks(new Date(Xt.created_at),"MMM d, yyyy h:mm a")}),Xt.message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:['"',Xt.message,'"']})]})]},Xt.id)})})})]}),He&&He.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-5 w-5 text-sky-500"}),"Sent Emails"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"space-y-3",children:He.map(Xt=>e.jsxs(bs,{children:[e.jsx(Di,{asChild:!0,children:e.jsxs("button",{className:"w-full text-left flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors cursor-pointer",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-sky-500/10 flex items-center justify-center text-sky-600 flex-shrink-0",children:e.jsx(Hs,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:Xt.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",Xt.to_email," · ",ks(new Date(Xt.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5 text-sky-500"}),Xt.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",Xt.to_email," · ",ks(new Date(Xt.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden rounded-lg border bg-white",children:e.jsx("iframe",{srcDoc:Xt.body,className:"w-full h-[400px] border-0",sandbox:"",title:`Email: ${Xt.subject}`})})]})]},Xt.id))})})]})]}),e.jsx(bs,{open:!!de,onOpenChange:Xt=>!Xt&&ie(null),children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Video Preview"})}),de&&e.jsx(eKs,{videoId:de})]})})]})]})}),qe&&d&&Me&&e.jsx(Ty,{open:ye,onOpenChange:_e,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:Me.email},gmailEmail:Ie}),d&&d.email&&e.jsx(TWs,{open:Ce,onOpenChange:Ee,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:d.email}})]}):e.jsx(Cs,{title:"Contact Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This contact was not found."}),e.jsx(B,{onClick:()=>t("/mission-control/contacts"),children:"Back to Contacts"})]})})}function aKs({rangeDays:s}){const{user:t}=gs(),n=Gt(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),{data:d=[],isLoading:u}=lt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let f=q.from("email_campaigns").select("id, name, subject, status, sent_at, scheduled_at, created_at, total_recipients, sent_count, open_count, click_count, bounce_count").eq("user_id",t.id).like("name","Newsletter:%").order("created_at",{ascending:!1}).limit(50);if(s){const v=new Date(Date.now()-s*864e5).toISOString();f=f.gte("created_at",v)}const{data:g,error:b}=await f;if(b)throw b;return g||[]}}),{data:h}=lt({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:f,error:g}=await q.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",r).order("sent_at",{ascending:!1}).limit(2e3);if(g)throw g;return f||[]}}),p=async()=>{if(!(!i||!t)){c(!0);try{const{data:f,error:g}=await q.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(g)throw g;if(!f||f.length===0){ae.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:b}=await q.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!b)throw new Error("Original campaign not found");const{data:v,error:j}=await q.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:b.subject,body_html:b.body_html,from_email:b.from_email,reply_to_email:b.reply_to_email,total_recipients:f.length,status:"draft"}).select("id").single();if(j)throw j;const _=f.map(A=>({campaign_id:v.id,contact_id:A.contact_id,email:A.email,name:A.name,status:"pending"}));for(let A=0;A<_.length;A+=500){const T=_.slice(A,A+500),{error:D}=await q.from("email_campaign_recipients").insert(T);if(D)throw D}const{error:S}=await q.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:v.id}});if(S)throw S;ae.success(`Resending to ${f.length} non-opener${f.length===1?"":"s"}!`),l(null),n.invalidateQueries({queryKey:["newsletter-campaigns"]})}catch(f){console.error("Resend failed:",f),ae.error(`Resend failed: ${f.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(fe,{children:e.jsxs(Ae,{className:"p-0",children:[e.jsxs("div",{className:"px-4 py-3 border-b flex items-center gap-2",children:[e.jsx(yo,{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(f=>{const g=f.sent_count||0,b=g>0?f.open_count/g*100:0,v=g>0?f.click_count/g*100:0,j=f.sent_at?Yv(new Date,new Date(f.sent_at)):0,_=f.status==="sent"&&j>=3&&g>0&&f.open_counta(f.id),children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),_&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>l(f),children:[e.jsx(BA,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),f.status==="sent"&&g>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(bG,{icon:e.jsx(cr,{className:"h-3.5 w-3.5"}),label:"Sent",value:g,sub:`of ${f.total_recipients}`}),e.jsx(bG,{icon:e.jsx(Ir,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:f.open_count,sub:`${b.toFixed(1)}%`,children:e.jsx(xi,{value:b,className:"h-1 mt-1"})}),e.jsx(bG,{icon:e.jsx(oc,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:f.click_count,sub:`${v.toFixed(1)}%`,children:e.jsx(xi,{value:v,className:"h-1 mt-1"})}),e.jsx(bG,{icon:e.jsx(uL,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:f.bounce_count,sub:f.bounce_count>0?"review":"none"})]})]},f.id)})})]})}),e.jsx(ug,{open:!!r,onOpenChange:f=>!f&&a(null),children:e.jsxs(ox,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(r0,{children:e.jsx(a0,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:h?h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients yet."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2",children:"Recipient"}),e.jsx("th",{className:"text-left py-2",children:"Opened"}),e.jsx("th",{className:"text-left py-2",children:"Clicked"}),e.jsx("th",{className:"text-left py-2",children:"Status"})]})}),e.jsx("tbody",{children:h.map(f=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"py-2",children:[e.jsx("div",{className:"font-medium truncate max-w-[180px]",children:f.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:f.email})]}),e.jsx("td",{className:"py-2 text-xs",children:f.opened_at?e.jsx(ze,{variant:"default",className:"text-xs",children:ks(new Date(f.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:f.clicked_at?e.jsx(ze,{variant:"default",className:"text-xs bg-purple-600",children:ks(new Date(f.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[f.status==="sent"&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"sent"}),f.status==="pending"&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:"queued"}),f.status==="failed"&&e.jsx(ze,{variant:"destructive",className:"text-xs",title:f.error_message||"",children:"failed"}),f.status==="suppressed"&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},f.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Oo,{open:!!i,onOpenChange:f=>!f&&l(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Resend to non-openers?"}),e.jsxs(Mo,{children:["This will send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',i==null?void 0:i.subject,'"']})," again only to contacts who didn't open the original. Consider tweaking the subject next time — but a clean resend is a great way to recover lost opens."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{disabled:o,children:"Cancel"}),e.jsx(jo,{onClick:p,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(BA,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function bG({icon:s,label:t,value:n,sub:r,children:a}){return e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsxs("div",{className:"flex items-baseline gap-1.5 mt-0.5",children:[e.jsx("span",{className:"text-lg font-bold",children:n.toLocaleString()}),r&&e.jsx("span",{className:"text-xs text-muted-foreground",children:r})]}),a]})}function iKs(){const{user:s}=gs(),t=In(),n=Gt(),{data:r=[],isLoading:a}=lt({queryKey:["scheduled-email-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("email_campaigns").select("id, name, subject, scheduled_at, total_recipients, status, created_at").eq("user_id",s.id).eq("status","scheduled").order("scheduled_at",{ascending:!0});if(u)throw u;return d||[]},refetchInterval:3e4}),i=async(d,u)=>{const{data:{session:h}}=await q.auth.getSession(),f=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-schedule-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({action:d,campaign_id:u})})).json();if(!f.success)throw new Error(f.error||`Failed to ${d}`);return f},l=gt({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=gt({mutationFn:d=>i("delete",d),onSuccess:()=>{ae.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)}),c=gt({mutationFn:async({id:d,iso:u})=>{const{error:h}=await q.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(h)throw h;await i("schedule",d)},onSuccess:()=>{ae.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)});return a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading scheduled emails..."}):r.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(gr,{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(oKs,{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 oKs({campaign:s,onEdit:t,onCancel:n,onDelete:r,onReschedule:a,isBusy:i}){const l=s.scheduled_at?new Date(s.scheduled_at):null,[o,c]=N.useState(!1),[d,u]=N.useState(l||void 0),[h,p]=N.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),f=()=>{if(!d)return ae.error("Pick a date");const g=new Date(`${ks(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(g).getTime()gp(g.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:f,disabled:i,children:[i&&e.jsx(ss,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(Gc,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Cancel this scheduled send?"}),e.jsxs(Mo,{children:["The email will move back to ",e.jsx("strong",{children:"Draft"})," and won't send at the scheduled time. You can re-schedule or delete it later."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep scheduled"}),e.jsx(jo,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this scheduled email?"}),e.jsx(Mo,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep"}),e.jsx(jo,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}function lKs({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 _G({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:Et("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(ga,{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 cKs({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(lKs,{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(_G,{icon:e.jsx(xr,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(_G,{icon:e.jsx(Ir,{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(_G,{icon:e.jsx(oc,{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(_G,{icon:e.jsx(gr,{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 ZZe=["Gmail","Mass Email","Campaign","Client Portal Invite"],dKs={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 uKs(){const{user:s}=gs(),[t,n]=yl(),{data:r=[],isLoading:a}=rwt(),[i,l]=N.useState(""),[o,c]=N.useState("all"),[d,u]=N.useState("30"),[h,p]=N.useState(!1),[f,g]=N.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:b}=bh(),{data:v=0}=lt({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:L}=await q.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return L||0},refetchInterval:3e4});N.useEffect(()=>{const L=new URLSearchParams(t);f==="scheduled"?L.set("tab","scheduled"):L.delete("tab"),n(L,{replace:!0})},[f]);const j=N.useMemo(()=>Array.from(new Set(r.map(L=>L.contact_id).filter(Boolean))),[r]),{data:_}=lt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,j.length],enabled:j.length>0,queryFn:async()=>{const{data:L}=await q.from("innercircle_contacts").select("id, first_name, last_name").in("id",j),M=new Map;return(L||[]).forEach(F=>{M.set(F.id,[F.first_name,F.last_name].filter(Boolean).join(" ")||"Contact")}),M}}),S=N.useMemo(()=>{const L=d==="all"?null:Date.now()-parseInt(d)*864e5,M=i.trim().toLowerCase();return r.filter(F=>{if(o!=="all"&&F.channel!==o||L&&new Date(F.sent_at).getTime(){const L={};let M=0,F=0,z=0;return S.forEach(V=>{L[V.channel]=(L[V.channel]||0)+1,(V.channel==="Campaign"||V.channel==="Mass Email")&&(z++,V.opened_at&&M++,V.clicked_at&&F++)}),{byChannel:L,opened:M,clicked:F,trackable:z}},[S]),T=d==="all"?"All time":`Last ${d} days`,D=ZZe.map(L=>A.byChannel[L]?`${A.byChannel[L]} ${L}`:null).filter(Boolean).join(" · ");return e.jsx(Cs,{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(cr,{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 ${f==="sent"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(cr,{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 ${f==="scheduled"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(gr,{className:"h-3.5 w-3.5"})," Scheduled",v>0&&e.jsx(ze,{variant:"secondary",className:"ml-0.5 h-5 min-w-5 px-1.5 text-xs",children:v})]})]}),e.jsxs(B,{onClick:()=>p(!0),className:"rounded-full",children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs($r,{value:f,onValueChange:L=>g(L),className:"space-y-5",children:[e.jsxs(ls,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(cKs,{total:S.length,opened:A.opened,clicked:A.clicked,trackable:A.trackable,scheduled:v,rangeLabel:T,channelSummary:D,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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search subject, recipient, contact...",value:i,onChange:L=>l(L.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(us,{value:o,onValueChange:c,children:[e.jsx(cs,{className:"w-[170px] rounded-full h-9",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Channels"}),ZZe.map(L=>e.jsx(Ze,{value:L,children:L},L))]})]}),e.jsxs(us,{value:d,onValueChange:u,children:[e.jsx(cs,{className:"w-[150px] rounded-full h-9",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"7",children:"Last 7 days"}),e.jsx(Ze,{value:"30",children:"Last 30 days"}),e.jsx(Ze,{value:"90",children:"Last 90 days"}),e.jsx(Ze,{value:"365",children:"Last year"}),e.jsx(Ze,{value:"all",children:"All time"})]})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-3 px-1",children:[e.jsx(vw,{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(aKs,{rangeDays:d==="all"?null:parseInt(d)}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):S.length===0?e.jsx(fe,{className:"rounded-2xl",children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Hs,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No sent emails match your filters."})]})}):e.jsx(fe,{className:"rounded-2xl overflow-hidden",children:e.jsx(Ae,{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(Kw,{children:e.jsxs(Ac,{children:[e.jsxs(Mc,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(vw,{className:"h-3 w-3"})]}),e.jsx(yc,{className:"max-w-xs",children:"Open & click tracking works for Mass Emails and Campaigns. Emails sent through your connected Gmail inbox aren't tracked."})]})})})]})}),e.jsx("tbody",{children:S.slice(0,500).map(L=>{const M=L.contact_id?_==null?void 0:_.get(L.contact_id):null,F=L.channel==="Campaign"||L.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:ks(new Date(L.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(ze,{variant:"outline",className:dKs[L.channel],children:L.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:L.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:L.to_email}),e.jsx("td",{className:"py-3 px-4",children:L.contact_id&&M?e.jsx(Ln,{to:`/mission-control/contacts/${L.contact_id}`,className:"text-primary hover:underline",children:M}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-3 px-4",children:F?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs(ze,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(xr,{className:"h-3 w-3"})," Delivered"]}),L.opened_at&&e.jsxs(ze,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Ir,{className:"h-3 w-3"})," Opened"]}),L.clicked_at&&e.jsxs(ze,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(oc,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},L.id)})})]}),S.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",S.length," — narrow your filters to see more."]})]})})})]}),e.jsx(ls,{value:"scheduled",className:"mt-0",children:e.jsx(iKs,{})})]}),e.jsx(Ty,{open:h,onOpenChange:p,gmailEmail:b})]})})}const QZe={Crown:xf,FileText:Nr,Users:_n,Globe:lc,Star:ua,Phone:Pr,MessageSquare:Ci,PenTool:a4,Video:vr,Gift:Bi},wG=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function hKs(){var kt,Qt;const s=In(),{user:t}=gs(),{data:n}=Cy(),{data:r}=ars(),{data:a}=hrs(),{data:i}=npt(),{data:l}=XD(),{data:o}=rrs(),c=mrs(),d=irs(),u=lrs(),h=crs(),p=drs(),f=urs(),g=ors(),[b,v]=N.useState(null),[j,_]=N.useState(!1),[S,A]=N.useState(null),[T,D]=N.useState(""),[L,M]=N.useState(""),[F,z]=N.useState([]),[V,W]=N.useState(null),[K,Y]=N.useState(null),[ee,ne]=N.useState(null),[oe,pe]=N.useState(!1),[ce,de]=N.useState(""),[ie,ye]=N.useState(""),[_e,Me]=N.useState(""),[Te,Ce]=N.useState(""),Ee=(ns,$s)=>a==null?void 0:a.some(Ds=>Ds.plan_id===ns&&Ds.relationship_type_id===$s&&Ds.active),De=ns=>a==null?void 0:a.find($s=>$s.relationship_type_id===ns&&$s.active),Ie=async(ns,$s)=>{const Ds=Ee(ns,$s);await c.mutateAsync({planId:ns,relationshipTypeId:$s,active:!Ds})},Fe=(r==null?void 0:r.filter(ns=>ns.active&&!ns.owner_user_id))||[],qe=(r==null?void 0:r.filter(ns=>ns.owner_user_id===(t==null?void 0:t.id)))||[],ve=n==null?void 0:n.find(ns=>ns.id===b),Je=b?De(b):null,we=r==null?void 0:r.find(ns=>ns.id===(Je==null?void 0:Je.plan_id)),it=async()=>{if(!T.trim())return;const ns=await d.mutateAsync({name:T,description:L});ns&&F.length>0&&await p.mutateAsync({planId:ns.id,items:F}),Ye()},Ne=async()=>{!T.trim()||!S||(await u.mutateAsync({id:S,name:T,description:L}),await p.mutateAsync({planId:S,items:F}),Ye())},He=ns=>{var $s;A(ns.id),D(ns.name),M(ns.description||""),z((($s=ns.items)==null?void 0:$s.map(Ds=>({month_number:Ds.month_number,action_type_id:Ds.action_type_id,default_script_id:Ds.default_script_id||void 0,notes:Ds.notes||void 0})))||[]),_(!0)},$e=async(ns,$s)=>{if(ns.owner_user_id===(t==null?void 0:t.id)){He(ns);return}try{const Ds=await g.mutateAsync({sourcePlanId:ns.id,newName:`${ns.name} (My Copy)`});if(!Ds)return;await c.mutateAsync({planId:ns.id,relationshipTypeId:$s,active:!1}),await c.mutateAsync({planId:Ds.id,relationshipTypeId:$s,active:!0}),A(Ds.id),D(Ds.name),M(Ds.description||""),z((ns.items||[]).map(Dt=>({month_number:Dt.month_number,action_type_id:Dt.action_type_id,default_script_id:Dt.default_script_id||void 0,notes:Dt.notes||void 0}))),_(!0)}catch{}},Ye=()=>{_(!1),A(null),D(""),M(""),z([])},Ke=(ns,$s)=>{Y($s)},rt=(ns,$s,Ds)=>{z(Dt=>[...Dt.filter($t=>$t.month_number!==ns),{month_number:ns,action_type_id:$s,default_script_id:Ds}]),W(null),Y(null)},tt=ns=>{z($s=>$s.filter(Ds=>Ds.month_number!==ns))},at=async()=>{if(!ce.trim()||!ie.trim()||!K)return;const ns=await f.mutateAsync({actionTypeId:K,title:ce,scriptBody:ie,emailSubject:_e||void 0,tone:Te||void 0});ns&&V!==null&&rt(V,K,ns.id),pe(!1),de(""),ye(""),Me(""),Ce("")},Ge=K?o==null?void 0:o.filter(ns=>ns.action_type_id===K&&ns.active):[],dt=ns=>QZe[ns||"Phone"]||Pr,Bt=ns=>QZe[ns||"Users"]||_n;return e.jsxs(Cs,{title:"Touchpoint Plans",description:"Assign plans to your contact groups",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Touchpoint Plans"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(fl,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(B,{onClick:()=>_(!0),className:"w-full sm:w-auto",children:[e.jsx(As,{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(ns=>ns.active).map(ns=>{const $s=Bt(ns.icon),Ds=(i==null?void 0:i[ns.id])||0,Dt=De(ns.id),St=r==null?void 0:r.find(ht=>ht.id===(Dt==null?void 0:Dt.plan_id)),$t=b===ns.id;return e.jsxs("button",{onClick:()=>v(ns.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${$t?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx($s,{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:ns.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Ds," contacts"]})]}),St?e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[e.jsx(zi,{className:"h-3 w-3 mr-1"}),St.name.split(" ")[0]]}):e.jsx(ze,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},ns.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:b&&ve?e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[(()=>{const ns=Bt(ve.icon);return e.jsx(ns,{className:"h-5 w-5"})})(),ve.name," Touchpoint Plan"]}),e.jsxs(Hn,{children:["Choose a plan for your ",ve.name," contacts"]})]}),e.jsxs(Ae,{className:"space-y-6",children:[we&&e.jsxs("div",{className:"p-4 bg-primary/5 rounded-lg border border-primary/20",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[e.jsx(zi,{className:"h-4 w-4 text-green-500"}),"Currently using: ",we.name]}),we.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:we.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:g.isPending||c.isPending,onClick:()=>$e(we,b),children:[e.jsx(Nv,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>Ie(we.id,b),children:"Disable"})]})]}),we.items&&we.items.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:wG.map((ns,$s)=>{var $t,ht;const Ds=(($t=we.items)==null?void 0:$t.filter(Ut=>Ut.month_number===$s+1))||[],Dt=(ht=Ds[0])==null?void 0:ht.action_type,St=Dt?dt(Dt.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${Ds.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:ns}),St&&e.jsx(St,{className:"h-4 w-4 mx-auto mt-1",style:{color:(Dt==null?void 0:Dt.color)||"#3B82F6"}})]},$s)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:we?"Switch to a Different Plan":"Choose a Plan"}),Fe.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"}),Fe.map(ns=>{var Ds;const $s=(we==null?void 0:we.id)===ns.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${$s?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ns.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((Ds=ns.items)==null?void 0:Ds.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>ne(ns.id),children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:g.isPending,onClick:()=>{const Dt=`${ns.name} (Copy)`;g.mutate({sourcePlanId:ns.id,newName:Dt})},children:e.jsx(ta,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:$s?"outline":"default",disabled:$s||c.isPending,onClick:()=>Ie(ns.id,b),children:$s?"Active":"Use This"})]})]},ns.id)})]}),qe.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),qe.map(ns=>{var Ds;const $s=(we==null?void 0:we.id)===ns.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${$s?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ns.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((Ds=ns.items)==null?void 0:Ds.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>ne(ns.id),children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>He(ns),children:e.jsx(Nv,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(ns.id),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})}),e.jsx(B,{size:"sm",variant:$s?"outline":"default",disabled:$s||c.isPending,onClick:()=>Ie(ns.id,b),children:$s?"Active":"Use This"})]})]},ns.id)})]}),Fe.length===0&&qe.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No plans available. Create a custom plan to get started."})]})]})]}):e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(yr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Select a contact group to view and assign plans"})]})})})]}),e.jsx(fe,{className:"bg-muted/50",children:e.jsx(Ae,{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(bs,{open:j,onOpenChange:ns=>{ns?_(!0):Ye()},children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:S?"Edit Touchpoint Plan":"Create Custom Touchpoint Plan"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(ge,{id:"plan-name",value:T,onChange:ns=>D(ns.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Ts,{id:"plan-description",value:L,onChange:ns=>M(ns.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(se,{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:wG.map((ns,$s)=>{const Ds=$s+1,Dt=F.find(ht=>ht.month_number===Ds),St=Dt?l==null?void 0:l.find(ht=>ht.id===Dt.action_type_id):null,$t=St?dt(St.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>W(V===Ds?null:Ds),className:` w-full p-3 rounded-lg border text-center transition-all ${Dt?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${V===Ds?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:ns}),$t?e.jsx($t,{className:"h-5 w-5 mx-auto mt-1",style:{color:(St==null?void 0:St.color)||"#3B82F6"}}):e.jsx(As,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),Dt&&e.jsx("button",{type:"button",onClick:ht=>{ht.stopPropagation(),tt(Ds)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(Fn,{className:"h-3 w-3"})})]},$s)})}),V!==null&&!K&&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 ",wG[V-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(ns=>ns.active).map(ns=>{const $s=dt(ns.icon);return e.jsxs("button",{type:"button",onClick:()=>Ke(V,ns.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx($s,{className:"h-4 w-4",style:{color:ns.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:ns.name})]},ns.id)})})]}),V!==null&&K&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-medium",children:"Step 2: Select a script (optional)"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>Y(null),children:[e.jsx(fl,{className:"h-4 w-4 mr-1"})," Back"]})]}),e.jsxs("div",{className:"space-y-2 max-h-[300px] overflow-y-auto pr-1",children:[e.jsx("button",{type:"button",onClick:()=>rt(V,K),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"})]})}),Ge==null?void 0:Ge.map(ns=>e.jsx("button",{type:"button",onClick:()=>rt(V,K,ns.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:ns.title}),ns.tone&&e.jsx(ze,{variant:"secondary",className:"text-xs mt-1",children:ns.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[ns.script_body.substring(0,100),"..."]})]})},ns.id)),e.jsxs("button",{type:"button",onClick:()=>pe(!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(As,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Create Custom Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Write your own script for this action"})]})]})]})]})]}),F.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[F.length," touchpoint",F.length!==1?"s":""," per year"]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:Ye,children:"Cancel"}),e.jsxs(B,{onClick:S?Ne:it,disabled:!T.trim()||d.isPending||u.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),S?"Save Changes":"Create Plan"]})]})]})}),e.jsx(bs,{open:oe,onOpenChange:pe,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-title",children:"Script Title"}),e.jsx(ge,{id:"script-title",value:ce,onChange:ns=>de(ns.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(us,{value:Te,onValueChange:Ce,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select tone..."})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"friendly",children:"Friendly"}),e.jsx(Ze,{value:"professional",children:"Professional"}),e.jsx(Ze,{value:"casual",children:"Casual"}),e.jsx(Ze,{value:"formal",children:"Formal"})]})]})]}),((Qt=(kt=l==null?void 0:l.find(ns=>ns.id===K))==null?void 0:kt.name)==null?void 0:Qt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(ge,{id:"script-email-subject",value:_e,onChange:ns=>Me(ns.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Ts,{id:"script-body",value:ie,onChange:ns=>ye(ns.target.value),placeholder:"Write your script here... You can use {{FirstName}} and {{LastName}} as placeholders.",rows:6}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Tip: Use ","{{FirstName}}"," and ","{{LastName}}"," as placeholders"]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>pe(!1),children:"Cancel"}),e.jsxs(B,{onClick:at,disabled:!ce.trim()||!ie.trim()||f.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(bs,{open:!!ee,onOpenChange:ns=>{ns||ne(null)},children:e.jsx(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const ns=r==null?void 0:r.find(Dt=>Dt.id===ee);if(!ns)return null;const $s=ns.owner_user_id===(t==null?void 0:t.id),Ds=[...ns.items||[]].sort((Dt,St)=>Dt.month_number-St.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[ns.name,!$s&&e.jsx(ze,{variant:"secondary",children:"Template"})]}),ns.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ns.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Ds.length," touchpoint",Ds.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(Dt,St)=>St+1).map(Dt=>{const St=Ds.find(Es=>Es.month_number===Dt),$t=St?l==null?void 0:l.find(Es=>Es.id===St.action_type_id):null,ht=St!=null&&St.default_script_id?o==null?void 0:o.find(Es=>Es.id===St.default_script_id):null,Ut=$t?dt($t.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${St?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:wG[Dt-1]}),St&&$t?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Ut&&e.jsx(Ut,{className:"h-4 w-4",style:{color:$t.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:$t.name}),ht&&e.jsx(ze,{variant:"outline",className:"text-xs",children:ht.title})]}),ht&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:ht.script_body}),St.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:St.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},Dt)})})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>ne(null),children:"Close"}),$s?e.jsxs(B,{onClick:()=>{const Dt=r==null?void 0:r.find(St=>St.id===ee);Dt&&(ne(null),He(Dt))},children:[e.jsx(Nv,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs(B,{disabled:g.isPending,onClick:()=>{g.mutate({sourcePlanId:ns.id,newName:`${ns.name} (Copy)`}),ne(null)},children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const INe="https://cma.relevelup.com";function awt({open:s,onOpenChange:t,cma:n}){var ne;const{user:r}=gs(),{toast:a}=Ua(),[i,l]=N.useState([]),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f,g]=N.useState(""),[b,v]=N.useState(""),[j,_]=N.useState(!1),[S,A]=N.useState(null),[T,D]=N.useState(!1),[L,M]=N.useState(!1),[F,z]=N.useState(null);N.useEffect(()=>{!s||!r||(async()=>{var Me;const[oe,pe,ce,de,ie]=await Promise.all([q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),q.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),q.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),q.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),q.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),ye=(oe.data||[]).filter(Te=>Te.email&&Te.email.includes("@"));l(ye),A(pe.data||null),D(!!((Me=ce.data)!=null&&Me.is_active)),M(!!(de.data&&de.data.length>0)),z(ie.data||null);const _e=n.contact_id?ye.find(Te=>Te.id===n.contact_id):null;_e&&(c(_e),p(_e.email))})()},[s,r,n.contact_id]),N.useEffect(()=>{var de;if(!s)return;const oe=((de=n.subject)==null?void 0:de.address)||"your home",pe=((S==null?void 0:S.name)||"").split(" ")[0]||"your agent",ce=(o==null?void 0:o.first_name)||"there";g(`Your home value report for ${oe}`),v(`Hi ${ce}, I put together a fresh market analysis for ${oe}. It pulls live comparable sales, active listings, and pending homes near you so you can see exactly where your value sits today. Take a look here — it only takes a minute: {{cma_link}} When you've had a chance to review, I'd love to hear your thoughts. Reply to this email or give me a call any time. Talk soon, ${(S==null?void 0:S.name)||pe}`)},[s,o==null?void 0:o.id,S==null?void 0:S.name,(ne=n.subject)==null?void 0:ne.address]);const V=N.useMemo(()=>T?"Gmail (your inbox)":L?"Amazon SES":null,[T,L]),W=!!(h.trim()&&f.trim()&&b.trim()&&V&&!j),K=oe=>{c(oe),p(oe.email||""),u(!1)},Y=oe=>{const pe=`${INe}/${n.share_token}?e=${oe}`,ie=b.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(Me=>`

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

`).join(""),ye=S!=null&&S.use_email_signature&&(S!=null&&S.email_signature)?`
${S.email_signature}
`:`
${S!=null&&S.name?`
${S.name}
`:""} ${S!=null&&S.brokerage_name?`
${S.brokerage_name}
`:""} ${S!=null&&S.phone?`
${S.phone}
`:""} ${S!=null&&S.email?``:""}
`,_e=``;return`
${ie} ${ye}
Prepared with LevelUp · ReLevelUp Real Estate
${_e}
`},ee=async()=>{if(!(!r||!W)){_(!0);try{const{data:oe,error:pe}=await q.from("cma_email_sends").insert({cma_id:n.id,agent_id:r.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:h.trim(),subject:f.trim(),sent_via:T?"gmail":"ses"}).select("id").single();if(pe)throw pe;const ce=Y(oe.id);if(T){const{data:de,error:ie}=await q.functions.invoke("gmail-send",{body:{to:h.trim(),subject:f.trim(),body:ce}});if(ie)throw ie;if(!(de!=null&&de.success))throw new Error((de==null?void 0:de.error)||"Gmail send failed")}else if(L){const de=(F==null?void 0:F.display_name)||(S==null?void 0:S.name)||"ReLevelUp",ie=`${de.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:ye,error:_e}=await q.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${de} <${ie}>`,subject:f.trim(),body_html:ce,reply_to:(F==null?void 0:F.reply_to_email)||(S==null?void 0:S.email)||void 0}});if(_e)throw _e;if(!(ye!=null&&ye.success))throw new Error((ye==null?void 0:ye.error)||"SES send failed")}o&&!n.contact_id&&await q.from("cmas").update({contact_id:o.id}).eq("id",n.id),a({title:"CMA sent",description:`Delivered to ${h.trim()}`}),t(!1)}catch(oe){console.error("Send CMA error:",oe),a({title:"Send failed",description:oe.message||"Could not send email",variant:"destructive"})}finally{_(!1)}}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"w-5 h-5"}),"Send CMA to contact"]})}),V?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:V})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact"}),e.jsxs(Wo,{open:d,onOpenChange:u,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[o?`${o.first_name} ${o.last_name||""}`.trim():"Pick a contact (optional)",e.jsx(Hg,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(zo,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search contacts…"}),e.jsxs(e0,{children:[e.jsx(t0,{children:"No contacts with email found."}),e.jsx(s0,{children:i.map(oe=>e.jsxs(ex,{value:`${oe.first_name} ${oe.last_name||""} ${oe.email}`,onSelect:()=>K(oe),children:[e.jsx(Lr,{className:Et("w-4 h-4 mr-2",(o==null?void 0:o.id)===oe.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[oe.first_name," ",oe.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:oe.email})]})]},oe.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"To email"}),e.jsx(ge,{type:"email",value:h,onChange:oe=>p(oe.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subject"}),e.jsx(ge,{value:f,onChange:oe=>g(oe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Message"}),e.jsx(Ts,{rows:10,value:b,onChange:oe=>v(oe.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("code",{children:"{{cma_link}}"})," will be replaced with a styled button linking to ",e.jsxs("code",{children:["cma.relevelup.com/",n.share_token]}),". Email opens are tracked and shown on the contact's Signals."]})]}),e.jsxs("div",{className:"rounded border bg-muted/40 p-3 text-sm flex items-center gap-2",children:[e.jsx(tr,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Public link:"}),e.jsx("a",{className:"text-primary underline truncate",href:`${INe}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${INe}/${n.share_token}`})]})]}):e.jsx("div",{className:"p-4 rounded border bg-amber-50 text-amber-900 text-sm",children:"Connect Gmail or set up Amazon SES under Integrations to send CMAs by email."}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:ee,disabled:!W,children:[j?e.jsx(ss,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(cr,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function mKs({onCreated:s}){const[t,n]=N.useState(!1),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),h=LWs(),p=J_t(),{toast:f}=Ua(),[g,b]=N.useState([]),v=async()=>{var S;b([]);try{const A=await h.mutateAsync({address:r,city:i,state:o,zip:d});b(A.matches||[]),(S=A.matches)!=null&&S.length||f({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(A){f({title:"Search failed",description:A.message,variant:"destructive"})}},j=async S=>{const A=await p.mutateAsync({subject:S});n(!1),s(A.id)},_=async()=>{if(!r||!i||!o){f({title:"Address, city, state required"});return}const S=await p.mutateAsync({subject:{address:r,city:i,state:o,zip:d}});n(!1),s(S.id)};return e.jsxs(bs,{open:t,onOpenChange:n,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(As,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{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(ge,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:S=>a(S.target.value)}),e.jsx(ge,{placeholder:"City",value:i,onChange:S=>l(S.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{placeholder:"ST",maxLength:2,value:o,onChange:S=>c(S.target.value.toUpperCase())}),e.jsx(ge,{placeholder:"ZIP",value:d,onChange:S=>u(S.target.value)})]})]}),e.jsxs(B,{onClick:v,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(ss,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(_r,{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((S,A)=>{var T;return e.jsxs("button",{onClick:()=>j(S),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:S.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[S.city,", ",S.state," ",S.zip," · ",S.bedrooms??"?"," bd / ",S.bathrooms??"?"," ba · ",((T=S.sqft)==null?void 0:T.toLocaleString())??"?"," sqft",S.mlsNumber?` · MLS# ${S.mlsNumber}`:""," · ",S.source_provider]})]},A)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs(B,{variant:"outline",onClick:_,disabled:p.isPending,className:"w-full",children:[e.jsx(zr,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function pKs(){const{data:s,isLoading:t}=EWs(),n=PWs(),r=In(),{toast:a}=Ua(),[i,l]=N.useState(null);return e.jsx(Cs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-6xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx(Nr,{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(mKs,{onCreated:o=>r(`/mission-control/cma/${o}`)})]}),t?e.jsx("p",{className:"text-muted-foreground",children:"Loading…"}):s!=null&&s.length?e.jsx("div",{className:"grid gap-3",children:s.map(o=>{var c,d,u;return e.jsx(fe,{className:"hover:shadow-md transition",children:e.jsxs(Ae,{className:"p-4 flex flex-wrap items-center gap-3 justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx("div",{className:"font-semibold",children:o.title||((c=o.subject)==null?void 0:c.address)||"Untitled CMA"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[(d=o.subject)==null?void 0:d.city,", ",(u=o.subject)==null?void 0:u.state," · ",o.buyer_mode?"Buyer":"Seller"," ·"," ",e.jsx(ze,{variant:o.status==="shared"?"default":"secondary",className:"ml-1",children:o.status})]}),o.price_likely?e.jsxs("div",{className:"text-sm mt-1",children:["Suggested: ",e.jsxs("span",{className:"font-medium",children:["$",o.price_likely.toLocaleString()]}),o.price_low&&o.price_high?e.jsxs("span",{className:"text-muted-foreground",children:[" · $",o.price_low.toLocaleString(),"–$",o.price_high.toLocaleString()]}):null]}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>r(`/mission-control/cma/${o.id}`),children:"Open"}),o.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{const h=`https://cma.relevelup.com/${o.share_token}`;navigator.clipboard.writeText(h),a({title:"Share link copied"})},children:e.jsx(tr,{className:"w-4 h-4"})}),e.jsxs(B,{variant:"secondary",size:"sm",onClick:()=>l(o),children:[e.jsx(Hs,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{confirm("Delete this CMA?")&&n.mutate(o.id)},children:e.jsx(bn,{className:"w-4 h-4"})})]})]})},o.id)})}):e.jsx(fe,{children:e.jsx(Ae,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(awt,{open:!!i,onOpenChange:o=>!o&&l(null),cma:i})]})})}function fKs(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 XZe(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 xKs({subject:s,comps:t,radiusMiles:n,onMarkerClick:r}){const a=N.useRef(null),i=N.useRef(null),l=N.useRef([]),[o,c]=N.useState(null);N.useEffect(()=>{let u=!1;return(async()=>{const{data:h}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();!u&&(h!=null&&h.value)&&c(h.value)})(),()=>{u=!0}},[]);const d=N.useMemo(()=>{const u=Number(s==null?void 0:s.latitude),h=Number(s==null?void 0:s.longitude);return!Number.isFinite(u)||!Number.isFinite(h)?null:{lat:u,lng:h}},[s==null?void 0:s.latitude,s==null?void 0:s.longitude]);return N.useEffect(()=>{if(!o||!a.current||i.current||!d)return;ml.accessToken=o;const u=new ml.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new ml.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:XZe(d.lat,d.lng,n)}),u.addLayer({id:"radius-fill",type:"fill",source:"radius",paint:{"fill-color":"#2563eb","fill-opacity":.08}}),u.addLayer({id:"radius-line",type:"line",source:"radius",paint:{"line-color":"#2563eb","line-width":2,"line-dasharray":[2,2],"line-opacity":.5}})}),i.current=u,()=>{u.remove(),i.current=null}},[o,d]),N.useEffect(()=>{const u=i.current;if(!u||!d)return;const h=()=>{const p=u.getSource("radius");p&&p.setData(XZe(d.lat,d.lng,n))};u.isStyleLoaded()?h():u.once("load",h)},[n,d]),N.useEffect(()=>{const u=i.current;if(!u||!d)return;l.current.forEach(v=>v.remove()),l.current=[];const h=document.createElement("div");h.style.cssText=` width: 28px; height: 28px; border-radius: 50%; background: hsl(222 47% 11%); border: 3px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.3); display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: 700; `,h.textContent="★";const p=new ml.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new ml.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(p);const f=new ml.LngLatBounds;f.extend([d.lng,d.lat]),t.forEach((v,j)=>{const _=Number(v.latitude),S=Number(v.longitude);if(!Number.isFinite(_)||!Number.isFinite(S))return;const A=fKs(v.status),T=document.createElement("div");T.style.cssText="width:22px;height:22px;";const D=document.createElement("div");D.style.cssText=` width: 22px; height: 22px; border-radius: 50%; background: ${A}; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.25); cursor: pointer; opacity: ${v.selected===!1?.4:1}; transition: transform 0.15s; transform-origin: center; `,D.onmouseenter=()=>{D.style.transform="scale(1.25)"},D.onmouseleave=()=>{D.style.transform="scale(1)"},r&&(D.onclick=()=>r(j)),T.appendChild(D);const L=v.soldPrice||v.price,M=new ml.Popup({offset:14}).setHTML(`
${v.address??""}
${v.status??""}`+(L?` · $${L.toLocaleString()}`:"")+"
"),F=new ml.Marker({element:T}).setLngLat([S,_]).setPopup(M).addTo(u);l.current.push(F),f.extend([S,_])});const b=n*1.60934/110.574;f.extend([d.lng,d.lat+b]),f.extend([d.lng,d.lat-b]);try{u.fitBounds(f,{padding:60,maxZoom:14,duration:600})}catch{}},[t,d,n,s.address,r]),d?e.jsxs("div",{className:"relative w-full h-[420px] rounded-xl overflow-hidden border shadow-sm",children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),!o&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted/40 text-sm text-muted-foreground",children:"Loading map…"}),e.jsxs("div",{className:"absolute bottom-3 left-3 bg-background/95 backdrop-blur rounded-lg shadow-md border px-3 py-2 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"hsl(222 47% 11%)"}}),"Subject"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#2563eb"}}),"Active"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#f59e0b"}}),"Pending"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#16a34a"}}),"Closed"]})]})]}):e.jsx("div",{className:"w-full h-[420px] rounded-xl border bg-muted/30 flex items-center justify-center text-sm text-muted-foreground",children:"Subject property has no coordinates — map unavailable."})}let Sg=null;function gKs(){if(Sg)return Sg;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return Sg={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},Sg;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 Sg={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},Sg;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(Sg={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},Sg):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(Sg={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},Sg):(Sg={canRunVirtualBg:!0,renderer:r},Sg)}catch{return Sg={canRunVirtualBg:!0},Sg}}const yKs=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function vKs({value:s,onChange:t,isLoading:n=!1,disabled:r=!1,className:a}){const i=N.useRef(null),[l,o]=N.useState(!1),[c]=N.useState(()=>gKs()),d=!c.canRunVirtualBg,{data:u=[],refetch:h}=lt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:v}}=await q.auth.getUser();if(!v)return[];const{data:j,error:_}=await q.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return _?(console.error("Failed to load backgrounds:",_),[]):j||[]}}),p=u.map(v=>({type:"image",label:v.name,imageUrl:v.image_url,thumbnail:v.thumbnail_url||v.image_url})),f=[...yKs,...p],g=v=>v.type!==s.type?!1:v.type==="image"?v.imageUrl===s.imageUrl:!0,b=async v=>{var _;const j=(_=v.target.files)==null?void 0:_[0];if(j){if(!j.type.startsWith("image/")){ae.error("Please select an image file");return}if(j.size>5*1024*1024){ae.error("Image must be under 5MB");return}o(!0);try{const{data:{user:S}}=await q.auth.getUser();if(!S)throw new Error("Not authenticated");const A=j.name.split(".").pop()||"jpg",T=`${S.id}/${crypto.randomUUID()}.${A}`,{error:D}=await q.storage.from("video-backgrounds").upload(T,j,{contentType:j.type});if(D)throw D;const{data:L}=q.storage.from("video-backgrounds").getPublicUrl(T),M=L.publicUrl,{error:F}=await q.from("video_backgrounds").insert({name:j.name.replace(/\.[^.]+$/,""),image_url:M,thumbnail_url:M,category:"custom",is_stock:!1,user_id:S.id});if(F)throw F;await h(),t({type:"image",imageUrl:M,blurRadius:15}),ae.success("Background uploaded!")}catch(S){console.error("Upload error:",S),ae.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Et("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(Dl,{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(ss,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),f.map((v,j)=>{const _=g(v);return e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:v.type,imageUrl:v.imageUrl,blurRadius:15}),className:Et("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:[v.type==="none"&&e.jsx(eL,{className:"h-4 w-4 text-muted-foreground"}),v.type==="blur"&&e.jsx("div",{className:"w-full h-full bg-gradient-to-br from-primary/20 to-primary/40 flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Blur"})}),v.type==="image"&&v.thumbnail&&e.jsx("img",{src:v.thumbnail,alt:v.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:v.label})]},`${v.type}-${v.imageUrl||j}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var v;return(v=i.current)==null?void 0:v.click()},className:Et("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(ss,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(As,{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:b}),e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({...s,mirror:!s.mirror}),className:Et("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(i9,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var uD=typeof self<"u"?self:{};function iwt(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=uD,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 lwt(s){uD.setTimeout(()=>{throw s},0)}var oTe,jKs=iwt(610401301,!1),eQe=iwt(748402147,!0);function tQe(){var s=uD.navigator;return s&&(s=s.userAgent)?s:""}const sQe=uD.navigator;function B1e(s){return B1e[" "](s),s}oTe=sQe&&sQe.userAgentData||null,B1e[" "]=function(){};const cwt={};let E7=null;function NKs(s){const t=s.length;let n=3*t/4;n%3?n=Math.floor(n):"=.".indexOf(s[t-1])!=-1&&(n="=.".indexOf(s[t-2])!=-1?n-2:n-1);const r=new Uint8Array(n);let a=0;return function(i,l){function o(d){for(;c>4),h!=64&&(l(u<<4&240|h>>2),p!=64&&l(h<<6&192|p))}}(s,function(i){r[a++]=i}),a!==n?r.subarray(0,a):r}function dwt(){if(!E7){E7={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));cwt[n]=r;for(let a=0;a0)&&(tQe().indexOf("Trident")!=-1||tQe().indexOf("MSIE")!=-1))&&typeof btoa=="function";const nQe=/[-_.]/g,SKs={"-":"+",_:"/",".":"="};function CKs(s){return SKs[s]||""}function hwt(s){if(!uwt)return NKs(s);s=nQe.test(s)?s.replace(nQe,CKs):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,pwt(s=Error(),"incident"),lwt(s))}}function CR(){return typeof BigInt=="function"}var TR=typeof Symbol=="function"&&typeof Symbol()=="symbol";function sj(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 AKs=sj("jas",void 0,!0),rQe=sj(void 0,"0di"),zF=sj(void 0,"1oa"),gy=sj(void 0,Symbol()),MKs=sj(void 0,"0ub"),IKs=sj(void 0,"0ubs"),cTe=sj(void 0,"0ubsb"),PKs=sj(void 0,"0actk"),pD=sj("m_m","Pa",!0),aQe=sj();const fwt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},xwt=Object.defineProperties,ji=TR?AKs:"Ga";var d6;const iQe=[];function UU(s,t){TR||ji in s||xwt(s,fwt),s[ji]|=t}function Ym(s,t){TR||ji in s||xwt(s,fwt),s[ji]=t}function qU(s){return UU(s,34),s}function b$(s){return UU(s,8192),s}Ym(iQe,7),d6=Object.freeze(iQe);var fD={};function _y(s,t){return t===void 0?s.h!==OM&&!!(2&(0|s.v[ji])):!!(2&t)&&s.h!==OM}const OM={};function CLe(s,t){if(s!=null){if(typeof s=="string")s=s?new Aw(s,hD):RM();else if(s.constructor!==Aw)if(kLe(s))s=s.length?new Aw(new Uint8Array(s),hD):RM();else{if(!t)throw Error();s=void 0}}return s}class oQe{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 LKs=Object.freeze({});function gwt(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"),lQe=$1e(s=>typeof s=="string"),RKs=$1e(s=>typeof s=="boolean"),U1e=typeof uD.BigInt=="function"&&typeof uD.BigInt(0)=="bigint";function yy(s){var t=s;if(lQe(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(DKs(t)&&!Number.isSafeInteger(t))throw Error(String(t));return U1e?BigInt(s):s=RKs(s)?s?"1":"0":lQe(s)?s.trim()||"0":String(s)}var dTe=$1e(s=>U1e?s>=FKs&&s<=BKs:s[0]==="-"?cQe(s,OKs):cQe(s,zKs));const OKs=Number.MIN_SAFE_INTEGER.toString(),FKs=U1e?BigInt(Number.MIN_SAFE_INTEGER):void 0,zKs=Number.MAX_SAFE_INTEGER.toString(),BKs=U1e?BigInt(Number.MAX_SAFE_INTEGER):void 0;function cQe(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;Au=t,em=(s-t)/4294967296>>>0}function xD(s){if(s<0){dQe(-s);const[t,n]=ALe(Au,em);Au=t>>>0,em=n>>>0}else dQe(s)}function TLe(s){const t=UKs||(UKs=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),em=0,Au=t.getUint32(0,!0)}function vwt(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:_$(s,t)}function qKs(s,t){return yy(CR()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):_$(s,t))}function bwt(s,t){return CR()?yy(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else CR()?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+uQe(n)+uQe(s));return n}function uQe(s){return s=String(s),"0000000".slice(s.length)+s}function ELe(s,t){if(2147483648&t)if(CR())s=""+(BigInt(0|t)<>>0));else{const[n,r]=ALe(s,t);s="-"+_$(n,r)}else s=_$(s,t);return s}function q1e(s){if(s.length<16)xD(Number(s));else if(CR())s=BigInt(s),Au=Number(s&BigInt(4294967295))>>>0,em=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");em=Au=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));em*=1e6,Au=1e6*Au+i,Au>=4294967296&&(em+=Math.trunc(Au/4294967296),em>>>=0,Au>>>=0)}if(t){const[r,a]=ALe(Au,em);Au=r,em=a}}}function ALe(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function Sb(s){return Array.prototype.slice.call(s)}const VU=typeof BigInt=="function"?BigInt.asIntN:void 0,VKs=typeof BigInt=="function"?BigInt.asUintN:void 0,FM=Number.isSafeInteger,V1e=Number.isFinite,gD=Math.trunc,HKs=yy(0);function A7(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 lw(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function w$(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 _wt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const GKs=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function HU(s){switch(typeof s){case"bigint":return!0;case"number":return V1e(s);case"string":return GKs.test(s);default:return!1}}function AR(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return V1e(s)?0|s:void 0}function wwt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return V1e(s)?s>>>0:void 0}function jwt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(q1e(s),ELe(Au,em))}function MLe(s){if(s=gD(s),!FM(s)){xD(s);var t=Au,n=em;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=vwt(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function Nwt(s){var t=gD(Number(s));return FM(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),jwt(s))}function kwt(s){var t=gD(Number(s));return FM(t)?yy(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),CR()?yy(VU(64,BigInt(s))):yy(jwt(s)))}function Swt(s){return FM(s)?s=yy(MLe(s)):(s=gD(s),FM(s)?s=String(s):(xD(s),s=ELe(Au,em)),s=yy(s)),s}function Uge(s){const t=typeof s;return s==null?s:t==="bigint"?yy(VU(64,s)):HU(s)?t==="string"?kwt(s):Swt(s):void 0}function Cwt(s){if(typeof s!="string")throw Error();return s}function GU(s){if(s!=null&&typeof s!="string")throw Error();return s}function jf(s){return s==null||typeof s=="string"?s:void 0}function ILe(s,t,n,r){return s!=null&&s[pD]===fD?s:Array.isArray(s)?((r=(n=0|s[ji])|32&r|2&r)!==n&&Ym(s,r),new t(s)):(n?2&r?((s=t[rQe])||(qU((s=new t).v),s=t[rQe]=s),t=s):t=new t:t=void 0,t)}function WKs(s,t,n){if(t)e:{if(!HU(t=s))throw lTe("int64");switch(typeof t){case"string":t=kwt(t);break e;case"bigint":t=yy(VU(64,t));break e;default:t=Swt(t)}}else t=Uge(s);return(s=t)==null?n?HKs:void 0:s}const KKs={};let YKs=function(){try{return B1e(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class LNe{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 ZKs=YKs?(Object.setPrototypeOf(LNe.prototype,Map.prototype),Object.defineProperties(LNe.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),LNe):class extends Map{constructor(){super()}};function hQe(s){return s}function DNe(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var vN=class extends ZKs{constructor(s,t,n=hQe,r=hQe){super(),this.J=0|s[ji],this.K=t,this.S=n,this.fa=this.K?QKs:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return DNe(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 QKs(s,t,n,r,a,i){return s=ILe(s,r,n,i),a&&(s=LLe(s)),s}function XKs(s){return[s,this.get(s)]}let JKs;function mQe(){return JKs||(JKs=new vN(qU([]),void 0,void 0,void 0,KKs))}function H1e(s){return gy?s[gy]:void 0}function qge(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}vN.prototype.toJSON=void 0;var uTe=class{};const eYs={Ka:!0};function tYs(s,t){t<100||mD(IKs,1)}function G1e(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=gy;!a&&TR&&l&&(i=s[l])&&qge(i,tYs),l=[];var o=s.length;let c;i=4294967295;let d=!1;const u=!!(64&t),h=u?128&t?0:-1:void 0;1&t||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?i=--o:c=void 0,!u||128&t||a||(d=!0,i=i-h+h)),t=void 0;for(var p=0;p=i){const g=p-h;(t??(t={}))[g]=f}else l[p]=f}if(c)for(let f in c){if((o=c[f])==null||(o=n(o,r))==null)continue;let g;p=+f,u&&!Number.isNaN(p)&&(g=p+h){g[v]=Sb(j)}),g.da=f.da,g}(s)),l}function sYs(s){return s[0]=j$(s[0]),s[1]=j$(s[1]),s}function j$(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return dTe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[ji];return s.length===0&&1&t?void 0:G1e(s,t,j$)}if(s!=null&&s[pD]===fD)return Twt(s);if(s instanceof Aw){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(uwt){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 vN?s=s.size!==0?s.V(sYs):void 0:void 0}return s}let nYs,rYs;function Twt(s){return G1e(s=s.v,0|s[ji],j$)}function sM(s,t){return Ewt(s,t[0],t[1])}function Ewt(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[ji],eQe&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(eQe)throw Error("carr");mD(PKs,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&Ym(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 Ym(s,64|a|r),s}function aYs(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[ji];return s.length===0&&1&n?void 0:pQe(s,n,t)}if(s!=null&&s[pD]===fD)return fQe(s);if(s instanceof vN){if(2&(t=s.J))return s;if(!s.size)return;if(n=qU(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 Wc(s,t,n,r){PR(s),Gm(s=s.v,0|s[ji],t,n,r)}function Gm(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[ji]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function iA(){return LKs===void 0?2:4}function oA(s,t,n,r,a){let i=s.v,l=0|i[ji];r=_y(s,l)?1:r,a=!!a||r===3,r===2&&IR(s)&&(i=s.v,l=0|i[ji]);let o=(s=RLe(i,t))===d6?7:0|s[ji],c=OLe(o,l);var d=!(4&c);if(d){4&c&&(s=Sb(s),o=0,c=rM(c,l),l=Gm(i,l,t,s));let u=0,h=0;for(;u{const o=ILe(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!_y(r)&&u6(s,t),r}function Yl(s,t,n,r){let a=s.v,i=0|a[ji];if((t=Dwt(a,i,t,n,r))==null)return t;if(i=0|a[ji],!_y(s,i)){const l=LLe(t);l!==t&&(IR(s)&&(a=s.v,i=0|a[ji]),i=Gm(a,i,n,t=l,r),u6(a,i))}return t}function Rwt(s,t,n,r,a,i,l,o){var c=_y(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&IR(s)&&(n=0|(t=s.v)[ji]);var d=(s=RLe(t,a))===d6?7:0|s[ji],u=OLe(d,n);if(o=!(4&u)){var h=s,p=n;const f=!!(2&u);f&&(p|=2);let g=!f,b=!0,v=0,j=0;for(;v32)for(a|=(127&n)>>4,i=3;i<32&&128&n;i+=7)n=l[o++],a|=(127&n)<>>0,a>>>0);throw Error()}function VLe(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function Hge(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],aM(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 iYs(s){return z4(s)}function aM(s,t){if(s.g=t,t>s.l)throw Error()}function Fwt(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 zwt(s,t){if(t==0)return RM();var n=Fwt(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):$Ks?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?RM():new Aw(n,hD)}var xQe=[];function Bwt(s,t,n,r){if(Gge.length){const a=Gge.pop();return a.o(r),a.g.init(s,t,n,r),a}return new oYs(s,t,n,r)}function $wt(s){s.g.clear(),s.l=-1,s.h=-1,Gge.length<100&&Gge.push(s)}function Uwt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=qw(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function ipe(s){switch(s.h){case 0:s.h!=0?ipe(s):VLe(s.g);break;case 1:aM(s=s.g,s.g+8);break;case 2:if(s.h!=2)ipe(s);else{var t=qw(s.g);aM(s=s.g,s.g+t)}break;case 5:aM(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!Uwt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}ipe(s)}break;default:throw Error()}}function WU(s,t,n){const r=s.g.l;var a=qw(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 HLe(s){var t=qw(s.g),n=Fwt(s=s.g,t);if(s=s.h,bKs){var r,a=s;(r=PNe)||(r=PNe=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(jG===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),jG=!0}catch{jG=!1}}throw!jG&&(PNe=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?g3():(o=s[i++],l<194||(192&o)!=128?(i--,g3()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?g3():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,g3()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?g3():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,g3()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):g3(),n.length>=8192&&(c=JZe(c,n),n.length=0)}i=JZe(c,n)}return i}function qwt(s){const t=qw(s.g);return zwt(s.g,t)}function K1e(s,t,n){var r=qw(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let lYs;function yQe(s){return s?/^-?\d+$/.test(s)?(q1e(s),new mTe(Au,em)):null:cYs||(cYs=new mTe(0,0))}var mTe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let cYs;function GL(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 DR(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function Y1e(s,t){if(t>=0)DR(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function GLe(s){var t=Au;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 yD(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function n1(s,t,n){DR(s.g,8*t+n)}function WLe(s,t){return n1(s,t,2),t=s.g.end(),yD(s,t),t.push(s.h),t}function KLe(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 Z1e(s,t,n){n1(s,t,2),DR(s.g,n.length),yD(s,s.g.end()),yD(s,n)}function Wge(s,t,n,r){n!=null&&(t=WLe(s,t),r(n,s),KLe(s,t))}function nj(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var YLe=nj(),Vwt=nj(),ZLe=nj(),QLe=nj(),XLe=nj(),Hwt=nj(),dYs=nj(),Q1e=nj(),Gwt=nj(),Wwt=nj();function rj(s,t,n){var r=s.v;gy&&gy in r&&(r=r[gy])&&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 Ni=class{constructor(s,t){this.v=Ewt(s,t,void 0,2048)}toJSON(){return Twt(this)}j(){var a;var s=HYs,t=this.v,n=s.g,r=gy;if(TR&&r&&((a=t[r])==null?void 0:a[n])!=null&&mD(MKs,3),t=s.g,aQe&&gy&&aQe===void 0&&(r=(n=this.v)[gy])&&(r=r.da))try{r(n,t,eYs)}catch(i){lwt(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[ji];return DLe(this,s,t)?PLe(this,s,!0):new this.constructor(MR(s,t,!1))}};Ni.prototype[pD]=fD,Ni.prototype.toString=function(){return this.v.toString()};var RR=class{constructor(s,t,n){this.g=s,this.h=t,s=YLe,this.l=!!s&&n===s||!1}};function X1e(s,t){return new RR(s,t,YLe)}function Kwt(s,t,n,r,a){Wge(s,n,Xwt(t,r),a)}const uYs=X1e(function(s,t,n,r,a){return s.h===2&&(WU(s,BLe(t,r,n),a),!0)},Kwt),hYs=X1e(function(s,t,n,r,a){return s.h===2&&(WU(s,BLe(t,r,n),a),!0)},Kwt);var J1e=Symbol(),ebe=Symbol(),pTe=Symbol(),vQe=Symbol(),bQe=Symbol();let Ywt,Zwt;function h6(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 nYs||(nYs=[0,void 0,!0]);case"number":return h>0?void 0:h===0?rYs||(rYs=[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,Ywt??(Ywt=i),Zwt??(Zwt=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 e8e(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=h6(ebe,JLe,e8e,r).T),l||(l=t8e(r)),a)}function t8e(s){let t=s[pTe];if(t!=null)return t;const n=h6(ebe,JLe,e8e,s);return t=n.ma?(r,a)=>Ywt(r,a,n):(r,a)=>{for(;Uwt(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=pYs(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,ipe(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=zwt(o.g,c);l=void 0,o=r,c&&((l=o[gy]??(o[gy]=new uTe))[i]??(l[i]=[])).push(c)}}return(r=H1e(r))&&(r.da=n.qa[bQe]),!0},s[pTe]=t,s[bQe]=mYs.bind(s),t}function mYs(s,t,n,r){var a=this[ebe];const i=this[pTe],l=sM(void 0,a.T),o=H1e(s);if(o){var c=!1,d=a.ba;if(d){if(a=(u,h,p)=>{if(p.length!==0)if(d[h])for(const f of p){u=Bwt(f);try{c=!0,i(l,u)}finally{$wt(u)}}else r==null||r(s,h,p)},t==null)qge(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[ji];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=ER(u),p=(f,g)=>{if(bN(s,f,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}g!=null&&(u=Gm(s,u,f,g,h)),delete o[f]};t==null?gwt(l,0|l[ji],(f,g)=>{p(f,g)}):p(t,bN(l,t,h))}}}}function pYs(s){const t=(s=Qwt(s))[0].g;if(s=s[1]){const n=t8e(s),r=h6(ebe,JLe,e8e,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function tbe(s,t,n){s[t]=n.h}function sbe(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=h6(J1e,tbe,sbe,r).T),a||(a=Jwt(r)))}function Jwt(s){let t=s[vQe];if(!t){const n=h6(J1e,tbe,sbe,s);t=(r,a)=>ejt(r,a,n),s[vQe]=t}return t}function ejt(s,t,n){gwt(s,0|s[ji],(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=Qwt(c))[0].h;if(c=c[1]){const u=Jwt(c),h=h6(J1e,tbe,sbe,c).T;c=l.ma?Zwt(h,u):(p,f,g)=>d(p,f,g,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||mD(cTe,3)}}),(s=H1e(s))&&qge(s,(r,a,i)=>{for(yD(t,t.g.end()),r=0;r{Wge(s,n,sM([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),GL(s.g,n.h,n.g);break;default:n=yQe(t),GL(s.g,n.h,n.g)}}function njt(s,t,n){(t=AR(t))!=null&&t!=null&&(n1(s,n,0),Y1e(s.g,t))}function rjt(s,t,n){(t=_wt(t))!=null&&(n1(s,n,0),s.g.g.push(t?1:0))}function ajt(s,t,n){(t=jf(t))!=null&&Z1e(s,n,owt(t))}function ijt(s,t,n,r,a){Wge(s,n,Xwt(t,r),a)}function ojt(s,t,n){(t=t==null||typeof t=="string"||t instanceof Aw?t:void 0)!=null&&Z1e(s,n,ULe(t,!0).buffer)}function ljt(s,t,n){(t=wwt(t))!=null&&t!=null&&(n1(s,n,0),DR(s.g,t))}function cjt(s,t,n){return(s.h===5||s.h===2)&&(t=LR(t,0|t[ji],n),s.h==2?K1e(s,Hge,t):t.push(Hge(s.g)),!0)}var rm=hx(function(s,t,n){return s.h===5&&(mx(t,n,Hge(s.g)),!0)},tjt,Q1e),gYs=FR(cjt,function(s,t,n){if((t=OR(lw,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"))||(q1e(r),r=_$(Au,em))),r;if(a==="number")return(r=gD(r))>=0&&FM(r)||(xD(r),r=vwt(Au,em)),r}}(t),t!=null&&(typeof t=="string"&&gQe(t),t!=null))switch(n1(s,n,0),typeof t){case"number":s=s.g,xD(t),GL(s,Au,em);break;case"bigint":n=BigInt.asUintN(64,t),n=new hTe(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),GL(s.g,n.h,n.g);break;default:n=gQe(t),GL(s.g,n.h,n.g)}},dYs),qm=hx(function(s,t,n){return s.h===0&&(mx(t,n,z4(s.g)),!0)},njt,QLe),KU=FR(function(s,t,n){return(s.h===0||s.h===2)&&(t=LR(t,0|t[ji],n),s.h==2?K1e(s,z4,t):t.push(z4(s.g)),!0)},function(s,t,n){if((t=OR(AR,t))!=null&&t.length){n=WLe(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=Bwt(n,void 0,void 0,i);try{const l=new s,o=l.v;t8e(t)(o,n);var a=l}finally{$wt(n)}}return a}}function nbe(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}}}};ejt(this.v,t,h6(J1e,tbe,sbe,s)),yD(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=jQe.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=FNe)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function NG(s,...t){if(t.length===0)return NQe(s[0]);let n=s[0];for(let r=0;r({index:Lv(r,1)??0??-1,score:Eh(r,2)??0,categoryName:jf(Ou(r,3))??""??"",displayName:jf(Ou(r,4))??""??""})),headIndex:t,headName:n}}function YYs(s){const t={classifications:_N(s,AYs,1).map(n=>{var r;return d8e(((r=Yl(n,yjt,4))==null?void 0:r.g())??[],Lv(n,2)??0,jf(Ou(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(dTe(n)?n=Number(n):(n=VU(64,n),n=dTe(n)?Number(n):String(n)),n):HU(n)?typeof n=="number"?MLe(n):Nwt(n):void 0}(Ou(s,2,void 0,void 0,Uge))!=null&&(t.timestampMs=Hjt(Ou(s,2,void 0,void 0,Uge)??Awt)),t}function Gjt(s){var l,o;var t=oA(s,3,lw,iA()),n=oA(s,2,AR,iA()),r=oA(s,1,jf,iA()),a=oA(s,9,jf,iA());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function RQe(s,t){if(s.length!==t.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${s.length} vs. ${t.length}).`);let n=0,r=0,a=0;for(let i=0;i=1&&Number(s[1])>=17))}async function OQe(s){if(typeof importScripts!="function"){const t=document.createElement("script");return t.src=s.toString(),t.crossOrigin="anonymous",new Promise((n,r)=>{t.addEventListener("load",()=>{n()},!1),t.addEventListener("error",a=>{r(a)},!1),document.body.appendChild(t)})}try{importScripts(s.toString())}catch(t){if(!(t instanceof TypeError))throw t;await self.import(s.toString())}}function Yjt(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 Si(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 FQe(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]=Yjt(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 zQe(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 A_(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function Mk(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)}}hP.forVisionTasks=function(s,t=!1){return SG("vision",s??NG``,t)},hP.forTextTasks=function(s,t=!1){return SG("text",s??NG``,t)},hP.forGenAiTasks=function(s,t=!1){return SG("genai",s??NG``,t)},hP.forAudioTasks=function(s,t=!1){return SG("audio",s??NG``,t)},hP.isSimdSupported=function(s=!1){return Wjt(s)};async function QYs(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await OQe(i),!self.ModuleFactory||l&&(await OQe(l),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&c&&((i=self.Module).locateFile=c.locateFile,c.mainScriptUrlOrBlob&&(i.mainScriptUrlOrBlob=c.mainScriptUrlOrBlob)),c=await self.ModuleFactory(self.Module||c),self.ModuleFactory=self.Module=void 0,new a(c,o)})(s,n.wasmLoaderPath,n.assetLoaderPath,t,{locateFile:a=>a.endsWith(".wasm")?n.wasmBinaryPath.toString():n.assetBinaryPath&&a.endsWith(".data")?n.assetBinaryPath.toString():a}),await s.o(r),s}function $Ne(s,t){const n=Yl(s.baseOptions,Kge,1)||new Kge;typeof t=="string"?(Wc(n,2,GU(t)),Wc(n,1)):t instanceof Uint8Array&&(Wc(n,1,CLe(t,!1)),Wc(n,2)),Qi(s.baseOptions,0,1,n)}function BQe(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 ui(s,t){s.C=Math.max(s.C,t)}function obe(s,t){s.B=new c0,wy(s.B,2,"PassThroughCalculator"),fu(s.B,"free_memory"),Ll(s.B,"free_memory_unused_out"),Vu(t,"free_memory"),r1(t,s.B)}function vD(s,t){fu(s.B,t),Ll(s.B,t+"_unused_out")}function lbe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var vTe=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=Yl(this.baseOptions,Kge,1))!=null&&a.g()||(i=Yl(this.baseOptions,Kge,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=Yl(d.baseOptions,MQe,3);if(!h){var p=h=new MQe,f=new kQe;Mz(p,4,ope,f)}"delegate"in u&&(u.delegate==="GPU"?(u=h,p=new jYs,Mz(u,2,ope,p)):(u=h,p=new kQe,Mz(u,4,ope,p))),Qi(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),$Ne(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)$Ne(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const u=[];for(var h=0;;){const{done:p,value:f}=await d.read();if(p)break;u.push(f),h+=f.length}if(u.length===0)return new Uint8Array(0);if(u.length===1)return u[0];d=new Uint8Array(h),h=0;for(const p of u)d.set(p,h),h+=p.length;return d}(c.modelAssetBuffer).then(d=>{$Ne(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=NYs(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,BQe(this)}finishProcessing(){this.g.finishProcessing(),BQe(this)}close(){this.B=void 0,this.g.closeGraph()}};function j4(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}vTe.prototype.close=vTe.prototype.close;class XYs{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 $Qe(s,t,n){const r=s.g;if(n=j4(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 UQe(s,t){const n=s.g,r=j4(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=j4(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=j4(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 XYs(n,r,a,i)}function u8e(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function JYs(s,t,n,r){return u8e(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=UQe(s,!0)),n=s.u):(s.A||(s.A=UQe(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function Zjt(s,t,n){return u8e(s,t),s=j4(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 Qjt(s,t,n){u8e(s,t),s.B||(s.B=j4(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 eZs(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var Xjt=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=j4(s.createProgram(),"Failed to create WebGL program"),this.X=$Qe(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=$Qe(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 L2(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 bTe(s){var t=L2(s,1);if(!t){if(t=L2(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=bD(s);var n=h8e(s);if(Qjt(n,r,Jjt(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 bTe(this)}N(){return Jjt(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=bD(this),a=h8e(this);r.activeTexture(r.TEXTURE1),n=Zjt(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=e2t(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),Qjt(a,r,n),JYs(a,r,!1,()=>{t2t(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),_Te(this)}),eZs(a),_Te(this)}}s.push(n)}return new yp(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&bD(this).deleteTexture(L2(this,2)),qQe=-1}};yp.prototype.close=yp.prototype.close,yp.prototype.clone=yp.prototype.clone,yp.prototype.getAsWebGLTexture=yp.prototype.N,yp.prototype.getAsFloat32Array=yp.prototype.ia,yp.prototype.getAsUint8Array=yp.prototype.ja,yp.prototype.hasWebGLTexture=yp.prototype.R,yp.prototype.hasFloat32Array=yp.prototype.ka,yp.prototype.hasUint8Array=yp.prototype.Fa;var qQe=250;function $b(...s){return s.map(([t,n])=>({start:t,end:n}))}const tZs=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((VQe=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:Kjt()?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?'),Si(this,r||"input_audio",i=>{Si(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){A_(this,"__graph_config__",t=>{s(t)}),Si(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),Si(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){Si(this,t,r=>{const[a,i]=FQe(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){Si(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){Si(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){Si(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){Si(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){Si(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){Si(this,t,r=>{Si(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){Si(this,t,r=>{zQe(this,Object.keys(s),a=>{zQe(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){Si(this,n,a=>{Si(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){Si(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){Si(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){Si(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){Si(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){Si(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){Si(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){Si(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)Si(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){Si(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){Si(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){Si(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){Si(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){Si(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){Si(this,t,n=>{Si(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){Si(this,n,r=>{Si(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){Si(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){Si(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){Si(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){Si(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){Si(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){Si(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)Si(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){A_(this,s,t),Si(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){Mk(this,s,t),Si(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){A_(this,s,t),Si(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){Mk(this,s,t),Si(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){A_(this,s,t),Si(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){Mk(this,s,t),Si(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){A_(this,s,t),Si(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){Mk(this,s,t),Si(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){A_(this,s,t),Si(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){Mk(this,s,t),Si(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){A_(this,s,t),Si(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){Mk(this,s,t),Si(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){A_(this,s,t),Si(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){Mk(this,s,t),Si(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?'),A_(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),Si(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 VQe{get ga(){return this.i}pa(s,t,n){Si(this,t,r=>{const[a,i]=FQe(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){A_(this,s,t),Si(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){Mk(this,s,t),Si(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var VQe,Ub=class extends tZs{};async function Gl(s,t,n){return async function(r,a,i,l){return QYs(r,a,i,l)}(s,n.canvas??(Kjt()?void 0:document.createElement("canvas")),t,n)}function s2t(s,t,n,r){if(s.U){const i=new jjt;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].");Li(i,1,(a.left+a.right)/2),Li(i,2,(a.top+a.bottom)/2),Li(i,4,a.right-a.left),Li(i,3,a.bottom-a.top)}else Li(i,1,.5),Li(i,2,.5),Li(i,4,1),Li(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(Li(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=Yjt(t);n=Eh(i,3)*o/l,a=Eh(i,4)*l/o,Li(i,4,n),Li(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 qb(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'.");s2t(s,t,n,s.C+1)}function ij(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'.");s2t(s,t,n,r)}function _D(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 yp([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var jy=class extends vTe{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new Xjt}l(s,t=!0){if("runningMode"in s&&Wc(this.baseOptions,2,w$(!!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()}};jy.prototype.close=jy.prototype.close;var cv=class extends jy{constructor(s,t){super(new Ub(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},Qi(s=this.h=new abe,0,1,t=new gh),Li(this.h,2,.5),Li(this.h,3,.3)}get baseOptions(){return Yl(this.h,gh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Li(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Li(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},qb(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},ij(this,s,n,t),this.j}m(){var s=new Ay;Vu(s,"image_in"),Vu(s,"norm_rect_in"),ic(s,"detections");const t=new Ey;rj(t,RYs,this.h);const n=new c0;wy(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),fu(n,"IMAGE:image_in"),fu(n,"NORM_RECT:norm_rect_in"),Ll(n,"DETECTIONS:detections"),n.o(t),r1(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=bjt(i),this.j.detections.push(Gjt(r));ui(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{ui(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};cv.prototype.detectForVideo=cv.prototype.G,cv.prototype.detect=cv.prototype.F,cv.prototype.setOptions=cv.prototype.o,cv.createFromModelPath=async function(s,t){return Gl(cv,s,{baseOptions:{modelAssetPath:t}})},cv.createFromModelBuffer=function(s,t){return Gl(cv,s,{baseOptions:{modelAssetBuffer:t}})},cv.createFromOptions=function(s,t){return Gl(cv,s,t)};var m8e=$b([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]),p8e=$b([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]),f8e=$b([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),n2t=$b([474,475],[475,476],[476,477],[477,474]),x8e=$b([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]),g8e=$b([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),r2t=$b([469,470],[470,471],[471,472],[472,469]),y8e=$b([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]),a2t=[...m8e,...p8e,...f8e,...x8e,...g8e,...y8e],i2t=$b([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 HQe(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var eh=class extends jy{constructor(s,t){super(new Ub(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,Qi(s=this.h=new Tjt,0,1,t=new gh),this.A=new Cjt,Qi(this.h,0,3,this.A),this.u=new abe,Qi(this.h,0,2,this.u),wN(this.u,4,1),Li(this.u,2,.5),Li(this.A,2,.5),Li(this.h,4,.5)}get baseOptions(){return Yl(this.h,gh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return"numFaces"in s&&wN(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Li(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Li(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Li(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 HQe(this),qb(this,s,t),this.j}G(s,t,n){return HQe(this),ij(this,s,n,t),this.j}m(){var s=new Ay;Vu(s,"image_in"),Vu(s,"norm_rect"),ic(s,"face_landmarks");const t=new Ey;rj(t,FYs,this.h);const n=new c0;wy(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),fu(n,"IMAGE:image_in"),fu(n,"NORM_RECT:norm_rect"),Ll(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),r1(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=YU(i),this.j.faceLandmarks.push(ibe(r));ui(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{ui(this,r)}),this.outputFaceBlendshapes&&(ic(s,"blendshapes"),Ll(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=rbe(i),this.j.faceBlendshapes.push(d8e(r.g()??[]));ui(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{ui(this,r)})),this.outputFacialTransformationMatrixes&&(ic(s,"face_geometry"),Ll(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=Yl(r=OYs(i),TYs,2))&&this.j.facialTransformationMatrixes.push({rows:Lv(r,1)??0??0,columns:Lv(r,2)??0??0,data:oA(r,3,lw,iA()).slice()??[]});ui(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{ui(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};eh.prototype.detectForVideo=eh.prototype.G,eh.prototype.detect=eh.prototype.F,eh.prototype.setOptions=eh.prototype.o,eh.createFromModelPath=function(s,t){return Gl(eh,s,{baseOptions:{modelAssetPath:t}})},eh.createFromModelBuffer=function(s,t){return Gl(eh,s,{baseOptions:{modelAssetBuffer:t}})},eh.createFromOptions=function(s,t){return Gl(eh,s,t)},eh.FACE_LANDMARKS_LIPS=m8e,eh.FACE_LANDMARKS_LEFT_EYE=p8e,eh.FACE_LANDMARKS_LEFT_EYEBROW=f8e,eh.FACE_LANDMARKS_LEFT_IRIS=n2t,eh.FACE_LANDMARKS_RIGHT_EYE=x8e,eh.FACE_LANDMARKS_RIGHT_EYEBROW=g8e,eh.FACE_LANDMARKS_RIGHT_IRIS=r2t,eh.FACE_LANDMARKS_FACE_OVAL=y8e,eh.FACE_LANDMARKS_CONTOURS=a2t,eh.FACE_LANDMARKS_TESSELATION=i2t;var v8e=$b([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 GQe(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function WQe(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 KQe(s,t=!0){const n=[];for(const a of s){var r=rbe(a);s=[];for(const i of r.g())r=t&&Lv(i,1)!=null?Lv(i,1)??0:-1,s.push({score:Eh(i,2)??0,index:r,categoryName:jf(Ou(i,3))??""??"",displayName:jf(Ou(i,4))??""??""});n.push(s)}return n}var I0=class extends jy{constructor(s,t){super(new Ub(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Qi(s=this.j=new Mjt,0,1,t=new gh),this.u=new i8e,Qi(this.j,0,2,this.u),this.D=new a8e,Qi(this.u,0,3,this.D),this.A=new Ajt,Qi(this.u,0,2,this.A),this.h=new zYs,Qi(this.j,0,3,this.h),Li(this.A,2,.5),Li(this.u,4,.5),Li(this.D,2,.5)}get baseOptions(){return Yl(this.j,gh,1)}set baseOptions(s){Qi(this.j,0,1,s)}o(s){var a,i,l,o;if(wN(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Li(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Li(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Li(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new UI,n=t,r=yTe(s.cannedGesturesClassifierOptions,(a=Yl(this.h,UI,3))==null?void 0:a.l());Qi(n,0,2,r),Qi(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Yl(this.h,UI,3))==null||i.g());return s.customGesturesClassifierOptions?(Qi(n=t=new UI,0,2,r=yTe(s.customGesturesClassifierOptions,(l=Yl(this.h,UI,4))==null?void 0:l.l())),Qi(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Yl(this.h,UI,4))==null||o.g()),this.l(s)}Ha(s,t){return GQe(this),qb(this,s,t),WQe(this)}Ia(s,t,n){return GQe(this),ij(this,s,n,t),WQe(this)}m(){var s=new Ay;Vu(s,"image_in"),Vu(s,"norm_rect"),ic(s,"hand_gestures"),ic(s,"hand_landmarks"),ic(s,"world_hand_landmarks"),ic(s,"handedness");const t=new Ey;rj(t,BYs,this.j);const n=new c0;wy(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),fu(n,"IMAGE:image_in"),fu(n,"NORM_RECT:norm_rect"),Ll(n,"HAND_GESTURES:hand_gestures"),Ll(n,"LANDMARKS:hand_landmarks"),Ll(n,"WORLD_LANDMARKS:world_hand_landmarks"),Ll(n,"HANDEDNESS:handedness"),n.o(t),r1(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=YU(i);const l=[];for(const o of _N(r,wjt,1))l.push({x:Eh(o,1)??0,y:Eh(o,2)??0,z:Eh(o,3)??0,visibility:Eh(o,4)??0});this.landmarks.push(l)}ui(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{ui(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=WL(i);const l=[];for(const o of _N(r,_jt,1))l.push({x:Eh(o,1)??0,y:Eh(o,2)??0,z:Eh(o,3)??0,visibility:Eh(o,4)??0});this.worldLandmarks.push(l)}ui(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{ui(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(...KQe(r,!1)),ui(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{ui(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...KQe(r)),ui(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{ui(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function YQe(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}I0.prototype.recognizeForVideo=I0.prototype.Ia,I0.prototype.recognize=I0.prototype.Ha,I0.prototype.setOptions=I0.prototype.o,I0.createFromModelPath=function(s,t){return Gl(I0,s,{baseOptions:{modelAssetPath:t}})},I0.createFromModelBuffer=function(s,t){return Gl(I0,s,{baseOptions:{modelAssetBuffer:t}})},I0.createFromOptions=function(s,t){return Gl(I0,s,t)},I0.HAND_CONNECTIONS=v8e;var P0=class extends jy{constructor(s,t){super(new Ub(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Qi(s=this.h=new i8e,0,1,t=new gh),this.u=new a8e,Qi(this.h,0,3,this.u),this.j=new Ajt,Qi(this.h,0,2,this.j),wN(this.j,3,1),Li(this.j,2,.5),Li(this.u,2,.5),Li(this.h,4,.5)}get baseOptions(){return Yl(this.h,gh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return"numHands"in s&&wN(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Li(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Li(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Li(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],qb(this,s,t),YQe(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],ij(this,s,n,t),YQe(this)}m(){var s=new Ay;Vu(s,"image_in"),Vu(s,"norm_rect"),ic(s,"hand_landmarks"),ic(s,"world_hand_landmarks"),ic(s,"handedness");const t=new Ey;rj(t,$Ys,this.h);const n=new c0;wy(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),fu(n,"IMAGE:image_in"),fu(n,"NORM_RECT:norm_rect"),Ll(n,"LANDMARKS:hand_landmarks"),Ll(n,"WORLD_LANDMARKS:world_hand_landmarks"),Ll(n,"HANDEDNESS:handedness"),n.o(t),r1(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=YU(i),this.landmarks.push(ibe(r));ui(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{ui(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=WL(i),this.worldLandmarks.push(Pz(r));ui(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{ui(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=rbe(c);const d=[];for(const u of r.g())d.push({score:Eh(u,2)??0,index:Lv(u,1)??0??-1,categoryName:jf(Ou(u,3))??""??"",displayName:jf(Ou(u,4))??""??""});o.push(d)}l.call(i,...o),ui(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{ui(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};P0.prototype.detectForVideo=P0.prototype.G,P0.prototype.detect=P0.prototype.F,P0.prototype.setOptions=P0.prototype.o,P0.createFromModelPath=function(s,t){return Gl(P0,s,{baseOptions:{modelAssetPath:t}})},P0.createFromModelBuffer=function(s,t){return Gl(P0,s,{baseOptions:{modelAssetBuffer:t}})},P0.createFromOptions=function(s,t){return Gl(P0,s,t)},P0.HAND_CONNECTIONS=v8e;var o2t=$b([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 ZQe(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function QQe(s){try{if(!s.D)return s.h;s.D(s.h)}finally{lbe(s)}}function TG(s,t){s=YU(s),t.push(ibe(s))}var su=class extends jy{constructor(s,t){super(new Ub(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,Qi(s=this.j=new Rjt,0,1,t=new gh),this.I=new a8e,Qi(this.j,0,2,this.I),this.W=new UYs,Qi(this.j,0,3,this.W),this.u=new abe,Qi(this.j,0,4,this.u),this.O=new Cjt,Qi(this.j,0,5,this.O),this.A=new Ljt,Qi(this.j,0,6,this.A),this.M=new Djt,Qi(this.j,0,7,this.M),Li(this.u,2,.5),Li(this.u,3,.3),Li(this.O,2,.5),Li(this.A,2,.5),Li(this.A,3,.3),Li(this.M,2,.5),Li(this.I,2,.5)}get baseOptions(){return Yl(this.j,gh,1)}set baseOptions(s){Qi(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Li(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Li(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Li(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Li(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Li(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Li(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Li(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,ZQe(this),qb(this,s,r),QQe(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,ZQe(this),ij(this,s,a,t),QQe(this)}m(){var s=new Ay;Vu(s,"input_frames_image"),ic(s,"pose_landmarks"),ic(s,"pose_world_landmarks"),ic(s,"face_landmarks"),ic(s,"left_hand_landmarks"),ic(s,"left_hand_world_landmarks"),ic(s,"right_hand_landmarks"),ic(s,"right_hand_world_landmarks");const t=new Ey,n=new _Qe;wy(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))Wc(a,2,G1e(i,0,j$));else{if(!(typeof i=="string"||i instanceof Aw||kLe(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");aS(a,2,CLe(i,!1),RM())}}(n,this.j.g());const r=new c0;wy(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),$Le(r,8,_Qe,n),fu(r,"IMAGE:input_frames_image"),Ll(r,"POSE_LANDMARKS:pose_landmarks"),Ll(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Ll(r,"FACE_LANDMARKS:face_landmarks"),Ll(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Ll(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Ll(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Ll(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),r1(s,r),obe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{TG(a,this.h.poseLandmarks),ui(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{ui(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=WL(a),l.push(Pz(a)),ui(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{ui(this,a)}),this.outputPoseSegmentationMasks&&(Ll(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),vD(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[_D(this,a,!0,!this.D)],ui(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],ui(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{TG(a,this.h.faceLandmarks),ui(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{ui(this,a)}),this.outputFaceBlendshapes&&(ic(s,"extra_blendshapes"),Ll(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=rbe(a),l.push(d8e(a.g()??[]))),ui(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{ui(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{TG(a,this.h.leftHandLandmarks),ui(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{ui(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=WL(a),l.push(Pz(a)),ui(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{ui(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{TG(a,this.h.rightHandLandmarks),ui(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{ui(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=WL(a),l.push(Pz(a)),ui(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{ui(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};su.prototype.detectForVideo=su.prototype.G,su.prototype.detect=su.prototype.F,su.prototype.setOptions=su.prototype.o,su.createFromModelPath=function(s,t){return Gl(su,s,{baseOptions:{modelAssetPath:t}})},su.createFromModelBuffer=function(s,t){return Gl(su,s,{baseOptions:{modelAssetBuffer:t}})},su.createFromOptions=function(s,t){return Gl(su,s,t)},su.HAND_CONNECTIONS=v8e,su.POSE_CONNECTIONS=o2t,su.FACE_LANDMARKS_LIPS=m8e,su.FACE_LANDMARKS_LEFT_EYE=p8e,su.FACE_LANDMARKS_LEFT_EYEBROW=f8e,su.FACE_LANDMARKS_LEFT_IRIS=n2t,su.FACE_LANDMARKS_RIGHT_EYE=x8e,su.FACE_LANDMARKS_RIGHT_EYEBROW=g8e,su.FACE_LANDMARKS_RIGHT_IRIS=r2t,su.FACE_LANDMARKS_FACE_OVAL=y8e,su.FACE_LANDMARKS_CONTOURS=a2t,su.FACE_LANDMARKS_TESSELATION=i2t;var dv=class extends jy{constructor(s,t){super(new Ub(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},Qi(s=this.h=new Ojt,0,1,t=new gh)}get baseOptions(){return Yl(this.h,gh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return Qi(this.h,0,2,yTe(s,Yl(this.h,n8e,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},qb(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},ij(this,s,n,t),this.j}m(){var s=new Ay;Vu(s,"input_image"),Vu(s,"norm_rect"),ic(s,"classifications");const t=new Ey;rj(t,qYs,this.h);const n=new c0;wy(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),fu(n,"IMAGE:input_image"),fu(n,"NORM_RECT:norm_rect"),Ll(n,"CLASSIFICATIONS:classifications"),n.o(t),r1(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=YYs(MYs(r)),ui(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{ui(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};dv.prototype.classifyForVideo=dv.prototype.ta,dv.prototype.classify=dv.prototype.sa,dv.prototype.setOptions=dv.prototype.o,dv.createFromModelPath=function(s,t){return Gl(dv,s,{baseOptions:{modelAssetPath:t}})},dv.createFromModelBuffer=function(s,t){return Gl(dv,s,{baseOptions:{modelAssetBuffer:t}})},dv.createFromOptions=function(s,t){return Gl(dv,s,t)};var L0=class extends jy{constructor(s,t){super(new Ub(s,t),"image_in","norm_rect",!0),this.h=new Fjt,this.embeddings={embeddings:[]},Qi(s=this.h,0,1,t=new gh)}get baseOptions(){return Yl(this.h,gh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){var t=this.h,n=Yl(this.h,AQe,2);return n=n?n.clone():new AQe,s.l2Normalize!==void 0?Wc(n,1,w$(s.l2Normalize)):"l2Normalize"in s&&Wc(n,1),s.quantize!==void 0?Wc(n,2,w$(s.quantize)):"quantize"in s&&Wc(n,2),Qi(t,0,2,n),this.l(s)}za(s,t){return qb(this,s,t),this.embeddings}Aa(s,t,n){return ij(this,s,n,t),this.embeddings}m(){var s=new Ay;Vu(s,"image_in"),Vu(s,"norm_rect"),ic(s,"embeddings_out");const t=new Ey;rj(t,VYs,this.h);const n=new c0;wy(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),fu(n,"IMAGE:image_in"),fu(n,"NORM_RECT:norm_rect"),Ll(n,"EMBEDDINGS:embeddings_out"),n.o(t),r1(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=LYs(r),this.embeddings=function(i){return{embeddings:_N(i,PYs,1).map(l=>{var d,u;const o={headIndex:Lv(l,3)??0??-1,headName:jf(Ou(l,4))??""??""};var c=l.v;return Dwt(c,0|c[ji],EQe,RNe(l,1))!==void 0?(l=oA(l=Yl(l,EQe,RNe(l,1),void 0),1,lw,iA()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=Yl(l,IYs,RNe(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:Hjt(Ou(i,2,void 0,void 0,Uge)??Awt)}}(r),ui(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{ui(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};L0.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=RQe(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=RQe(DQe(s.quantizedEmbedding),DQe(t.quantizedEmbedding))}return s},L0.prototype.embedForVideo=L0.prototype.Aa,L0.prototype.embed=L0.prototype.za,L0.prototype.setOptions=L0.prototype.o,L0.createFromModelPath=function(s,t){return Gl(L0,s,{baseOptions:{modelAssetPath:t}})},L0.createFromModelBuffer=function(s,t){return Gl(L0,s,{baseOptions:{modelAssetBuffer:t}})},L0.createFromOptions=function(s,t){return Gl(L0,s,t)};var wTe=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 sZs(s){var n,r;const t=function(a){return _N(a,c0,1)}(s.ca()).filter(a=>(jf(Ou(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=Yl(t[0],Ey,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=jf(Ou(a,1))??""})}function XQe(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function JQe(s){try{const t=new wTe(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{lbe(s)}}wTe.prototype.close=wTe.prototype.close;var zx=class extends jy{constructor(s,t){super(new Ub(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new c8e,this.A=new zjt,Qi(this.h,0,3,this.A),Qi(s=this.h,0,1,t=new gh)}get baseOptions(){return Yl(this.h,gh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Wc(this.h,2,GU(s.displayNamesLocale)):"displayNamesLocale"in s&&Wc(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){sZs(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,XQe(this),qb(this,s,r),JQe(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,XQe(this),ij(this,s,a,t),JQe(this)}Da(){return this.u}m(){var s=new Ay;Vu(s,"image_in"),Vu(s,"norm_rect");const t=new Ey;rj(t,$jt,this.h);const n=new c0;wy(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),fu(n,"IMAGE:image_in"),fu(n,"NORM_RECT:norm_rect"),n.o(t),r1(s,n),obe(this,s),this.outputConfidenceMasks&&(ic(s,"confidence_masks"),Ll(n,"CONFIDENCE_MASKS:confidence_masks"),vD(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>_D(this,i,!0,!this.j)),ui(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],ui(this,r)})),this.outputCategoryMask&&(ic(s,"category_mask"),Ll(n,"CATEGORY_MASK:category_mask"),vD(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=_D(this,r,!1,!this.j),ui(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,ui(this,r)})),ic(s,"quality_scores"),Ll(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,ui(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,ui(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};zx.prototype.getLabels=zx.prototype.Da,zx.prototype.segmentForVideo=zx.prototype.La,zx.prototype.segment=zx.prototype.segment,zx.prototype.setOptions=zx.prototype.o,zx.createFromModelPath=function(s,t){return Gl(zx,s,{baseOptions:{modelAssetPath:t}})},zx.createFromModelBuffer=function(s,t){return Gl(zx,s,{baseOptions:{modelAssetBuffer:t}})},zx.createFromOptions=function(s,t){return Gl(zx,s,t)};var jTe=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()}};jTe.prototype.close=jTe.prototype.close;var M_=class extends jy{constructor(s,t){super(new Ub(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new c8e,this.u=new zjt,Qi(this.h,0,3,this.u),Qi(s=this.h,0,1,t=new gh)}get baseOptions(){return Yl(this.h,gh,1)}set baseOptions(s){Qi(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 Ujt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new BNe;aS(i,3,w$(!0),!1),aS(i,1,A7(t.keypoint.x),0),aS(i,2,A7(t.keypoint.y),0),Mz(r,1,gTe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new GYs;for(i of t.scribble)aS(t=new BNe,3,w$(!0),!1),aS(t,1,A7(i.x),0),aS(t,2,A7(i.y),0),$Le(o,1,BNe,t);Mz(r,2,gTe,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),qb(this,s,a);e:{try{const o=new jTe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{lbe(this)}l=void 0}return l}m(){var s=new Ay;Vu(s,"image_in"),Vu(s,"roi_in"),Vu(s,"norm_rect_in");const t=new Ey;rj(t,$jt,this.h);const n=new c0;wy(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),fu(n,"IMAGE:image_in"),fu(n,"ROI:roi_in"),fu(n,"NORM_RECT:norm_rect_in"),n.o(t),r1(s,n),obe(this,s),this.outputConfidenceMasks&&(ic(s,"confidence_masks"),Ll(n,"CONFIDENCE_MASKS:confidence_masks"),vD(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>_D(this,i,!0,!this.j)),ui(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],ui(this,r)})),this.outputCategoryMask&&(ic(s,"category_mask"),Ll(n,"CATEGORY_MASK:category_mask"),vD(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=_D(this,r,!1,!this.j),ui(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,ui(this,r)})),ic(s,"quality_scores"),Ll(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,ui(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,ui(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};M_.prototype.segment=M_.prototype.segment,M_.prototype.setOptions=M_.prototype.o,M_.createFromModelPath=function(s,t){return Gl(M_,s,{baseOptions:{modelAssetPath:t}})},M_.createFromModelBuffer=function(s,t){return Gl(M_,s,{baseOptions:{modelAssetBuffer:t}})},M_.createFromOptions=function(s,t){return Gl(M_,s,t)};var uv=class extends jy{constructor(s,t){super(new Ub(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},Qi(s=this.h=new qjt,0,1,t=new gh)}get baseOptions(){return Yl(this.h,gh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Wc(this.h,2,GU(s.displayNamesLocale)):"displayNamesLocale"in s&&Wc(this.h,2),s.maxResults!==void 0?wN(this.h,3,s.maxResults):"maxResults"in s&&Wc(this.h,3),s.scoreThreshold!==void 0?Li(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&Wc(this.h,4),s.categoryAllowlist!==void 0?Vge(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&Wc(this.h,5),s.categoryDenylist!==void 0?Vge(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&Wc(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},qb(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},ij(this,s,n,t),this.j}m(){var s=new Ay;Vu(s,"input_frame_gpu"),Vu(s,"norm_rect"),ic(s,"detections");const t=new Ey;rj(t,WYs,this.h);const n=new c0;wy(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),fu(n,"IMAGE:input_frame_gpu"),fu(n,"NORM_RECT:norm_rect"),Ll(n,"DETECTIONS:detections"),n.o(t),r1(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=bjt(i),this.j.detections.push(Gjt(r));ui(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{ui(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};uv.prototype.detectForVideo=uv.prototype.G,uv.prototype.detect=uv.prototype.F,uv.prototype.setOptions=uv.prototype.o,uv.createFromModelPath=async function(s,t){return Gl(uv,s,{baseOptions:{modelAssetPath:t}})},uv.createFromModelBuffer=function(s,t){return Gl(uv,s,{baseOptions:{modelAssetBuffer:t}})},uv.createFromOptions=function(s,t){return Gl(uv,s,t)};var NTe=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 eXe(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function tXe(s){try{const t=new NTe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{lbe(s)}}NTe.prototype.close=NTe.prototype.close;var D0=class extends jy{constructor(s,t){super(new Ub(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,Qi(s=this.h=new Vjt,0,1,t=new gh),this.A=new Djt,Qi(this.h,0,3,this.A),this.j=new Ljt,Qi(this.h,0,2,this.j),wN(this.j,4,1),Li(this.j,2,.5),Li(this.A,2,.5),Li(this.h,4,.5)}get baseOptions(){return Yl(this.h,gh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return"numPoses"in s&&wN(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Li(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Li(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Li(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,eXe(this),qb(this,s,r),tXe(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,eXe(this),ij(this,s,a,t),tXe(this)}m(){var s=new Ay;Vu(s,"image_in"),Vu(s,"norm_rect"),ic(s,"normalized_landmarks"),ic(s,"world_landmarks"),ic(s,"segmentation_masks");const t=new Ey;rj(t,KYs,this.h);const n=new c0;wy(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),fu(n,"IMAGE:image_in"),fu(n,"NORM_RECT:norm_rect"),Ll(n,"NORM_LANDMARKS:normalized_landmarks"),Ll(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),r1(s,n),obe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=YU(i),this.landmarks.push(ibe(r));ui(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],ui(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=WL(i),this.worldLandmarks.push(Pz(r));ui(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],ui(this,r)}),this.outputSegmentationMasks&&(Ll(n,"SEGMENTATION_MASK:segmentation_masks"),vD(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>_D(this,i,!0,!this.u)),ui(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],ui(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};D0.prototype.detectForVideo=D0.prototype.G,D0.prototype.detect=D0.prototype.F,D0.prototype.setOptions=D0.prototype.o,D0.createFromModelPath=function(s,t){return Gl(D0,s,{baseOptions:{modelAssetPath:t}})},D0.createFromModelBuffer=function(s,t){return Gl(D0,s,{baseOptions:{modelAssetBuffer:t}})},D0.createFromOptions=function(s,t){return Gl(D0,s,t)},D0.POSE_CONNECTIONS=o2t;let lA=null,M7=null;async function nZs(){return lA||M7||(M7=(async()=>{const s=await hP.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return lA=await zx.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}),lA})(),M7)}function rZs(s,t,n,r,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+u]);const p=Math.min(h,n-1)-Math.max(u+1,0)+1;i[c+d]=o/p}}for(let l=0;l=0&&(o-=i[d*n+l]);const h=Math.min(u,r-1)-Math.max(d+1,0)+1;t[c*n+l]=o/h}}}function aZs(){lA&&(lA.close(),lA=null,M7=null)}function iZs(s,t){const n=N.useRef(null),r=N.useRef(null),a=N.useRef(null),i=N.useRef(null),l=N.useRef(0);N.useRef(0);const[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(null),f=t.type!=="none"&&s!==null;return N.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const g=new Image;g.crossOrigin="anonymous",g.src=t.imageUrl,g.onload=()=>{i.current=g}}else i.current=null},[t.type,t.imageUrl]),N.useEffect(()=>{if(!f||!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}},[f,s]),N.useEffect(()=>{if(!f){c(null),p(null);return}let g=!1;return(async()=>{u(!0),p(null);try{const v=await nZs();if(g)return;u(!1);const j=a.current;if(!j||(await new Promise(Ee=>{if(j.videoWidth>0)return Ee();j.onloadedmetadata=()=>Ee(),setTimeout(Ee,2e3)}),g))return;const _=j.videoWidth||640,S=j.videoHeight||480,A=n.current;if(!A)return;A.width=_,A.height=S;const T=A.getContext("2d",{willReadFrequently:!1,alpha:!1});r.current||(r.current=document.createElement("canvas"));const D=r.current;D.width=_,D.height=S;const L=D.getContext("2d",{willReadFrequently:!1}),M=document.createElement("canvas");M.width=_,M.height=S;const F=M.getContext("2d",{alpha:!1}),z=document.createElement("canvas");z.width=_,z.height=S;const V=z.getContext("2d",{willReadFrequently:!1}),W=V.createImageData(_,S),K=W.data;for(let Ee=0;EeY.addTrack(Ee)),g||c(Y);const ne=t.blurRadius??15,oe=t.mirror??!1,pe=new Float32Array(_*S),ce=new Float32Array(_*S),de=new Float32Array(_*S);let ie=!1;const ye=4,_e=.35,Me=typeof j.requestVideoFrameCallback=="function",Te=()=>{if(g||!a.current)return;const Ee=a.current;if(Ee.readyState<2){Ce(Ee);return}try{const De=performance.now(),Fe=v.segmentForVideo(Ee,De).confidenceMasks;if(Fe&&Fe.length>0){ce.fill(0);for(let qe=1;qe1?1:it}}if(rZs(ce,pe,_,S,ye),ie)for(let qe=0;qe=1?255:Je*255|0}if(V.putImageData(W,0,0),t.type==="blur")F.filter=`blur(${ne}px)`,F.drawImage(Ee,0,0,_,S),F.filter="none",T.drawImage(M,0,0);else if(t.type==="image"&&i.current){const qe=i.current,ve=qe.width/qe.height,Je=_/S;let we=0,it=0,Ne=qe.width,He=qe.height;ve>Je?(Ne=qe.height*Je,we=(qe.width-Ne)/2):(He=qe.width/Je,it=(qe.height-He)/2),T.drawImage(qe,we,it,Ne,He,0,0,_,S)}else T.fillStyle="#000",T.fillRect(0,0,_,S);L.globalCompositeOperation="source-over",L.clearRect(0,0,_,S),L.drawImage(Ee,0,0,_,S),L.globalCompositeOperation="destination-in",L.drawImage(z,0,0),L.globalCompositeOperation="source-over",oe?(T.save(),T.translate(_,0),T.scale(-1,1),T.drawImage(D,0,0),T.restore()):T.drawImage(D,0,0);for(const qe of Fe)qe.close()}else T.drawImage(Ee,0,0,_,S)}catch{T.drawImage(Ee,0,0,_,S)}Ce(Ee)},Ce=Ee=>{g||(Me?Ee.requestVideoFrameCallback(()=>Te()):l.current=requestAnimationFrame(Te))};Ce(j)}catch(v){console.error("[useVirtualBackground] init error:",v),g||(u(!1),p(v.message||"Failed to initialize virtual background"))}})(),()=>{g=!0,l.current&&cancelAnimationFrame(l.current),c(null)}},[f,t.type,t.blurRadius,t.imageUrl,s]),N.useEffect(()=>()=>{aZs()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:f,error:h}}function m6({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,className:a,teleprompterContent:i}){const l=N.useRef(null),o=N.useRef(null),c=N.useRef(null),[d,u]=N.useState(null),h=N.useRef([]),p=N.useRef(null),f=N.useRef(null),g=N.useRef(null),b=N.useRef(null),v=kR(),[j,_]=N.useState("camera"),S=N.useRef(null),A=N.useRef(null),T=N.useRef(null),D=N.useRef(null),L=N.useRef(null),M=N.useRef(null),[F,z]=N.useState(!0),[V,W]=N.useState(!0),[K,Y]=N.useState(null),[ee,ne]=N.useState(!1),[oe,pe]=N.useState(!1),[ce,de]=N.useState(null),[ie,ye]=N.useState(null),[_e,Me]=N.useState(0),[Te,Ce]=N.useState("user"),[Ee,De]=N.useState(0),[Ie,Fe]=N.useState(!1),[qe,ve]=N.useState(!0),[Je,we]=N.useState(null),[it,Ne]=N.useState(!1),[He,$e]=N.useState(null),Ye=N.useRef(null),[Ke,rt]=N.useState(()=>{try{const er=localStorage.getItem("video-bg-config");if(er)return JSON.parse(er)}catch{}return{type:"none"}});N.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(Ke))}catch{}},[Ke]);const[tt,at]=N.useState([]),[Ge,dt]=N.useState([]),[Bt,kt]=N.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[Qt,ns]=N.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});N.useEffect(()=>{try{localStorage.setItem("video-mic-id",Bt)}catch{}},[Bt]),N.useEffect(()=>{try{localStorage.setItem("video-cam-id",Qt)}catch{}},[Qt]),N.useEffect(()=>{var lr,Fs,$n;if(!((lr=navigator.mediaDevices)!=null&&lr.enumerateDevices))return;const er=async()=>{try{const Cr=await navigator.mediaDevices.enumerateDevices();at(Cr.filter(ts=>ts.kind==="audioinput")),dt(Cr.filter(ts=>ts.kind==="videoinput"))}catch(Cr){console.warn("[VideoRecorder] enumerateDevices failed",Cr)}};return er(),($n=(Fs=navigator.mediaDevices).addEventListener)==null||$n.call(Fs,"devicechange",er),()=>{var Cr,ts;return(ts=(Cr=navigator.mediaDevices).removeEventListener)==null?void 0:ts.call(Cr,"devicechange",er)}},[K]);const{canvasRef:$s,compositedStream:Ds,isLoading:Dt,isActive:St,error:$t}=iZs(d,Ke),ht=N.useRef(n);ht.current=n;const Ut=N.useCallback(er=>{z(er)},[]),Es=N.useRef(F),Xt=N.useCallback(()=>{T.current&&(cancelAnimationFrame(T.current),T.current=null),D.current&&(D.current.terminate(),D.current=null),S.current&&(S.current.getTracks().forEach(er=>er.stop()),S.current=null),L.current&&(L.current.getTracks().forEach(er=>er.stop()),L.current=null),M.current&&(M.current.srcObject=null,M.current=null)},[]),Ys=N.useCallback(async()=>{var er;try{const lr=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});S.current=lr;let Fs=null;try{Fs=await navigator.mediaDevices.getUserMedia({video:Qt?{deviceId:{exact:Qt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let $n=null;try{$n=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...Bt?{deviceId:{exact:Bt}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",$n.getAudioTracks().map(sr=>sr.label))}catch(sr){console.warn("[VideoRecorder] No mic audio for screen recording",sr);try{$n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const Cr=lr.getVideoTracks()[0],ts=Cr.getSettings(),Oe=ts.width||1920,Qe=ts.height||1080,ct=document.createElement("canvas");ct.width=Oe,ct.height=Qe,A.current=ct;const vt=ct.getContext("2d");let It=null;Fs&&(It=document.createElement("video"),It.srcObject=Fs,It.muted=!0,It.playsInline=!0,It.autoplay=!0,await It.play(),M.current=It);const qt=document.createElement("video");qt.srcObject=lr,qt.muted=!0,qt.playsInline=!0,qt.autoplay=!0,await qt.play();const xs=()=>{if(vt.drawImage(qt,0,0,Oe,Qe),It&&It.readyState>=2){const sr=Math.round(Oe*.2),Tr=Math.round(sr*(It.videoHeight/It.videoWidth||.75)),Ot=Oe-sr-20,wn=Qe-Tr-20,kr=12;vt.save(),vt.beginPath(),vt.moveTo(Ot+kr,wn),vt.lineTo(Ot+sr-kr,wn),vt.quadraticCurveTo(Ot+sr,wn,Ot+sr,wn+kr),vt.lineTo(Ot+sr,wn+Tr-kr),vt.quadraticCurveTo(Ot+sr,wn+Tr,Ot+sr-kr,wn+Tr),vt.lineTo(Ot+kr,wn+Tr),vt.quadraticCurveTo(Ot,wn+Tr,Ot,wn+Tr-kr),vt.lineTo(Ot,wn+kr),vt.quadraticCurveTo(Ot,wn,Ot+kr,wn),vt.closePath(),vt.clip(),vt.translate(Ot+sr,wn),vt.scale(-1,1),vt.drawImage(It,0,0,sr,Tr),vt.restore(),vt.strokeStyle="rgba(255,255,255,0.6)",vt.lineWidth=2,vt.beginPath(),vt.moveTo(Ot+kr,wn),vt.lineTo(Ot+sr-kr,wn),vt.quadraticCurveTo(Ot+sr,wn,Ot+sr,wn+kr),vt.lineTo(Ot+sr,wn+Tr-kr),vt.quadraticCurveTo(Ot+sr,wn+Tr,Ot+sr-kr,wn+Tr),vt.lineTo(Ot+kr,wn+Tr),vt.quadraticCurveTo(Ot,wn+Tr,Ot,wn+Tr-kr),vt.lineTo(Ot,wn+kr),vt.quadraticCurveTo(Ot,wn,Ot+kr,wn),vt.closePath(),vt.stroke()}},as="let id=null;onmessage=(e)=>{if(e.data&&e.data.type==='start'){clearInterval(id);id=setInterval(()=>postMessage('tick'),Math.round(1000/(e.data.fps||30)))}else if(e.data==='stop'){clearInterval(id);id=null}}",Ns=new Blob([as],{type:"application/javascript"}),ln=new Worker(URL.createObjectURL(Ns));D.current=ln,ln.onmessage=()=>xs(),ln.postMessage({type:"start",fps:30}),xs();const Ks=ct.captureStream(30),Un=[],br=lr.getAudioTracks();br.length&&Un.push(...br),$n&&Un.push(...$n.getAudioTracks());const Ar=new MediaStream([...Ks.getVideoTracks(),...Un]);return L.current=Ar,Cr.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),Xt()},Ar}catch(lr){return console.error("[VideoRecorder] Screen capture error:",lr),lr.name!=="NotAllowedError"&&((er=ht.current)==null||er.call(ht,"Failed to start screen capture: "+(lr.message||"Unknown error"))),null}},[Xt]),Ss=N.useCallback(async()=>{var lr,Fs;W(!0),we(null);const er=v&&F;console.log("[VideoRecorder] initCamera start",{isMobile:v,usePortraitMode:F,shouldBePortrait:er,facingMode:Te});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(vt=>vt.stop()));const $n=v&&er?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Cr=Qt?{...$n,deviceId:{exact:Qt}}:{...$n,facingMode:{ideal:Te}},ts={echoCancellation:!0,noiseSuppression:!0,...Bt?{deviceId:{exact:Bt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Cr);const Oe=await navigator.mediaDevices.getUserMedia({video:Cr,audio:ts});if(console.log("[VideoRecorder] getUserMedia success"),Oe.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=Oe,u(Oe),Y(!0);const ct=Oe.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",ct.width,"x",ct.height),l.current){const vt=l.current;vt.srcObject=Oe,vt.muted=!0,vt.playsInline=!0,vt.autoplay=!0,vt.setAttribute("muted",""),vt.setAttribute("playsinline",""),vt.setAttribute("autoplay","");try{(lr=vt.load)==null||lr.call(vt)}catch(qt){console.warn("[VideoRecorder] videoEl.load failed",qt)}const It=async()=>{try{return await vt.play(),console.log("[VideoRecorder] preview play ok"),Ne(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:vt.readyState,videoWidth:vt.videoWidth,videoHeight:vt.videoHeight})},300),!0}catch(qt){return console.warn("[VideoRecorder] preview play blocked",qt),Ne(!0),!1}};await new Promise(qt=>{let xs=!1;const as=()=>{xs||(xs=!0,qt())},Ns=()=>{It().finally(as)};vt.onloadedmetadata=Ns,vt.onloadeddata=Ns,setTimeout(as,1500)})}try{f.current=new AudioContext;const vt=f.current.createMediaStreamSource(Oe);g.current=f.current.createAnalyser(),g.current.fftSize=256,vt.connect(g.current);const It=()=>{if(g.current){const qt=new Uint8Array(g.current.frequencyBinCount);g.current.getByteFrequencyData(qt);const xs=qt.reduce((as,Ns)=>as+Ns)/qt.length;De(Math.min(100,xs/128*100))}b.current=requestAnimationFrame(It)};It()}catch(vt){console.warn("Audio context not available:",vt)}}catch($n){console.error("Camera initialization error:",$n),Y(!1);let Cr="Failed to access camera or microphone.";$n.name==="NotAllowedError"?Cr="Camera permission denied. Please allow camera access in your browser settings.":$n.name==="NotFoundError"?Cr="No camera found. Please connect a camera and try again.":$n.name==="NotReadableError"?Cr="Camera is in use by another application. Please close other apps using the camera.":$n.message&&(Cr=$n.message),we(Cr),(Fs=ht.current)==null||Fs.call(ht,Cr)}finally{W(!1)}},[Te,v,F,Bt,Qt]);N.useEffect(()=>{Es.current!==F&&K&&!ee&&!ie&&(Es.current=F,Ss())},[F,K,ee,ie,Ss]),N.useEffect(()=>(Ss(),()=>{c.current&&c.current.getTracks().forEach(er=>er.stop()),p.current&&clearInterval(p.current),b.current&&cancelAnimationFrame(b.current),f.current&&f.current.close(),Ye.current&&clearInterval(Ye.current),ie&&URL.revokeObjectURL(ie),Xt()}),[Ss,ie]),N.useEffect(()=>{if(V||K!==!0||ie)return;const er=c.current,lr=l.current;!er||!lr||St||(lr.srcObject!==er&&(lr.srcObject=er,lr.muted=!0,lr.playsInline=!0,lr.autoplay=!0,lr.setAttribute("muted",""),lr.setAttribute("playsinline",""),lr.setAttribute("autoplay","")),lr.play().then(()=>Ne(!1)).catch(Fs=>{Ne(!0),console.warn("Live preview play blocked on mount:",Fs)}))},[K,V,ie,St]),N.useEffect(()=>{r==null||r(ee)},[ee,r]);const Bs=N.useCallback(async()=>{if(ie)return;const er=l.current;if(er)try{await er.play(),Ne(!1)}catch(lr){Ne(!0),console.warn("Live preview still blocked (needs user gesture):",lr)}},[ie]),Us=N.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),p.current&&(clearInterval(p.current),p.current=null),Xt(),ne(!1),pe(!1)},[Xt]),sn=N.useCallback(async()=>{let er=null;if(j==="screen"){if(er=await Ys(),!er)return}else er=St&&Ds?Ds:c.current;if(!er)return;Bs(),h.current=[],Me(0);const Fs=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Cr=>MediaRecorder.isTypeSupported(Cr)),$n=new MediaRecorder(er,Fs?{mimeType:Fs,videoBitsPerSecond:j==="screen"?4e6:25e5}:{videoBitsPerSecond:j==="screen"?4e6:25e5});$n.ondataavailable=Cr=>{Cr.data.size>0&&h.current.push(Cr.data)},$n.onstop=()=>{var Qe;const Cr=$n.mimeType||Fs||((Qe=h.current[0])==null?void 0:Qe.type)||"video/webm",ts=new Blob(h.current,{type:Cr});de(ts);const Oe=URL.createObjectURL(ts);ye(Oe)},o.current=$n,$n.start(100),ne(!0),p.current=setInterval(()=>{Me(Cr=>Cr>=s-1?(Us(),s):Cr+1)},1e3)},[Bs,s,Us,St,Ds,j,Ys]),Jn=N.useCallback(()=>{Ye.current&&(clearInterval(Ye.current),Ye.current=null),$e(3);let er=3;Ye.current=setInterval(()=>{er-=1,er<=0?(Ye.current&&clearInterval(Ye.current),Ye.current=null,$e(null),sn()):$e(er)},1e3)},[sn]),fn=N.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),pe(!0),p.current&&clearInterval(p.current))},[]),Sn=N.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),pe(!1),p.current=setInterval(()=>{Me(er=>er>=s-1?(Us(),s):er+1)},1e3))},[s,Us]),Gn=N.useCallback(()=>{ie&&URL.revokeObjectURL(ie),de(null),ye(null),Me(0),Fe(!1),ve(!0),l.current&&c.current&&!St&&(l.current.srcObject=c.current,l.current.muted=!0,Bs())},[Bs,ie,St]),Hr=N.useCallback(()=>{Ce(er=>er==="user"?"environment":"user")},[]),pi=N.useCallback(()=>{ce&&t(ce,_e)},[ce,_e,t]),Ms=N.useCallback(()=>{l.current&&ie&&(Ie?l.current.pause():(ve(!1),l.current.muted=!1,l.current.play()),Fe(!Ie))},[ie,Ie]);N.useEffect(()=>{if(!ie)return;const er=l.current;if(!er)return;ve(!1),er.pause(),er.removeAttribute("src"),er.srcObject=null,er.load(),er.src=ie,er.currentTime=0,er.playsInline=!0,er.muted=!1,er.onended=()=>Fe(!1);const lr=()=>{var Cr;const Fs=er.error,$n=Fs?`Recorded video failed to play (code ${Fs.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",Fs),(Cr=ht.current)==null||Cr.call(ht,$n)};return er.addEventListener("error",lr),er.load(),()=>{er.removeEventListener("error",lr)}},[ie]);const bi=er=>{const lr=Math.floor(er/60),Fs=er%60;return`${lr}:${Fs.toString().padStart(2,"0")}`},Rr=j==="screen"?"aspect-video":v&&F?"aspect-[9/16]":"aspect-video";return V?e.jsx("div",{className:Et("flex items-center justify-center bg-black rounded-lg",Rr,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(ss,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):K===!1?e.jsx("div",{className:Et("flex items-center justify-center bg-black rounded-lg",Rr,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(Gi,{className:"h-12 w-12 mx-auto mb-4 text-destructive"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Camera Access Required"}),e.jsx("p",{className:"text-gray-400 mb-4 text-sm",children:Je||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(B,{onClick:()=>Ss(),variant:"secondary",className:"w-full",children:[e.jsx(Ai,{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:Et("flex flex-col gap-2",a),children:[!ee&&!ie&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(B,{variant:j==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>_("camera"),children:[e.jsx(pf,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(B,{variant:j==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>_("screen"),children:[e.jsx(FA,{className:"h-4 w-4"}),"Screen"]})]}),j==="camera"&&!ee&&!ie&&e.jsx(vKs,{value:Ke,onChange:rt,isLoading:Dt,disabled:ee}),!ee&&!ie&&(tt.length>0||Ge.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[tt.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Bv,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(us,{value:Bt||"default",onValueChange:er=>kt(er==="default"?"":er),children:[e.jsx(cs,{className:"h-8 text-xs",children:e.jsx(hs,{placeholder:"Default microphone"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"default",children:"Default microphone"}),tt.map(er=>e.jsx(Ze,{value:er.deviceId,children:er.label||`Microphone ${er.deviceId.slice(0,6)}`},er.deviceId))]})]})]}),Ge.length>1&&j==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(pf,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(us,{value:Qt||"default",onValueChange:er=>ns(er==="default"?"":er),children:[e.jsx(cs,{className:"h-8 text-xs",children:e.jsx(hs,{placeholder:"Default camera"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"default",children:"Default camera"}),Ge.map(er=>e.jsx(Ze,{value:er.deviceId,children:er.label||`Camera ${er.deviceId.slice(0,6)}`},er.deviceId))]})]})]})]}),j==="camera"&&v&&!ee&&!ie&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(gb,{className:Et("h-4 w-4",F?"text-muted-foreground":"text-primary")}),e.jsx(se,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(vn,{id:"orientation-toggle",checked:F,onCheckedChange:Ut}),e.jsx(se,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(rg,{className:Et("h-4 w-4",F?"text-primary":"text-muted-foreground")})]}),j==="screen"&&!ee&&!ie&&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(FA,{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:Et("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{Bs()},children:[e.jsx("video",{ref:l,src:ie??void 0,className:Et("w-full bg-black",F&&!ie?"object-contain":"object-cover",Rr,!ie&&Te==="user"!==(Ke.mirror??!1)&&"scale-x-[-1]",St&&!ie&&"hidden"),playsInline:!0,controls:!!ie,muted:ie?qe:!0,autoPlay:!ie},ie??"live"),St&&!ie&&e.jsx("canvas",{ref:$s,className:Et("w-full bg-black",F?"object-contain":"object-cover",Rr,Te==="user"!==(Ke.mirror??!1)&&"scale-x-[-1]")}),St&&Dt&&!ie&&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(ss,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!ie&&it&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx(B,{type:"button",variant:"secondary",onClick:()=>void Bs(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!ie&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),He!==null&&!ie&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-30 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:He},He),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),ee&&e.jsxs("div",{className:"absolute top-4 left-4 flex items-center gap-2 bg-black/50 px-3 py-1.5 rounded-full",children:[e.jsx("div",{className:Et("w-3 h-3 rounded-full",oe?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[bi(_e)," / ",bi(s)]})]}),ee&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(xi,{value:_e/s*100,className:"h-1 rounded-none"})}),!ie&&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(Bv,{className:"h-4 w-4 text-white"}),e.jsx("div",{className:"w-20 h-2 bg-white/20 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-green-500 transition-all duration-75",style:{width:`${Ee}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:ie?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:Gn,children:[e.jsx(Ai,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Ms,children:Ie?e.jsx(_f,{className:"h-5 w-5"}):e.jsx(Al,{className:"h-5 w-5"})}),e.jsxs(B,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:pi,children:[e.jsx(Lr,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[j==="camera"?e.jsx(B,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Hr,disabled:ee||He!==null,children:e.jsx(Fh,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!ee&&He===null?e.jsx(B,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:j==="screen"?sn:Jn,children:j==="screen"?e.jsx(FA,{className:"h-6 w-6"}):e.jsx(vr,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:oe?Sn:fn,children:oe?e.jsx(Al,{className:"h-5 w-5"}):e.jsx(_f,{className:"h-5 w-5"})}),e.jsx(B,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:Us,children:e.jsx(cy,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function oZs({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=gs(),{toast:a}=Ua(),[i,l]=N.useState(!1),o=async(c,d)=>{if(r){l(!0);try{const u=c.type.includes("mp4")?"mp4":"webm",h=`${r.id}/${crypto.randomUUID()}.${u}`,{error:p}=await q.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(p)throw p;const{data:f,error:g}=await q.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(g||!(f!=null&&f.signedUrl))throw g||new Error("Could not sign video URL");n(f.signedUrl,Math.round(d)),a({title:"Video added to your CMA"}),t(!1)}catch(u){a({title:"Upload failed",description:u==null?void 0:u.message,variant:"destructive"})}finally{l(!1)}}};return e.jsx(bs,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(ws,{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(ss,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(m6,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function lZs({value:s,onChange:t}){const{user:n}=gs(),[r,a]=N.useState(!1);return e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(vr,{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(Ae,{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(Fn,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(Al,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(o6,{userId:n==null?void 0:n.id,triggerLabel:"Pick from Library",triggerVariant:"outline",triggerSize:"default",triggerClassName:"w-full justify-center gap-2",onSelect:()=>{},onSelectVideo:i=>t({url:i.playback_url,thumb:i.thumbnail_url,label:i.title||i.recipient_name})}),e.jsxs(B,{variant:"outline",onClick:()=>a(!0),className:"gap-2",children:[e.jsx(vr,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(oZs,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function eb(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function cZs({open:s,onOpenChange:t,subject:n,onSave:r,isSaving:a}){const[i,l]=N.useState({bedrooms:"",bathrooms:"",sqft:"",yearBuilt:"",propertyType:"",propertySubType:""});N.useEffect(()=>{s&&l({bedrooms:(n==null?void 0:n.bedrooms)!=null?String(n.bedrooms):"",bathrooms:(n==null?void 0:n.bathrooms)!=null?String(n.bathrooms):"",sqft:(n==null?void 0:n.sqft)!=null?String(n.sqft):"",yearBuilt:(n==null?void 0:n.yearBuilt)!=null?String(n.yearBuilt):"",propertyType:(n==null?void 0:n.propertyType)||"Residential",propertySubType:(n==null?void 0:n.propertySubType)||"Single Family"})},[s,n]);const o=async()=>{await r({bedrooms:eb(i.bedrooms),bathrooms:eb(i.bathrooms),sqft:eb(i.sqft),yearBuilt:eb(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{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(se,{className:"text-xs",children:"Beds"}),e.jsx(ge,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Baths"}),e.jsx(ge,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Sq Ft"}),e.jsx(ge,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Year Built"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Property Type"}),e.jsx(ge,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subtype"}),e.jsx(ge,{value:i.propertySubType,onChange:c=>l(d=>({...d,propertySubType:c.target.value})),placeholder:"Single Family"})]})]}),e.jsxs(B,{className:"w-full",onClick:o,disabled:a,children:[a?e.jsx(ss,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function dZs({open:s,onOpenChange:t,subject:n,onAdd:r}){const[a,i]=N.useState({address:"",city:"",state:"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""});N.useEffect(()=>{s&&i({address:"",city:(n==null?void 0:n.city)||"",state:(n==null?void 0:n.state)||"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""})},[s,n]);const l=()=>{const o=eb(a.price),c=eb(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:eb(a.bedrooms),bathrooms:eb(a.bathrooms),sqft:c,yearBuilt:eb(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{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(se,{className:"text-xs",children:"Address"}),e.jsx(ge,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"City"}),e.jsx(ge,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"State"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Status"}),e.jsx(ge,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Price"}),e.jsx(ge,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Sq Ft"}),e.jsx(ge,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Beds"}),e.jsx(ge,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Baths"}),e.jsx(ge,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Year Built"}),e.jsx(ge,{className:"max-w-[180px]",inputMode:"numeric",value:a.yearBuilt,onChange:o=>i(c=>({...c,yearBuilt:o.target.value})),placeholder:"2005"})]}),e.jsxs(B,{className:"w-full",onClick:l,disabled:!a.address.trim()||!eb(a.price)||!eb(a.sqft),children:[e.jsx(As,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function uZs(){var Ce,Ee,De,Ie,Fe,qe,ve;const{id:s}=_i(),t=In(),{toast:n}=Ua(),{data:r,isLoading:a}=AWs(s),{data:i}=MWs(s),l=IWs(),o=DWs(),c=RWs(),{leadSite:d,isLoading:u}=Pp(),[h,p]=N.useState([]),[f,g]=N.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[b,v]=N.useState(null),[j,_]=N.useState(!1),[S,A]=N.useState({low:"",likely:"",high:"",note:""}),[T,D]=N.useState(!1),[L,M]=N.useState(!1),[F,z]=N.useState(!1),[V,W]=N.useState(null),K=async Je=>{var Ye,Ke;if(!r||!(Je!=null&&Je.address)||!(Je!=null&&Je.city)||!(Je!=null&&Je.state))return Je;let we={...Je};const it=async rt=>{const{data:tt,error:at}=await q.functions.invoke("cma-subject-lookup",{body:{address:rt.address,city:rt.city,state:rt.state,zip:rt.zip,latitude:rt.latitude,longitude:rt.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(at)throw at;return(tt==null?void 0:tt.matches)||[]},Ne=rt=>{const at=rt.find(kt=>Number.isFinite(Number(kt.latitude))&&Number.isFinite(Number(kt.longitude)))||rt[0];if(!at)return;const Ge=typeof at.match_type=="string"&&at.match_type.startsWith("nearby-"),dt=Ge&&Number.isFinite(Number(we.latitude))&&Number.isFinite(Number(we.longitude)),Bt=kt=>at[kt]!==void 0&&at[kt]!==null&&at[kt]!==""&&at[kt]!==0?at[kt]:we[kt];we={...we,bedrooms:Bt("bedrooms"),bathrooms:Bt("bathrooms"),sqft:Bt("sqft"),yearBuilt:Bt("yearBuilt"),lotSize:Bt("lotSize"),propertyType:Bt("propertyType"),propertySubType:Bt("propertySubType"),source_provider:at.source_provider??we.source_provider,match_type:at.match_type??we.match_type,matched_mls_address:Ge?at.address:we.matched_mls_address,latitude:dt?we.latitude:at.latitude??we.latitude,longitude:dt?we.longitude:at.longitude??we.longitude,mlsNumber:Ge?we.mlsNumber:at.mlsNumber??we.mlsNumber,photos:!Ge&&Array.isArray(at.photos)&&at.photos.length?at.photos:we.photos}};Ne(await it(we));const He=()=>Number.isFinite(Number(we.latitude))&&Number.isFinite(Number(we.longitude));if(!He()){const{data:rt}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),tt=rt==null?void 0:rt.value;if(tt){const at=encodeURIComponent(`${we.address}, ${we.city}, ${we.state} ${we.zip||""}`.trim()),dt=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${at}.json?access_token=${tt}&limit=1&country=us`)).json(),Bt=(Ke=(Ye=dt==null?void 0:dt.features)==null?void 0:Ye[0])==null?void 0:Ke.center;Array.isArray(Bt)&&Bt.length===2&&(we.longitude=Bt[0],we.latitude=Bt[1])}}if((!we.bedrooms||!we.bathrooms||!we.sqft||!we.yearBuilt)&&He())try{Ne(await it(we))}catch(rt){console.warn("second-pass subject lookup failed",rt)}return JSON.stringify(we)!==JSON.stringify(Je)&&await l.mutateAsync({id:r.id,patch:{subject:we}}),we};N.useEffect(()=>{var it,Ne;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 Je=(it=r==null?void 0:r.settings)==null?void 0:it.priceOverride;Je!=null&&Je.enabled&&(_(!0),A({low:Je.low!=null?String(Je.low):"",likely:Je.likely!=null?String(Je.likely):"",high:Je.high!=null?String(Je.high):"",note:Je.note??""}));const we=(Ne=r==null?void 0:r.settings)==null?void 0:Ne.personalVideo;we!=null&&we.url&&W({url:we.url,thumb:we.thumb,label:we.label})},[r==null?void 0:r.id]);const Y=N.useRef(!1);N.useEffect(()=>{Y.current||i!=null&&i.length&&(p(i.map(Je=>({...Je.snapshot,selected:Je.selected,manual:Je.manual,score:Je.score}))),Y.current=!0)},[i]);const ee=N.useRef(null);N.useEffect(()=>{if(!r||u)return;const Je=r.subject||{},we=Number.isFinite(Number(Je.latitude))&&Number.isFinite(Number(Je.longitude)),it=!!(Number(Je.bedrooms)||Number(Je.bathrooms)||Number(Je.sqft)||Number(Je.yearBuilt));if(we&&it)return;const Ne=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;ee.current!==Ne&&(!Je.address||!Je.city||!Je.state||(ee.current=Ne,(async()=>{try{await K(Je)}catch(He){console.warn("subject enrich failed",He)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const ne=N.useMemo(()=>r?WZe(r.subject,h):null,[r,h]),oe=async()=>{if(r)try{const Je=await K(r.subject),we=await o.mutateAsync({subject:Je,filters:f,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});p(we.comps.map(it=>({...it,selected:!0})).slice(0,12)),n({title:`Found ${we.comps.length} comps`,description:`Top ${Math.min(12,we.comps.length)} auto-selected.`})}catch(Je){n({title:"Search failed",description:Je.message,variant:"destructive"})}},pe=Je=>{p(we=>we.map((it,Ne)=>Ne===Je?{...it,selected:!it.selected}:it))},ce=Je=>{p(we=>we.filter((it,Ne)=>Ne!==Je))},de=async Je=>{if(!r)return;const we=Object.fromEntries(Object.entries(Je).filter(([,Ne])=>Ne!=null&&Ne!=="")),it={...r.subject,...we,manually_enriched:!0};await l.mutateAsync({id:r.id,patch:{subject:it}}),n({title:"Subject details saved",description:it.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},ie=Je=>{p(we=>[{...Je,selected:!0,manual:!0},...we]),n({title:"Manual comp added"})},ye=async(Je=!1)=>{if(!r)return;const we=WZe(r.subject,h),it=Ke=>{const rt=Number(String(Ke).replace(/[^0-9.]/g,""));return Number.isFinite(rt)&&rt>0?Math.round(rt):null},Ne=j?it(S.likely):null,He=j?it(S.low):null,$e=j?it(S.high):null,Ye=j&&Ne;await l.mutateAsync({id:r.id,patch:{settings:{...f,priceOverride:{enabled:j,low:He,likely:Ne,high:$e,note:S.note||null},personalVideo:V},price_low:Ye?He??Ne:we.low??null,price_likely:Ye?Ne:we.likely??null,price_high:Ye?$e??Ne:we.high??null,status:Je?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Je?"CMA published":"CMA saved"})},_e=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx(Cs,{children:e.jsx("div",{className:"p-6",children:e.jsx(ss,{className:"w-6 h-6 animate-spin"})})});const Me=h.filter(Je=>Je.selected).length,Te=!((Ce=r.subject)!=null&&Ce.bedrooms)||!((Ee=r.subject)!=null&&Ee.bathrooms)||!((De=r.subject)!=null&&De.sqft)||!((Ie=r.subject)!=null&&Ie.yearBuilt);return e.jsx(Cs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-7xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-2 flex-wrap",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/cma"),children:[e.jsx(Wr,{className:"w-4 h-4 mr-1"})," All CMAs"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>ye(!1),disabled:l.isPending,children:[e.jsx(Ho,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs(B,{onClick:()=>ye(!0),disabled:l.isPending,children:[e.jsx(Hl,{className:"w-4 h-4 mr-1"}),"Publish & Share"]}),r.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"secondary",onClick:()=>{navigator.clipboard.writeText(_e),n({title:"Link copied"})},children:[e.jsx(tr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs(B,{onClick:()=>D(!0),children:[e.jsx(Hs,{className:"w-4 h-4 mr-1"}),"Send to Contact"]})]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"lg:col-span-1 space-y-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Subject Property"})}),e.jsxs(Ae,{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:"})," ",((Fe=r.subject.sqft)==null?void 0:Fe.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),Te&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-amber-950 space-y-2",children:[e.jsx("p",{className:"font-medium",children:"No panic — we can still build this."}),e.jsx("p",{className:"text-xs leading-relaxed",children:"If the MLS/feed does not return beds, baths, sqft, or year, add them manually and LevelUp will use them for comps and pricing."}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>M(!0),children:[e.jsx(ja,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!Te&&e.jsxs(B,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>M(!0),children:[e.jsx(ja,{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(se,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(ge,{type:"number",defaultValue:"",onBlur:async Je=>{const we=Number(Je.target.value);we>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:we}}})}})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(xw,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Ae,{className:"space-y-3",children:[ne!=null&&ne.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(j&&Number(S.likely)>0?Number(S.likely):ne.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(qe=ne.low)==null?void 0:qe.toLocaleString()," – $",(ve=ne.high)==null?void 0:ve.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",ne.ppsf,"/sqft median · ",Me," 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(se,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(vn,{id:"override-toggle",checked:j,onCheckedChange:_})]}),j&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"My suggested price"}),e.jsx(ge,{type:"number",placeholder:"e.g. 750000",value:S.likely,onChange:Je=>A(we=>({...we,likely:Je.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Range low"}),e.jsx(ge,{type:"number",placeholder:"optional",value:S.low,onChange:Je=>A(we=>({...we,low:Je.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Range high"}),e.jsx(ge,{type:"number",placeholder:"optional",value:S.high,onChange:Je=>A(we=>({...we,high:Je.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Ts,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:S.note,onChange:Je=>A(we=>({...we,note:Je.target.value}))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Save to apply. Your price will replace the comp-based number on the shared report."})]})]})]})]}),e.jsx(lZs,{value:V,onChange:W}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Filters"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(f.sqftPct*100),"%"]}),e.jsx($m,{value:[f.sqftPct*100],min:5,max:50,step:5,onValueChange:([Je])=>g(we=>({...we,sqftPct:Je/100}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Search radius: ",f.maxMiles," mi"]}),e.jsx($m,{value:[f.maxMiles],min:1,max:25,step:1,onValueChange:([Je])=>g(we=>({...we,maxMiles:Je}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Sold within: ",f.monthsBack," months"]}),e.jsx($m,{value:[f.monthsBack],min:1,max:24,step:1,onValueChange:([Je])=>g(we=>({...we,monthsBack:Je}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Je=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(hi,{checked:f.statuses.includes(Je),onCheckedChange:we=>g(it=>({...it,statuses:we?[...it.statuses,Je]:it.statuses.filter(Ne=>Ne!==Je)}))})," ",Je]},Je))]}),e.jsxs(B,{className:"w-full",onClick:oe,disabled:o.isPending,children:[o.isPending?e.jsx(ss,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(un,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>z(!0),children:[e.jsx(As,{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(xKs,{subject:r.subject,comps:h,radiusMiles:f.maxMiles,onMarkerClick:Je=>v(Je)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-lg font-semibold",children:["Comparables (",h.length,")"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Me," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Je,we)=>{var it;return e.jsx(fe,{className:Je.selected?"":"opacity-50",children:e.jsxs(Ae,{className:"p-3 flex gap-3 items-center",children:[e.jsx(hi,{checked:Je.selected,onCheckedChange:()=>pe(we)}),e.jsxs("button",{type:"button",onClick:()=>v(we),className:"flex gap-3 items-center flex-1 min-w-0 text-left hover:bg-muted/40 -mx-1 px-1 py-1 rounded transition",children:[e.jsx(Tfe,{photos:Je.photos,className:"w-20 h-16 rounded flex-none"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate hover:underline",children:Je.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Je.city,", ",Je.state," · ",Je.bedrooms??"?","bd/",Je.bathrooms??"?","ba · ",((it=Je.sqft)==null?void 0:it.toLocaleString())??"?"," sqft",Je.yearBuilt?` · ${Je.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(ze,{variant:"outline",className:"mr-1",children:Je.status}),Je.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Je.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Je.soldPrice||Je.price||0).toLocaleString()]}),Je.sqft&&(Je.soldPrice||Je.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Je.soldPrice||Je.price)/Je.sqft),"/sqft"]}):null]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>v(we),title:"View details",children:e.jsx(Ir,{className:"w-4 h-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ce(we),title:"Remove",children:e.jsx(bn,{className:"w-4 h-4"})})]})},we)})}):e.jsx(fe,{children:e.jsx(Ae,{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:[Te&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>M(!0),children:"Fill subject details"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>z(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(Yht,{comp:b!=null?h[b]:null,open:b!=null,onClose:()=>v(null)}),e.jsx(cZs,{open:L,onOpenChange:M,subject:r.subject,onSave:de,isSaving:l.isPending}),e.jsx(dZs,{open:F,onOpenChange:z,subject:r.subject,onAdd:ie}),e.jsx(awt,{open:T,onOpenChange:D,cma:r})]})})}function hZs(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 l2t="popby_geocode_cache_v1";function mZs(){try{return JSON.parse(localStorage.getItem(l2t)||"{}")}catch{return{}}}function pZs(s){try{localStorage.setItem(l2t,JSON.stringify(s))}catch{}}function fZs({contacts:s,onLogPopby:t}){const[n,r]=N.useState(null),[a,i]=N.useState("idle"),[l,o]=N.useState(5),[c,d]=N.useState(""),[u,h]=N.useState(new Map),[p,f]=N.useState(!1);N.useEffect(()=>{(async()=>{const{data:_}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();_!=null&&_.value&&d(_.value)})()},[]);const g=N.useMemo(()=>s.filter(_=>_.isDue&&(_.address||_.city&&_.state||_.zip)),[s]),b=()=>{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})};N.useEffect(()=>{if(!c||!n||g.length===0)return;let _=!1;const S=mZs(),A=new Map;g.forEach(D=>{const L=[D.address,D.city,D.state,D.zip].filter(Boolean).join("|").toLowerCase();S[L]&&A.set(D.id,S[L])}),h(new Map(A));const T=g.filter(D=>!([D.address,D.city,D.state,D.zip].filter(Boolean).join("|").toLowerCase()in S));if(T.length!==0)return f(!0),(async()=>{const D=[...T],L=async()=>{var M,F;for(;D.length&&!_;){const z=D.shift(),V=[z.address,z.city,z.state,z.zip].filter(Boolean),W=V.join("|").toLowerCase(),K=V.join(", ");try{const ee=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(K)}.json?limit=1&access_token=${c}`)).json();if((F=(M=ee==null?void 0:ee.features)==null?void 0:M[0])!=null&&F.center){const[ne,oe]=ee.features[0].center;S[W]={lat:oe,lng:ne},A.set(z.id,{lat:oe,lng:ne})}else S[W]=null}catch{}}};await Promise.all([L(),L(),L(),L()]),_||(pZs(S),h(new Map(A)),f(!1))})(),()=>{_=!0}},[c,n,g]);const v=N.useMemo(()=>{if(!n)return[];const _=[];return g.forEach(S=>{const A=u.get(S.id);if(!A)return;const T=hZs(n.lat,n.lng,A.lat,A.lng);T<=l&&_.push({...S,distanceMiles:T,lat:A.lat,lng:A.lng})}),_.sort((S,A)=>S.distanceMiles-A.distanceMiles)},[n,g,u,l]),j=_=>{const A=/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(A,"_blank","noopener")};return e.jsxs(fe,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(lL,{className:"h-5 w-5 text-primary"}),"Nearby Now"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Due contacts within driving distance — perfect for errand-day pop-bys."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(us,{value:String(l),onValueChange:_=>o(Number(_)),children:[e.jsx(cs,{className:"w-[110px] h-9",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"2",children:"2 miles"}),e.jsx(Ze,{value:"5",children:"5 miles"}),e.jsx(Ze,{value:"10",children:"10 miles"}),e.jsx(Ze,{value:"25",children:"25 miles"})]})]}),e.jsxs(B,{size:"sm",variant:a==="ok"?"outline":"default",onClick:b,disabled:a==="loading",children:[a==="loading"?e.jsx(Ai,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(lL,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Ae,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(Ca,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"Tap ",e.jsx("span",{className:"font-medium text-foreground",children:'"Use my location"'})," to see who's close by right now."]}),a==="denied"&&e.jsxs("div",{className:"text-center py-6 text-sm text-destructive flex flex-col items-center gap-2",children:[e.jsx(Gi,{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&&p&&v.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ws,{className:"h-14 w-full"}),e.jsx(Ws,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!p&&v.length===0&&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."]}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ze,{variant:"secondary",className:"font-medium",children:[v.length," nearby"]}),p&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ai,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:v.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(ze,{variant:"outline",className:"text-xs",children:_.distanceMiles<1?`${(_.distanceMiles*5280).toFixed(0)} ft`:`${_.distanceMiles.toFixed(1)} mi`}),_.daysOverdue>0&&e.jsxs(ze,{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(B,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${_.phone}`,children:e.jsx(Pr,{className:"h-4 w-4"})})}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>j(_),className:"h-9 w-9",title:"Directions",children:e.jsx(g9,{className:"h-4 w-4"})}),e.jsxs(B,{size:"sm",onClick:()=>t(_),children:[e.jsx(Bi,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},_.id))})]})]})]})}const xZs="0dde5abb-0005-4c8c-a471-30d0cbc9e280",gZs=[{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 yZs(){const s=In(),t=D_t(),{data:n}=iGs(),{data:r}=Cy(),{data:a}=wLe(),{data:i}=R1e(90),{data:l}=lx(),o=uGs(),c=cGs(),d=lGs(),u=dGs(),{data:h=[],isLoading:p}=lt({queryKey:["popby-templates"],queryFn:async()=>{const{data:ee,error:ne}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",xZs).order("publish_date",{ascending:!1});if(ne)throw ne;const{data:oe}=await q.from("template_likes").select("template_id"),{data:pe}=await q.from("template_comments").select("template_id"),ce=new Map;oe==null||oe.forEach(ie=>{ce.set(ie.template_id,(ce.get(ie.template_id)||0)+1)});const de=new Map;return pe==null||pe.forEach(ie=>{de.set(ie.template_id,(de.get(ie.template_id)||0)+1)}),(ee||[]).map(ie=>({...ie,likesCount:ce.get(ie.id)||0,commentsCount:de.get(ie.id)||0}))}}),f=ee=>{const ne=l==null?void 0:l.find(oe=>oe.id===ee);return ne?`${ne.first_name} ${ne.last_name||""}`.trim():"Unknown"},g=ee=>{if(!ee)return null;const ne=n==null?void 0:n.find(oe=>oe.id===ee);return(ne==null?void 0:ne.name)||null},[b,v]=N.useState(null),[j,_]=N.useState(!1),[S,A]=N.useState(!1),[T,D]=N.useState(!1),[L,M]=N.useState({popby_item_id:"",notes:""}),[F,z]=N.useState({name:"",description:""}),V=async()=>{b&&(await c.mutateAsync({contact_id:b.id,popby_item_id:L.popby_item_id||void 0,notes:L.notes||void 0}),_(!1),v(null),M({popby_item_id:"",notes:""}))},W=async()=>{F.name.trim()&&(await d.mutateAsync({name:F.name.trim(),description:F.description.trim()||void 0}),D(!1),z({name:"",description:""}))},K=async(ee,ne)=>{await u.mutateAsync({relationship_type_id:ee,frequency_days:parseInt(ne)})},Y=ee=>{var oe;const ne=a==null?void 0:a.find(pe=>pe.relationship_type_id===ee);return((oe=ne==null?void 0:ne.frequency_days)==null?void 0:oe.toString())||"90"};return e.jsx(Cs,{title:"Popbys",description:"Drop off gifts to stay top of mind",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Popbys"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-primary",children:o.thisWeekCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Week"})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-emerald-500",children:o.thisMonthCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Month"})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-amber-500",children:o.dueCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Due Now"})]})})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(B,{variant:"outline",onClick:()=>A(!0),children:[e.jsx(Vo,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(B,{variant:"outline",onClick:()=>D(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs($r,{defaultValue:"due",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"due",children:"Due for Popby"}),e.jsx(Zt,{value:"activity",children:"Recent Activity"}),e.jsx(Zt,{value:"library",children:"Popby Library"}),e.jsx(Zt,{value:"templates",children:"Popby Templates"})]}),e.jsxs(ls,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(fZs,{contacts:t||[],onLogPopby:ee=>{v(ee),_(!0)}}),!t||t.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Bi,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No contacts due for a popby right now!"}),e.jsx("p",{className:"text-sm mt-1",children:"Great job staying connected."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(ee=>e.jsx(fe,{className:"hover:shadow-md transition-shadow",children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:[ee.first_name," ",ee.last_name]}),ee.daysOverdue>0&&e.jsxs(ze,{variant:"destructive",className:"text-xs",children:[ee.daysOverdue,"+ days overdue"]}),ee.daysSinceLastPopby===null&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Never visited"})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-1 text-sm text-muted-foreground",children:[ee.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),ee.city||ee.address]}),ee.tags&&ee.tags.length>0&&e.jsx("span",{children:ee.tags.map(ne=>{var oe;return(oe=ne.relationship_type)==null?void 0:oe.name}).join(", ")})]}),ee.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",ks(new Date(ee.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ee.phone&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${ee.phone}`,children:e.jsx(Pr,{className:"h-4 w-4"})})}),e.jsxs(B,{size:"sm",onClick:()=>{v(ee),_(!0)},children:[e.jsx(zi,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},ee.id))})]}),e.jsx(ls,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(gr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby activity yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Start logging popbys to see your history here."})]})}):e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Ae,{className:"space-y-3",children:i.map(ee=>e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0 last:pb-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/10 flex items-center justify-center",children:e.jsx(Bi,{className:"h-5 w-5 text-orange-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:f(ee.contact_id)}),g(ee.popby_item_id)&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:g(ee.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:ks(new Date(ee.completed_at),"MMM d, yyyy h:mm a")}),ee.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ee.notes})]})]},ee.id))})]})}),e.jsx(ls,{value:"library",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[n==null?void 0:n.map(ee=>e.jsx(fe,{children:e.jsx(Ae,{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(Bi,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:ee.name}),ee.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:ee.description}),!ee.owner_user_id&&e.jsx(ze,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},ee.id)),e.jsx(fe,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>D(!0),children:e.jsx(Ae,{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(As,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(ls,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[h.length," template",h.length!==1?"s":""," found"]}),p&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(4)].map((ee,ne)=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ws,{className:"h-5 w-16"}),e.jsx(Ws,{className:"h-5 w-20"})]})]})},ne))}),!p&&h.length===0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Oc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby templates available yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Check back soon for new templates."})]})}),!p&&h.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:h.map(ee=>e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${ee.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:ee.preview_image_url?e.jsx("img",{src:ee.preview_image_url,alt:ee.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})}),e.jsxs(Ae,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:ee.name}),ee.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:tB(ee.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(ze,{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(Hm,{className:"h-3.5 w-3.5"}),ee.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),ee.commentsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:ne=>{ne.stopPropagation(),s(`/templates/${ee.id}`)},children:[e.jsx(tr,{className:"h-4 w-4"}),"View Template"]})]})]},ee.id))})]})]}),e.jsx(bs,{open:j,onOpenChange:_,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Log Popby for ",b==null?void 0:b.first_name," ",b==null?void 0:b.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Popby Item (optional)"}),e.jsxs(us,{value:L.popby_item_id,onValueChange:ee=>M(ne=>({...ne,popby_item_id:ee})),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select a popby item..."})}),e.jsx(ds,{children:n==null?void 0:n.map(ee=>e.jsx(Ze,{value:ee.id,children:ee.name},ee.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes (optional)"}),e.jsx(Ts,{placeholder:"Any notes about this popby...",value:L.notes,onChange:ee=>M(ne=>({...ne,notes:ee.target.value}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsx(B,{onClick:V,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(bs,{open:S,onOpenChange:A,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{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(ee=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(se,{className:"font-medium",children:ee.name}),e.jsxs(us,{value:Y(ee.id),onValueChange:ne=>K(ee.id,ne),children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{})}),e.jsx(ds,{children:gZs.map(ne=>e.jsx(Ze,{value:ne.value,children:ne.label},ne.value))})]})]},ee.id))]}),e.jsx(Xn,{children:e.jsx(B,{onClick:()=>A(!1),children:"Done"})})]})}),e.jsx(bs,{open:T,onOpenChange:D,children:e.jsxs(vs,{children:[e.jsx(ws,{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(se,{children:"Name *"}),e.jsx(ge,{placeholder:"e.g., Homemade cookies",value:F.name,onChange:ee=>z(ne=>({...ne,name:ee.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{placeholder:"Optional description...",value:F.description,onChange:ee=>z(ne=>({...ne,description:ee.target.value}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(B,{onClick:W,disabled:!F.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const vZs=Zw({property_address:go().min(1,"Property address is required"),city:go().optional(),state:go().optional(),zip:go().optional(),transaction_type:wMe(["buyer","seller"]),close_date:go().min(1,"Close date is required"),sale_price:X9().min(0,"Sale price must be positive"),commission_amount:X9().optional(),lead_source_id:go().optional(),client_type_id:go().optional(),contact_id:go().optional(),notes:go().optional(),is_win:yWt()});function c2t({open:s,onOpenChange:t,transaction:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(""),h=Wye(),p=eas(),{data:f}=KM(),{data:g}=Cy(),{data:b}=lx(),v=Gye(),j=k6e(),{data:_}=Kye(),S=(_==null?void 0:_.show_commission)??!0,A=zye({resolver:Bye(vZs),defaultValues:{property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1}});N.useEffect(()=>{n?A.reset({property_address:n.property_address,city:n.city||"",state:n.state||"",zip:n.zip||"",transaction_type:n.transaction_type,close_date:n.close_date,sale_price:Number(n.sale_price),commission_amount:n.commission_amount?Number(n.commission_amount):void 0,lead_source_id:n.lead_source_id||void 0,client_type_id:n.client_type_id||void 0,contact_id:n.contact_id||void 0,notes:n.notes||"",is_win:n.is_win}):A.reset({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1})},[n,A]);const T=async F=>{const z={property_address:F.property_address,transaction_type:F.transaction_type,close_date:F.close_date,sale_price:F.sale_price,is_win:F.is_win,commission_amount:F.commission_amount||null,lead_source_id:F.lead_source_id||null,client_type_id:F.client_type_id||null,contact_id:F.contact_id||null,city:F.city||null,state:F.state||null,zip:F.zip||null,notes:F.notes||null};n?await p.mutateAsync({id:n.id,...z}):await h.mutateAsync(z),t(!1)},D=async()=>{if(!i.trim())return;const[F,...z]=i.trim().split(" "),V=z.join(" ")||null,W=await v.mutateAsync({first_name:F,last_name:V,tagIds:[]});W&&(A.setValue("contact_id",W.id),l(""),c(!1),a(!1))},L=async()=>{if(!d.trim())return;const F=await j.mutateAsync(d.trim());F&&(A.setValue("lead_source_id",F.id),u(""))},M=b==null?void 0:b.find(F=>F.id===A.watch("contact_id"));return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(ws,{children:e.jsx(_s,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(mi,{className:"max-h-[70vh] pr-4",children:e.jsx($ye,{...A,children:e.jsxs("form",{onSubmit:A.handleSubmit(T),className:"space-y-4",children:[e.jsx(Cu,{control:A.control,name:"property_address",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Property Address *"}),e.jsx(lu,{children:e.jsx(ge,{placeholder:"123 Main St",...F})}),e.jsx(Zx,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(Cu,{control:A.control,name:"city",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"City"}),e.jsx(lu,{children:e.jsx(ge,{placeholder:"City",...F})})]})}),e.jsx(Cu,{control:A.control,name:"state",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"State"}),e.jsx(lu,{children:e.jsx(ge,{placeholder:"TX",...F})})]})}),e.jsx(Cu,{control:A.control,name:"zip",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Zip"}),e.jsx(lu,{children:e.jsx(ge,{placeholder:"75001",...F})})]})})]}),e.jsx(Cu,{control:A.control,name:"transaction_type",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Transaction Type *"}),e.jsxs(us,{onValueChange:F.onChange,value:F.value,children:[e.jsx(lu,{children:e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select type"})})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"})]})]}),e.jsx(Zx,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Cu,{control:A.control,name:"close_date",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Close Date *"}),e.jsx(lu,{children:e.jsx(ge,{type:"date",...F})}),e.jsx(Zx,{})]})}),e.jsx(Cu,{control:A.control,name:"sale_price",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Sale Price *"}),e.jsx(lu,{children:e.jsx(ge,{type:"number",placeholder:"0",...F,onChange:z=>F.onChange(Number(z.target.value))})}),e.jsx(Zx,{})]})})]}),S&&e.jsx(Cu,{control:A.control,name:"commission_amount",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Commission"}),e.jsx(lu,{children:e.jsx(ge,{type:"number",placeholder:"0",...F,value:F.value??"",onChange:z=>F.onChange(z.target.value?Number(z.target.value):void 0)})})]})}),e.jsx(Cu,{control:A.control,name:"lead_source_id",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Lead Source"}),e.jsxs(us,{onValueChange:F.onChange,value:F.value||"",children:[e.jsx(lu,{children:e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select source"})})}),e.jsx(ds,{children:f==null?void 0:f.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{placeholder:"Add custom source...",value:d,onChange:F=>u(F.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:L,disabled:!d.trim(),children:e.jsx(As,{className:"h-4 w-4"})})]}),e.jsx(Cu,{control:A.control,name:"client_type_id",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Client Type"}),e.jsxs(us,{onValueChange:F.onChange,value:F.value||"",children:[e.jsx(lu,{children:e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select client type"})})}),e.jsx(ds,{children:g==null?void 0:g.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))})]})]})}),e.jsx(Cu,{control:A.control,name:"contact_id",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Client Contact"}),e.jsxs(Wo,{open:r,onOpenChange:a,children:[e.jsx(Ko,{asChild:!0,children:e.jsx(lu,{children:e.jsxs(B,{variant:"outline",role:"combobox",className:Et("w-full justify-between",!F.value&&"text-muted-foreground"),children:[M?`${M.first_name} ${M.last_name||""}`.trim():"Select contact",e.jsx(Hg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(zo,{className:"w-full p-0",align:"start",children:[e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search contacts..."}),e.jsxs(e0,{children:[e.jsx(t0,{children:e.jsxs("div",{className:"p-2 space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!o&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(s0,{children:b==null?void 0:b.map(z=>e.jsxs(ex,{value:`${z.first_name} ${z.last_name||""}`,onSelect:()=>{F.onChange(z.id),a(!1)},children:[e.jsx(Lr,{className:Et("mr-2 h-4 w-4",z.id===F.value?"opacity-100":"opacity-0")}),z.first_name," ",z.last_name||""]},z.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(ge,{placeholder:"Enter contact name...",value:i,onChange:z=>l(z.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:D,disabled:!i.trim()||v.isPending,children:"Add Contact"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(Cu,{control:A.control,name:"notes",render:({field:F})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Notes"}),e.jsx(lu,{children:e.jsx(Ts,{placeholder:"Any notes about this transaction...",...F})})]})}),e.jsx(Cu,{control:A.control,name:"is_win",render:({field:F})=>e.jsxs(iu,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ou,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(lu,{children:e.jsx(vn,{checked:F.value,onCheckedChange:F.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:h.isPending||p.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function b8e({transactions:s,showCommission:t,isLoading:n,agentNameMap:r,readOnly:a}){const[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,p]=N.useState("all"),[f,g]=N.useState("all"),[b,v]=N.useState("all"),[j,_]=N.useState(!1),S=tas(),A=Wye(),{data:T}=KM();Cy();const D=kR(),L=z=>{const{id:V,created_at:W,updated_at:K,lead_source:Y,client_type:ee,contact:ne,...oe}=z;A.mutate(oe)},M=()=>{o&&(S.mutate(o),c(null))},F=s.filter(z=>{var ne,oe,pe,ce;const V=d===""||z.property_address.toLowerCase().includes(d.toLowerCase())||((oe=(ne=z.contact)==null?void 0:ne.first_name)==null?void 0:oe.toLowerCase().includes(d.toLowerCase()))||((ce=(pe=z.contact)==null?void 0:pe.last_name)==null?void 0:ce.toLowerCase().includes(d.toLowerCase())),W=h==="all"||z.transaction_type===h,K=f==="all"||z.lead_source_id===f,Y=b==="all"||z.client_type_id===b,ee=!j||z.is_win;return V&&W&&K&&Y&&ee});return n?e.jsx(fe,{children:e.jsx(Ae,{className:"p-6 space-y-4",children:[1,2,3].map(z=>e.jsx(Ws,{className:"h-16 w-full"},z))})}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs(Pt,{children:["Transactions (",F.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search...",value:d,onChange:z=>u(z.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(cs,{className:"w-[100px]",children:e.jsx(hs,{placeholder:"Type"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"})]})]}),e.jsxs(us,{value:f,onValueChange:g,children:[e.jsx(cs,{className:"w-[130px]",children:e.jsx(hs,{placeholder:"Lead Source"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Sources"}),T==null?void 0:T.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))]})]}),e.jsxs(B,{variant:j?"default":"outline",size:"sm",onClick:()=>_(!j),children:[e.jsx(vc,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Ae,{children:F.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):D?e.jsx("div",{className:"space-y-3",children:F.map(z=>e.jsxs(fe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium truncate",children:z.property_address}),z.is_win&&e.jsx(vc,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[z.city,z.state?`, ${z.state}`:""]})]}),e.jsx(ze,{variant:z.transaction_type==="buyer"?"default":"secondary",children:z.transaction_type})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Close Date: "}),sze(z.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),gc(z.sale_price)]}),t&&z.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),gc(z.commission_amount)]}),z.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),z.lead_source.name]}),z.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),z.contact.first_name," ",z.contact.last_name]}),r&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),r[z.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>l(z),children:e.jsx(Tu,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>L(z),children:e.jsx(ta,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(z.id),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})]},z.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[r&&e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Property"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Close Date"}),e.jsx(Ct,{children:"Sale Price"}),t&&e.jsx(Ct,{children:"Commission"}),e.jsx(Ct,{children:"Lead Source"}),e.jsx(Ct,{children:"Client"}),!a&&e.jsx(Ct,{className:"w-[50px]"})]})}),e.jsx(pa,{children:F.map(z=>{var V;return e.jsxs(Gs,{children:[r&&e.jsx(ut,{className:"font-medium text-sm",children:r[z.owner_user_id]||"Unknown"}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[z.is_win&&e.jsx(vc,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:z.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[z.city,z.state?`, ${z.state}`:""]})]})]})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.transaction_type==="buyer"?"default":"secondary",children:z.transaction_type})}),e.jsx(ut,{children:sze(z.close_date)}),e.jsx(ut,{children:gc(z.sale_price)}),t&&e.jsx(ut,{children:z.commission_amount?gc(z.commission_amount):"-"}),e.jsx(ut,{children:((V=z.lead_source)==null?void 0:V.name)||"-"}),e.jsx(ut,{children:z.contact?`${z.contact.first_name} ${z.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(ut,{children:e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(Lg,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[e.jsxs(Xr,{onClick:()=>l(z),children:[e.jsx(Tu,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Xr,{onClick:()=>L(z),children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(Xr,{onClick:()=>c(z.id),className:"text-destructive",children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},z.id)})})]})})})]}),e.jsx(c2t,{open:!!i,onOpenChange:z=>!z&&l(null),transaction:i||void 0}),e.jsx(Oo,{open:!!o,onOpenChange:z=>!z&&c(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Transaction?"}),e.jsx(Mo,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:M,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function d2t({goals:s,stats:t,year:n,showCommission:r}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===n?a:12,l=12-i,o=(p,f)=>{if(!f||f===0)return null;const g=Math.min(p/f*100,100),b=Math.max(f-p,0),v=l>0?b/l:0,j=i/12*100,_=g>=j?"ahead":g>=j*.8?"on-track":"behind";return{percent:g,remaining:b,pace:v,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=p=>{switch(p){case"ahead":return e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(mo,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(ze,{variant:"secondary",children:[e.jsx(xb,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(ze,{variant:"destructive",children:[e.jsx(bb,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wc,{className:"h-5 w-5 text-primary"}),e.jsxs(Pt,{children:[n," Goals Progress"]})]})}),e.jsx(Ae,{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(xi,{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(xi,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[gc(t.totalVolume,!0)," of ",gc(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 ",gc(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(xi,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[gc(t.totalCommission,!0)," of ",gc(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 ",gc(u.pace,!0),"/month"]})]})]})})]})}const bZs={light:"",dark:".dark"},u2t=N.createContext(null);function h2t(){const s=N.useContext(u2t);if(!s)throw new Error("useChart must be used within a ");return s}const m2t=N.forwardRef(({id:s,className:t,children:n,config:r,...a},i)=>{const l=N.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(u2t.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":o,ref:i,className:Et("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(_Zs,{id:o,config:r}),e.jsx(Sw,{children:n})]})})});m2t.displayName="Chart";const _Zs=({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(bZs).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},p2t=N.forwardRef(({active:s,payload:t,className:n,indicator:r="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:u,nameKey:h,labelKey:p},f)=>{const{config:g}=h2t(),b=N.useMemo(()=>{var T;if(a||!(t!=null&&t.length))return null;const[j]=t,_=`${p||j.dataKey||j.name||"value"}`,S=kTe(g,j,_),A=!p&&typeof l=="string"?((T=g[l])==null?void 0:T.label)||l:S==null?void 0:S.label;return o?e.jsx("div",{className:Et("font-medium",c),children:o(A,t)}):A?e.jsx("div",{className:Et("font-medium",c),children:A}):null},[l,o,t,a,c,g,p]);if(!s||!(t!=null&&t.length))return null;const v=t.length===1&&r!=="dot";return e.jsxs("div",{ref:f,className:Et("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",n),children:[v?null:b,e.jsx("div",{className:"grid gap-1.5",children:t.map((j,_)=>{const S=`${h||j.name||j.dataKey||"value"}`,A=kTe(g,j,S),T=u||j.payload.fill||j.color;return e.jsx("div",{className:Et("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",r==="dot"&&"items-center"),children:d&&(j==null?void 0:j.value)!==void 0&&j.name?d(j.value,j.name,j,_,j.payload):e.jsxs(e.Fragment,{children:[A!=null&&A.icon?e.jsx(A.icon,{}):!i&&e.jsx("div",{className:Et("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":r==="dot","w-1":r==="line","w-0 border-[1.5px] border-dashed bg-transparent":r==="dashed","my-0.5":v&&r==="dashed"}),style:{"--color-bg":T,"--color-border":T}}),e.jsxs("div",{className:Et("flex flex-1 justify-between leading-none",v?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[v?b:null,e.jsx("span",{className:"text-muted-foreground",children:(A==null?void 0:A.label)||j.name})]}),j.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:j.value.toLocaleString()})]})]})},j.dataKey)})})]})});p2t.displayName="ChartTooltip";const wZs=N.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=h2t();return n!=null&&n.length?e.jsx("div",{ref:i,className:Et("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=kTe(l,o,c);return e.jsxs("div",{className:Et("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});wZs.displayName="ChartLegend";function kTe(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 EG=["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 _8e({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(fe,{children:e.jsx(Ae,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):e.jsxs("div",{className:"grid gap-6",children:[n&&e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Ae,{className:"overflow-hidden",children:e.jsx(m2t,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(Sw,{width:"100%",height:"100%",children:e.jsxs(xLe,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(mLe,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Bw,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx($w,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(kp,{content:e.jsx(p2t,{})}),e.jsx(zw,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ae,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(Sw,{width:"100%",height:"100%",children:e.jsxs(gLe,{children:[e.jsx(Bb,{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(gR,{fill:EG[i%EG.length]},`cell-${i}`))}),e.jsx(kp,{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:EG[i%EG.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function jZs(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=mMe(t,r,new Date);if(z4e(a))return ks(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(z4e(r))return ks(r,"yyyy-MM-dd")}catch{}return null}const NZs=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function kZs({open:s,onOpenChange:t}){const[n,r]=N.useState([]),[a,i]=N.useState(!1),[l,o]=N.useState(0),{data:c}=KM(),{data:d}=Cy(),u=Wye(),h=()=>{const j=NZs.join(","),_=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),S=`${j} ${_}`,A=new Blob([S],{type:"text/csv"}),T=URL.createObjectURL(A),D=document.createElement("a");D.href=T,D.download="transaction-import-template.csv",D.click(),URL.revokeObjectURL(T)},p=j=>{const _=j.split(` `).filter(A=>A.trim());if(_.length<2)return[];const S=_[0].split(",").map(A=>A.trim().toLowerCase().replace(/['"]/g,""));return _.slice(1).map((A,T)=>{var oe,pe,ce,de;const D=[];let L="",M=!1;for(const ie of A)ie==='"'?M=!M:ie===","&&!M?(D.push(L.trim()),L=""):L+=ie;D.push(L.trim());const F=ie=>{var _e;const ye=S.indexOf(ie);return ye>=0?(_e=D[ye])==null?void 0:_e.replace(/^["']|["']$/g,"").trim():""},z=(oe=F("transaction_type"))==null?void 0:oe.toLowerCase(),V=(pe=F("sale_price"))==null?void 0:pe.replace(/[$,]/g,""),W=(ce=F("commission_amount"))==null?void 0:ce.replace(/[$,]/g,""),K=(de=F("is_win"))==null?void 0:de.toLowerCase(),Y=F("close_date"),ee=jZs(Y);let ne;return F("property_address")?["buyer","seller"].includes(z)?ee?(!V||isNaN(Number(V)))&&(ne="Invalid sale price"):ne=`Invalid date format: "${Y}" - use MM/DD/YYYY or YYYY-MM-DD`:ne='Transaction type must be "buyer" or "seller"':ne="Missing property address",{property_address:F("property_address"),city:F("city"),state:F("state"),zip:F("zip"),transaction_type:z==="seller"?"seller":"buyer",close_date:ee||"",sale_price:Number(V)||0,commission_amount:W?Number(W):null,lead_source_name:F("lead_source"),client_type_name:F("client_type"),is_win:["yes","true","1"].includes(K),notes:F("notes"),error:ne}})},f=j=>{var A;const _=(A=j.target.files)==null?void 0:A[0];if(!_)return;const S=new FileReader;S.onload=T=>{var M;const D=(M=T.target)==null?void 0:M.result,L=p(D);r(L)},S.readAsText(_)},g=async()=>{const j=n.filter(A=>!A.error);if(j.length===0){ae.error("No valid transactions to import");return}i(!0),o(0);let _=0,S=0;for(let A=0;AM.name.toLowerCase()===T.lead_source_name.toLowerCase()),L=d==null?void 0:d.find(M=>M.name.toLowerCase()===T.client_type_name.toLowerCase());await u.mutateAsync({property_address:T.property_address,city:T.city||null,state:T.state||null,zip:T.zip||null,transaction_type:T.transaction_type,close_date:T.close_date,sale_price:T.sale_price,commission_amount:T.commission_amount,lead_source_id:(D==null?void 0:D.id)||null,client_type_id:(L==null?void 0:L.id)||null,contact_id:null,notes:T.notes||null,is_win:T.is_win}),_++}catch(D){S++,console.error("Failed to import transaction:",D)}o(Math.round((A+1)/j.length*100))}i(!1),_>0&&ae.success(`Imported ${_} transaction${_>1?"s":""}`),S>0&&ae.error(`Failed to import ${S} transaction${S>1?"s":""}`),r([]),t(!1)},b=n.filter(j=>!j.error).length,v=n.filter(j=>j.error).length;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Import Transactions"}),e.jsx(Qn,{children:"Upload a CSV file with your past transactions"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Download Template"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Get a CSV template with the correct format"})]}),e.jsxs(B,{variant:"outline",onClick:h,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(ge,{id:"csv-file",type:"file",accept:".csv",onChange:f})]}),n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ze,{variant:"outline",children:[n.length," rows found"]}),b>0&&e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"}),b," valid"]}),v>0&&e.jsxs(ze,{variant:"destructive",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"}),v," errors"]})]}),e.jsx(mi,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((j,_)=>e.jsxs("div",{className:`p-2 rounded text-sm ${j.error?"bg-destructive/10":"bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:j.property_address||"(no address)"}),e.jsx(ze,{variant:j.transaction_type==="buyer"?"default":"secondary",children:j.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[j.close_date," • $",j.sale_price.toLocaleString()]}),j.error&&e.jsx(IIe,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(PIe,{className:"text-xs",children:j.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(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:g,disabled:b===0||a,children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Import ",b," Transaction",b!==1?"s":""]})]})]})]})})}const SZs=Zw({transactions_goal:X9().min(0).optional(),volume_goal:X9().min(0).optional(),gci_goal:X9().min(0).optional()});function CZs({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=sas(),{data:i}=Kye(),l=(i==null?void 0:i.show_commission)??!0,o=zye({resolver:Bye(SZs),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});N.useEffect(()=>{r?o.reset({transactions_goal:r.transactions_goal??void 0,volume_goal:r.volume_goal?Number(r.volume_goal):void 0,gci_goal:r.gci_goal?Number(r.gci_goal):void 0}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[r,o,s]);const c=async d=>{await a.mutateAsync({year:n,transactions_goal:d.transactions_goal??null,volume_goal:d.volume_goal??null,gci_goal:l?d.gci_goal??null:null}),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[n," Goals"]}),e.jsx(Qn,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx($ye,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(Cu,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Transactions Goal"}),e.jsx(lu,{children:e.jsx(ge,{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(Gme,{children:"Total number of deals you want to close"}),e.jsx(Zx,{})]})}),e.jsx(Cu,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"Volume Goal ($)"}),e.jsx(lu,{children:e.jsx(ge,{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(Gme,{children:"Total sales volume you want to achieve"}),e.jsx(Zx,{})]})}),l&&e.jsx(Cu,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(iu,{children:[e.jsx(ou,{children:"GCI Goal ($)"}),e.jsx(lu,{children:e.jsx(ge,{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(Gme,{children:"Gross commission income target"}),e.jsx(Zx,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function w8e({transactions:s,isLoading:t}){const n=N.useRef(null),r=N.useRef(null),a=N.useRef([]),i=N.useRef(null),{isAdmin:l}=gs(),[o,c]=N.useState(""),[d,u]=N.useState(!0),[h,p]=N.useState(0),[f,g]=N.useState(!1),b=s.filter(j=>j.latitude!=null&&j.longitude!=null),v=s.filter(j=>j.latitude==null||j.longitude==null);return N.useEffect(()=>{(async()=>{u(!0);try{const{data:_}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();_!=null&&_.value&&c(_.value)}catch(_){console.error("Error fetching mapbox token:",_)}u(!1)})()},[]),N.useEffect(()=>{if(!o||v.length===0||f)return;(async()=>{var S;g(!0);let _=0;for(const A of v){const T=[A.property_address,A.city,A.state,A.zip].filter(Boolean).join(", ");if(T)try{const L=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(T)}.json?access_token=${o}&limit=1`)).json();if((S=L.features)!=null&&S[0]){const[M,F]=L.features[0].center;await q.from("scorecard_transactions").update({latitude:F,longitude:M}).eq("id",A.id),A.latitude=F,A.longitude=M,_++}}catch(D){console.error("Geocode error:",D)}}p(_),g(!1)})()},[o,s]),N.useEffect(()=>{if(!n.current||!o||r.current)return;ml.accessToken=o;const j=s.filter(A=>A.latitude!=null&&A.longitude!=null);let _=[-98.5795,39.8283],S=4;if(j.length>0){const A=j.reduce((D,L)=>D+L.longitude,0)/j.length,T=j.reduce((D,L)=>D+L.latitude,0)/j.length;_=[A,T],S=j.length===1?12:10}return r.current=new ml.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:S,center:_}),r.current.addControl(new ml.NavigationControl,"top-right"),()=>{var A;(A=r.current)==null||A.remove(),r.current=null}},[o]),N.useEffect(()=>{var _;if(!r.current||!o)return;a.current.forEach(S=>S.remove()),a.current=[],(_=i.current)==null||_.remove();const j=s.filter(S=>S.latitude!=null&&S.longitude!=null);if(j.forEach(S=>{var F;const A=S.transaction_type==="buyer",T=A?"#3B82F6":"#10B981",D=document.createElement("div");D.className="cursor-pointer",D.innerHTML=`
${A?'':''}
`;const L=new ml.Popup({offset:25,closeButton:!0}).setHTML(`
${S.property_address}
${S.city?`
${S.city}${S.state?", "+S.state:""} ${S.zip||""}
`:""}
${A?"Buyer":"Seller"} $${Number(S.sale_price).toLocaleString()}
Closed: ${ll(S.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(F=S.lead_source)!=null&&F.name?" · "+S.lead_source.name:""}
${S.contact?`
Client: ${S.contact.first_name} ${S.contact.last_name||""}
`:""}
`),M=new ml.Marker(D).setLngLat([S.longitude,S.latitude]).setPopup(L).addTo(r.current);a.current.push(M)}),j.length>1){const S=new ml.LngLatBounds;j.forEach(A=>S.extend([A.longitude,A.latitude])),r.current.fitBounds(S,{padding:60,maxZoom:13})}else j.length===1&&r.current.flyTo({center:[j[0].longitude,j[0].latitude],zoom:12})},[s,o,f]),d||t?e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center h-[50vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Ca,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"No Transactions Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add transactions to see them plotted on the map."})]})]})}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#3B82F6"}}),e.jsx("span",{children:"Buyer"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#10B981"}}),e.jsx("span",{children:"Seller"})]}),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[b.length," of ",s.length," mapped",f&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Gi,{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 f2t=()=>{const{data:s}=Xv();return lt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:n}=await q.from("team_members").select("user_id").eq("team_id",s.teamId);if(n)throw n;const r=t.map(l=>l.user_id),{data:a,error:i}=await q.from("profiles").select("id, name, email, avatar_url").in("id",r);if(i)throw i;return a||[]},enabled:!!(s!=null&&s.teamId)&&(s==null?void 0:s.role)==="team_leader"})},TZs=s=>{const{data:t}=Xv(),{data:n}=f2t();return lt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const r=n.map(o=>o.id);let a=q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",r).order("close_date",{ascending:!1});s&&(a=a.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:i,error:l}=await a;if(l)throw l;return i},enabled:!!n&&n.length>0})};function EZs(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 AZs(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function MZs({year:s}){var p;const{data:t,isLoading:n}=f2t(),{data:r,isLoading:a}=TZs(s),i=In(),l=n||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:u,teamChartStats:h}=N.useMemo(()=>{if(!t||!r)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const f=t.map(z=>EZs(z,r));f.sort((z,V)=>V.totalVolume-z.totalVolume);const g={};t.forEach(z=>{g[z.id]=z.name||z.email});const b=r.length,v=r.reduce((z,V)=>z+Number(V.sale_price),0),j=r.reduce((z,V)=>z+(Number(V.commission_amount)||0),0),_=r.filter(z=>z.transaction_type==="buyer").length,S=r.filter(z=>z.transaction_type==="seller").length,A={};r.forEach(z=>{var W;const V=((W=z.lead_source)==null?void 0:W.name)||"Unknown";A[V]=(A[V]||0)+1});const T=Object.entries(A).sort((z,V)=>V[1]-z[1])[0],D={};r.forEach(z=>{const V=ll(z.close_date).toLocaleString("default",{month:"short"});D[V]=(D[V]||0)+1});const M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(z=>({month:z,count:D[z]||0})),F=Object.entries(A).map(([z,V])=>({name:z,count:V})).sort((z,V)=>V.count-z.count);return{aggregate:{totalTxns:b,buyerCount:_,sellerCount:S,totalVolume:v,avgPrice:b>0?v/b:0,totalGCI:j,topSource:T?{name:T[0],count:T[1]}:null,memberCount:t.length},memberStats:f,topPerformer:f[0]||null,agentNameMap:g,teamChartStats:{transactionsByMonth:M,leadSourceBreakdown:F}}},[t,r]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(f=>e.jsx(Ws,{className:"h-24"},f))}),e.jsx(Ws,{className:"h-64"})]}):!o||c.length===0?e.jsx(fe,{className:"py-12",children:e.jsxs(Ae,{className:"text-center space-y-2",children:[e.jsx(_n,{className:"h-10 w-10 mx-auto text-muted-foreground"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No Team Data"}),e.jsxs("p",{className:"text-muted-foreground",children:["No scorecard transactions found for your team members in ",s,"."]})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_n,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Members"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.memberCount})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(zr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Team Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.totalTxns}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.buyerCount,"B / ",o.sellerCount,"S"]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{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:gc(o.totalVolume,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(mo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:gc(o.avgPrice,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{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:gc(o.totalGCI,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(vc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((p=o.topSource)==null?void 0:p.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(fe,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Ae,{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(vo,{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:gc(d.totalVolume,!0)})]})]})}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"Member Performance"})}),e.jsx(Ae,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{className:"text-center",children:"Transactions"}),e.jsx(Ct,{className:"text-center",children:"B / S"}),e.jsx(Ct,{className:"text-right",children:"Volume"}),e.jsx(Ct,{className:"text-right",children:"Avg Price"}),e.jsx(Ct,{className:"text-right",children:"GCI"}),e.jsx(Ct,{className:"text-right"})]})}),e.jsx(pa,{children:c.map((f,g)=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[g===0&&f.totalTransactions>0&&e.jsx(vo,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:f.member.avatar_url||void 0}),e.jsx(ia,{className:"text-xs",children:AZs(f.member.name,f.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:f.member.name||f.member.email}),f.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.member.email})]})]})}),e.jsx(ut,{className:"text-center font-semibold",children:f.totalTransactions}),e.jsxs(ut,{className:"text-center text-sm",children:[f.buyerCount," / ",f.sellerCount]}),e.jsx(ut,{className:"text-right font-medium",children:gc(f.totalVolume,!0)}),e.jsx(ut,{className:"text-right text-sm",children:gc(f.averagePrice,!0)}),e.jsx(ut,{className:"text-right font-medium",children:gc(f.totalGCI,!0)}),e.jsx(ut,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${f.member.id}`),children:e.jsx(Ir,{className:"h-4 w-4"})})})]},f.member.id))})]})})})]}),e.jsxs($r,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"transactions",children:[e.jsx(Ep,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Zt,{value:"charts",children:[e.jsx(yo,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Zt,{value:"map",children:[e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(ls,{value:"transactions",children:e.jsx(b8e,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(ls,{value:"charts",children:h&&e.jsx(_8e,{stats:h,year:s})}),e.jsx(ls,{value:"map",children:e.jsx(w8e,{transactions:r||[],isLoading:a})})]})]})}const lpe=new Date().getFullYear(),sXe=Array.from({length:10},(s,t)=>lpe-t),AG="all";function IZs(){var W;const[s,t]=N.useState(lpe),n=s===null?AG:String(s),r=K=>t(K===AG?null:Number(K)),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState("my"),{data:g}=Xv(),b=(g==null?void 0:g.role)==="team_leader",{data:v,isLoading:j}=S6e(s??void 0),{yearStats:_,lifetimeStats:S,isLoading:A,showCommission:T}=_pt(s??void 0),{data:D,isLoading:L}=bpt(s??lpe),{data:M}=Kye(),F=nas(),z=()=>{if(!v||v.length===0)return;const K=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...T?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],Y=v.map(ce=>{var de,ie;return[ce.property_address,ce.city||"",ce.state||"",ce.zip||"",ce.transaction_type,ce.close_date,ce.sale_price,...T?[ce.commission_amount||""]:[],((de=ce.lead_source)==null?void 0:de.name)||"",((ie=ce.client_type)==null?void 0:ie.name)||"",ce.contact?`${ce.contact.first_name} ${ce.contact.last_name||""}`.trim():"",ce.is_win?"Yes":"No",ce.notes||""]}),ee=[K,...Y].map(ce=>ce.map(de=>`"${String(de).replace(/"/g,'""')}"`).join(",")).join(` `),ne=new Blob([ee],{type:"text/csv"}),oe=URL.createObjectURL(ne),pe=document.createElement("a");pe.href=oe,pe.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,pe.click(),URL.revokeObjectURL(oe)},V=!v||v.length===0;return e.jsxs(Cs,{title:"Scorecard",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),b&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx(B,{variant:p==="my"?"default":"ghost",size:"sm",onClick:()=>f("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(B,{variant:p==="team"?"default":"ghost",size:"sm",onClick:()=>f("team"),className:"h-8",children:[e.jsx(_n,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),p==="team"&&b?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Team Performance"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Aggregate stats and member comparison"})]}),e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(cs,{className:"w-[140px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:AG,children:"All Years"}),sXe.map(K=>e.jsx(Ze,{value:String(K),children:K},K))]})]})]}),e.jsx(MZs,{year:s??void 0})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),e.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(cs,{className:"w-[140px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:AG,children:"All Years"}),sXe.map(K=>e.jsx(Ze,{value:String(K),children:K},K))]})]}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(Vo,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(Pt,{className:"text-lg",children:"Settings"})}),e.jsx(Ae,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(se,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(vn,{checked:(M==null?void 0:M.show_commission)??!0,onCheckedChange:K=>F.mutate({show_commission:K})})]})})]}),V&&!j?e.jsx(fe,{className:"py-12",children:e.jsxs(Ae,{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(yo,{className:"h-8 w-8 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Start Tracking Your Success"}),e.jsx("p",{className:"text-muted-foreground max-w-md mx-auto mt-1",children:"Add your past transactions to see your performance metrics, track your goals, and celebrate your wins."})]}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),e.jsxs("div",{className:"pt-4 border-t mt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),e.jsx(B,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Download CSV Template"]})})]})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(wc,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(B,{variant:"outline",onClick:z,disabled:V,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"CSV Template"]})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(zr,{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:[S.totalTransactions," lifetime"]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_n,{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(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:gc(_.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[gc(S.totalVolume,!0)," lifetime"]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(mo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:gc(_.averagePrice,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(vc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((W=_.topLeadSource)==null?void 0:W.name)||"-"}),_.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[_.topLeadSource.count," deals"]})]})}),T&&e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:gc(_.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[gc(S.totalCommission,!0)," lifetime"]})]})}),T&&_.totalNetToAgent>0&&_.totalNetToAgent!==_.totalCommission&&e.jsx(fe,{children:e.jsxs(Ae,{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(Zl,{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:gc(_.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[gc(S.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&D&&e.jsx(d2t,{goals:D,stats:_,year:s,showCommission:T}),e.jsxs($r,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"transactions",children:"Transactions"}),e.jsx(Zt,{value:"charts",children:"Charts"}),e.jsxs(Zt,{value:"map",children:[e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(ls,{value:"transactions",children:e.jsx(b8e,{transactions:v||[],showCommission:T,isLoading:j})}),e.jsx(ls,{value:"charts",children:e.jsx(_8e,{stats:_,year:s??void 0})}),e.jsx(ls,{value:"map",children:e.jsx(w8e,{transactions:v||[],isLoading:j})})]})]})]})]}),e.jsx(c2t,{open:a,onOpenChange:i}),e.jsx(kZs,{open:l,onOpenChange:o}),e.jsx(CZs,{open:c,onOpenChange:d,year:s??lpe,existingGoals:D})]})}function x2t({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a}){const{user:i}=gs(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1);N.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:v,error:j}=await q.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(j)throw j;if(v&&v.share_token)o(v);else if(v&&!v.share_token){const{data:_,error:S}=await q.from("listing_shares").update({share_type:"referral_link"}).eq("id",v.id).select("id, share_token, click_count, lead_count").single();if(S)throw S;o(_)}else{const{data:_,error:S}=await q.from("listing_shares").insert({listing_id:n,sharing_agent_id:i.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(S)throw S;o(_)}}catch(v){console.error("Error creating share link:",v),ae.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,n]);const p=l!=null&&l.share_token?`https://listings.relevelup.com/${r||n}?ref=${l.share_token}`:"",f=async()=>{try{await navigator.clipboard.writeText(p),h(!0),ae.success("Link copied to clipboard!"),setTimeout(()=>h(!1),2e3)}catch{ae.error("Failed to copy link")}},g=b=>{const v=encodeURIComponent(p),j=encodeURIComponent(`Check out this listing: ${a}`);switch(b){case"email":window.open(`mailto:?subject=${j}&body=${v}`);break;case"text":window.open(`sms:?body=${j}%20${v}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${v}`,"_blank");break}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Qn,{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(se,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:c?"Generating...":p,readOnly:!0,className:"font-mono text-sm"}),e.jsx(B,{onClick:f,disabled:c||!p,variant:u?"default":"outline",children:u?e.jsx(Lr,{className:"h-4 w-4"}):e.jsx(ta,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>g("email"),disabled:c,children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>g("text"),disabled:c,children:[e.jsx(Ci,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>g("facebook"),disabled:c,children:[e.jsx(Oh,{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(se,{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(Ir,{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(_n,{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 PZs={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"},LZs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},DZs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function RZs({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,showActions:i}){var v,j;const{user:l}=gs(),{data:o}=ppt(s.id),c=mpt(),[d,u]=N.useState(!1),h=_=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(_),p=((v=s.photos)==null?void 0:v.find(_=>_.is_primary))||((j=s.photos)==null?void 0:j[0]),f=(l==null?void 0:l.id)===s.agent_id,g=async _=>{_.stopPropagation();try{const S=await c.mutateAsync(s.id);ae.success(S.saved?"Listing saved!":"Listing removed from saved")}catch{ae.error("Failed to save listing")}},b=_=>{if(_.stopPropagation(),l)u(!0);else{const S=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(S),ae.success("Link copied to clipboard!")}};return e.jsxs(fe,{className:"overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group",onClick:t,children:[e.jsxs("div",{className:"relative aspect-[4/3] bg-muted",children:[p?e.jsx("img",{src:p.photo_url,alt:s.property_address||s.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(cy,{className:"h-12 w-12"})}),e.jsx(ze,{className:`absolute top-2 left-2 ${PZs[s.status]} text-white border-0`,children:LZs[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(ua,{className:"h-4 w-4 text-white fill-white"})}),e.jsxs("div",{className:"absolute bottom-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(B,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:g,children:e.jsx(yi,{className:`h-4 w-4 ${o?"fill-pink-500 text-pink-500":""}`})}),e.jsx(B,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:b,title:f?"Copy link":"Share & earn leads",children:f?e.jsx(Hl,{className:"h-4 w-4"}):e.jsx(un,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(x2t,{open:d,onOpenChange:u,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`}),e.jsxs(Ae,{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(ze,{variant:"outline",className:"text-xs",children:[e.jsx(_n,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),e.jsxs("div",{children:[s.property_address&&e.jsx("p",{className:"font-medium truncate",children:s.property_address}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),s.city,", ",s.state,s.neighborhood&&` • ${s.neighborhood}`]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ny,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Tp,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cy,{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(ze,{variant:"secondary",className:"text-xs",children:DZs[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(Ir,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hl,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yi,{className:"h-3 w-3"}),s.save_count]})]}),i&&(n||r||a)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a&&e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-violet-500/60 text-violet-600 hover:bg-violet-50",onClick:_=>{_.stopPropagation(),a()},children:[e.jsx(xL,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1",onClick:_=>{_.stopPropagation(),n()},children:[e.jsx(Tu,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx(B,{variant:"destructive",size:"sm",onClick:_=>{_.stopPropagation(),r()},children:e.jsx(bn,{className:"h-4 w-4"})})]})]})]})}const j8e="lu_listing_selection_v1",Yge=24,Zge=new Set;function g2t(){try{return JSON.parse(sessionStorage.getItem(j8e)||"{}")}catch{return{}}}function UNe(s){try{sessionStorage.setItem(j8e,JSON.stringify(s))}catch{}Zge.forEach(t=>t())}let b2=g2t();function OZs(){b2=g2t(),Zge.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===j8e&&OZs()});const iS={getSnapshot:()=>b2,subscribe(s){return Zge.add(s),()=>Zge.delete(s)},toggle(s){const t={...b2};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=Yge)return!1;t[s.mlsNumber]=s}return b2=t,UNe(t),!0},remove(s){const t={...b2};delete t[s],b2=t,UNe(t)},clear(){b2={},UNe({})},has(s){return!!b2[s]},all(){return Object.values(b2)}};function y2t(){const s=N.useSyncExternalStore(iS.subscribe,iS.getSnapshot,iS.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:iS.toggle,remove:iS.remove,clear:iS.clear}}const FZs=new Set(["office_exclusive","coming_soon","pre_market"]);function zZs(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=FZs.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 MG(s){const{has:t}=y2t(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(RZs,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),iS.toggle(zZs(s.listing))||ae.error(`You can select up to ${Yge} listings`)},title:r?"Remove from email":"Add to email",className:`absolute top-3 right-3 z-10 h-8 w-8 rounded-full flex items-center justify-center shadow-md border transition ${r?"bg-primary text-primary-foreground border-primary":"bg-white/95 text-foreground border-white hover:bg-white"}`,children:r?e.jsx(Lr,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"})})]})}function BZs({open:s,onOpenChange:t,listings:n}){const{user:r}=gs(),{leadSite:a}=Pp(),[i,l]=N.useState("grid"),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(new Set),[b,v]=N.useState(!1),[j,_]=N.useState(!1),{data:S}=M1e(),[A,T]=N.useState(!1);N.useEffect(()=>{!s||!(r!=null&&r.id)||q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle().then(({data:ee})=>_(!!(ee!=null&&ee.gmail_email)))},[s,r==null?void 0:r.id]),N.useEffect(()=>{if(s){if(!o){const ee=Array.from(new Set(n.map(oe=>oe.city).filter(Boolean))),ne=ee.length===1?` in ${ee[0]}`:"";c(n.length===1?`New listing for you${ne}`:`${n.length} hand-picked listings${ne}`)}d||u(`Hi {{first_name}}, Thought of you — I just picked a few properties I think you'll love. Take a look and let me know if anything catches your eye. Happy to set up a private showing whenever works.`)}},[s]);const{data:D=[],isLoading:L}=lt({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:ee}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, city").eq("owner_user_id",r.id).not("email","is",null).neq("email","").order("first_name");return ee||[]},enabled:!!(r!=null&&r.id)&&s}),{data:M}=lt({queryKey:["send-listings-suggestions",n.map(ee=>ee.mlsNumber).join(",")],queryFn:async()=>{const{data:ee,error:ne}=await q.functions.invoke("listing-email-suggestions",{body:{listings:n.map(oe=>({mlsNumber:oe.mlsNumber,city:oe.city,state:oe.state,price:oe.price,bedrooms:oe.bedrooms,bathrooms:oe.bathrooms}))}});if(ne)throw ne;return ee},enabled:s&&n.length>0}),F=(M==null?void 0:M.suggestions)||[],z=N.useMemo(()=>{const ee=h.trim().toLowerCase();return ee?D.filter(ne=>`${ne.first_name??""} ${ne.last_name??""} ${ne.email} ${ne.city??""}`.toLowerCase().includes(ee)):D},[D,h]),V=ee=>{g(ne=>{const oe=new Set(ne);return oe.has(ee)?oe.delete(ee):oe.add(ee),oe})},W=()=>{g(ee=>{const ne=new Set(ee);return F.forEach(oe=>ne.add(oe.contact_id)),ne})},K=n.length>0&&n.every(ee=>ee.mlsNumber.startsWith("lx-")),Y=async()=>{if(!K&&!(a!=null&&a.id)){ae.error("You need an active lead site to send listings.");return}if(!o.trim())return ae.error("Subject is required");if(f.size===0)return ae.error("Pick at least one recipient");if(!j&&S&&!S.hasVerifiedSes){T(!0);return}const ee=D.filter(ne=>f.has(ne.id)).map(ne=>({contact_id:ne.id,email:ne.email,first_name:ne.first_name,last_name:ne.last_name}));v(!0);try{const{data:ne,error:oe}=await q.functions.invoke("listing-email-send",{body:{lead_site_id:(a==null?void 0:a.id)||null,layout:i,subject:o.trim(),intro_message:d.trim()||null,listings:n.map(pe=>({mlsNumber:pe.mlsNumber,address:pe.address,city:pe.city,state:pe.state,zip:pe.zip,price:pe.price,bedrooms:pe.bedrooms,bathrooms:pe.bathrooms,sqft:pe.sqft,status:pe.status,photos:(pe.photos||[]).slice(0,1),description:pe.description||"",external_url:pe.externalUrl||null,is_private:pe.is_private===!0})),recipients:ee}});if(oe)throw oe;if(!(ne!=null&&ne.success))throw new Error((ne==null?void 0:ne.error)||"Send failed");ae.success(`Sent ${ne.sent}/${ee.length} via ${j?"Gmail":"Amazon SES"}${ne.failed?` · ${ne.failed} failed`:""}`),iS.clear(),g(new Set),t(!1)}catch(ne){ae.error((ne==null?void 0:ne.message)||"Failed to send")}finally{v(!1)}};return e.jsxs(bs,{open:s,onOpenChange:t,children:[e.jsxs(vs,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(ws,{className:"px-6 pt-6 pb-2",children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(Qn,{children:K?"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(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Selected listings"}),e.jsx("div",{className:"mt-2 flex gap-2 overflow-x-auto pb-1",children:n.map(ee=>{var ne;return e.jsxs("div",{className:"shrink-0 w-32 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("div",{className:"h-20 w-full bg-muted",children:((ne=ee.photos)==null?void 0:ne[0])&&e.jsx("img",{src:ee.photos[0],alt:"",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"p-1.5",children:[e.jsxs("div",{className:"text-[11px] font-semibold truncate",children:["$",(ee.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[ee.city,", ",ee.state]})]})]},ee.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(se,{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(vf,{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(nl,{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(se,{htmlFor:"subject",children:"Subject"}),e.jsx(ge,{id:"subject",value:o,onChange:ee=>c(ee.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"intro",children:"Personal message"}),e.jsx(Ts,{id:"intro",value:d,onChange:ee=>u(ee.target.value),placeholder:"Optional intro shown above the listings…",className:"mt-1 min-h-[120px]"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Use ",e.jsx("code",{className:"px-1 rounded bg-muted",children:"{{first_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 text-xs text-muted-foreground",children:["Sending via"," ",e.jsx("span",{className:"font-medium text-foreground",children:j?"your connected Gmail":"Amazon SES"}),". Every click tracks back to the contact and triggers a buyer signal."]})]}),e.jsxs("div",{className:"flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"px-6 pt-4 pb-2 space-y-3",children:[F.length>0&&e.jsxs(fe,{className:"p-3 bg-amber-50/50 border-amber-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"text-sm font-medium",children:[F.length," smart ",F.length===1?"match":"matches"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:W,children:"Add all"})]}),e.jsx(mi,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:F.slice(0,12).map(ee=>{const ne=f.has(ee.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(hi,{checked:ne,onCheckedChange:()=>V(ee.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[ee.first_name," ",ee.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",ee.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:ee.reason})]})]},ee.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",z.length,")"]}),f.size>0&&e.jsxs(ze,{variant:"secondary",children:[f.size," selected"]})]}),e.jsx(ge,{placeholder:"Search contacts…",value:h,onChange:ee=>p(ee.target.value)})]}),e.jsx("div",{className:"flex-1 overflow-hidden px-6 pb-2",children:e.jsx("div",{className:"border rounded-md h-full",children:e.jsx(mi,{className:"h-full",children:L?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):z.length===0?e.jsx("div",{className:"p-4 text-sm text-muted-foreground text-center",children:"No contacts found"}):e.jsx("div",{className:"divide-y",children:z.map(ee=>{const ne=f.has(ee.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(hi,{checked:ne,onCheckedChange:()=>V(ee.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[ee.first_name," ",ee.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[ee.email,ee.city&&e.jsxs(e.Fragment,{children:[" · ",ee.city]})]})]})]},ee.id)})})})})}),e.jsxs("div",{className:"px-6 py-2 text-xs text-muted-foreground border-t flex items-center justify-between",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:f.size})," recipients"]}),f.size>0&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>g(new Set),children:[e.jsx(Fn,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(Xn,{className:"px-6 py-4 border-t bg-muted/30",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsx(B,{onClick:Y,disabled:b||f.size===0,children:b?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send to ",f.size," ",f.size===1?"contact":"contacts"]})})]})]}),e.jsx(I1e,{open:A,onOpenChange:T,hasPending:!!(S!=null&&S.hasPendingSes),pendingEmails:S==null?void 0:S.pendingEmails})]})}function $Zs(){const{selected:s,count:t,remove:n,clear:r}=y2t(),[a,i]=N.useState(!1);return t===0?null:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 z-50 w-[min(96vw,820px)]",children:e.jsxs("div",{className:"rounded-2xl border bg-background/95 backdrop-blur shadow-2xl p-3 flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-primary/10 text-primary flex items-center justify-center font-semibold",children:t}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium leading-tight",children:[t," listing",t===1?"":"s"," selected"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t>=Yge?"Max reached":`Pick up to ${Yge}`})]})]}),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(Fn,{className:"h-4 w-4 text-white"})})]},l.mlsNumber)}),t>6&&e.jsxs("div",{className:"shrink-0 h-12 w-12 rounded-md border bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:["+",t-6]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(bn,{className:"h-4 w-4"})," Clear"]}),e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(cr,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(BZs,{open:a,onOpenChange:i,listings:s})]})}const UZs=[{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"}],qZs=[{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 VZs({filters:s,onFiltersChange:t,onClose:n}){const r=()=>{t({sortBy:"newest"})};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(Pt,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:r,children:"Clear All"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Fn,{className:"h-4 w-4"})})]})]}),e.jsxs(Ae,{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(se,{children:"Status"}),e.jsxs(us,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"All statuses"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),UZs.map(a=>e.jsx(Ze,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Type"}),e.jsxs(us,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"All types"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),qZs.map(a=>e.jsx(Ze,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Min Price"}),e.jsx(ge,{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(se,{children:"Max Price"}),e.jsx(ge,{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(se,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(vn,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function HZs({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(vo,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(X2,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(vc,{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(ze,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Ae,{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(Hl,{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(zr,{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(X2,{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(vo,{className:"h-6 w-6 text-amber-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Community MVP"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Top performer"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Community Leaderboard"})}),e.jsx(Ae,{children:e.jsxs($r,{defaultValue:"sharers",children:[e.jsxs(Ur,{className:"w-full",children:[e.jsxs(Zt,{value:"sharers",className:"flex-1",children:[e.jsx(Hl,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Zt,{value:"listers",className:"flex-1",children:[e.jsx(zr,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(ls,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(ls,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const nXe={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},rXe={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 GZs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function WZs({listings:s,isLoading:t}){const n=In(),r=N.useRef(null),a=N.useRef(null),i=N.useRef([]),{isAdmin:l}=gs(),[o,c]=N.useState(""),[d,u]=N.useState(!0),[h,p]=N.useState(!1),f=s.filter(b=>b.latitude!=null&&b.longitude!=null),g=s.filter(b=>(b.latitude==null||b.longitude==null)&&(b.property_address||b.city));return N.useEffect(()=>{(async()=>{u(!0);try{const{data:v}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();v!=null&&v.value&&c(v.value)}catch(v){console.error("Error fetching mapbox token:",v)}u(!1)})()},[]),N.useEffect(()=>{if(!o||g.length===0||h)return;(async()=>{var v;p(!0);for(const j of g){const _=[j.property_address,j.city,j.state].filter(Boolean).join(", ");if(_)try{const A=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(_)}.json?access_token=${o}&limit=1`)).json();if((v=A.features)!=null&&v[0]){const[T,D]=A.features[0].center;await q.from("listings").update({latitude:D,longitude:T}).eq("id",j.id),j.latitude=D,j.longitude=T}}catch(S){console.error("Geocode error:",S)}}p(!1)})()},[o,s]),N.useEffect(()=>{if(!r.current||!o||a.current)return;ml.accessToken=o;const b=s.filter(_=>_.latitude!=null&&_.longitude!=null);let v=[-98.5795,39.8283],j=4;if(b.length>0){const _=b.reduce((A,T)=>A+T.longitude,0)/b.length,S=b.reduce((A,T)=>A+T.latitude,0)/b.length;v=[_,S],j=b.length===1?12:10}return a.current=new ml.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:j,center:v}),a.current.addControl(new ml.NavigationControl,"top-right"),()=>{var _;(_=a.current)==null||_.remove(),a.current=null}},[o]),N.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(v=>v.remove()),i.current=[];const b=s.filter(v=>v.latitude!=null&&v.longitude!=null);if(b.forEach(v=>{var D,L,M;const j=nXe[v.status]||"#10B981",_=((D=v.photos)==null?void 0:D.find(F=>F.is_primary))||((L=v.photos)==null?void 0:L[0]),S=document.createElement("div");S.className="cursor-pointer",S.innerHTML=`
`;const A=new ml.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${_!=null&&_.photo_url?``:""}
${GZs(v.price)}
${v.property_address||""}
${v.city}, ${v.state}
${rXe[v.status]||v.status} ${v.bedrooms?`${v.bedrooms} bed`:""} ${v.bathrooms?`${v.bathrooms} bath`:""}
${(M=v.agent)!=null&&M.name?`
Listed by ${v.agent.name}
`:""}
Click to view details →
`),T=new ml.Marker(S).setLngLat([v.longitude,v.latitude]).setPopup(A).addTo(a.current);i.current.push(T)}),b.length>1){const v=new ml.LngLatBounds;b.forEach(j=>v.extend([j.longitude,j.latitude])),a.current.fitBounds(v,{padding:60,maxZoom:13})}else b.length===1&&a.current.flyTo({center:[b[0].longitude,b[0].latitude],zoom:12})},[s,o,h]),N.useEffect(()=>(window.__navigateToListing__=b=>{n(`/mission-control/listings/${b}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center h-[60vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Ca,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"No Listings Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add listings to see them on the map."})]})]})}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:[Object.entries(nXe).map(([b,v])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:v}}),e.jsx("span",{className:"text-xs",children:rXe[b]})]},b)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[f.length," of ",s.length," mapped",h&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Gi,{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 STe="homereel_mv_prefill",CTe="homereel_mv_badge_default";function v2t(s){try{sessionStorage.setItem(STe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(CTe,JSON.stringify(s.badge))}catch{}}function Mgn(){try{const s=sessionStorage.getItem(STe);return s?(sessionStorage.removeItem(STe),JSON.parse(s)):null}catch{return null}}function Ign(){try{const s=sessionStorage.getItem(CTe);return s?(sessionStorage.removeItem(CTe),JSON.parse(s)):null}catch{return null}}function b2t(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 KZs(){var F,z,V,W,K,Y,ee,ne;const s=In(),{brokerageId:t}=gs(),{data:n,isLoading:r}=cpt(),[a,i]=N.useState("feed"),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState({sortBy:"newest"}),{data:p,isLoading:f}=dpt({...u,city:c||u.city}),{data:g,isLoading:b}=zrs(),{data:v,isLoading:j}=upt(),{data:_,isLoading:S}=qrs(),{data:A,isLoading:T}=Grs(),{data:D}=Hrs(),L=hpt(),M=async oe=>{if(confirm("Are you sure you want to delete this listing? This action cannot be undone."))try{await L.mutateAsync(oe),ae.success("Listing deleted successfully")}catch{ae.error("Failed to delete listing")}};return r?e.jsx(Cs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):n?e.jsxs(Cs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(zr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(p==null?void 0:p.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(yi,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(g==null?void 0:g.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(NA,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(v==null?void 0:v.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(_n,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((F=_==null?void 0:_.sent)==null?void 0:F.length)||0)+(((z=_==null?void 0:_.received)==null?void 0:z.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs($r,{value:a,onValueChange:i,children:[e.jsxs(Ur,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Zt,{value:"feed",children:"Community Feed"}),t&&e.jsx(Zt,{value:"brokerage",children:"Brokerage"}),e.jsx(Zt,{value:"my-listings",children:"My Listings"}),e.jsx(Zt,{value:"saved",children:"Saved"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"map",children:"Map"}),e.jsx(Zt,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(ls,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by city or neighborhood...",value:c,onChange:oe=>d(oe.target.value),className:"pl-9"})]}),e.jsxs(us,{value:u.sortBy,onValueChange:oe=>h({...u,sortBy:oe}),children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"Sort by"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"newest",children:"Newest First"}),e.jsx(Ze,{value:"updated",children:"Recently Updated"}),e.jsx(Ze,{value:"price_asc",children:"Price: Low to High"}),e.jsx(Ze,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(Fv,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(VZs,{filters:u,onFiltersChange:h,onClose:()=>o(!1)}),f?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((oe,pe)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ae,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"}),e.jsx(Ws,{className:"h-4 w-1/4"})]})]},pe))}):(p==null?void 0:p.length)===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx(zr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to share a listing with the community!"}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:p==null?void 0:p.map(oe=>e.jsx(MG,{listing:oe,onClick:()=>s(`/mission-control/listings/${oe.id}`)},oe.id))})]}),e.jsx(ls,{value:"my-listings",className:"space-y-4",children:j?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((oe,pe)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ae,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"})]})]},pe))}):(v==null?void 0:v.length)===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx(NA,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Share your listings with the LevelUp community!"}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Your First Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v==null?void 0:v.map(oe=>e.jsx(MG,{listing:oe,showActions:!0,onClick:()=>s(`/mission-control/listings/${oe.id}`),onEdit:()=>s(`/mission-control/listings/${oe.id}/edit`),onDelete:()=>M(oe.id),onCreateMusicVideo:()=>{const pe=(oe.photos??[]).slice().sort((ce,de)=>(de.is_primary?1:0)-(ce.is_primary?1:0)||(ce.sort_order??0)-(de.sort_order??0)).map(ce=>ce.photo_url).filter(Boolean);if(pe.length===0){ae.error("Add photos to this listing first.");return}v2t({photos:pe,details:{address:oe.property_address||`${oe.city??""} ${oe.state??""}`.trim(),beds:oe.bedrooms?String(oe.bedrooms):"",baths:oe.bathrooms?String(oe.bathrooms):"",sqft:oe.square_footage?String(oe.square_footage):"",price:oe.price?String(oe.price):"",highlights:oe.description||""},sourceLabel:"My Listings",badge:b2t(oe.status,oe.price)}),s("/admin/beta/homereel?tab=music-video")}},oe.id))})}),e.jsx(ls,{value:"saved",className:"space-y-4",children:b?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((oe,pe)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ae,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"})]})]},pe))}):(g==null?void 0:g.length)===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx(yi,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:g==null?void 0:g.map(oe=>e.jsx(MG,{listing:oe.listing,onClick:()=>s(`/mission-control/listings/${oe.listing.id}`)},oe.id))})}),e.jsx(ls,{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(Hl,{className:"h-4 w-4"}),"Referrals Sent (",((V=_==null?void 0:_.sent)==null?void 0:V.length)||0,")"]}),((W=_==null?void 0:_.sent)==null?void 0:W.length)===0?e.jsx(fe,{children:e.jsx(Ae,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(K=_==null?void 0:_.sent)==null?void 0:K.map(oe=>{var pe,ce;return e.jsx(fe,{children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:oe.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((pe=oe.listing)==null?void 0:pe.property_address)||((ce=oe.listing)==null?void 0:ce.city)})]}),e.jsx(ze,{variant:oe.status==="closed"?"default":"secondary",children:oe.status.replace("_"," ")})]})})},oe.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(_n,{className:"h-4 w-4"}),"Referrals Received (",((Y=_==null?void 0:_.received)==null?void 0:Y.length)||0,")"]}),((ee=_==null?void 0:_.received)==null?void 0:ee.length)===0?e.jsx(fe,{children:e.jsx(Ae,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(ne=_==null?void 0:_.received)==null?void 0:ne.map(oe=>{var pe;return e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:oe.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(pe=oe.sender)==null?void 0:pe.name]})]}),e.jsx(ze,{variant:oe.status==="closed"?"default":"secondary",children:oe.status.replace("_"," ")})]}),e.jsx(B,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${oe.listing_id}`),children:"View Listing"})]})},oe.id)})})]})]})}),t&&e.jsx(ls,{value:"brokerage",className:"space-y-4",children:T?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((oe,pe)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ae,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"})]})]},pe))}):(A==null?void 0:A.length)===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx(NA,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No brokerage listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No agents in your brokerage have added listings yet."}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add a Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:A==null?void 0:A.map(oe=>e.jsx(MG,{listing:oe,onClick:()=>s(`/mission-control/listings/${oe.id}`)},oe.id))})}),e.jsx(ls,{value:"map",children:e.jsx(WZs,{listings:p||[],isLoading:f})}),e.jsx(ls,{value:"leaderboard",children:e.jsx(HZs,{leaderboard:D})})]})]}),e.jsx($Zs,{})]}):e.jsx(Cs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx(zr,{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 _2t(s){return lt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:n}=await q.from("listing_documents").select("*").eq("listing_id",s).order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function YZs(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async({listingId:n,file:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s.id}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await q.storage.from("listing-documents").upload(i,r,{contentType:r.type||void 0});if(l)throw l;const{data:o,error:c}=await q.from("listing_documents").insert({listing_id:n,owner_user_id:s.id,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["listing-documents",r.listingId]})}})}function ZZs(){const s=Gt();return gt({mutationFn:async({id:t,storage_path:n,listingId:r})=>{await q.storage.from("listing-documents").remove([n]);const{error:a}=await q.from("listing_documents").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function QZs(){const s=Gt();return gt({mutationFn:async({id:t,visible:n,listingId:r})=>{const{error:a}=await q.from("listing_documents").update({visible_on_exchange:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}async function w2t(s){const{data:t,error:n}=await q.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const XZs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function JZs({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=_2t(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 w2t(i);window.open(l,"_blank")}catch{ae.error("Failed to open document")}};return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Nr,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(Ae,{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(Nr,{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:XZs(i.file_size)})]}),e.jsx(Da,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}const eQs=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)}`},aXe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),y3="#D4AF37",iXe="#0F172A",oXe=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}),lXe=(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)},I7=(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()}…`},tQs=(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},nQs=s=>s instanceof DOMException||s instanceof Error?s.name:null;function j2t({listingId:s,open:t,onOpenChange:n}){var T,D;const{data:r}=N6e(s||""),[a,i]=N.useState(null),[l,o]=N.useState(!1),[c,d]=N.useState(null),[u,h]=N.useState(null),p=((r==null?void 0:r.photos)||[]).slice().sort((L,M)=>L.is_primary&&!M.is_primary?-1:!L.is_primary&&M.is_primary?1:(L.sort_order??0)-(M.sort_order??0));N.useEffect(()=>{var M;if(!t)return;const L=((M=p[0])==null?void 0:M.photo_url)||null;h(F=>F||L)},[t,r==null?void 0:r.id,p.length]),N.useEffect(()=>{let L=!1;if(!(!t||!(r!=null&&r.agent_id)))return(async()=>{var V,W,K,Y;const{data:M}=await q.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",r.agent_id).maybeSingle();if(L)return;const F=M,z=((V=F==null?void 0:F.brokerage)==null?void 0:V.name)||((K=(W=r.agent)==null?void 0:W.brokerage)==null?void 0:K.name)||null;i({name:(F==null?void 0:F.name)||((Y=r.agent)==null?void 0:Y.name)||"Agent",phone:(F==null?void 0:F.phone)||(F==null?void 0:F.phone_e164)||null,avatar_url:(F==null?void 0:F.avatar_url)||null,brokerage:z})})(),()=>{L=!0}},[t,r==null?void 0:r.agent_id]),N.useEffect(()=>{if(!t){d(null),h(null);return}if(!r||!a)return;const L=setTimeout(()=>{f()},350);return()=>clearTimeout(L)},[t,r==null?void 0:r.id,a==null?void 0:a.name,u]);const f=async()=>{if(!(!r||!a)){o(!0);try{const L=document.createElement("canvas");L.width=1080,L.height=1080;const M=L.getContext("2d");if(!M)throw new Error("Canvas unavailable");if(M.fillStyle=iXe,M.fillRect(0,0,1080,1080),_){const Y=await oXe(_);lXe(M,Y,0,0,1080,1080)}const F=M.createLinearGradient(0,0,0,1080);F.addColorStop(0,"rgba(15,23,42,0.58)"),F.addColorStop(.34,"rgba(15,23,42,0.16)"),F.addColorStop(.62,"rgba(15,23,42,0.48)"),F.addColorStop(1,"rgba(15,23,42,0.98)"),M.fillStyle=F,M.fillRect(0,0,1080,1080),M.fillStyle=y3,M.fillRect(56,62,72,2),M.font="600 22px Arial, sans-serif",sQs(M,"JUST LISTED",146,72,8),M.save(),M.shadowColor="rgba(0,0,0,0.55)",M.shadowBlur=24,M.shadowOffsetY=4,M.fillStyle="#F8FAFC",M.font="600 64px Georgia, serif",M.textBaseline="top";const z=tQs(M,r.property_address||`${r.city||""}, ${r.state||""}`.trim(),952,2);let V=z.length>1?590:654;z.forEach(Y=>{M.fillText(Y,64,V),V+=70}),M.restore();const W=[r.city,r.state].filter(Boolean).join(", ")+(r.neighborhood?` · ${r.neighborhood}`:"");M.fillStyle="rgba(248,250,252,0.9)",M.font="600 26px Arial, sans-serif",M.fillText(I7(M,W.toUpperCase(),952),64,V+8),M.fillStyle=y3,M.font="700 56px Arial, sans-serif",M.fillText(aXe(r.price),64,V+58),A.length>0&&(M.fillStyle="rgba(248,250,252,0.86)",M.font="600 22px Arial, sans-serif",M.fillText(I7(M,A.join(" · "),430),360,V+78));const K=M.createLinearGradient(0,880,0,1080);if(K.addColorStop(0,"rgba(15,23,42,0.96)"),K.addColorStop(1,"#0B1322"),M.fillStyle=K,M.fillRect(0,880,1080,200),M.fillStyle=y3,M.fillRect(0,880,1080,2),M.save(),M.beginPath(),M.arc(124,980,60,0,Math.PI*2),M.closePath(),M.fillStyle="#1E293B",M.fill(),M.lineWidth=6,M.strokeStyle=y3,M.stroke(),M.clip(),a.avatar_url)try{const Y=await oXe(a.avatar_url);lXe(M,Y,64,920,120,120)}catch{M.fillStyle=y3,M.font="700 48px Arial, sans-serif",M.textAlign="center",M.textBaseline="middle",M.fillText(a.name.charAt(0).toUpperCase(),124,982)}else M.fillStyle=y3,M.font="700 48px Arial, sans-serif",M.textAlign="center",M.textBaseline="middle",M.fillText(a.name.charAt(0).toUpperCase(),124,982);M.restore(),M.textAlign="left",M.textBaseline="alphabetic",M.fillStyle="#F8FAFC",M.font="600 38px Georgia, serif",M.fillText(I7(M,a.name,S?430:820),212,970),a.brokerage&&(M.fillStyle=y3,M.font="600 20px Arial, sans-serif",M.fillText(I7(M,a.brokerage.toUpperCase(),S?430:820),212,1008)),S&&(M.textAlign="right",M.fillStyle="rgba(212,175,55,0.86)",M.font="600 16px Arial, sans-serif",M.fillText("CALL · TEXT",1016,958),M.fillStyle="#F8FAFC",M.font="600 38px Arial, sans-serif",M.fillText(S,1016,1008)),d(L.toDataURL("image/png"))}catch(L){console.error("Generate graphic error",L),ae.error("Could not generate graphic")}finally{o(!1)}}},g=async L=>(await fetch(L)).blob(),b=async()=>{if(!c)return;const L=document.createElement("a");L.href=c,L.download=`just-listed-${(r==null?void 0:r.slug)||(r==null?void 0:r.id)||"graphic"}.png`,L.click(),ae.success("Downloaded!")},v=async()=>{if(c)try{const L=await g(c);await navigator.clipboard.write([new ClipboardItem({"image/png":L})]),ae.success("Copied to clipboard")}catch{ae.error("Copy not supported in this browser")}},j=async()=>{if(c)try{const L=await g(c),M=new File([L],"just-listed.png",{type:"image/png"});navigator.canShare&&navigator.canShare({files:[M]})?await navigator.share({files:[M],title:"Just Listed"}):b()}catch(L){nQs(L)!=="AbortError"&&ae.error("Share failed")}},_=u||((T=p[0])==null?void 0:T.photo_url)||null,S=eQs(a==null?void 0:a.phone),A=[r!=null&&r.bedrooms?`${r.bedrooms} BD`:null,r!=null&&r.bathrooms?`${r.bathrooms} BA`:null,r!=null&&r.square_footage?`${r.square_footage.toLocaleString()} SF`:null].filter(Boolean);return e.jsx(bs,{open:t,onOpenChange:n,children:e.jsx(vs,{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(ws,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(_s,{className:"flex items-center gap-2 pr-8",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(Qn,{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:iXe},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?aXe(r.price):""}),A.length>0&&e.jsx("span",{className:"truncate text-[8px] font-semibold uppercase tracking-[0.14em] text-white/80",children:A.join(" · ")})]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 flex h-[52px] items-center border-t border-amber-400 bg-slate-950/95 px-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-amber-400 bg-slate-800 text-xs font-bold text-amber-300",children:a!=null&&a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:"",className:"h-full w-full object-cover"}):(D=a==null?void 0:a.name)==null?void 0:D.charAt(0).toUpperCase()}),e.jsxs("div",{className:"ml-2 min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-serif text-xs font-semibold text-white",children:a==null?void 0:a.name}),(a==null?void 0:a.brokerage)&&e.jsx("div",{className:"truncate text-[7px] font-semibold uppercase tracking-[0.18em] text-amber-300",children:a.brokerage})]}),S&&e.jsx("div",{className:"ml-2 shrink-0 text-[9px] font-semibold text-white",children:S})]}),l&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-slate-950/80 text-white/85",children:[e.jsx(ss,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Crafting your graphic…"})]})]}),p.length>1&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose photo"}),e.jsx("div",{className:"flex gap-2 pb-2",style:{overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch"},children:p.map(L=>{const M=u===L.photo_url;return e.jsx("button",{type:"button",onClick:()=>h(L.photo_url),className:`relative shrink-0 h-14 w-14 rounded-md overflow-hidden border-2 transition ${M?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:L.photo_url,alt:"",className:"w-full h-full object-cover"})},L.id)})})]})]}),e.jsxs("div",{className:"px-5 pb-5 pt-2 shrink-0 border-t bg-background flex flex-wrap justify-end gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>void f(),disabled:l||!r||!a,children:"Regenerate"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:v,disabled:!c,className:"gap-1.5",children:[e.jsx(ta,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:j,disabled:!c,className:"gap-1.5",children:[e.jsx(Hl,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs(B,{size:"sm",onClick:b,disabled:!c,className:"gap-1.5",children:[e.jsx(Da,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function rQs(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const aQs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function iQs({open:s,onOpenChange:t,listing:n}){const{user:r}=gs(),{data:a=[],isLoading:i}=lx(),{data:l=[]}=Cy(),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,p]=N.useState(new Set),[f,g]=N.useState(!1),[b,v]=N.useState(null);N.useEffect(()=>{s||(c(""),u("all"),p(new Set),g(!1))},[s]),N.useEffect(()=>{!s||!r||(async()=>{const{data:M}=await q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();v((M==null?void 0:M.gmail_email)||null)})()},[s,r]);const j=N.useMemo(()=>a.filter(M=>M.email),[a]),_=N.useMemo(()=>{let M=j;if(d!=="all"&&(M=M.filter(F=>{var z;return(z=F.tags)==null?void 0:z.some(V=>V.relationship_type_id===d)})),o.trim()){const F=o.toLowerCase();M=M.filter(z=>`${z.first_name||""} ${z.last_name||""}`.toLowerCase().includes(F)||(z.email||"").toLowerCase().includes(F))}return M},[j,o,d]),S=()=>{h.size===_.length?p(new Set):p(new Set(_.map(M=>M.id)))},A=M=>{const F=new Set(h);F.has(M)?F.delete(M):F.add(M),p(F)},T=N.useMemo(()=>j.filter(M=>h.has(M.id)).map(M=>({id:M.id,first_name:M.first_name||"there",last_name:M.last_name,email:M.email})),[j,h]),{defaultSubject:D,defaultBody:L}=N.useMemo(()=>{var ie,ye,_e,Me;const M=n.property_address||`${n.city}, ${n.state}`,F=rQs(n.price),z=aQs[n.property_type]||"home",V=n.bedrooms?`${n.bedrooms} bed`:"",W=n.bathrooms?`${n.bathrooms} bath`:"",K=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",Y=[V,W,K].filter(Boolean).join(" • "),ee=`https://listings.relevelup.com/${n.slug||n.id}`,ne=((ye=(ie=n.photos)==null?void 0:ie.find(Te=>Te.is_primary))==null?void 0:ye.photo_url)||((Me=(_e=n.photos)==null?void 0:_e[0])==null?void 0:Me.photo_url)||"",pe={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[n.status]||"New Listing",ce=`${pe}: ${M} — ${F}`,de=`

Hi {{first_name}},

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

${ne?` ${M} `:""}
${pe}

${F}

${M}

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

${Y?`

${Y} • ${z}

`:""} View Photos & Details →

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

Talk soon,

`;return{defaultSubject:ce,defaultBody:de}},[n]);return f?e.jsx(Ty,{open:f,onOpenChange:M=>{g(M),M||t(!1)},bulkContacts:T,defaultSubject:D,defaultBody:L,gmailEmail:b}):e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Qn,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search contacts...",value:o,onChange:M=>c(M.target.value),className:"pl-9"})]}),e.jsxs(us,{value:d,onValueChange:u,children:[e.jsx(cs,{className:"sm:w-[180px]",children:e.jsx(hs,{placeholder:"Filter by tag"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All contacts"}),l.map(M=>e.jsx(Ze,{value:M.id,children:M.name},M.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm border-y py-2",children:[e.jsxs("button",{type:"button",onClick:S,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(hi,{checked:_.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(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(_n,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(mi,{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(ss,{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:j.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:_.map(M=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(hi,{checked:h.has(M.id),onCheckedChange:()=>A(M.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[M.first_name," ",M.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:M.email})]}),M.tags&&M.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:M.tags.slice(0,2).map(F=>{var z;return e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(z=F.relationship_type)==null?void 0:z.name},F.id)})})]},M.id))})}),e.jsx(cl,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:b?`Sending from ${b}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>g(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(Hs,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}function Ev(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 ZU(){const s=fa();return lt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function N2t(){const s=fa(),t=Gt();return gt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:n}=await q.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function cbe(){const s=fa();return lt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function k2t(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_pipeline").insert({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||null,contact_id:n.contact_id||null,listing_id:n.listing_id||null,property_address:n.property_address||null,city:n.city||null,state:n.state||null,zip_code:n.zip_code||null,expected_price:n.expected_price||null,expected_commission:n.expected_commission||null,commission_percentage:n.commission_percentage||3,target_close_date:n.target_close_date||null,contract_date:n.contract_date||null,listing_date:n.listing_date||null,priority:n.priority||"medium",probability:n.probability||50,notes:n.notes||null,owner_user_id:s}).select().single();if(a)throw a;return await q.from("deal_activities").insert([{deal_id:r.id,activity_type:"system",title:"Deal created",description:`Deal "${n.deal_name}" was created`}]),r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function S2t(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function oQs(){const s=Gt();return gt({mutationFn:async({dealId:t,stageId:n,stageName:r})=>{const{data:a,error:i}=await q.from("deal_pipeline").update({stage_id:n}).eq("id",t).select().single();if(i)throw i;return await q.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${r}`,metadata:{new_stage_id:n,new_stage_name:r}}),a},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function lQs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("deal_pipeline").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function cQs(s){return lt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function dQs(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-activities",n.deal_id]})}})}function uQs(s){return lt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function hQs(){const s=Gt();return gt({mutationFn:async({id:t,is_completed:n,deal_id:r})=>{const{data:a,error:i}=await q.from("deal_checklist_items").update({is_completed:n,completed_at:n?new Date().toISOString():null}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function mQs(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("deal_checklist_items").insert([{deal_id:t.deal_id,title:t.title,description:t.description||null,due_date:t.due_date||null,sort_order:t.sort_order||0}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function pQs(){const s=fa();return lt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(n)throw n;const r=(t==null?void 0:t.filter(o=>{var c,d,u;return!((c=o.deal_pipeline_stages)!=null&&c.is_won_stage)&&!((d=o.deal_pipeline_stages)!=null&&d.is_lost_stage)&&((u=o.deal_pipeline_stages)==null?void 0:u.name)!=="Cancelled"}))||[],a=(t==null?void 0:t.filter(o=>{var c;return(c=o.deal_pipeline_stages)==null?void 0:c.is_won_stage}))||[],i=new Date().getFullYear(),l=a.filter(o=>{const c=o.actual_close_date;return c?new Date(c).getFullYear()===i:!0});return{totalDeals:(t==null?void 0:t.length)||0,activeDeals:r.length,wonDeals:a.length,pipelineValue:r.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:r.reduce((o,c)=>o+(c.expected_commission||0),0),expectedNetToAgent:r.reduce((o,c)=>o+(Ev(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+(Ev(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0),0),ytdWonNet:l.reduce((o,c)=>o+(Ev(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(Ev(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Ev(c)||0)*d},0)}},enabled:!!s})}function fQs(s){const t=fa();return lt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:n,error:r}=await q.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("listing_id",s).maybeSingle();if(r)throw r;return n},enabled:!!t&&!!s})}function xQs(){const s=Gt();return gt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update({listing_id:n}).eq("id",t).select().single();if(a)throw a;return await q.from("deal_activities").insert({deal_id:t,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:n}}),r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",n.listingId]})}})}function gQs(){const s=Gt();return gt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update({listing_id:null}).eq("id",t).select().single();if(a)throw a;return{data:r,listingId:n}},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",t.listingId]})}})}function yQs({listing:s}){const t=In(),[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l,isLoading:o}=fQs(s.id),{data:c,isLoading:d}=ZU(),{data:u,isLoading:h}=cbe(),p=N2t(),f=xQs(),g=gQs(),b=k2t(),v=(u==null?void 0:u.filter(T=>!T.listing_id))||[],j=T=>{if(!(c!=null&&c.length))return null;switch(T){case"coming_soon":case"active":case"price_improvement":return c.find(D=>D.name==="Active");case"under_contract":return c.find(D=>D.name==="Under Contract");case"sold":return c.find(D=>D.is_won_stage);default:return c.find(D=>D.name==="Active")}},_=async()=>{i(!0);try{c!=null&&c.length||await p.mutateAsync();const T=j(s.status);await b.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(T==null?void 0:T.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(T){console.error("Failed to create deal:",T),ae.error("Failed to create deal")}finally{i(!1)}},S=async()=>{if(!n){ae.error("Please select a deal");return}try{await f.mutateAsync({dealId:n,listingId:s.id}),ae.success("Listing linked to deal!"),r("")}catch{ae.error("Failed to link listing")}},A=async()=>{if(l)try{await 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(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Q2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ss,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(fe,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"flex items-center gap-2 text-base",children:[e.jsx(El,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Ae,{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(ze,{variant:"secondary",className:"text-xs",style:{backgroundColor:`${l.deal_pipeline_stages.color}20`,color:l.deal_pipeline_stages.color},children:l.deal_pipeline_stages.name})})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes sync automatically between the listing and pipeline."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(za,{className:"h-3 w-3 ml-1"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:A,disabled:g.isPending,children:g.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(VA,{className:"h-4 w-4"})})]})]})]}):e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Pt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Q2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link this listing to your pipeline to track the deal and sync status changes."}),e.jsxs(B,{onClick:_,disabled:a||b.isPending,className:"w-full",size:"sm",children:[a||b.isPending?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(As,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(cs,{className:"flex-1 text-sm",children:e.jsx(hs,{placeholder:"Link to existing deal..."})}),e.jsx(ds,{children:v.map(T=>e.jsx(Ze,{value:T.id,children:T.deal_name},T.id))})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:S,disabled:!n||f.isPending,children:f.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(El,{className:"h-4 w-4"})})]})]})]})]})}const vQs={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"},bQs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},cXe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function _Qs(){var oe,pe,ce,de,ie,ye,_e,Me,Te;const{listingId:s}=_i(),t=In(),{user:n}=gs(),{data:r,isLoading:a}=N6e(s||""),{data:i}=ppt(s||""),{data:l}=$rs(s||""),o=mpt(),c=Brs(),d=Urs(),u=hpt(),h=Vrs(),[p,f]=N.useState(!1),[g,b]=N.useState(!1),[v,j]=N.useState(!1),[_,S]=N.useState(!1),[A,T]=N.useState(!1),[D,L]=N.useState(null),[M,F]=N.useState({buyerName:"",buyerType:"",notes:""}),z=(n==null?void 0:n.id)===(r==null?void 0:r.agent_id),V=Ce=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ce),W=async Ce=>{const Ee=`https://listings.relevelup.com/${(r==null?void 0:r.slug)||(r==null?void 0:r.id)}`,De=`Check out this listing: ${(r==null?void 0:r.property_address)||(r==null?void 0:r.city)}`;d.mutate({listingId:r.id,shareType:Ce});try{switch(Ce){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Ee)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Ee),ae.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${De} ${Ee}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(De)}&body=${encodeURIComponent(`Check out this listing: ${Ee}`)}`);break}}catch(Ie){console.error("Share error:",Ie),ae.error("Failed to share")}},K=async()=>{try{await u.mutateAsync(r.id),ae.success("Listing deleted"),t("/mission-control/listings")}catch{ae.error("Failed to delete listing")}},Y=async()=>{if(!M.buyerName.trim()){ae.error("Please enter buyer name");return}try{await h.mutateAsync({listingId:r.id,listingAgentId:r.agent_id,buyerName:M.buyerName,buyerType:M.buyerType||void 0,notes:M.notes||void 0}),ae.success("Referral sent successfully!"),b(!1),F({buyerName:"",buyerType:"",notes:""})}catch{ae.error("Failed to send referral")}},ee=Ce=>{var Je,we;const Ee=(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`,De=V((r==null?void 0:r.price)||0),Ie=r!=null&&r.bedrooms?`${r.bedrooms}BD`:"",Fe=r!=null&&r.bathrooms?`${r.bathrooms}BA`:"",qe=r!=null&&r.square_footage?`${r.square_footage.toLocaleString()}SF`:"",ve=[Ie,Fe,qe].filter(Boolean).join(" | ");switch(Ce){case"just_listed":return`🏡 JUST LISTED! ${Ee} ${De} ${ve} ${(r==null?void 0:r.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Je=r==null?void 0:r.city)==null?void 0:Je.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Ee} Now ${De}! ${ve} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${cXe[(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! ${ve} DM me for details! 📩 #ComingSoon #RealEstate #${(we=r==null?void 0:r.city)==null?void 0:we.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(Cs,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-10 w-32"}),e.jsx(Ws,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(Ws,{className:"h-48"}),e.jsx(Ws,{className:"h-48"}),e.jsx(Ws,{className:"h-48"})]})]})});if(!r)return e.jsx(Cs,{title:"Listing Not Found",description:"",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx(B,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const ne=((oe=r.photos)==null?void 0:oe.find(Ce=>Ce.is_primary))||((pe=r.photos)==null?void 0:pe[0]);return e.jsxs(Cs,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>ne&&L(ne.photo_url),children:ne?e.jsx("img",{src:ne.photo_url,alt:"Primary",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No photos"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:(ce=r.photos)==null?void 0:ce.slice(1,5).map((Ce,Ee)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>L(Ce.photo_url),children:e.jsx("img",{src:Ce.photo_url,alt:`Photo ${Ee+2}`,className:"w-full h-full object-cover"})},Ce.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ae,{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(ze,{className:`${vQs[r.status]} text-white border-0`,children:bQs[r.status]}),r.is_featured&&e.jsxs(ze,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(ua,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),r.open_to_referrals&&e.jsxs(ze,{variant:"outline",children:[e.jsx(_n,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:V(r.price)}),r.property_address&&e.jsx("p",{className:"text-xl font-medium",children:r.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(Ca,{className:"h-4 w-4"}),r.city,", ",r.state,r.neighborhood&&` • ${r.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>o.mutate(r.id),children:e.jsx(yi,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>c.mutate(r.id),children:l?e.jsx(fw,{className:"h-4 w-4"}):e.jsx(lm,{className:"h-4 w-4"})}),!z&&e.jsxs(B,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>j(!0),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(Hl,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(cc,{children:[e.jsxs(Xr,{onClick:()=>W("copy"),children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(Xr,{onClick:()=>W("facebook"),children:[e.jsx(Oh,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(Xr,{onClick:()=>W("text"),children:[e.jsx(Ci,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(Xr,{onClick:()=>W("email"),children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>{const Ce=(r.photos??[]).slice().sort((Ee,De)=>(De.is_primary?1:0)-(Ee.is_primary?1:0)||(Ee.sort_order??0)-(De.sort_order??0)).map(Ee=>Ee.photo_url).filter(Boolean);if(Ce.length===0){ae.error("Add photos to this listing first.");return}v2t({photos:Ce,details:{address:r.property_address||`${r.city??""} ${r.state??""}`.trim(),beds:r.bedrooms?String(r.bedrooms):"",baths:r.bathrooms?String(r.bathrooms):"",sqft:r.square_footage?String(r.square_footage):"",price:r.price?String(r.price):"",highlights:r.description||""},sourceLabel:"Listing Exchange",badge:b2t(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(xL,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>T(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(un,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs(B,{variant:"outline",onClick:()=>S(!0),className:"gap-2",children:[e.jsx(Hs,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs(B,{onClick:()=>t(`/mission-control/listings/${r.id}/customize`),className:"gap-2 bg-gradient-to-r from-primary to-primary/80 hover:opacity-95 text-primary-foreground shadow-md",children:[e.jsx(un,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/listings/${r.id}/edit`),children:[e.jsx(Tu,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>f(!0),children:e.jsx(bn,{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(ny,{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(Tp,{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(cy,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),r.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(yr,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.year_built}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"pt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(ze,{variant:"secondary",children:[e.jsx(Ga,{className:"h-3 w-3 mr-1"}),cXe[r.property_type]]}),r.lot_size&&e.jsxs(ze,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(ze,{variant:"secondary",children:"HOA"})]}),r.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})]}),r.agent_notes&&r.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.agent_notes})]}),r.mls_link&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-4 mt-4 border-t text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ir,{className:"h-4 w-4"}),r.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hl,{className:"h-4 w-4"}),r.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yi,{className:"h-4 w-4"}),r.save_count," saves"]})]})]})}),r.allow_sharing&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"Share Content"})}),e.jsx(Ae,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Ce=>e.jsxs("div",{className:"p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("p",{className:"font-medium text-sm capitalize",children:[Ce.replace("_"," ")," Caption"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(ee(Ce)),ae.success("Caption copied!")},children:e.jsx(ta,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:ee(Ce)})]},Ce))})]}),e.jsx(JZs,{listingId:r.id,ownerOnly:z})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Ae,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-lg font-semibold text-primary",children:((ie=(de=r.agent)==null?void 0:de.name)==null?void 0:ie.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((ye=r.agent)==null?void 0:ye.name)||"Unknown"}),((Me=(_e=r.agent)==null?void 0:_e.brokerage)==null?void 0:Me.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),!z&&e.jsx("div",{className:"space-y-2",children:((Te=r.agent)==null?void 0:Te.email)&&e.jsx(B,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${r.agent.email}`,children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),z&&e.jsx(yQs,{listing:r}),!z&&r.open_to_referrals&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Ae,{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Have a buyer interested in this property? Send a referral to the listing agent."}),e.jsx(B,{className:"w-full",onClick:()=>b(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(bs,{open:!!D,onOpenChange:()=>L(null),children:e.jsx(vs,{className:"max-w-4xl",children:e.jsx("img",{src:D||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(bs,{open:p,onOpenChange:f,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete Listing"}),e.jsx(Qn,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:K,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(bs,{open:g,onOpenChange:b,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Send Buyer Referral"}),e.jsx(Qn,{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(se,{children:"Buyer Name *"}),e.jsx(ge,{value:M.buyerName,onChange:Ce=>F({...M,buyerName:Ce.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Buyer Type"}),e.jsxs(us,{value:M.buyerType,onValueChange:Ce=>F({...M,buyerType:Ce}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select type"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"first_time",children:"First-Time Buyer"}),e.jsx(Ze,{value:"investor",children:"Investor"}),e.jsx(Ze,{value:"relocating",children:"Relocating"}),e.jsx(Ze,{value:"upgrade",children:"Upgrading"}),e.jsx(Ze,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes"}),e.jsx(Ts,{value:M.notes,onChange:Ce=>F({...M,notes:Ce.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(B,{onClick:Y,disabled:h.isPending,children:h.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(x2t,{open:v,onOpenChange:j,listingId:(r==null?void 0:r.id)||"",listingSlug:(r==null?void 0:r.slug)||null,listingTitle:(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`}),r&&e.jsx(iQs,{open:_,onOpenChange:S,listing:r}),e.jsx(j2t,{listingId:(r==null?void 0:r.id)||null,open:A,onOpenChange:T})]})}function wQs({onImport:s}){const[t,n]=N.useState(""),[r,a]=N.useState([]),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),h=N.useRef(),p=N.useRef(null);N.useEffect(()=>{const _=S=>{p.current&&!p.current.contains(S.target)&&c(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);const f=async _=>{if(_.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:S,error:A}=await q.functions.invoke("mls-listing-search",{body:{query:_}});if(A)throw A;a((S==null?void 0:S.listings)||[]),c(!0)}catch(S){console.error("MLS search error:",S),a([])}finally{l(!1)}},g=_=>{n(_),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>f(_),400)},b=_=>{u(_.mlsNumber),s(_),c(!1),n(`${_.address}, ${_.city}`),ae.success(`Imported: ${_.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},v=_=>_?`$${_.toLocaleString()}`:"",j=_=>{const S=(_||"").toLowerCase();return S.includes("single")||S.includes("detached")?"Single Family":S.includes("condo")?"Condo":S.includes("town")?"Townhouse":S.includes("land")||S.includes("lot")?"Land":S.includes("multi")?"Multi-Family":S.includes("commercial")?"Commercial":_||"Other"};return e.jsxs(fe,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(Da,{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(Ae,{children:e.jsxs("div",{ref:p,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{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(ss,{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(Fn,{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:()=>b(_),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(Ca,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:_.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:v(_.price)}),_.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(ny,{className:"h-3 w-3"})," ",_.bedrooms]}),_.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Tp,{className:"h-3 w-3"})," ",_.bathrooms]}),_.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(eN,{className:"h-3 w-3"})," ",_.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(ze,{variant:"outline",className:"text-[10px]",children:j(_.propertyType)}),_.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[_.photos.length," photos"]})]})]},_.mlsNumber))})]})})]})}function jQs({photo:s,onRemove:t,onSetPrimary:n}){const{attributes:r,listeners:a,setNodeRef:i,transform:l,transition:o,isDragging:c}=Fve({id:s.id}),d={transform:F4.Transform.toString(l),transition:o};return e.jsxs("div",{ref:i,style:d,className:Et("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(Uu,{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(Fn,{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(ua,{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 NQs({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){const l=Eve(z8(oR,{activationConstraint:{distance:5}})),o=[...s].sort((d,u)=>(d.sort_order??0)-(u.sort_order??0)),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const p=o.findIndex(j=>j.id===u.id),f=o.findIndex(j=>j.id===h.id),g=[...o],[b]=g.splice(p,1);g.splice(f,0,b);const v=g.map((j,_)=>({...j,sort_order:_}));a(v)};return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag photos to reorder. Hover to set primary."}),e.jsx(Dve,{sensors:l,collisionDetection:Ave,onDragEnd:c,children:e.jsx(Ove,{items:o.map(d=>d.id),strategy:IU,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(d=>e.jsx(jQs,{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(ss,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{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 kQs({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=In(),{user:a}=gs(),[i,l]=N.useState(!1),[o,c]=N.useState([]),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,g]=N.useState({});N.useEffect(()=>{s&&a?b():p(null)},[s,a]);const b=async()=>{if(!s)return;const{data:F,error:z}=await q.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!z&&F&&(p(F),v(F))},v=async F=>{try{const{data:z,error:V}=await q.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:F.bunny_video_id,isAgentVideo:!0}});!V&&(z!=null&&z.thumbnailUrl)&&g(W=>({...W,[F.id]:{thumbnailUrl:z.thumbnailUrl}}))}catch(z){console.warn("Failed to get signed URL",z)}},j=async()=>{if(a){u(!0);try{const{data:F,error:z}=await q.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(z)throw z;c(F||[]),F!=null&&F.length&&_(F)}catch(F){console.error("Error fetching videos:",F),ae.error("Failed to load videos")}finally{u(!1)}}},_=async F=>{var z;try{const V=F.map(ne=>ne.bunny_video_id),{data:W,error:K}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:V,isAgentVideo:!0}});if(K)throw K;const Y=(W==null?void 0:W.assets)||{},ee={};for(const ne of F)(z=Y[ne.bunny_video_id])!=null&&z.thumbnailUrl&&(ee[ne.id]={thumbnailUrl:Y[ne.bunny_video_id].thumbnailUrl});g(ne=>({...ne,...ee}))}catch(V){console.warn("Failed to bulk-fetch signed URLs",V)}},S=()=>{l(!0),j()},A=F=>{t(F.id),p(F),l(!1),ae.success("Video selected")},T=()=>{t(null),p(null)},D=()=>{const F=n?`/mission-control/listings/${n}/edit`:"/mission-control/listings/new";r(`/mission-control/video?returnUrl=${encodeURIComponent(F)}`)},L=F=>{if(!F)return"0:00";const z=Math.floor(F/60),V=F%60;return`${z}:${V.toString().padStart(2,"0")}`},M=F=>{var z;return((z=f[F.id])==null?void 0:z.thumbnailUrl)||F.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[h?e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ae,{className:"p-0",children:e.jsxs("div",{className:"flex items-start gap-4 p-4",children:[e.jsxs("div",{className:"relative w-32 h-20 bg-muted rounded-lg overflow-hidden flex-shrink-0",children:[M(h)?e.jsx("img",{src:M(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(vr,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/30 flex items-center justify-center",children:e.jsx(Al,{className:"h-6 w-6 text-white fill-white"})}),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:L(h.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.title||"Untitled Video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Property Video Tour"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:S,children:"Change"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:T,className:"text-destructive hover:text-destructive",children:e.jsx(Fn,{className:"h-4 w-4"})})]})]})})}):e.jsx(fe,{className:"border-dashed",children:e.jsx(Ae,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(vr,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Add a video walkthrough to showcase this property"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 justify-center",children:[e.jsxs(B,{type:"button",variant:"outline",onClick:S,className:"gap-2",children:[e.jsx(Wg,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(B,{type:"button",variant:"outline",onClick:D,className:"gap-2",children:[e.jsx(pf,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Wg,{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(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(vr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No videos in your library yet"}),e.jsxs(B,{onClick:D,className:"gap-2",children:[e.jsx(pf,{className:"h-4 w-4"}),"Record Your First Video"]})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 p-1",children:o.map(F=>e.jsxs("button",{type:"button",onClick:()=>A(F),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===F.id?"border-primary ring-2 ring-primary/20":"border-transparent hover:border-muted-foreground/30"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[M(F)?e.jsx("img",{src:M(F),alt:F.title||"Video",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(vr,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center",children:e.jsx(Al,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),F.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:L(F.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:F.title||"Untitled Video"})})]},F.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:D,className:"gap-2",children:[e.jsx(pf,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const SQs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function CQs({listingId:s}){const t=N.useRef(null),{data:n=[],isLoading:r}=_2t(s),a=YZs(),i=ZZs(),l=QZs(),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 w2t(d);window.open(u,"_blank")}catch{ae.error("Failed to open document")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:t,type:"file",multiple:!0,accept:".pdf,application/pdf",className:"hidden",onChange:d=>o(d.target.files)}),e.jsxs(B,{type:"button",variant:"outline",onClick:()=>{var d;return(d=t.current)==null?void 0:d.click()},disabled:a.isPending,className:"w-full",children:[a.isPending?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Upload PDFs (disclosures, etc.)"]}),r?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No documents yet. Upload PDFs that other agents can download from your listing."}):e.jsx("div",{className:"space-y-2",children:n.map(d=>e.jsxs(fe,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Nr,{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:SQs(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(Ir,{className:"h-3 w-3"}):e.jsx(gf,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(vn,{checked:d.visible_on_exchange,onCheckedChange:u=>l.mutate({id:d.id,visible:u,listingId:s}),className:"ml-1"})]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>{confirm(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(Fn,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const TQs=[{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"}],EQs=[{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 AQs({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=Fve({id:s}),u={transform:F4.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(Uu,{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(Fn,{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(ua,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function MQs({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=Eve(z8(oR,{activationConstraint:{distance:5}})),o=s.map((d,u)=>`pending-${u}`),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const p=o.indexOf(u.id),f=o.indexOf(h.id),g=[...s],b=[...t],[v]=g.splice(p,1),[j]=b.splice(p,1);g.splice(f,0,v),b.splice(f,0,j),r(g,b)};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(Dve,{sensors:l,collisionDetection:Ave,onDragEnd:c,children:e.jsx(Ove,{items:o,strategy:IU,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(AQs,{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(ss,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{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 dXe(){const{listingId:s}=_i(),[t]=yl(),n=t.get("brokerage"),r=In(),{user:a}=gs(),{hasLeadSite:i}=Pp(),l=!!s&&s!=="new",o=!!n&&!l,[c,d]=N.useState([]),[u,h]=N.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:p,isLoading:f}=N6e(l?s:""),g=Irs(),b=Prs(),v=Lrs(),j=Drs(),_=Rrs(),S=Ors(),A=Frs(),{data:T=[]}=lt({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:_e,error:Me}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(Me)throw Me;return _e||[]},enabled:o}),[D,L]=N.useState(""),[M,F]=N.useState(!1),[z,V]=N.useState([]),[W,K]=N.useState([]),[Y,ee]=N.useState({property_address:"",city:"",state:"",neighborhood:"",price:"",property_type:"single_family",status:"active",bedrooms:"",bathrooms:"",square_footage:"",lot_size:"",year_built:"",has_hoa:!1,description:"",agent_notes:"",agent_notes_public:!1,mls_link:"",video_link:"",video_id:null,allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0});N.useEffect(()=>{var _e,Me,Te,Ce,Ee;p&&l&&ee({property_address:p.property_address||"",city:p.city||"",state:p.state||"",neighborhood:p.neighborhood||"",price:((_e=p.price)==null?void 0:_e.toString())||"",property_type:p.property_type,status:p.status,bedrooms:((Me=p.bedrooms)==null?void 0:Me.toString())||"",bathrooms:((Te=p.bathrooms)==null?void 0:Te.toString())||"",square_footage:((Ce=p.square_footage)==null?void 0:Ce.toString())||"",lot_size:p.lot_size||"",year_built:((Ee=p.year_built)==null?void 0:Ee.toString())||"",has_hoa:p.has_hoa,description:p.description||"",agent_notes:p.agent_notes||"",agent_notes_public:p.agent_notes_public,mls_link:p.mls_link||"",video_link:p.video_link||"",video_id:p.video_id||null,allow_sharing:p.allow_sharing,open_to_referrals:p.open_to_referrals,open_to_social_promotion:p.open_to_social_promotion,share_with_brokerage:p.share_with_brokerage??!1,is_public:p.is_public})},[p,l]);const ne=_e=>{var Ee,De;const Me={"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=(_e.propertyType||"").toLowerCase(),Ce=((Ee=Object.entries(Me).find(([Ie])=>Te.includes(Ie)))==null?void 0:Ee[1])||"other";ee(Ie=>({...Ie,property_address:_e.address||Ie.property_address,city:_e.city||Ie.city,state:_e.state||Ie.state,price:_e.price?String(_e.price):Ie.price,property_type:Ce,bedrooms:_e.bedrooms?String(_e.bedrooms):Ie.bedrooms,bathrooms:_e.bathrooms?String(_e.bathrooms):Ie.bathrooms,square_footage:_e.sqft?String(_e.sqft):Ie.square_footage,lot_size:_e.lotSize?String(_e.lotSize):Ie.lot_size,year_built:_e.yearBuilt?String(_e.yearBuilt):Ie.year_built,description:_e.description||Ie.description})),((De=_e.photos)==null?void 0:De.length)>0&&(d(_e.photos),W.forEach(Ie=>URL.revokeObjectURL(Ie)),V([]),K([]))},oe=_e=>{if(!_e)return;const Me=Array.from(_e);V(Ce=>[...Ce,...Me]);const Te=Me.map(Ce=>URL.createObjectURL(Ce));K(Ce=>[...Ce,...Te])},pe=_e=>{URL.revokeObjectURL(W[_e]),V(Me=>Me.filter((Te,Ce)=>Ce!==_e)),K(Me=>Me.filter((Te,Ce)=>Ce!==_e))},ce=async _e=>{var Me;if(!(!_e||!p)){F(!0);try{for(const Te of Array.from(_e)){const Ce=Te.name.split(".").pop(),Ee=`${a==null?void 0:a.id}/${p.id}/${Date.now()}.${Ce}`,{error:De}=await q.storage.from("listing-photos").upload(Ee,Te);if(De)throw De;const{data:{publicUrl:Ie}}=q.storage.from("listing-photos").getPublicUrl(Ee);await j.mutateAsync({listingId:p.id,photoUrl:Ie,isPrimary:!((Me=p.photos)!=null&&Me.length)})}ae.success("Photos uploaded!")}catch(Te){console.error("Upload error:",Te),ae.error("Failed to upload photos")}finally{F(!1)}}},de=async _e=>{for(let Me=0;Me{if(p)try{await _.mutateAsync({photoId:_e,listingId:p.id}),ae.success("Photo removed")}catch{ae.error("Failed to remove photo")}},ye=async _e=>{if(_e.preventDefault(),!Y.city.trim()||!Y.state.trim()||!Y.price){ae.error("Please fill in required fields (City, State, Price)");return}if(o&&!D){ae.error("Please select an agent to assign this listing to");return}try{const Me={property_address:Y.property_address||null,city:Y.city,state:Y.state,neighborhood:Y.neighborhood||null,price:Number(Y.price),property_type:Y.property_type,status:Y.status,bedrooms:Y.bedrooms?Number(Y.bedrooms):null,bathrooms:Y.bathrooms?Number(Y.bathrooms):null,square_footage:Y.square_footage?Number(Y.square_footage):null,lot_size:Y.lot_size||null,year_built:Y.year_built?Number(Y.year_built):null,has_hoa:Y.has_hoa,description:Y.description||null,agent_notes:Y.agent_notes||null,agent_notes_public:Y.agent_notes_public,mls_link:Y.mls_link||null,video_link:Y.video_link||null,video_id:Y.video_id||null,allow_sharing:Y.allow_sharing,open_to_referrals:Y.open_to_referrals,open_to_social_promotion:Y.open_to_social_promotion,share_with_brokerage:Y.share_with_brokerage,is_public:Y.is_public};if(l)await v.mutateAsync({id:s,...Me}),ae.success("Listing updated!"),r(`/mission-control/listings/${s}`);else{F(!0);let Te;if(o&&D?Te=await b.mutateAsync({agentId:D,...Me}):Te=await g.mutateAsync(Me),z.length>0)try{await de(Te.id),W.forEach(Ee=>URL.revokeObjectURL(Ee)),V([]),K([])}catch(Ee){console.error("Photo upload error:",Ee),ae.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Ee=0;Eer(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),o?"Back to Brokerage":"Back to Listings"]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[o&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Assign to Agent *"})}),e.jsxs(Ae,{children:[e.jsxs(us,{value:D,onValueChange:L,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select an agent..."})}),e.jsx(ds,{children:T.map(_e=>e.jsx(Ze,{value:_e.id,children:_e.name||_e.email},_e.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(wQs,{onImport:ne}),c.length>0&&e.jsxs(fe,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(Da,{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(Ae,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((_e,Me)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:_e,alt:"",className:"w-full h-full object-cover"})},Me)),c.length>12&&e.jsxs("div",{className:"aspect-square rounded bg-muted flex items-center justify-center text-sm text-muted-foreground font-medium",children:["+",c.length-12]})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(Fn,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Property Details"})}),e.jsx(Ae,{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(se,{children:"Property Address"}),e.jsx(ge,{value:Y.property_address,onChange:_e=>ee({...Y,property_address:_e.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"City *"}),e.jsx(ge,{value:Y.city,onChange:_e=>ee({...Y,city:_e.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"State *"}),e.jsx(ge,{value:Y.state,onChange:_e=>ee({...Y,state:_e.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Neighborhood"}),e.jsx(ge,{value:Y.neighborhood,onChange:_e=>ee({...Y,neighborhood:_e.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Price *"}),e.jsx(ge,{type:"number",value:Y.price,onChange:_e=>ee({...Y,price:_e.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Type"}),e.jsxs(us,{value:Y.property_type,onValueChange:_e=>ee({...Y,property_type:_e}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:EQs.map(_e=>e.jsx(Ze,{value:_e.value,children:_e.label},_e.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(us,{value:Y.status,onValueChange:_e=>ee({...Y,status:_e}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:TQs.map(_e=>e.jsx(Ze,{value:_e.value,children:_e.label},_e.value))})]})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Property Specs (Optional)"})}),e.jsx(Ae,{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(se,{children:"Bedrooms"}),e.jsx(ge,{type:"number",value:Y.bedrooms,onChange:_e=>ee({...Y,bedrooms:_e.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Bathrooms"}),e.jsx(ge,{type:"number",step:"0.5",value:Y.bathrooms,onChange:_e=>ee({...Y,bathrooms:_e.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Sq Ft"}),e.jsx(ge,{type:"number",value:Y.square_footage,onChange:_e=>ee({...Y,square_footage:_e.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Lot Size"}),e.jsx(ge,{value:Y.lot_size,onChange:_e=>ee({...Y,lot_size:_e.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Year Built"}),e.jsx(ge,{type:"number",value:Y.year_built,onChange:_e=>ee({...Y,year_built:_e.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(vn,{checked:Y.has_hoa,onCheckedChange:_e=>ee({...Y,has_hoa:_e})}),e.jsx(se,{children:"Has HOA"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Description & Links"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{value:Y.description,onChange:_e=>ee({...Y,description:_e.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Agent Notes"}),e.jsx(Ts,{value:Y.agent_notes,onChange:_e=>ee({...Y,agent_notes:_e.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{checked:Y.agent_notes_public,onCheckedChange:_e=>ee({...Y,agent_notes_public:_e})}),e.jsx(se,{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(se,{children:"MLS Link"}),e.jsx(ge,{value:Y.mls_link,onChange:_e=>ee({...Y,mls_link:_e.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video Link"}),e.jsx(ge,{value:Y.video_link,onChange:_e=>ee({...Y,video_link:_e.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Ae,{children:e.jsx(kQs,{selectedVideoId:Y.video_id,onVideoSelect:_e=>ee({...Y,video_id:_e}),listingId:l?s:void 0})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Photos"})}),e.jsx(Ae,{children:l&&(p!=null&&p.photos)?e.jsx(NQs,{photos:p.photos,uploading:M,onUpload:_e=>ce(_e),onRemove:_e=>ie(_e),onReorder:_e=>{S.mutate({photos:_e.map(Me=>({id:Me.id,sort_order:Me.sort_order,is_primary:Me.is_primary}))})},onSetPrimary:_e=>{p&&A.mutate({photoId:_e,listingId:p.id})}}):e.jsx(MQs,{photoUrls:W,onRemove:pe,onReorder:(_e,Me)=>{K(_e),V(Me)},pendingPhotos:z,uploading:M,onUpload:oe})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Ae,{children:l&&s?e.jsx(CQs,{listingId:s}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Save the listing first, then you can upload PDFs (disclosures, floor plans, HOA docs, etc.) for other agents to download."})})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Sharing & Collaboration"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(vn,{checked:Y.allow_sharing,onCheckedChange:_e=>ee({...Y,allow_sharing:_e})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(vn,{checked:Y.open_to_referrals,onCheckedChange:_e=>ee({...Y,open_to_referrals:_e})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(vn,{checked:Y.open_to_social_promotion,onCheckedChange:_e=>ee({...Y,open_to_social_promotion:_e})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(vn,{checked:Y.share_with_brokerage,onCheckedChange:_e=>ee({...Y,share_with_brokerage:_e})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(vn,{checked:Y.is_public,onCheckedChange:_e=>ee({...Y,is_public:_e})})]})]})]}),e.jsx(B,{type:"submit",className:"w-full",size:"lg",disabled:g.isPending||v.isPending,children:g.isPending||v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(j2t,{listingId:u.listingId,open:u.open,onOpenChange:_e=>{if(!_e){const{nextPath:Me}=u;h({open:!1,listingId:null,nextPath:Me}),r(Me)}}})]})}const TTe=[{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"}],C2t=[{type:"extra_video",label:"Extra Video / Reel",icon:vr,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:Y7,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:nl,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:yb,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:gr,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:tl,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],IQs=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],qNe={sections:Object.fromEntries(TTe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},PQs=()=>Math.random().toString(36).slice(2,10);function LQs(){const{listingId:s}=_i(),t=In(),{user:n}=gs(),r=Gt(),[a,i]=N.useState("desktop"),[l,o]=N.useState(qNe),[c,d]=N.useState(!1),[u,h]=N.useState(0),{data:p,isLoading:f}=lt({queryKey:["listing-customize",s],queryFn:async()=>{const{data:z,error:V}=await q.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if(V)throw V;return z},enabled:!!s});N.useEffect(()=>{var z,V;p!=null&&p.page_config&&o({...qNe,...p.page_config||{},sections:{...qNe.sections,...((z=p.page_config)==null?void 0:z.sections)||{}},addons:((V=p.page_config)==null?void 0:V.addons)||[]})},[p==null?void 0:p.id]);const g=!!n&&!!p&&n.id===p.agent_id,b=N.useMemo(()=>p?`/public/listing/${p.slug||p.id}?preview=1&t=${u}`:"",[p,u]),v=N.useMemo(()=>p?`https://listings.relevelup.com/${p.slug||p.id}`:"",[p]),j=gt({mutationFn:async()=>{const{error:z}=await q.from("listings").update({page_config:l}).eq("id",s);if(z)throw z},onSuccess:()=>{ae.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(z=>z+1)},onError:z=>ae.error(`Save failed: ${z.message||"Try again"}`)}),_=z=>{o(V=>({...V,...z})),d(!0)},S=(z,V)=>_({sections:{...l.sections||{},[z]:V}}),A=z=>_({addons:[...l.addons||[],{id:PQs(),type:z,data:{}}]}),T=(z,V)=>_({addons:(l.addons||[]).map(W=>W.id===z?{...W,data:{...W.data,...V}}:W)}),D=z=>_({addons:(l.addons||[]).filter(V=>V.id!==z)}),L=(z,V)=>{const W=[...l.addons||[]],K=W.findIndex(ee=>ee.id===z);if(K<0)return;const Y=K+V;Y<0||Y>=W.length||([W[K],W[Y]]=[W[Y],W[K]],_({addons:W}))};if(f)return e.jsx(Cs,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!p)return e.jsx(Cs,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!g)return e.jsx(Cs,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx(B,{className:"mt-3",onClick:()=>t(`/mission-control/listings/${p.id}`),children:"Back"})]})});const M=(l.addons||[]).length,F=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs(Cs,{title:"",description:"",children:[e.jsxs("div",{className:"sticky top-0 z-30 -mx-4 sm:-mx-6 px-4 sm:px-6 py-3 bg-background/85 backdrop-blur border-b flex items-center gap-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t(`/mission-control/listings/${p.id}`),children:[e.jsx(Wr,{className:"h-4 w-4 mr-1.5"})," Back"]}),e.jsxs("div",{className:"hidden md:flex flex-col leading-tight",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"Customize Public Page"}),e.jsx("p",{className:"text-sm font-medium truncate max-w-[420px]",children:p.property_address||`${p.city}, ${p.state}`})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[c&&e.jsx("span",{className:"text-xs text-amber-600 hidden sm:inline",children:"Unsaved changes"}),e.jsxs("div",{className:"hidden md:inline-flex rounded-lg border bg-muted p-0.5",children:[e.jsxs("button",{onClick:()=>i("desktop"),className:`h-8 px-2.5 rounded-md text-xs flex items-center gap-1.5 ${a==="desktop"?"bg-background shadow-sm":"text-muted-foreground"}`,children:[e.jsx(gb,{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(rg,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(z=>z+1),children:[e.jsx(Ai,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx(B,{size:"sm",onClick:()=>j.mutate(),disabled:!c||j.isPending,children:j.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Ho,{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(mi,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(BF,{icon:e.jsx(un,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(z=>e.jsx("button",{onClick:()=>_({hero_style:z}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===z?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:z},z))})]})}),e.jsx(BF,{icon:e.jsx(xl,{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"}),IQs.map(z=>e.jsx("button",{onClick:()=>_({accent_color:z}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===z?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:z},"aria-label":z},z))]})}),e.jsx(BF,{icon:e.jsx(Rm,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Ts,{value:l.custom_note||"",onChange:z=>_({custom_note:z.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(BF,{icon:e.jsx(E2,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${F} of ${TTe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:TTe.map(z=>{var W;const V=((W=l.sections)==null?void 0:W[z.key])!==!1;return e.jsxs("div",{className:"flex items-center justify-between p-3.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:z.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:z.hint})]}),e.jsx(vn,{checked:V,onCheckedChange:K=>S(z.key,K)})]},z.key)})})}),e.jsxs(BF,{icon:e.jsx(As,{className:"h-4 w-4"}),title:"Add-on modules",desc:"Drop in extras to make this page unique",rightLabel:M?`${M} added`:void 0,children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:C2t.map(z=>e.jsxs("button",{onClick:()=>A(z.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${z.accent}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-7 w-7 rounded-md bg-background border flex items-center justify-center",children:e.jsx(z.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:z.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:z.desc})]},z.type))}),(l.addons||[]).length>0&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"On this page · drag to reorder"}),(l.addons||[]).map((z,V)=>e.jsx(DQs,{addon:z,onChange:W=>T(z.id,W),onRemove:()=>D(z.id),onMoveUp:V>0?()=>L(z.id,-1):void 0,onMoveDown:VL(z.id,1):void 0},z.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx(B,{className:"w-full",onClick:()=>j.mutate(),disabled:!c||j.isPending,children:j.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Ho,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(fe,{className:"h-full overflow-hidden bg-neutral-100 p-4 lg:p-6 border rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Ir,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx(ze,{variant:"outline",className:"text-[10px] border-amber-400 text-amber-700 bg-amber-50 ml-1",children:"Save to update"}),!c&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600 ml-1",children:[e.jsx(Lr,{className:"h-3 w-3"})," In sync"]})]}),e.jsxs("div",{className:"lg:hidden inline-flex rounded-lg border bg-background p-0.5",children:[e.jsx("button",{onClick:()=>i("desktop"),className:`h-7 px-2 rounded ${a==="desktop"?"bg-muted":""}`,children:e.jsx(gb,{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(rg,{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:b,title:"Preview",className:"w-full h-full border-0"},u)})})]})})]})]})}function BF({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 DQs({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=C2t.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(Uu,{className:"h-3.5 w-3.5"})})}),e.jsx("div",{className:"h-7 w-7 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(l,{className:"h-3.5 w-3.5"})}),e.jsx("p",{className:"text-sm font-medium flex-1",children:i.label}),e.jsxs("div",{className:"flex items-center gap-1",children:[a&&e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:a,"aria-label":"Move down",children:e.jsx(Uu,{className:"h-3.5 w-3.5 rotate-180"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:n,"aria-label":"Remove",children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Video URL"}),e.jsx(ge,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Title (optional)"}),e.jsx(ge,{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(se,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(Ts,{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(se,{className:"text-xs",children:"Quote"}),e.jsx(Ts,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Attribution"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Headline"}),e.jsx(ge,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Button label"}),e.jsx(ge,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Link URL"}),e.jsx(ge,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const T2t="teleprompter_settings",VNe={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function RQs(){try{const s=localStorage.getItem(T2t);return s?{...VNe,...JSON.parse(s)}:VNe}catch{return VNe}}function OQs(s){try{localStorage.setItem(T2t,JSON.stringify(s))}catch{}}function N8e({text:s,isVisible:t,onToggleVisibility:n,isRecording:r=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=N.useRef(null),c=N.useRef(null),d=N.useRef(0),u=N.useRef(0),[h,p]=N.useState(RQs),{scrollSpeed:f,fontSize:g,lineHeight:b,opacity:v,position:j,isMirrored:_}=h,S=N.useCallback((W,K)=>{p(Y=>{const ee={...Y,[W]:K};return OQs(ee),ee})},[]),[A,T]=N.useState(!1),[D,L]=N.useState(null),M=N.useCallback(W=>{if(!o.current)return;d.current===0&&(d.current=W);const K=W-d.current;d.current=W,u.current+=f*K/1e3;const Y=Math.floor(u.current);Y>0&&(o.current.scrollTop+=Y,u.current-=Y);const{scrollTop:ee,scrollHeight:ne,clientHeight:oe}=o.current;if(ee+oe>=ne){T(!1);return}c.current=requestAnimationFrame(M)},[f]);N.useEffect(()=>(A?(d.current=0,u.current=0,c.current=requestAnimationFrame(M)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[A,M]),N.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){L(3);let W=3;const K=setInterval(()=>{W-=1,W<=0?(clearInterval(K),L(null),i==null||i(),T(!0)):L(W)},1e3);return()=>clearInterval(K)}else setTimeout(()=>T(!0),100);else r||(T(!1),L(null))},[r,t,a,i]);const F=N.useCallback(()=>{o.current&&(o.current.scrollTop=0),T(!1)},[]),z=N.useCallback(()=>{T(W=>!W)},[]);if(!t)return e.jsx("div",{className:Et("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs(B,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const V={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Et("absolute inset-0 pointer-events-none",l),children:[D!==null&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:D},D),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:Et("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",V[j],D!==null&&"opacity-30"),style:{opacity:D!==null?.3:v},children:e.jsxs("div",{ref:o,className:Et("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:b,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(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsx(B,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Vo,{className:"h-4 w-4"})})}),e.jsx(zo,{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(se,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:f})]}),e.jsx($m,{value:[f],onValueChange:([W])=>S("scrollSpeed",W),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(se,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[g,"px"]})]}),e.jsx($m,{value:[g],onValueChange:([W])=>S("fontSize",W),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(se,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.toFixed(1)})]}),e.jsx($m,{value:[b*10],onValueChange:([W])=>S("lineHeight",W/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(se,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(v*100),"%"]})]}),e.jsx($m,{value:[v*100],onValueChange:([W])=>S("opacity",W/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:j==="top"?"default":"outline",size:"sm",onClick:()=>S("position","top"),children:e.jsx(sx,{className:"h-4 w-4"})}),e.jsx(B,{variant:j==="center"?"default":"outline",size:"sm",onClick:()=>S("position","center"),children:e.jsx(xb,{className:"h-4 w-4"})}),e.jsx(B,{variant:j==="bottom"?"default":"outline",size:"sm",onClick:()=>S("position","bottom"),children:e.jsx(io,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs",children:"Mirror Mode"}),e.jsx(vn,{checked:_,onCheckedChange:W=>S("isMirrored",W)})]})]})})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:z,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:A?e.jsx(_f,{className:"h-4 w-4"}):e.jsx(Al,{className:"h-4 w-4"})}),e.jsx(B,{variant:"secondary",size:"icon",onClick:F,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Fh,{className:"h-4 w-4"})}),e.jsxs(B,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(gf,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function FQs({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=Ua(),[i,l]=N.useState(""),[o,c]=N.useState(null),[d,u]=N.useState("levelup"),{data:h,isLoading:p}=FGs(),{data:f,isLoading:g}=zGs(),{data:b,isLoading:v}=BGs(),j=$Gs(),_=N.useMemo(()=>f?f.filter(L=>{const M=!i||L.title.toLowerCase().includes(i.toLowerCase())||L.script_text.toLowerCase().includes(i.toLowerCase())||L.tags.some(z=>z.toLowerCase().includes(i.toLowerCase())),F=!o||L.category_id===o;return M&&F}):[],[f,i,o]),S=N.useMemo(()=>b?b.filter(L=>!i||L.title.toLowerCase().includes(i.toLowerCase())||L.script_text.toLowerCase().includes(i.toLowerCase())):[],[b,i]),A=L=>{s({title:L.title,text:L.script_text})},T=async L=>{try{await j.mutateAsync(L),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},D=p||g||v;return e.jsxs("div",{className:Et("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search scripts...",value:i,onChange:L=>l(L.target.value),className:"pl-9"})]})}),e.jsxs($r,{value:d,onValueChange:L=>u(L),className:"flex-1 flex flex-col",children:[e.jsxs(Ur,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Zt,{value:"levelup",children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Zt,{value:"my-scripts",children:[e.jsx(Rv,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(ls,{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(ze,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(L=>e.jsx(ze,{variant:o===L.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(L.id),children:L.name},L.id))]}),e.jsx(mi,{className:"flex-1 max-h-[50vh]",children:D?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ss,{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(Nr,{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(L=>e.jsxs(fe,{className:Et("cursor-pointer hover:bg-accent/50 transition-colors",n===L.id&&"ring-2 ring-primary"),onClick:()=>A(L),children:[e.jsx(Mt,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Pt,{className:"text-sm font-medium truncate",children:L.title}),L.category&&e.jsx(ze,{variant:"secondary",className:"mt-1 text-xs",children:L.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:M=>{M.stopPropagation(),T(L)},children:e.jsx(Rv,{className:"h-4 w-4"})}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Ae,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:L.script_text})})]},L.id))})})]}),e.jsxs(ls,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs(B,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(mi,{className:"flex-1 max-h-[50vh]",children:v?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):S.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Rv,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No saved scripts"}),e.jsx("p",{className:"text-sm mt-1",children:"Save LevelUp scripts or create your own"})]}):e.jsx("div",{className:"space-y-2",children:S.map(L=>e.jsxs(fe,{className:Et("cursor-pointer hover:bg-accent/50 transition-colors",n===L.id&&"ring-2 ring-primary"),onClick:()=>A(L),children:[e.jsx(Mt,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Pt,{className:"text-sm font-medium truncate",children:L.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:L.is_custom?e.jsx(ze,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Ae,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:L.script_text})})]},L.id))})})]})]})]})}function zQs({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=N.useState(()=>{const o=DL(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(se,{className:"text-sm font-medium",children:"Share Page Template"}),r&&e.jsx(ss,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:Rns.map(o=>{const c=Ons(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(uy,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(hy,{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(io,{className:Et("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(my,{className:"pt-2",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.map(h=>{const p=s===h.id;return e.jsxs("button",{type:"button",onClick:()=>t(h.id),disabled:r,className:Et("relative rounded-lg border-2 p-2.5 text-left transition-all hover:shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",p?"border-primary ring-1 ring-primary/20 bg-primary/5":"border-muted hover:border-muted-foreground/30"),children:[p&&e.jsx("div",{className:"absolute top-1 right-1 w-4 h-4 rounded-full bg-primary flex items-center justify-center",children:e.jsx(Lr,{className:"h-2.5 w-2.5 text-primary-foreground"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"opacity-70 shrink-0",children:h.icon}),e.jsx("span",{className:"text-sm font-medium truncate",children:h.name})]})]},h.id)})})})]},o.id)})}),n&&s!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Will show: "',DL(s).headerText(n),'"']})]})}function E2t({open:s,onOpenChange:t,video:n,contactName:r,onTemplateUpdated:a}){const[i,l]=N.useState(n.page_template||"default"),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState(n.page_template||"default"),[f,g]=N.useState([]),[b,v]=N.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[j,_]=N.useState(!1),[S,A]=N.useState(!1),T=n.share_token?`https://video.relevelup.com/${n.share_token}`:"";N.useEffect(()=>{s&&f.length===0&&D()},[s]);const D=async()=>{A(!0);try{const{data:ee,error:ne}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ne)throw ne;const oe=(ee||[]).map(pe=>({id:pe.id,name:[pe.first_name,pe.last_name].filter(Boolean).join(" ")||"Unnamed",email:pe.email||null}));g(oe)}catch(ee){console.error("Failed to fetch contacts:",ee)}finally{A(!1)}},L=async ee=>{v(ee),_(!1),c(!0);try{const{error:ne}=await q.from("agent_videos").update({contact_id:(ee==null?void 0:ee.id)||null,recipient_name:(ee==null?void 0:ee.name)||null}).eq("id",n.id);if(ne)throw ne;ae.success(ee?`Assigned to ${ee.name}`:"Contact removed"),a==null||a()}catch(ne){console.error("Failed to update contact:",ne),ae.error("Failed to update contact")}finally{c(!1)}},M=async ee=>{l(ee),c(!0);try{const{error:ne}=await q.from("agent_videos").update({page_template:ee}).eq("id",n.id);if(ne)throw ne;p(ee),ae.success("Template saved!"),a==null||a()}catch(ne){console.error("Failed to save template:",ne),ae.error("Failed to save template"),l(h)}finally{c(!1)}},F=(b==null?void 0:b.name)||null,z=()=>{const ee=n.title||"Video Message",ne=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},V=async()=>{if(!n.thumbnail_url){ae.error("Video thumbnail not available yet");return}const ee=z(),ne=`Watch: ${n.title||"Video Message"} ${T}`;try{const oe=new Blob([ee],{type:"text/html"}),pe=new Blob([ne],{type:"text/plain"}),ce=new ClipboardItem({"text/html":oe,"text/plain":pe});await navigator.clipboard.write([ce]),ae.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(ne+` `+ee),ae.success("Copied! Paste into your email.")}},W=async()=>{await navigator.clipboard.writeText(T),u(!0),ae.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},K=()=>{const ne=DL(i).headerText(F),oe=i==="default"?`Check out this video: ${T}`:`${ne} Check out this special video: ${T}`;window.open(`sms:?body=${encodeURIComponent(oe)}`,"_self")},Y=()=>{const ee=DL(i),ne=ee.headerText(F),oe=i==="default"?n.title||"Video Message":ne,pe=`${ee.subText} Watch the video: ${T}`,ce=b!=null&&b.email?encodeURIComponent(b.email):"";window.open(`mailto:${ce}?subject=${encodeURIComponent(oe)}&body=${encodeURIComponent(pe)}`,"_self")};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(tl,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Qn,{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(se,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Wo,{open:j,onOpenChange:_,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":j,className:"flex-1 justify-between",disabled:o,children:[b?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Xi,{className:"h-4 w-4 text-muted-foreground"}),b.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(Hg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(zo,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search contacts..."}),e.jsxs(e0,{children:[e.jsx(t0,{children:S?"Loading...":"No contacts found."}),e.jsx(s0,{children:f.map(ee=>e.jsxs(ex,{value:ee.name,onSelect:()=>L(ee),children:[e.jsx(Lr,{className:Et("mr-2 h-4 w-4",(b==null?void 0:b.id)===ee.id?"opacity-100":"opacity-0")}),ee.name]},ee.id))})]})]})})]}),b&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>L(null),disabled:o,className:"shrink-0",children:e.jsx(Fn,{className:"h-4 w-4"})})]}),b&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',DL(i).headerText(b.name),'"']})]}),e.jsx(zQs,{selectedTemplate:i,onSelect:M,contactName:F,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:T,readOnly:!0,className:"font-mono text-sm"}),e.jsx(B,{onClick:W,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(ta,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Share for Email"}),e.jsxs(B,{variant:"outline",className:"w-full gap-2",onClick:V,children:[e.jsx(nl,{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(se,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:K,children:[e.jsx(Ci,{className:"h-4 w-4"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:Y,children:[e.jsx(Hs,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(Xn,{children:e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function BQs(){var $e;const s=In(),[t]=yl(),{toast:n}=Ua(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=V_t(),{data:u}=lx(),h=PN(),p=GGs(),[f,g]=N.useState("record"),[b,v]=N.useState(""),[j,_]=N.useState(!1),[S,A]=N.useState(!1),[T,D]=N.useState(!1),[L,M]=N.useState(null),[F,z]=N.useState(0),[V,W]=N.useState(0),[K,Y]=N.useState(null),[ee,ne]=N.useState(null),[oe,pe]=N.useState(r||""),[ce,de]=N.useState(""),[ie,ye]=N.useState(""),[_e,Me]=N.useState(null),[Te,Ce]=N.useState(null),[Ee,De]=N.useState(null),[Ie,Fe]=N.useState(!1),qe=N.useCallback(async(Ye,Ke)=>{M(Ye),g("uploading");try{const{videoId:rt,uploadUrl:tt}=await l6(ce||"Quick Video Touch");Y(rt);const{apiKey:at}=await c6(rt),Ge=new XMLHttpRequest;Ge.upload.onprogress=Qt=>{Qt.lengthComputable&&z(Qt.loaded/Qt.total*100)},await new Promise((Qt,ns)=>{Ge.onload=()=>{Ge.status>=200&&Ge.status<300?Qt():ns(new Error(`Upload failed: ${Ge.status}`))},Ge.onerror=()=>ns(new Error("Upload failed")),Ge.open("PUT",tt),Ge.setRequestHeader("AccessKey",at),Ge.send(Ye)}),g("processing");let dt=0;const Bt=Date.now(),kt=90*1e3;for(;dt<4;){if(await new Promise(ns=>setTimeout(ns,3e3)),Date.now()-Bt>kt){const ns=Ye.size/1048576,$s=`https://iframe.mediadelivery.net/play/${rt}/${rt}`;await h.mutateAsync({bunny_video_id:rt,playback_url:$s,file_size_mb:ns,title:ce||"Quick Video Touch",notes:ie||void 0,contact_id:oe&&oe!=="none"?oe:void 0,status:"processing",touch_type:"video_touch"}),n({title:"Video saved — still processing",description:'Your video has been saved and will appear in your library with a "processing" badge. It will be ready to share once encoding completes (usually within a few minutes).',duration:8e3}),s("/mission-control/video-library");return}const Qt=await Uw(rt);if(dt=Qt.status,W(Qt.encodeProgress||0),dt===4)ne({playbackUrl:Qt.directPlayUrl,thumbnailUrl:Qt.thumbnailUrl,previewUrl:Qt.previewUrl||null,duration:Qt.length||Ke,fileSizeMb:(Qt.storageSize||Ye.size)/(1024*1024)});else if(dt===5||dt===6)throw new Error("Video processing failed")}g("details")}catch(rt){console.error("Upload error:",rt),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),g("record")}},[ce,n]),ve=async()=>{if(!(!K||!ee))try{const Ye=oe&&oe!=="none"?oe:null,Ke=await h.mutateAsync({bunny_video_id:K,contact_id:Ye,playback_url:ee.playbackUrl,thumbnail_url:ee.thumbnailUrl,preview_url:ee.previewUrl,duration_seconds:ee.duration,file_size_mb:ee.fileSizeMb,title:ce||"Quick Video Touch",notes:ie,task_id:a||null,status:"ready"});Me(Ke.id),Ce(Ke.share_token||null),Ye&&await p.mutateAsync({contactId:Ye,videoId:Ke.id,notes:ie}),n({title:"Video saved successfully!"}),g("share")}catch(Ye){console.error("Save video error:",Ye),n({title:"Failed to save video",description:(Ye==null?void 0:Ye.message)||"Please try again.",variant:"destructive"})}},Je=(Ye,Ke)=>{navigator.clipboard.writeText(Ke),De(Ye),setTimeout(()=>De(null),2e3),n({title:"Copied to clipboard!"})},we=()=>Te?`https://video.relevelup.com/${Te}`:(ee==null?void 0:ee.playbackUrl)||"",it=()=>{const Ye=u==null?void 0:u.find(Ge=>Ge.id===oe),Ke=Ye?`${Ye.first_name}`:"",rt=(Ye==null?void 0:Ye.phone)||"",tt=(Ye==null?void 0:Ye.email)||"",at=we();return{text:`Hey${Ke?` ${Ke}`:""}! I recorded a quick video for you: ${at}`,link:at,contactPhone:rt,contactEmail:tt}},Ne=()=>{const{text:Ye,contactPhone:Ke}=it(),rt=Ke?`sms:${Ke}?body=${encodeURIComponent(Ye)}`:`sms:?body=${encodeURIComponent(Ye)}`;window.open(rt,"_self")},He=()=>{const{link:Ye,contactEmail:Ke}=it(),rt="Check out this video",tt=`I recorded a quick video for you: ${Ye}`,at=Ke?`mailto:${Ke}?subject=${encodeURIComponent(rt)}&body=${encodeURIComponent(tt)}`:`mailto:?subject=${encodeURIComponent(rt)}&body=${encodeURIComponent(tt)}`;window.open(at,"_self")};return i?e.jsx(Cs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(Wr,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"QuickVid"}),e.jsx("p",{className:"text-muted-foreground",children:"Record a personal video message"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Video Library"]}),c&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm text-warning",children:["Storage: ",o.toFixed(0),"% used"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.toFixed(0)," MB remaining"]})]})]})]}),f==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(m6,{maxDurationSeconds:600,onRecordingComplete:qe,onRecordingStateChange:D,className:"w-full",teleprompterContent:j&&b&&e.jsx(N8e,{text:b,isVisible:j,onToggleVisibility:()=>_(!1),isRecording:T,startCountdown:!1})}),!j&&b&&e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>_(!0),children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(fe,{className:"lg:col-span-1",children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsx(Ts,{placeholder:"Type or paste your script here...",value:b,onChange:Ye=>v(Ye.target.value),rows:6}),e.jsxs(ug,{open:S,onOpenChange:A,children:[e.jsx(oU,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full",children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(ox,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(r0,{className:"p-4 border-b",children:e.jsx(a0,{children:"Select a Script"})}),e.jsx(FQs,{onSelectScript:Ye=>{v(Ye.text),A(!1),_(!0)},className:"h-[calc(100vh-80px)]"})]})]}),b&&e.jsx(B,{className:"w-full",onClick:()=>_(!0),children:"Use Script"})]})]})]}),f==="uploading"&&e.jsx(fe,{className:"max-w-md mx-auto",children:e.jsxs(Ae,{className:"pt-6 text-center",children:[e.jsx(Sa,{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(xi,{value:F,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[F.toFixed(0),"%"]})]})}),f==="processing"&&e.jsx(fe,{className:"max-w-md mx-auto",children:e.jsxs(Ae,{className:"pt-6 text-center space-y-4",children:[e.jsx(ss,{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(xi,{value:V,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[V.toFixed(0),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:`This usually takes 30-60 seconds. If it takes longer, we'll auto-save your video and you can find it in your Video Library — look for the "processing" badge.`})]})}),f==="details"&&e.jsxs(fe,{className:"max-w-lg mx-auto",children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Video Details"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ge,{value:ce,onChange:Ye=>de(Ye.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Attach to Contact (Optional)"}),e.jsxs(us,{value:oe,onValueChange:pe,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"No contact - use anywhere"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(tl,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),u==null?void 0:u.map(Ye=>e.jsx(Ze,{value:Ye.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xi,{className:"h-4 w-4"}),Ye.first_name," ",Ye.last_name]})},Ye.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ts,{value:ie,onChange:Ye=>ye(Ye.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(B,{className:"w-full",onClick:ve,disabled:h.isPending,children:[h.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),f==="share"&&e.jsxs(fe,{className:"max-w-lg mx-auto",children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Share your video with one click:"}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs(B,{variant:"outline",className:"justify-start",onClick:Ne,children:[e.jsx(Ci,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:He,children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Je("link",it().link),children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Copy Video Link",Ee==="link"&&e.jsx(Lr,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Fe(!0),children:[e.jsx(xl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx(B,{onClick:()=>{g("record"),M(null),Y(null),ne(null)},children:"Record Another"})]})]})]}),_e&&Te&&e.jsx(E2t,{open:Ie,onOpenChange:Fe,video:{id:_e,share_token:Te,title:ce||null,contact_id:oe||null,thumbnail_url:(ee==null?void 0:ee.thumbnailUrl)||null},contactName:(($e=u==null?void 0:u.find(Ye=>Ye.id===oe))==null?void 0:$e.first_name)||null})]})}):e.jsx(Cs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(Dl,{className:"h-16 w-16 text-destructive mx-auto mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Storage Limit Reached"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"You've reached your video storage limit. Delete videos from your library to record more."}),e.jsx(B,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function $Qs({open:s,onOpenChange:t,video:n,gmailEmail:r,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=N.useState([]),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,b]=N.useState(""),[v,j]=N.useState(""),[_,S]=N.useState(""),[A,T]=N.useState(!1),D=O_t(),L=n.share_token?`https://video.relevelup.com/share/video/${n.share_token}`:"",M=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:a||n.thumbnail_url||"",F=n.title||"Video Message";N.useEffect(()=>{s&&l.length===0&&z()},[s]),N.useEffect(()=>{if(s&&(j(`I recorded a video for you — ${F}`),S("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),b(""),n.contact_id)){const ne=l.find(oe=>oe.id===n.contact_id);ne&&(d(ne),b(ne.email||""))}},[s,n.contact_id,l]);const z=async()=>{f(!0);try{const{data:ne,error:oe}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(oe)throw oe;o(ne||[])}catch{console.error("Failed to fetch contacts")}finally{f(!1)}},V=ne=>{d(ne),h(!1),b(ne.email||""),S(`Hey ${ne.first_name}! I recorded a quick video just for you. Click below to watch it:`),j(`I recorded a video for you — ${F}`)},W=()=>{d(null),b(""),S("Hey! I recorded a quick video just for you. Click below to watch it:")},K=ne=>`${ne.first_name} ${ne.last_name||""}`.trim(),Y=ne=>{const oe=_.split(/\n\n+/).map(de=>`

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

`).join(""),pe=ne?z_t(ne):L,ce=ne?``:"";return`
${oe}

▶ Watch Video

${ce}
`},ee=async()=>{var ne;if(!g){ae.error("Please enter a recipient email");return}if(!L){ae.error("Video does not have a share link");return}T(!0);try{let oe;try{const ye=c?K(c):g.split("@")[0];oe=(await D.mutateAsync({video_id:n.id,recipient_email:g,recipient_name:ye,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(ye){console.warn("Failed to create tracking record, sending without tracking:",ye)}const pe=Y(oe),{data:ce,error:de}=await q.functions.invoke("gmail-send",{body:{to:g,subject:v,body:pe,contactId:(c==null?void 0:c.id)||null}});let ie=null;if(de&&((ne=de.context)!=null&&ne.json))try{ie=await de.context.json()}catch{}if((ie==null?void 0:ie.error)==="insufficient_scope"||(ce==null?void 0:ce.error)==="insufficient_scope"){ae.error((ie==null?void 0:ie.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(de)throw new Error((ie==null?void 0:ie.message)||de.message);if(!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||"Failed to send");ae.success("Video email sent!"),t(!1),i==null||i()}catch(oe){console.error("Gmail send error:",oe),ae.error("Failed to send: "+(oe instanceof Error?oe.message:"Unknown error"))}finally{T(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hs,{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(se,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Wo,{open:u,onOpenChange:h,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"flex-1 justify-between",children:[c?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Xi,{className:"h-4 w-4 text-muted-foreground"}),K(c),c.email&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",c.email,")"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(Hg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(zo,{className:"w-[350px] p-0",align:"start",children:e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search contacts..."}),e.jsxs(e0,{children:[e.jsx(t0,{children:p?"Loading...":"No contacts found."}),e.jsx(s0,{children:l.filter(ne=>ne.email).map(ne=>e.jsxs(ex,{value:`${ne.first_name} ${ne.last_name||""} ${ne.email||""}`,onSelect:()=>V(ne),children:[e.jsx(Lr,{className:Et("mr-2 h-4 w-4",(c==null?void 0:c.id)===ne.id?"opacity-100":"opacity-0")}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:K(ne)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ne.email})]})]},ne.id))})]})]})})]}),c&&e.jsx(B,{variant:"ghost",size:"icon",onClick:W,className:"shrink-0",children:e.jsx(Fn,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(ge,{id:"video-to",value:g,onChange:ne=>b(ne.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-subject",children:"Subject"}),e.jsx(ge,{id:"video-subject",value:v,onChange:ne=>j(ne.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Ts,{id:"video-message",value:_,onChange:ne=>S(ne.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx(se,{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:[M?e.jsx("img",{src:M,alt:F,className:"w-full aspect-video object-cover"}):e.jsx("div",{className:"w-full aspect-video flex items-center justify-center bg-muted",children:e.jsx(Al,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/80 flex items-center justify-center shadow",children:e.jsx(Al,{className:"h-5 w-5 text-primary ml-0.5"})})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients will see the thumbnail with a play button. Clicking opens the video page."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:A,children:"Cancel"}),e.jsxs(B,{onClick:ee,disabled:A||!g||!v,className:"gap-2",children:[A?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),A?"Sending...":"Send Video Email"]})]})]})]})})}const UQs=()=>{const{user:s}=gs();return lt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_videos",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})};function qQs({recipient:s}){return s.watched_at?e.jsxs(ze,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(Al,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(ze,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(Fm,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(ze,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(Ir,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:[e.jsx(cr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function VQs({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=wGs(n);return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(yo,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(Ws,{className:"h-12 w-full"},o))}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recipients tracked for this video yet."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs("div",{className:"text-center p-2 rounded-lg bg-muted/50",children:[e.jsx("div",{className:"text-lg font-bold",children:a.length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Sent"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-amber-50",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:a.filter(l=>l.opened_at).length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Opened"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-blue-50",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:a.filter(l=>l.clicked_at).length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Clicked"})]})]}),e.jsx(mi,{className:"h-[400px]",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Recipient"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Sent"}),e.jsx(Ct,{children:"Last Activity"})]})}),e.jsx(pa,{children:a.map(l=>e.jsxs(Gs,{children:[e.jsx(ut,{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(ut,{children:e.jsx(qQs,{recipient:l})}),e.jsx(ut,{className:"text-xs text-muted-foreground",children:ks(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(ut,{className:"text-xs text-muted-foreground",children:l.last_activity_at?Go(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function HQs(){const{data:s,isLoading:t}=jGs(),{data:n=[],isLoading:r}=NGs(),[a,i]=N.useState(null),l=t||r,o=n.reduce((c,d)=>{const u=d.agent_videos,h=(u==null?void 0:u.id)||d.video_id;return c[h]||(c[h]={videoId:h,title:(u==null?void 0:u.title)||"Untitled",thumbnailUrl:u==null?void 0:u.thumbnail_url,recipients:[]}),c[h].recipients.push(d),c},{});return l?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((c,d)=>e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(Ae,{children:e.jsx(Ws,{className:"h-8 w-16"})})]},d))})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(cr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(Ir,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Ae,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.openRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalOpened)||0," opened"]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(Fm,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Ae,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.clickRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalClicked)||0," clicked"]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Hn,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Ae,{children:Object.keys(o).length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No tracked sends yet. Send a video via Gmail to start tracking."}):e.jsx("div",{className:"space-y-2",children:Object.values(o).map(c=>{const d=c.recipients.filter(h=>h.opened_at).length,u=c.recipients.filter(h=>h.clicked_at).length;return e.jsxs("button",{onClick:()=>i({id:c.videoId,title:c.title}),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-left",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:c.thumbnailUrl?e.jsx("img",{src:c.thumbnailUrl,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer",onError:h=>{const p=h.currentTarget;p.style.display="none",p.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(vr,{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(cr,{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(Ir,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(Fm,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(mo,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(VQs,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function GQs({previewSrc:s,thumbnailSrc:t,alt:n,isHovered:r}){const[a,i]=N.useState(!1),[l,o]=N.useState(!1),c=r&&s&&!a,d=t&&!l;return!d&&!c?e.jsx("div",{className:"w-full h-full flex items-center justify-center absolute inset-0 bg-muted",children:e.jsx(vr,{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 WQs({video:s,previewSrc:t,thumbnailSrc:n,onOpen:r,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:u,onSendViaGmail:h,isGmailConnected:p,getContactName:f,getShareUrl:g,copyToClipboard:b,formatDuration:v}){const[j,_]=N.useState(!1);return e.jsxs(fe,{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(GQs,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:j}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(Al,{className:"h-6 w-6 text-primary ml-1"})})}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:v(s.duration_seconds)}),s.status!=="ready"&&e.jsx(ze,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Ae,{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(Xi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),e.jsx("span",{children:ks(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(Ir,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),p&&s.share_token&&e.jsxs(B,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:S=>{S.stopPropagation(),h==null||h()},children:[e.jsx(Hs,{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(Xi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),e.jsx("span",{children:ks(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(Ir,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:S=>S.stopPropagation(),children:e.jsx(Lg,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",className:"bg-popover",children:[e.jsxs(Xr,{onClick:S=>{S.stopPropagation(),r()},children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(Qg,{}),e.jsxs(Xr,{onClick:S=>{S.stopPropagation(),u()},children:[e.jsx(xl,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(Xr,{onClick:S=>{S.stopPropagation(),b(g(s),"Share link")},children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(Xr,{onClick:S=>{S.stopPropagation(),o()},children:[e.jsx(SA,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(Xr,{onClick:S=>{S.stopPropagation(),c()},children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(Xr,{onClick:S=>{S.stopPropagation(),d()},children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),p&&s.share_token&&e.jsxs(Xr,{onClick:S=>{S.stopPropagation(),h==null||h()},children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(Xr,{onClick:S=>{S.stopPropagation(),i()},children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(Qg,{}),s.contact_id&&e.jsxs(Xr,{onClick:S=>{S.stopPropagation(),l()},children:[e.jsx(Xi,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(Xr,{onClick:S=>{S.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function KQs(){var $s,Ds;const s=In(),{data:t,isLoading:n,refetch:r}=UGs(),{data:a}=z1e(),{data:i}=lx(),l=HGs(),o=VGs(),{isGmailConnected:c,gmailEmail:d}=bh(),{data:u}=Xv(),{data:h=[],isLoading:p}=UQs(),[f,g]=N.useState("my"),[b,v]=N.useState(""),[j,_]=N.useState(null),[S,A]=N.useState(!1),[T,D]=N.useState(!1),[L,M]=N.useState(!1),[F,z]=N.useState(!1),[V,W]=N.useState(!1),[K,Y]=N.useState(""),[ee,ne]=N.useState(!1),[oe,pe]=N.useState(!1),[ce,de]=N.useState(!1),[ie,ye]=N.useState(!1),[_e,Me]=N.useState(""),[Te,Ce]=N.useState({}),Ee=Dt=>{if(!Dt)return"Unassigned";const St=i==null?void 0:i.find($t=>$t.id===Dt);return St?`${St.first_name} ${St.last_name||""}`.trim():"Unknown"},De=Dt=>{if(!Dt)return"0:00";const St=Math.floor(Dt/60),$t=Dt%60;return`${St}:${$t.toString().padStart(2,"0")}`},[Ie,Fe]=N.useState("all"),qe=t==null?void 0:t.filter(Dt=>{const St=Dt.category||"general";if(Ie==="general"&&St!=="general"||Ie==="open_house"&&St!=="open_house")return!1;if(!b)return!0;const $t=Ee(Dt.contact_id).toLowerCase(),ht=(Dt.title||"").toLowerCase(),Ut=(Dt.notes||"").toLowerCase();return $t.includes(b.toLowerCase())||ht.includes(b.toLowerCase())||Ut.includes(b.toLowerCase())}),ve=(t==null?void 0:t.filter(Dt=>(Dt.category||"general")==="open_house").length)||0,Je=(t==null?void 0:t.filter(Dt=>(Dt.category||"general")==="general").length)||0,we=(t||[]).filter(Dt=>Dt.status==="processing"&&Dt.bunny_video_id).map(Dt=>Dt.id).join(",");N.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const St=t.filter(ht=>ht.status==="processing"&&ht.bunny_video_id);if(!St.length)return;let $t=!1;for(const ht of St)try{const{data:Ut,error:Es}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:ht.bunny_video_id,isAgentVideo:!0}});if(Es||!Ut)continue;Ut.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:Ut.directPlayUrl,thumbnail_url:Ut.thumbnailUrl,preview_url:Ut.previewUrl,duration_seconds:Ut.length||ht.duration_seconds,updated_at:new Date().toISOString()}).eq("id",ht.id),$t=!0)}catch(Ut){console.warn("Reconcile check failed for video",ht.id,Ut)}$t&&r()})()},[we,r]),N.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const St=t.filter(Xt=>(Xt==null?void 0:Xt.bunny_video_id)&&!Te[Xt.id]);if(!St.length)return;const $t=St.map(Xt=>Xt.bunny_video_id),{data:ht,error:Ut}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:$t,isAgentVideo:!0}});if(Ut)throw Ut;const Es=(ht==null?void 0:ht.assets)||{};Ce(Xt=>{const Ys={...Xt};for(const Ss of St)Es[Ss.bunny_video_id]&&(Ys[Ss.id]={previewUrl:Es[Ss.bunny_video_id].previewUrl,thumbnailUrl:Es[Ss.bunny_video_id].thumbnailUrl});return Ys})})().catch(St=>console.warn("Failed to load signed Bunny asset URLs",St))},[t,Te]);const it=(a==null?void 0:a.total_storage_mb)||0,Ne=(a==null?void 0:a.max_storage_mb)||1024,He=it/Ne*100,$e=He>=80,Ye=He>=100,Ke=async(Dt,St)=>{await navigator.clipboard.writeText(Dt),ae.success(`${St} copied to clipboard`)},rt=Dt=>Dt.share_token?`https://video.relevelup.com/${Dt.share_token}`:Dt.playback_url||"",tt=Dt=>{const St=rt(Dt),$t=i==null?void 0:i.find(Ss=>Ss.id===Dt.contact_id),ht=Ee(Dt.contact_id),Ut=ht!=="Unassigned"?ht.split(" ")[0]:"",Es=($t==null?void 0:$t.phone)||"",Xt=`Hey${Ut?` ${Ut}`:""}! I recorded a quick video message for you. Check it out: ${St}`,Ys=Es?`sms:${Es}?body=${encodeURIComponent(Xt)}`:`sms:?body=${encodeURIComponent(Xt)}`;window.open(Ys,"_self")},at=Dt=>{const St=i==null?void 0:i.find(Ys=>Ys.id===Dt.contact_id),$t=(St==null?void 0:St.email)||"",ht=rt(Dt),Ut="Check out this video",Es=`I recorded a quick video for you: ${ht}`,Xt=$t?`mailto:${$t}?subject=${encodeURIComponent(Ut)}&body=${encodeURIComponent(Es)}`:`mailto:?subject=${encodeURIComponent(Ut)}&body=${encodeURIComponent(Es)}`;window.open(Xt,"_self")},Ge=Dt=>{var Ut;const St=rt(Dt),$t=Dt.title||"Video Message",ht=Dt.share_token?`https://video.relevelup.com/thumb/${Dt.share_token}`:((Ut=Te[Dt.id])==null?void 0:Ut.thumbnailUrl)||Dt.thumbnail_url||"";return``},dt=async Dt=>{if(!Dt.thumbnail_url&&!Dt.share_token){ae.error("Video thumbnail not available yet");return}const St=Ge(Dt),$t=rt(Dt),ht=`Watch: ${Dt.title||"Video Message"} ${$t}`;try{const Ut=new Blob([St],{type:"text/html"}),Es=new Blob([ht],{type:"text/plain"}),Xt=new ClipboardItem({"text/html":Ut,"text/plain":Es});await navigator.clipboard.write([Xt]),ae.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(ht+` `+St),ae.success("Copied! Paste into your email.")}},Bt=async Dt=>{try{ae.loading("Preparing download...",{id:"download"});const{data:St,error:$t}=await q.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:Dt.bunny_video_id,isAgentVideo:!0}});if($t||!(St!=null&&St.downloadUrl))throw new Error(($t==null?void 0:$t.message)||"Failed to get download URL");const Ut=`${((Dt.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,Es=await fetch(St.downloadUrl);if(!Es.ok)throw new Error("Failed to fetch video file");const Xt=await Es.blob(),Ys=URL.createObjectURL(Xt),Ss=document.createElement("a");Ss.href=Ys,Ss.download=Ut,Ss.rel="noreferrer",document.body.appendChild(Ss),Ss.click(),Ss.remove(),URL.revokeObjectURL(Ys),ae.success("Download started",{id:"download"})}catch(St){console.error("Download error:",St),ae.error("Could not force download (your browser may block it).",{id:"download"})}},kt=async Dt=>{_(Dt),ne(!0),Y(""),W(!0);try{const{data:St,error:$t}=await q.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:Dt.bunny_video_id,title:Dt.title,isAgentVideo:!0,shareToken:Dt.share_token}});if($t||!(St!=null&&St.html))throw new Error("Failed to generate CRM embed code");Y(St.html)}catch(St){console.error("CRM embed error:",St),ae.error("Failed to generate CRM embed code"),W(!1)}finally{ne(!1)}},Qt=Dt=>{_(Dt),A(!0)},ns=async()=>{if(j)try{await l.mutateAsync({id:j.id,bunnyVideoId:j.bunny_video_id,hardDelete:!0}),D(!1),_(null),ae.success("Video deleted successfully")}catch{ae.error("Failed to delete video")}};return e.jsx(Cs,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>g("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${f==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&(($s=u.team)==null?void 0:$s.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 ${f==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(_n,{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 ${f==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(yo,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),f==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>M(!0),children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(B,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),f==="team"?e.jsx(YQs,{videos:h,isLoading:p,searchTerm:b,setSearchTerm:v}):f==="analytics"?e.jsx(HQs,{}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:$e?"border-amber-500":Ye?"border-destructive":"",children:e.jsxs(Ae,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(c9,{className:`h-5 w-5 ${Ye?"text-destructive":$e?"text-amber-500":"text-muted-foreground"}`}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Storage Used"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[it.toFixed(1)," MB / ",Ne>=1024?`${(Ne/1024).toFixed(0)} GB`:`${Ne} MB`]})]}),e.jsx(xi,{value:Math.min(He,100),className:`h-2 ${Ye?"[&>div]:bg-destructive":$e?"[&>div]:bg-amber-500":""}`})]}),$e&&!Ye&&e.jsxs(ze,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ye&&e.jsxs(ze,{variant:"destructive",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Ye&&e.jsx("p",{className:"text-sm text-destructive mt-2",children:"You've reached your storage limit. Delete videos to record more."})]})}),e.jsx("div",{className:"flex gap-1 p-1 bg-muted rounded-lg w-fit",children:[{id:"all",label:"All",count:(t||[]).length},{id:"general",label:"My Videos",count:Je},{id:"open_house",label:"Open House Tours",count:ve}].map(Dt=>e.jsxs("button",{onClick:()=>Fe(Dt.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Ie===Dt.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[Dt.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:Dt.count})]},Dt.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search videos by contact, title, or notes...",value:b,onChange:Dt=>v(Dt.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"})}):(qe==null?void 0:qe.length)===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx(vr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No videos yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Record your first video touch to get started"}),e.jsxs(B,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(As,{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:qe==null?void 0:qe.map(Dt=>{var St,$t;return e.jsx(WQs,{video:Dt,previewSrc:(St=Te[Dt.id])==null?void 0:St.previewUrl,thumbnailSrc:($t=Te[Dt.id])==null?void 0:$t.thumbnailUrl,onOpen:()=>Qt(Dt),onDelete:()=>{_(Dt),D(!0)},onRename:()=>{_(Dt),Me(Dt.title||""),ye(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${Dt.contact_id}`),onGetEmbedCode:()=>{_(Dt),z(!0)},onCopyEmailHtml:()=>dt(Dt),onEmbedToCrm:()=>kt(Dt),onShareWithTemplate:()=>{_(Dt),pe(!0)},onSendViaGmail:()=>{_(Dt),de(!0)},isGmailConnected:c,getContactName:Ee,getShareUrl:rt,copyToClipboard:Ke,formatDuration:De},Dt.id)})}),e.jsx(bs,{open:S,onOpenChange:A,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:(j==null?void 0:j.title)||"Video Preview"}),e.jsx(Qn,{children:(j==null?void 0:j.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xi,{className:"h-3 w-3"}),Ee(j.contact_id)]})})]}),j&&e.jsxs("div",{className:"space-y-4",children:[j.status==="processing"?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6 bg-muted/50 rounded-lg border border-dashed border-border text-center space-y-4",children:[e.jsx("div",{className:"relative",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(ss,{className:"h-8 w-8 text-primary animate-spin"})})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Video is still processing"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm",children:"Your video is being encoded and will be ready shortly. This usually takes 1–3 minutes. Check back soon!"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{A(!1),r()},children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:j.playback_url?(()=>{let Dt=j.playback_url;return Dt.includes("iframe.mediadelivery.net/play/")&&(Dt=Dt.replace("/play/","/embed/"),Dt+=(Dt.includes("?")?"&":"?")+"autoplay=false&responsive=true"),Dt.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:Dt,title:j.title||"Video preview",className:"absolute top-0 left-0 w-full h-full rounded-lg",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0}):e.jsx("video",{src:j.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:j.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>ae.error("Video preview failed to load")},j.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(vr,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground ml-2",children:"Video not available"})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>tt(j),children:[e.jsx(Ci,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(B,{variant:"outline",onClick:()=>at(j),children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>Ke(rt(j),"Share link"),children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(B,{variant:"outline",onClick:()=>dt(j),children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(B,{variant:"outline",onClick:()=>Bt(j),children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),kt(j)},children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),pe(!0)},children:[e.jsx(xl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(j==null?void 0:j.share_token)&&e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),de(!0)},children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(B,{variant:"destructive",onClick:()=>{A(!1),D(!0)},children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(bs,{open:T,onOpenChange:D,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete Video"}),e.jsx(Qn,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:ns,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(H_t,{open:L,onOpenChange:M}),e.jsx(bs,{open:F,onOpenChange:z,children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Embed Video"}),e.jsx(Qn,{children:"Copy this code to embed the video on your website."})]}),j&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Embed Code"}),e.jsx(Ts,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(B,{className:"flex-1",onClick:()=>{const Dt=``;Ke(Dt,"Embed code")},children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Copy Embed Code"]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this code into your website's HTML where you want the video to appear. The video will automatically resize to fit its container."})]})]})}),j&&e.jsx(E2t,{open:oe,onOpenChange:pe,video:j,contactName:Ee(j.contact_id)}),j&&e.jsx($Qs,{open:ce,onOpenChange:de,video:j,gmailEmail:d,signedThumbnailUrl:(Ds=Te[j.id])==null?void 0:Ds.thumbnailUrl}),e.jsx(bs,{open:ie,onOpenChange:ye,children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Rename Video"}),e.jsx(Qn,{children:"Enter a new title for this video."})]}),e.jsx(ge,{value:_e,onChange:Dt=>Me(Dt.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:Dt=>{Dt.key==="Enter"&&_e.trim()&&o.mutate({id:j.id,title:_e.trim()},{onSuccess:()=>{ae.success("Video renamed"),ye(!1)}})}}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>ye(!1),children:"Cancel"}),e.jsx(B,{disabled:!_e.trim()||o.isPending,onClick:()=>{o.mutate({id:j.id,title:_e.trim()},{onSuccess:()=>{ae.success("Video renamed"),ye(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(bs,{open:V,onOpenChange:W,children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(tr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Qn,{children:"Copy this HTML code and paste it into your CRM's email editor. It uses a simple image + link format that works in all CRM email programs."})]}),ee?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ss,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):K?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"CRM Email HTML"}),e.jsx(Ts,{readOnly:!0,rows:12,value:K,className:"font-mono text-xs"})]}),e.jsxs(B,{className:"w-full",onClick:()=>{Ke(K,"CRM embed code")},children:[e.jsx(ta,{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 YQs({videos:s,isLoading:t,searchTerm:n,setSearchTerm:r}){const a=N.useMemo(()=>{if(!n)return s;const o=n.toLowerCase();return s.filter(c=>(c.title||"").toLowerCase().includes(o)||(c.owner_name||"").toLowerCase().includes(o)||(c.recipient_name||"").toLowerCase().includes(o))},[s,n]),i=N.useMemo(()=>{const o=new Map;return a.forEach(c=>{const d=o.get(c.owner_user_id);d?d.videos.push(c):o.set(c.owner_user_id,{name:c.owner_name,avatar:c.owner_avatar_url,videos:[c]})}),Array.from(o.entries())},[a]),l=o=>{if(!o)return"0:00";const c=Math.floor(o/60),d=o%60;return`${c}:${d.toString().padStart(2,"0")}`};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search team videos by title, owner, or recipient...",value:n,onChange:o=>r(o.target.value),className:"pl-10"})]}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):a.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx(_n,{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(aa,{className:"h-7 w-7",children:[e.jsx(ri,{src:c.avatar||""}),e.jsx(ia,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(ze,{variant:"secondary",className:"text-xs",children:c.videos.length})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:c.videos.map(d=>e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs("div",{className:"relative aspect-video bg-muted flex items-center justify-center",children:[d.thumbnail_url?e.jsx("img",{src:d.thumbnail_url,alt:d.title||"Video",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:u=>{u.target.style.display="none"}}):e.jsx(vr,{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(Ae,{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(Xi,{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(Ir,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),ks(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const ZQs=()=>{const{user:s}=gs();return lt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_deals",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},uXe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function QQs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=ZQs(),[a,i]=N.useState(""),[l,o]=N.useState("all"),c=N.useMemo(()=>{if(!n)return new Map;const g=new Map;let b=0;return n.forEach(v=>{g.has(v.owner_user_id)||(g.set(v.owner_user_id,{name:v.owner_name||"Unknown",avatar:v.owner_avatar_url,color:uXe[b%uXe.length]}),b++)}),g},[n]),d=N.useMemo(()=>Array.from(c.entries()).map(([g,b])=>({id:g,...b})),[c]),u=N.useMemo(()=>{if(!n)return[];let g=n;if(l!=="all"&&(g=g.filter(b=>b.owner_user_id===l)),a.trim()){const b=a.toLowerCase();g=g.filter(v=>{var j,_,S,A;return v.deal_name.toLowerCase().includes(b)||((j=v.contact_name)==null?void 0:j.toLowerCase().includes(b))||((_=v.property_address)==null?void 0:_.toLowerCase().includes(b))||((S=v.city)==null?void 0:S.toLowerCase().includes(b))||((A=v.owner_name)==null?void 0:A.toLowerCase().includes(b))})}return g},[n,a,l]),h=N.useMemo(()=>{const g=new Map;return u.forEach(b=>{const v=b.stage_name||"Unknown";g.has(v)||g.set(v,{name:v,color:b.stage_color,icon:b.stage_icon,deals:[],totalValue:0});const j=g.get(v);j.deals.push(b),j.totalValue+=b.sale_price||0}),Array.from(g.values())},[u]),p=g=>g>=1e6?`$${(g/1e6).toFixed(1)}M`:g>=1e3?`$${(g/1e3).toFixed(0)}K`:`$${g.toFixed(0)}`,f=g=>g?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(g):null;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(_n,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search deals...",value:a,onChange:g=>i(g.target.value),className:"pl-9"})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"All Members"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Members"}),d.map(g=>e.jsx(Ze,{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(Ws,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(Ws,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(Ws,{className:"h-24 w-full rounded-lg"})]},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(_n,{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 b=g.icon&&M0e[g.icon]||dm;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(b,{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(ze,{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:p(g.totalValue)})]}),e.jsx(mi,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:g.deals.map(v=>{const j=c.get(v.owner_user_id);return e.jsx(XQs,{deal:v,ownerColor:(j==null?void 0:j.color)||"#888",ownerName:(j==null?void 0:j.name)||"Unknown",ownerAvatar:(j==null?void 0:j.avatar)||null,formatPrice:f},v.id)})})})]},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 XQs({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(aa,{className:"h-4 w-4",children:[e.jsx(ri,{src:r||""}),e.jsx(ia,{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(ze,{variant:"outline",className:Et("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(zr,{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(Zl,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function JQs({members:s,enabledMembers:t,onToggleMember:n,isOpen:r,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:Et("shrink-0 border-r border-border/50 bg-muted/20 transition-all duration-300 flex flex-col",r?"w-[220px]":"w-[48px]"),children:[e.jsx("div",{className:"p-2 border-b border-border/50 shrink-0",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(_n,{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(fl,{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(mi,{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:Et("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(aa,{className:"h-7 w-7",children:[e.jsx(ri,{src:l.avatar_url||""}),e.jsx(ia,{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:Et("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(vn,{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(aa,{className:Et("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(ri,{src:l.avatar_url||""}),e.jsx(ia,{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 hXe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function eXs(){const s=fa(),{data:t}=Xv(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=lt({queryKey:["team-pipeline-members",r,s],queryFn:async()=>{const{data:i,error:l}=await q.from("team_members").select("user_id, role").eq("team_id",r).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(u=>u.user_id),{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((u,h)=>({id:u.id,name:u.name||"Unknown",avatar_url:u.avatar_url,color:hXe[h%hXe.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function tXs(s){return lt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at), deal_pipeline_stages(name) `).in("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return(t||[]).map(r=>{var a;return{...r,_stage_name:((a=r.deal_pipeline_stages)==null?void 0:a.name)||null}})},enabled:s.length>0})}function sXs(){const s=fa();return lt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:n}=await q.from("deal_tags").select("id, deal_id, tag").eq("owner_user_id",s);if(n)throw n;const r=t||[],a={},i=new Set;r.forEach(o=>{a[o.deal_id]||(a[o.deal_id]=[]),a[o.deal_id].push(o.tag),i.add(o.tag)});const l=Array.from(i).sort((o,c)=>o.localeCompare(c));return{tags:r,byDeal:a,unique:l}},enabled:!!s})}function A2t({stages:s,currentStageId:t,onStageSelect:n,disabled:r}){const[a,i]=N.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&n(c.id,c.name),i(!1)};return e.jsxs(jc,{open:a,onOpenChange:i,children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1.5",disabled:r,onClick:c=>c.stopPropagation(),children:[l&&e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:l.color}}),e.jsx("span",{className:"max-w-[80px] truncate",children:(l==null?void 0:l.name)||"Move"}),e.jsx(ga,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(cc,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&M0e[c.icon]||dm,u=c.id===t;return e.jsxs(Xr,{onClick:()=>o(c),className:Et("flex items-center gap-2 cursor-pointer",u&&"bg-accent"),children:[e.jsx("div",{className:"w-5 h-5 rounded flex items-center justify-center shrink-0",style:{backgroundColor:`${c.color}20`},children:e.jsx(d,{className:"h-3 w-3",style:{color:c.color}})}),e.jsx("span",{className:"flex-1",children:c.name}),u&&e.jsx(Lr,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const nXs={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"}},rXs={low:{color:"bg-slate-100 text-slate-600",dot:"bg-slate-400"},medium:{color:"bg-amber-100 text-amber-700",dot:"bg-amber-500"},high:{color:"bg-orange-100 text-orange-700",dot:"bg-orange-500"},urgent:{color:"bg-red-100 text-red-700",dot:"bg-red-500"}};function M2t({deal:s,onClick:t,isDragging:n,stages:r,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null}){var _,S;const c=kR(),d=nXs[s.deal_type],u=rXs[s.priority],h=N.useMemo(()=>s.target_close_date?Yv(ll(s.target_close_date),new Date):null,[s.target_close_date]),p=h!==null&&h<0,f=h!==null&&h<=7&&h>=0,g=N.useMemo(()=>{var D;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const A=((D=s.listing)==null?void 0:D.created_at)||s.listing_date;if(!A)return null;const T=s.contract_date?ll(s.contract_date):new Date;return Yv(T,ll(A))},[s]),b=l&&!s.scorecard_transaction_id,v=!!s.scorecard_transaction_id,j=A=>A?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(A):null;return e.jsx(fe,{className:Et("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",n&&"opacity-50 rotate-2 shadow-xl",p&&"border-red-200 bg-red-50/30",b&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),onClick:t,style:o?{borderLeftWidth:4,borderLeftColor:o.color}:void 0,children:e.jsxs(Ae,{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(aa,{className:"h-4 w-4",children:[e.jsx(ri,{src:o.avatar_url||""}),e.jsx(ia,{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(ze,{variant:"outline",className:Et("text-[10px] px-1.5 py-0 shrink-0",d.color),children:d.label})]}),s.contact&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(aa,{className:"h-5 w-5",children:e.jsxs(ia,{className:"text-[10px] bg-primary/10 text-primary",children:[(_=s.contact.first_name)==null?void 0:_[0],(S=s.contact.last_name)==null?void 0:S[0]]})}),e.jsxs("span",{className:"truncate",children:[s.contact.first_name," ",s.contact.last_name]})]}),s.listing&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(El,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),b&&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(vo,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),v&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(xr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),g!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(cm,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Et("font-medium",g>90?"text-red-600":g>60?"text-amber-600":"text-muted-foreground"),children:[g," 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(zr,{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(Zl,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:j(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",j(s.expected_commission)," GCI"]}),(()=>{const A=Ev(s);return A!==null&&A!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",j(A)," Net"]}):null})()]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:Et("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",u.color),children:[e.jsx("div",{className:Et("w-1.5 h-1.5 rounded-full",u.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[s.probability,"%"]})]}),i&&c&&r&&a?e.jsx(A2t,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(A,T)=>a(s.id,A,T)}):s.target_close_date?e.jsxs("div",{className:Et("flex items-center gap-1 text-[10px]",p&&"text-red-600",f&&!p&&"text-amber-600",!p&&!f&&"text-muted-foreground"),children:[p?e.jsx(Gi,{className:"h-3 w-3"}):e.jsx(yr,{className:"h-3 w-3"}),e.jsx("span",{children:p?`${Math.abs(h)}d overdue`:f?`${h}d left`:ks(ll(s.target_close_date),"MMM d")})]}):null]})]})})}function aXs({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d}){const u=N.useRef(null),h=t.reduce((v,j)=>v+(j.expected_price||0),0),p=t.reduce((v,j)=>v+(j.expected_commission||0),0),f=t.reduce((v,j)=>v+(Ev(j)||0),0),g=v=>v>=1e6?`$${(v/1e6).toFixed(1)}M`:v>=1e3?`$${(v/1e3).toFixed(0)}K`:`$${v.toFixed(0)}`,b=s.icon&&M0e[s.icon]||dm;return e.jsxs("div",{ref:u,className:Et("flex flex-col h-full min-w-[280px] max-w-[320px] bg-muted/30 rounded-xl border border-border/50 transition-all duration-200",o&&"border-primary/50 bg-primary/5 ring-2 ring-primary/20"),onDragOver:v=>i(v,s.id),onDrop:v=>l(v,s.id),children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center",style:{backgroundColor:`${s.color}20`},children:e.jsx(b,{className:"h-4 w-4",style:{color:s.color}})}),e.jsx("div",{children:e.jsx("h3",{className:"font-semibold text-sm",children:s.name})})]}),e.jsx(ze,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length})]}),h>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:g(h)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[g(p)," GCI"]}),f>0&&f!==p&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[g(f)," Net"]})]})]})]}),e.jsx(mi,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(v=>e.jsx("div",{draggable:!0,onDragStart:j=>{j.dataTransfer.effectAllowed="move",a(v.id,s.id)},children:e.jsx(M2t,{deal:v,onClick:()=>n(v),isWonStage:c,ownerInfo:(d==null?void 0:d(v))||null})},v.id)),t.length===0&&e.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground text-sm",children:[e.jsx("p",{className:"mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-xs",children:"Drag deals here or add new"})]})]})}),e.jsx("div",{className:"p-2 border-t border-border/50 shrink-0",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>r(s.id),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function iXs({stats:s,isLoading:t}){const n=a=>a>=1e6?`$${(a/1e6).toFixed(1)}M`:a>=1e3?`$${(a/1e3).toFixed(0)}K`:`$${a.toLocaleString()}`,r=[{label:"Active Deals",value:(s==null?void 0:s.activeDeals)||0,icon:wc,color:"text-blue-500",bgColor:"bg-blue-500/10"},{label:"Weighted GCI",value:n((s==null?void 0:s.weightedGCI)||0),icon:S9,color:"text-indigo-500",bgColor:"bg-indigo-500/10",tooltip:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:n((s==null?void 0:s.weightedNet)||0),icon:SL,color:"text-teal-500",bgColor:"bg-teal-500/10",tooltip:"Net to Agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:n((s==null?void 0:s.ytdWonNet)||0),icon:QS,color:"text-green-500",bgColor:"bg-green-500/10",subtitle:`${(s==null?void 0:s.ytdWonDeals)||0} deals`,tooltip:"Net commission from deals closed this year"},{label:"Projected Annual",value:n((s==null?void 0:s.projectedAnnualNet)||0),icon:mo,color:"text-amber-500",bgColor:"bg-amber-500/10",tooltip:"YTD Closed Net + Weighted Active Net"}];return t?e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[1,2,3,4,5].map(a=>e.jsx(fe,{className:"animate-pulse",children:e.jsx(Ae,{className:"p-4",children:e.jsx("div",{className:"h-10 bg-muted rounded"})})},a))}):e.jsx(Kw,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:r.map(a=>{const i=e.jsx(fe,{className:"border-border/50 hover:shadow-sm transition-shadow",children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Et("p-2 rounded-lg",a.bgColor),children:e.jsx(a.icon,{className:Et("h-5 w-5",a.color)})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:a.label}),e.jsx("p",{className:"text-xl font-bold",children:a.value}),"subtitle"in a&&a.subtitle&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a.subtitle})]})]})})},a.label);return"tooltip"in a&&a.tooltip?e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:i}),e.jsx(yc,{children:e.jsx("p",{children:a.tooltip})})]},a.label):i})})})}function oXs({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=gs(),[a,i]=N.useState(s.portal_enabled);if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(ze,{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(uy,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(hy,{className:"w-full p-4 flex items-center justify-between hover:bg-muted/50 transition-colors rounded-t-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(ze,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(io,{className:Et("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(my,{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(se,{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(vn,{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(se,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(db,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Et("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(Fd,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Rc,{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:Et("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(Fd,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(lc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm font-medium",children:"Public"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Shareable link"})]})]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/30",children:[e.jsx(hi,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"require_onboarding",className:"text-sm font-medium cursor-pointer",children:"Require client onboarding before portal access"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Client confirms contact details + preferences before viewing portal. Info is saved to your contacts."})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(hi,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(se,{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(se,{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(se,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(ge,{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(se,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(ge,{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(se,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(ge,{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(se,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(us,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"email",children:"Email"}),e.jsxs(Ze,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const lXs=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],cXs=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function dXs({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=ZU(),{data:i}=lx(),{data:l}=upt(),o=Gye(),c=k2t(),d=S2t(),u=NLe(),[h,p]=N.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[f,g]=N.useState(""),[b,v]=N.useState(!1),[j,_]=N.useState(!1),[S,A]=N.useState({first_name:"",last_name:"",email:"",phone:""}),T=(l==null?void 0:l.filter(K=>((n==null?void 0:n.listing_id)===K.id,!0)))||[],[D,L]=N.useState({deal_name:"",deal_type:"buyer",stage_id:"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",team_split_pct:"",referral_fee_pct:"",franchise_fee_pct:"",transaction_fee:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""});N.useEffect(()=>{var K,Y,ee,ne,oe,pe,ce,de;s&&(n?(L({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:((K=n.expected_price)==null?void 0:K.toString())||"",commission_percentage:((Y=n.commission_percentage)==null?void 0:Y.toString())||"3",brokerage_split_pct:((ee=n.brokerage_split_pct)==null?void 0:ee.toString())||"",team_split_pct:((ne=n.team_split_pct)==null?void 0:ne.toString())||"",referral_fee_pct:((oe=n.referral_fee_pct)==null?void 0:oe.toString())||"",franchise_fee_pct:((pe=n.franchise_fee_pct)==null?void 0:pe.toString())||"",transaction_fee:((ce=n.transaction_fee)==null?void 0:ce.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?ll(n.target_close_date):void 0,contract_date:n.contract_date?ll(n.contract_date):void 0,listing_date:n.listing_date?ll(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&g(`${n.contact.first_name} ${n.contact.last_name}`)):(L({deal_name:"",deal_type:"buyer",stage_id:r||((de=a==null?void 0:a[0])==null?void 0:de.id)||"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",team_split_pct:"",referral_fee_pct:"",franchise_fee_pct:"",transaction_fee:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""}),g(""),p({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,n,r,a]);const M=i==null?void 0:i.filter(K=>{var ye,_e,Me,Te,Ce;const Y=f.toLowerCase().trim();if(!Y)return!0;const ee=((ye=K.first_name)==null?void 0:ye.toLowerCase())||"",ne=((_e=K.last_name)==null?void 0:_e.toLowerCase())||"",oe=((Me=K.email)==null?void 0:Me.toLowerCase())||"",pe=((Ce=(Te=K.phone)==null?void 0:Te.toLowerCase)==null?void 0:Ce.call(Te))||"",ce=`${ee} ${ne}`.trim(),de=`${ne} ${ee}`.trim();if(ce.includes(Y)||de.includes(Y)||ee.includes(Y)||ne.includes(Y)||oe.includes(Y)||pe.includes(Y))return!0;const ie=Y.split(/\s+/).filter(Boolean);return ie.length>1?ie.every(Ee=>ee.includes(Ee)||ne.includes(Ee)||oe.includes(Ee)||pe.includes(Ee)):!1}).slice(0,8),F=()=>{const K=parseFloat(D.expected_price)||0,Y=parseFloat(D.commission_percentage)||0;return K*(Y/100)},z=()=>{const K=F();if(!K)return null;const Y=parseFloat(D.brokerage_split_pct)||0,ee=parseFloat(D.team_split_pct)||0,ne=parseFloat(D.referral_fee_pct)||0,oe=parseFloat(D.franchise_fee_pct)||0,pe=parseFloat(D.transaction_fee)||0;if(D.commission_calc_method==="referral_first"){let de=K;ne&&(de-=K*ne/100);let ie=de;return Y&&(ie-=de*Y/100),ee&&(ie-=K*ee/100),oe&&(ie-=K*oe/100),pe&&(ie-=pe),Math.max(0,ie)}let ce=K;return Y&&(ce=ce*((100-Y)/100)),ee&&(ce=ce*((100-ee)/100)),ne&&(ce=ce-K*ne/100),oe&&(ce=ce-K*oe/100),pe&&(ce=ce-pe),Math.max(0,ce)},V=async K=>{var Y,ee,ne;if(K.preventDefault(),!D.deal_name.trim()){ae.error("Please enter a deal name");return}try{const oe={deal_name:D.deal_name,deal_type:D.deal_type,stage_id:D.stage_id||null,contact_id:D.contact_id||null,listing_id:D.listing_id||null,property_address:D.property_address||null,city:D.city||null,state:D.state||null,zip_code:D.zip_code||null,expected_price:D.expected_price?parseFloat(D.expected_price):null,expected_commission:F()||null,commission_percentage:D.commission_percentage?parseFloat(D.commission_percentage):3,brokerage_split_pct:D.brokerage_split_pct?parseFloat(D.brokerage_split_pct):null,team_split_pct:D.team_split_pct?parseFloat(D.team_split_pct):null,referral_fee_pct:D.referral_fee_pct?parseFloat(D.referral_fee_pct):null,franchise_fee_pct:D.franchise_fee_pct?parseFloat(D.franchise_fee_pct):null,transaction_fee:D.transaction_fee?parseFloat(D.transaction_fee):null,commission_calc_method:D.commission_calc_method,target_close_date:((Y=D.target_close_date)==null?void 0:Y.toISOString().split("T")[0])||null,contract_date:((ee=D.contract_date)==null?void 0:ee.toISOString().split("T")[0])||null,listing_date:((ne=D.listing_date)==null?void 0:ne.toISOString().split("T")[0])||null,priority:D.priority,probability:parseInt(D.probability)||50,notes:D.notes||null};if(n)await d.mutateAsync({id:n.id,...oe}),ae.success("Deal updated successfully");else{const pe=await c.mutateAsync(oe);if(ae.success("Deal created successfully"),h.portal_enabled&&(pe!=null&&pe.id))try{await u.mutateAsync({deal_id:pe.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")}},W=c.isPending||d.isPending;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(Qn,{children:n?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:V,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(se,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(ge,{id:"deal_name",value:D.deal_name,onChange:K=>L(Y=>({...Y,deal_name:K.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Deal Type"}),e.jsxs(us,{value:D.deal_type,onValueChange:K=>L(Y=>({...Y,deal_type:K})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:lXs.map(K=>e.jsx(Ze,{value:K.value,children:K.label},K.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Stage"}),e.jsxs(us,{value:D.stage_id||"none",onValueChange:K=>L(Y=>({...Y,stage_id:K==="none"?"":K})),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select stage"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No Stage"}),a==null?void 0:a.map(K=>e.jsx(Ze,{value:K.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:K.color}}),K.name]})},K.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{value:f,onChange:K=>{g(K.target.value),v(!0),_(!1),K.target.value||L(Y=>({...Y,contact_id:""}))},onFocus:()=>v(!0),placeholder:"Search contacts...",className:"pl-9"}),b&&f&&e.jsxs("div",{className:"absolute z-10 w-full mt-1 bg-background border rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[M&&M.length>0?M.map(K=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{L(Y=>({...Y,contact_id:K.id})),g(`${K.first_name} ${K.last_name}`),v(!1)},children:[e.jsx(Xi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[K.first_name," ",K.last_name]}),K.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:K.email})]},K.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 K=f.trim().split(/\s+/);A({first_name:K[0]||"",last_name:K.slice(1).join(" ")||"",email:"",phone:""}),_(!0),v(!1)},children:[e.jsx(Fo,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',f.trim(),'"']})]})]})]}),j&&e.jsxs("div",{className:"border rounded-lg p-3 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(Fo,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>_(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ge,{placeholder:"First name *",value:S.first_name,onChange:K=>A(Y=>({...Y,first_name:K.target.value})),className:"h-8 text-sm"}),e.jsx(ge,{placeholder:"Last name",value:S.last_name,onChange:K=>A(Y=>({...Y,last_name:K.target.value})),className:"h-8 text-sm"}),e.jsx(ge,{placeholder:"Email",type:"email",value:S.email,onChange:K=>A(Y=>({...Y,email:K.target.value})),className:"h-8 text-sm"}),e.jsx(ge,{placeholder:"Phone",type:"tel",value:S.phone,onChange:K=>A(Y=>({...Y,phone:K.target.value})),className:"h-8 text-sm"})]}),e.jsx(B,{type:"button",size:"sm",className:"w-full h-8",disabled:!S.first_name.trim()||o.isPending,onClick:async()=>{try{const K=await o.mutateAsync({first_name:S.first_name.trim(),last_name:S.last_name.trim()||null,email:S.email.trim()||null,phone:S.phone.trim()||null});K&&(L(Y=>({...Y,contact_id:K.id})),g(`${K.first_name} ${K.last_name||""}`.trim()),_(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fo,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),T.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(El,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(us,{value:D.listing_id||"none",onValueChange:K=>{const Y=K==="none"?"":K,ee=T.find(ne=>ne.id===Y);L(ee?ne=>{var oe;return{...ne,listing_id:Y,deal_type:"seller",property_address:ee.property_address||ne.property_address,city:ee.city||ne.city,state:ee.state||ne.state,expected_price:((oe=ee.price)==null?void 0:oe.toString())||ne.expected_price}}:ne=>({...ne,listing_id:Y}))},children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select a listing to sync status..."})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"None"}),T.map(K=>e.jsx(Ze,{value:K.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:K.property_address||`${K.city}, ${K.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(K.price/1e3).toFixed(0),"K"]})]})},K.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(se,{htmlFor:"property_address",children:"Address"}),e.jsx(ge,{id:"property_address",value:D.property_address,onChange:K=>L(Y=>({...Y,property_address:K.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(ge,{id:"city",value:D.city,onChange:K=>L(Y=>({...Y,city:K.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ge,{id:"state",value:D.state,onChange:K=>L(Y=>({...Y,state:K.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(ge,{id:"zip_code",value:D.zip_code,onChange:K=>L(Y=>({...Y,zip_code:K.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(se,{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(ge,{id:"expected_price",type:"number",value:D.expected_price,onChange:K=>L(Y=>({...Y,expected_price:K.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{id:"commission_percentage",type:"number",step:"0.1",value:D.commission_percentage,onChange:K=>L(Y=>({...Y,commission_percentage:K.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(se,{children:"Expected GCI"}),e.jsx(ge,{value:F()?`$${F().toLocaleString()}`:"-",disabled:!0,className:"bg-muted"})]})]}),e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"text-xs font-medium text-muted-foreground cursor-pointer hover:text-foreground flex items-center gap-1 py-1",children:[e.jsx("span",{className:"group-open:rotate-90 transition-transform text-[10px]",children:"▶"}),"Commission Splits (optional)"]}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/50",children:[e.jsx(se,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(us,{value:D.commission_calc_method,onValueChange:K=>L(Y=>({...Y,commission_calc_method:K})),children:[e.jsx(cs,{className:"h-7 text-xs",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(Ze,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),D.commission_calc_method==="referral_first"&&e.jsx("p",{className:"text-[10px] text-muted-foreground bg-blue-50 dark:bg-blue-950/30 p-2 rounded",children:"💡 Referral fee is deducted from GCI first, then the brokerage split is applied to the remaining amount."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{type:"number",step:"1",min:"0",max:"100",value:D.brokerage_split_pct,onChange:K=>L(Y=>({...Y,brokerage_split_pct:K.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(se,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{type:"number",step:"1",min:"0",max:"100",value:D.team_split_pct,onChange:K=>L(Y=>({...Y,team_split_pct:K.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(se,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{type:"number",step:"1",min:"0",max:"100",value:D.referral_fee_pct,onChange:K=>L(Y=>({...Y,referral_fee_pct:K.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(se,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{type:"number",step:"1",min:"0",max:"100",value:D.franchise_fee_pct,onChange:K=>L(Y=>({...Y,franchise_fee_pct:K.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(se,{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(ge,{type:"number",step:"1",min:"0",value:D.transaction_fee,onChange:K=>L(Y=>({...Y,transaction_fee:K.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(se,{className:"text-xs",children:"Net to Agent"}),e.jsx(ge,{value:z()?`$${Math.round(z()).toLocaleString()}`:"-",disabled:!0,className:"bg-muted h-8 text-sm font-semibold"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Dates & Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Target Close Date"}),e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!D.target_close_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),D.target_close_date?ks(D.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:D.target_close_date,onSelect:K=>L(Y=>({...Y,target_close_date:K})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contract Date"}),e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!D.contract_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),D.contract_date?ks(D.contract_date,"PPP"):"Pick a date"]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:D.contract_date,onSelect:K=>L(Y=>({...Y,contract_date:K})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),(D.deal_type==="seller"||D.deal_type==="dual")&&!D.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(se,{children:"Listing Date (for Days on Market)"}),e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!D.listing_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),D.listing_date?ks(D.listing_date,"PPP"):"Pick a date"]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:D.listing_date,onSelect:K=>L(Y=>({...Y,listing_date:K})),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(se,{children:"Priority"}),e.jsxs(us,{value:D.priority,onValueChange:K=>L(Y=>({...Y,priority:K})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:cXs.map(K=>e.jsx(Ze,{value:K.value,children:K.label},K.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{type:"number",min:"0",max:"100",value:D.probability,onChange:K=>L(Y=>({...Y,probability:K.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(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Ts,{id:"notes",value:D.notes,onChange:K=>L(Y=>({...Y,notes:K.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(oXs,{formData:h,onChange:p}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:W,children:[W&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function uXs({dealId:s}){const t=fa(),n=Gt(),[r,a]=N.useState(""),[i,l]=N.useState(!1),{data:o=[]}=lt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:g,error:b}=await q.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(b)throw b;return g},enabled:!!s}),{data:c=[]}=lt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:g,error:b}=await q.from("deal_tags").select("tag").eq("owner_user_id",t);if(b)throw b;return[...new Set(g.map(j=>j.tag))].sort()},enabled:!!t}),d=gt({mutationFn:async g=>{if(!t)throw new Error("Not authenticated");const{error:b}=await q.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:g.trim()});if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=gt({mutationFn:async g=>{const{error:b}=await q.from("deal_tags").delete().eq("id",g);if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const g=r.trim();g&&(o.some(b=>b.tag.toLowerCase()===g.toLowerCase())||d.mutate(g))},p=o.map(g=>g.tag.toLowerCase()),f=c.filter(g=>g.toLowerCase().includes(r.toLowerCase())&&!p.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(ze,{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(Fn,{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(As,{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(ge,{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&&f.length>0&&e.jsx("div",{className:"absolute z-20 w-full mt-1 bg-background border rounded shadow-lg max-h-32 overflow-y-auto",children:f.map(g=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:b=>{b.preventDefault(),d.mutate(g)},children:g},g))})]})]})}function hXs(s){return lt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function mXs(){const s=fa(),t=Gt();return gt({mutationFn:async({dealId:n,file:r})=>{if(!s)throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await q.storage.from("deal-files").upload(i,r);if(l)throw l;const{data:o,error:c}=await q.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]})}})}function pXs(){const s=Gt();return gt({mutationFn:async({fileId:t,storagePath:n,dealId:r})=>{await q.storage.from("deal-files").remove([n]);const{error:a}=await q.from("deal_files").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function fXs(){const s=Gt();return gt({mutationFn:async({fileId:t,visible:n,dealId:r})=>{const{error:a}=await q.from("deal_files").update({visible_on_portal:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}async function xXs(s){const{data:t,error:n}=await q.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const mXe={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function I2t({open:s,onOpenChange:t}){const{data:n,isLoading:r}=BWs(),a=$Ws(),i=UWs(),l=qWs(),[o,c]=N.useState(!1),[d,u]=N.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,p]=N.useState(""),f=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((n==null?void 0:n.length)||0)+1}),u({question_text:"",field_type:"text",options:[],is_required:!1}),p(""),c(!1),ae.success("Question added")}catch{ae.error("Failed to add question")}},g=async _=>{try{await l.mutateAsync(_),ae.success("Question removed")}catch{ae.error("Failed to remove question")}},b=async(_,S)=>{try{await i.mutateAsync({id:_,is_required:S})}catch{ae.error("Failed to update question")}},v=()=>{h.trim()&&(u(_=>({..._,options:[..._.options,h.trim()]})),p(""))},j=_=>{u(S=>({...S,options:S.options.filter((A,T)=>T!==_)}))};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(ws,{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(mi,{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(ss,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(_=>{var S;return e.jsx("div",{className:"border rounded-lg p-3 space-y-2",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Uu,{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(ze,{variant:"secondary",className:"text-xs",children:mXe[_.field_type]||_.field_type}),_.is_required&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Required"})]}),_.field_type==="dropdown"&&((S=_.options)==null?void 0:S.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(vn,{checked:_.is_required,onCheckedChange:A=>b(_.id,A),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>g(_.id),children:e.jsx(bn,{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(se,{className:"text-sm font-medium",children:"Question"}),e.jsx(ge,{value:d.question_text,onChange:_=>u(S=>({...S,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(se,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(mXe).map(([_,S])=>e.jsx("button",{type:"button",onClick:()=>u(A=>({...A,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:S},_))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((_,S)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"flex-1 text-sm bg-muted/50 rounded px-2 py-1",children:_}),e.jsx("button",{onClick:()=>j(S),className:"text-muted-foreground hover:text-destructive",children:e.jsx(Fn,{className:"h-3.5 w-3.5"})})]},S)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:h,onChange:_=>p(_.target.value),onKeyDown:_=>_.key==="Enter"&&(_.preventDefault(),v()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(B,{variant:"outline",size:"sm",onClick:v,disabled:!h.trim(),className:"h-8",children:e.jsx(As,{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(vn,{checked:d.is_required,onCheckedChange:_=>u(S=>({...S,is_required:_}))}),e.jsx(se,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:f,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(ss,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Add Question"]})]})]})]})}),e.jsxs("div",{className:"flex justify-between pt-4 border-t shrink-0",children:[o?e.jsx("div",{}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function gXs({override:s,onChange:t}){const n=fa(),{data:r}=Hht(),[a,i]=N.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){ae.error("Image must be under 5MB");return}i(u);try{const h=await Ght(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){ae.error(`Upload failed: ${h.message||h}`)}finally{i(null)}}},c=Object.values(s||{}).some(d=>d!=null&&d!=="");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-primary/5 border border-primary/10",children:[e.jsx(un,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["These settings ",e.jsx("span",{className:"font-medium text-foreground",children:"override your global Portal Branding"})," for this deal only. Leave any field empty to use your global default."]})]}),e.jsx(pXe,{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(pXe,{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(fXe,{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(fXe,{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(se,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(ge,{value:s.tagline||"",onChange:d=>l({tagline:d.target.value||null}),placeholder:(r==null?void 0:r.tagline)||"Your trusted real estate advisor",maxLength:80,className:"mt-1"})]}),c&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(bn,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function pXe({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(se,{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:Et("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(nl,{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(ss,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Sa,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx(B,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})]})}function fXe({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(se,{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:Et("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(ge,{value:t||"",onChange:l=>r(l.target.value||null),placeholder:n||"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"}),t&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>r(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(bn,{className:"h-3 w-3"})})]})]})}function yXs({portalId:s,agentUserId:t}){const n=Gt(),{data:r,isLoading:a}=lt({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:h}=await q.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),p=h==null?void 0:h.brokerage_id,f=q.from("vendors").select("*").eq("is_active",!0),g=p?f.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${p})`):f.eq("owner_type","agent").eq("owner_user_id",t),[{data:b,error:v},{data:j},{data:_}]=await Promise.all([g.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(v)throw v;const S=new Map;(j||[]).forEach(T=>S.set(T.vendor_id,T.is_visible));const A=new Map;return(_||[]).forEach(T=>A.set(T.vendor_id,T.is_visible)),{vendors:b||[],selMap:S,overrideMap:A}}}),i=gt({mutationFn:async({vendorId:h,isVisible:p})=>{const{data:f}=await q.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(f){const{error:g}=await q.from("portal_vendor_overrides").update({is_visible:p}).eq("id",f.id);if(g)throw g}else{const{error:g}=await q.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:p});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(ss,{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(fb,{className:"w-10 h-10 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors in your library yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Add vendors in the Vendors tab of Client Portals, then toggle them here per portal."})]});const d=h=>{const p=c.get(h.id);if(p!==void 0)return p;if(h.is_required)return!0;const f=o.get(h.id);return f===void 0?!0:f!==!1},u=h=>{var p;return((p=ZD.find(f=>f.value===h))==null?void 0:p.label)||h};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Choose which vendors from your library appear in ",e.jsx("em",{children:"this specific portal"}),". Changes here only affect this deal — your global vendor library and other portals are unaffected."]}),e.jsx(mi,{className:"h-[400px] rounded-lg border",children:e.jsx("div",{className:"divide-y",children:l.map(h=>{const p=d(h);return e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-muted border flex items-center justify-center overflow-hidden shrink-0",children:h.logo_url?e.jsx("img",{src:h.logo_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-muted-foreground",children:h.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.company||h.name}),e.jsx(ze,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx(ze,{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(vn,{checked:p,disabled:h.is_required||i.isPending,onCheckedChange:f=>i.mutate({vendorId:h.id,isVisible:f})})]},h.id)})})})]})}function vXs({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=N.useState(""),[o,c]=N.useState(!1),{data:d,isLoading:u}=lt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:g,error:b}=await q.from("client_portals").select(` id, slug, client_name, client_email, deal_id, archived_at, deal_pipeline (id, deal_name, deal_type, property_address) `).eq("owner_user_id",t).neq("id",s).is("archived_at",null).eq("is_enabled",!0);if(b)throw b;return g},enabled:o||!!r}),h=N.useMemo(()=>!r||!d?null:d.find(g=>g.id===r),[r,d]),p=N.useMemo(()=>!d||!n?[]:d.filter(g=>{var b;return((b=g.client_email)==null?void 0:b.toLowerCase())===n.toLowerCase()&&g.id!==s}),[d,n,s]),f=N.useMemo(()=>{if(!d||!i.trim())return[];const g=i.toLowerCase();return d.filter(b=>{var j,_,S,A;const v=b.deal_pipeline;return((j=b.client_name)==null?void 0:j.toLowerCase().includes(g))||((_=b.client_email)==null?void 0:_.toLowerCase().includes(g))||((S=v==null?void 0:v.deal_name)==null?void 0:S.toLowerCase().includes(g))||((A=v==null?void 0:v.property_address)==null?void 0:A.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(se,{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(El,{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(B,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(VA,{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(se,{className:"text-sm font-medium",children:"Link Another Transaction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Combine buy + sell into one portal"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(El,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&p.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground font-medium",children:"✨ Suggested match (same client email)"}),p.map(g=>{const b=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(ze,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(b==null?void 0:b.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:(b==null?void 0:b.deal_name)||g.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:b==null?void 0:b.property_address})]}),e.jsx(El,{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(_r,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ge,{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(ss,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),f.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:f.map(g=>{const b=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(ze,{variant:"outline",className:"text-[10px] shrink-0",children:(b==null?void 0:b.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:(b==null?void 0:b.deal_name)||g.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:g.client_email})]})]},g.id)})}),i&&f.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function k8e({contactId:s,onVideoReady:t}){const[n,r]=N.useState(!1),[a,i]=N.useState("record"),[l,o]=N.useState(0),[c,d]=N.useState(0),u=PN(),h=()=>{i("record"),o(0),d(0)},p=g=>{!g&&(a==="uploading"||a==="processing")||(r(g),g||h())},f=N.useCallback(async(g,b)=>{i("uploading");try{const v="Card Video",{videoId:j,libraryId:_}=await l6(v),{uploadUrl:S,apiKey:A}=await c6(j),T=new XMLHttpRequest;T.upload.onprogress=W=>{W.lengthComputable&&o(W.loaded/W.total*100)},await new Promise((W,K)=>{T.onload=()=>T.status>=200&&T.status<300?W():K(new Error("Upload failed")),T.onerror=()=>K(new Error("Upload failed")),T.open("PUT",S),T.setRequestHeader("AccessKey",A),T.send(g)}),i("processing");let D=0;const L=Date.now(),M=9e4,F=`https://iframe.mediadelivery.net/embed/${_}/${j}`;for(;D<4;){if(await new Promise(K=>setTimeout(K,3e3)),Date.now()-L>M){const K=g.size/1048576;await u.mutateAsync({bunny_video_id:j,playback_url:`https://iframe.mediadelivery.net/play/${_}/${j}`,file_size_mb:K,title:v,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(F),ae.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const W=await Uw(j);if(D=W.status,d(W.encodeProgress||0),D===5||D===6)throw new Error("Video processing failed")}const z=await Uw(j),V=(z.storageSize||g.size)/(1024*1024);await u.mutateAsync({bunny_video_id:j,contact_id:s||void 0,playback_url:z.directPlayUrl||F,thumbnail_url:z.thumbnailUrl,preview_url:z.previewUrl||null,duration_seconds:z.length||b,file_size_mb:V,title:v,status:"ready",touch_type:"video"}),t(F),ae.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(v){console.error("Recording upload error:",v),ae.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(bs,{open:n,onOpenChange:p,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(vr,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(vs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(m6,{maxDurationSeconds:600,onRecordingComplete:f,onError:g=>ae.error(g)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(ss,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(xi,{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(ss,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(xi,{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(zi,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const bXs=s=>`portal-settings-draft:${s}`;function S8e({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=SR(),[i,l]=N.useState(!1),o=N.useMemo(()=>bXs(n.id),[n.id]),[c,d]=N.useState(!1),[u,h]=N.useState(n.next_step_text||""),[p,f]=N.useState(n.next_step_video_url||""),[g,b]=N.useState(n.inspection_date||""),[v,j]=N.useState(n.appraisal_date||""),[_,S]=N.useState(n.welcome_message||""),[A,T]=N.useState(n.review_url||""),[D,L]=N.useState(n.show_post_close_tips),[M,F]=N.useState(n.notify_client),[z,V]=N.useState(n.require_onboarding),[W,K]=N.useState(n.allow_spouse),[Y,ee]=N.useState(n.visibility),[ne,oe]=N.useState(n.stage_mapping||[]),[pe,ce]=N.useState(null),[de,ie]=N.useState(n.linked_portal_id||null),[ye,_e]=N.useState(n.referral_enabled??!0),[Me,Te]=N.useState(n.referral_reward_text||""),[Ce,Ee]=N.useState(n.referral_cta_headline||""),[De,Ie]=N.useState(n.homeowner_hub_video_url||""),[Fe,qe]=N.useState(n.branding_override||{}),ve=()=>{h(n.next_step_text||""),f(n.next_step_video_url||""),b(n.inspection_date||""),j(n.appraisal_date||""),S(n.welcome_message||""),T(n.review_url||""),L(n.show_post_close_tips),F(n.notify_client),V(n.require_onboarding),K(n.allow_spouse),ee(n.visibility),oe(n.stage_mapping||[]),ie(n.linked_portal_id||null),_e(n.referral_enabled??!0),Te(n.referral_reward_text||""),Ee(n.referral_cta_headline||""),Ie(n.homeowner_hub_video_url||""),qe(n.branding_override||{})};N.useEffect(()=>{d(!1);const Ye=localStorage.getItem(o);if(Ye)try{const Ke=JSON.parse(Ye);h(Ke.nextStepText||""),f(Ke.nextStepVideo||""),b(Ke.inspectionDate||""),j(Ke.appraisalDate||""),S(Ke.welcomeMessage||""),T(Ke.reviewUrl||""),L(!!Ke.showPostClose),F(!!Ke.notifyClient),V(!!Ke.requireOnboarding),K(!!Ke.allowSpouse),ee(Ke.visibility||n.visibility),oe(Ke.stageMapping||[]),ie(Ke.linkedPortalId??null),_e(Ke.referralEnabled??!0),Te(Ke.referralRewardText||""),Ee(Ke.referralCtaHeadline||""),Ie(Ke.homeownerHubVideoUrl||""),qe(Ke.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}ve(),d(!0)},[o,n]),N.useEffect(()=>{if(!c)return;const Ye={nextStepText:u,nextStepVideo:p,inspectionDate:g,appraisalDate:v,welcomeMessage:_,reviewUrl:A,showPostClose:D,notifyClient:M,requireOnboarding:z,allowSpouse:W,visibility:Y,stageMapping:ne,linkedPortalId:de,referralEnabled:ye,referralRewardText:Me,referralCtaHeadline:Ce,homeownerHubVideoUrl:De,brandingOverride:Fe};u!==(n.next_step_text||"")||p!==(n.next_step_video_url||"")||g!==(n.inspection_date||"")||v!==(n.appraisal_date||"")||_!==(n.welcome_message||"")||A!==(n.review_url||"")||D!==n.show_post_close_tips||M!==n.notify_client||z!==n.require_onboarding||W!==n.allow_spouse||Y!==n.visibility||JSON.stringify(ne)!==JSON.stringify(n.stage_mapping||[])||de!==(n.linked_portal_id||null)||ye!==(n.referral_enabled??!0)||Me!==(n.referral_reward_text||"")||Ce!==(n.referral_cta_headline||"")||De!==(n.homeowner_hub_video_url||"")||JSON.stringify(Fe)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ye)):localStorage.removeItem(o)},[u,p,g,v,_,A,D,M,z,W,Y,ne,de,ye,Me,Ce,De,Fe,o,c,n]);const Je=()=>{localStorage.removeItem(o),ve()},we=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:p||null,inspection_date:g||null,appraisal_date:v||null,welcome_message:_||null,review_url:A||null,show_post_close_tips:D,notify_client:M,require_onboarding:z,allow_spouse:W,visibility:Y,stage_mapping:ne.length>0?ne:null,linked_portal_id:de,referral_enabled:ye,referral_reward_text:Me||null,referral_cta_headline:Ce||null,homeowner_hub_video_url:De||null,branding_override:Object.values(Fe).some(Ke=>Ke!=null&&Ke!=="")?Fe:null});const Ye=n.linked_portal_id;de&&de!==Ye&&await q.from("client_portals").update({linked_portal_id:n.id}).eq("id",de),!de&&Ye&&await q.from("client_portals").update({linked_portal_id:null}).eq("id",Ye),localStorage.removeItem(o),ae.success("Portal settings saved"),t(!1)}catch{ae.error("Failed to save settings")}},it=()=>{oe([...ne,{label:""}])},Ne=Ye=>{oe(ne.filter((Ke,rt)=>rt!==Ye)),pe===Ye&&ce(null)},He=(Ye,Ke,rt)=>{const tt=[...ne];tt[Ye]={...tt[Ye],[Ke]:rt},oe(tt)},$e=()=>{const Ke=Dye(null).map(rt=>({label:rt.label,description:rt.description,stageId:void 0}));oe(Ke)};return e.jsxs(e.Fragment,{children:[e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Portal Settings"})}),e.jsxs($r,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Ur,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(Zt,{value:"general",children:"General"}),e.jsx(Zt,{value:"timeline",children:"Timeline"}),e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"vendors",children:"Vendors"}),e.jsx(Zt,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(ls,{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(se,{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(Ye=>e.jsx("button",{onClick:()=>ee(Ye),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${Y===Ye?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Ye.charAt(0).toUpperCase()+Ye.slice(1)},Ye))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(vn,{checked:z,onCheckedChange:V})]}),z&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>l(!0),className:"text-xs",children:"Manage"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(vn,{checked:W,onCheckedChange:K})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(vn,{checked:D,onCheckedChange:L})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(vn,{checked:M,onCheckedChange:F})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(vXs,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:de,onLink:ie})}),e.jsx("div",{children:e.jsx(ge,{type:"date",value:g,onChange:Ye=>b(Ye.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(ge,{type:"date",value:v,onChange:Ye=>j(Ye.target.value),className:"mt-1"})]})]}),e.jsx(ls,{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(se,{className:"text-sm font-medium",children:"Client-Facing Stages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Customize the client-friendly stage labels shown on the portal timeline"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:$e,className:"text-xs",children:"Auto-map"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground bg-muted/50 rounded-md p-2",children:'💡 These labels are what clients see. Click "More" on any stage to customize its description and add a video link. Internal pipeline stages are automatically translated to friendly names.'}),ne.length===0&&e.jsxs("div",{className:"border border-dashed rounded-lg p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No custom mapping — using default client-friendly journey stages"}),e.jsx(B,{variant:"outline",size:"sm",onClick:$e,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:ne.map((Ye,Ke)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Uu,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(ge,{value:Ye.label,onChange:rt=>He(Ke,"label",rt.target.value),placeholder:`Stage ${Ke+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>ce(pe===Ke?null:Ke),children:pe===Ke?"Less":"More"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Ne(Ke),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]}),pe===Ke&&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(se,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:Ye.description||"",onChange:rt=>He(Ke,"description",rt.target.value),placeholder:"e.g. Now it's time to start actively looking at homes",className:"mt-0.5 w-full rounded-md border border-input bg-background px-3 py-2 text-xs min-h-[50px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Video"}),Ye.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:Ye.video_url.length>40?Ye.video_url.slice(0,40)+"...":Ye.video_url}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>He(Ke,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(k8e,{onVideoReady:rt=>He(Ke,"video_url",rt)}),e.jsx(o6,{userId:r,onSelect:rt=>He(Ke,"video_url",rt),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const rt=prompt("Paste a YouTube or Loom URL:");rt&&He(Ke,"video_url",rt)},children:[e.jsx(tl,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},Ke))}),ne.length>0&&e.jsxs(B,{variant:"outline",size:"sm",onClick:it,className:"mt-2 text-xs w-full",children:[e.jsx(As,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(ls,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:_,onChange:Ye=>S(Ye.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(se,{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:Ye=>h(Ye.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(se,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(ge,{value:p,onChange:Ye=>f(Ye.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(se,{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(ge,{value:A,onChange:Ye=>T(Ye.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(se,{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(se,{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(vn,{checked:ye,onCheckedChange:_e})]}),ye&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Headline"}),e.jsx(ge,{value:Ce,onChange:Ye=>Ee(Ye.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(se,{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(ge,{value:Me,onChange:Ye=>Te(Ye.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(se,{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(ge,{value:De,onChange:Ye=>Ie(Ye.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(ls,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(yXs,{portalId:n.id,agentUserId:r})}),e.jsx(ls,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(gXs,{override:Fe,onChange:qe})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(B,{variant:"ghost",onClick:Je,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(B,{onClick:we,disabled:a.isPending,children:[a.isPending?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(I2t,{open:i,onOpenChange:l})]})}const _Xs=s=>`portal-update-draft:${s}`;function C8e({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=N.useMemo(()=>_Xs(n),[n]),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(!1),[g,b]=N.useState(a??!1),[v,j]=N.useState(!1),_=nwt();N.useEffect(()=>{j(!1);const T=localStorage.getItem(i);if(T)try{const D=JSON.parse(T);o(D.title||""),d(D.content||""),h(D.videoUrl||""),f(!!D.isStageChange),b(typeof D.sendNotification=="boolean"?D.sendNotification:a??!1),j(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),f(!1),b(a??!1),j(!0)},[i,a]),N.useEffect(()=>{if(!v)return;const T={title:l,content:c,videoUrl:u,isStageChange:p,sendNotification:g};l.trim()||c.trim()||u.trim()||p||g!==(a??!1)?localStorage.setItem(i,JSON.stringify(T)):localStorage.removeItem(i)},[l,c,u,p,g,v,i,a]);const S=()=>{localStorage.removeItem(i),o(""),d(""),h(""),f(!1),b(a??!1)},A=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:p}),g&&r)try{const T=Ew(r);await q.functions.invoke("send-portal-notification",{body:{portal_id:n,update_title:l.trim(),update_content:c.trim()||null,portal_url:T}}),ae.success("Update posted & client notified")}catch(T){console.error("Notification failed:",T),ae.success("Update posted (notification failed to send)")}else ae.success("Update posted to portal");S(),t(!1)}catch{ae.error("Failed to post update")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Title *"}),e.jsx(ge,{value:l,onChange:T=>o(T.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange:T=>d(T.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(se,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(ge,{value:u,onChange:T=>h(T.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("button",{type:"button",onClick:()=>f(!p),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${p?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-background text-muted-foreground border-input"}`,children:"📊 Stage Change"}),e.jsxs("button",{type:"button",onClick:()=>b(!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(lm,{className:"h-3 w-3"}):e.jsx(fw,{className:"h-3 w-3"}),g?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",onClick:S,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(B,{onClick:A,disabled:!l.trim()||_.isPending,children:[_.isPending?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function T8e({open:s,onOpenChange:t,portal:n,dealName:r}){const a=SR(),{isGmailConnected:i,gmailEmail:l}=bh(),[o,c]=N.useState(n.client_name||""),[d,u]=N.useState(n.client_email||""),[h,p]=N.useState(!1),[f,g]=N.useState(!1),b=Ew(n.slug),v=o.split(" ")[0]||"there",j=`Your Transaction Portal – ${r}`,_=`Hi ${v}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${b} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,S=()=>{navigator.clipboard.writeText(b),g(!0),setTimeout(()=>g(!1),2e3),ae.success("Portal link copied!")},A=async()=>{if(!d.trim()){ae.error("Please enter the client email");return}p(!0);try{await a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:D}=await q.functions.invoke("gmail-send",{body:{to:d,subject:j,body:_.replace(/\n/g,"
")}});if(D){let L="";try{const M=D==null?void 0:D.context;if(M&&typeof M.json=="function"){const F=await M.json();L=(F==null?void 0:F.message)||(F==null?void 0:F.error)||""}}catch{}throw new Error(L||D.message||"Failed to send invite")}ae.success(`Invite sent to ${d}`),t(!1)}catch(D){ae.error(D.message||"Failed to send invite")}finally{p(!1)}},T=()=>{const D=encodeURIComponent(j),L=encodeURIComponent(_);window.open(`mailto:${d}?subject=${D}&body=${L}`,"_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(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(ge,{value:o,onChange:D=>c(D.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(ge,{type:"email",value:d,onChange:D=>u(D.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{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:b})}),e.jsx(B,{variant:"outline",size:"icon",onClick:S,className:"shrink-0",children:f?e.jsx(Lr,{className:"h-4 w-4 text-emerald-600"}):e.jsx(ta,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(B,{onClick:A,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs(B,{onClick:T,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs(B,{variant:"ghost",onClick:S,className:"w-full text-muted-foreground",children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function wXs({deal:s}){const{isAdmin:t,user:n}=gs(),{data:r,isLoading:a}=FWs(s.id),i=NLe(),l=SR(),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,g]=N.useState(!1),b=`portal-management-ui:${s.id}`;if(N.useEffect(()=>{const D=sessionStorage.getItem(b);if(D)try{const L=JSON.parse(D);u(!!L.settingsOpen),p(!!L.composerOpen),g(!!L.inviteOpen)}catch{sessionStorage.removeItem(b)}},[b]),N.useEffect(()=>{d||h||f?sessionStorage.setItem(b,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:f})):sessionStorage.removeItem(b)},[d,h,f,b]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(ss,{className:"h-3 w-3 animate-spin ml-auto"})]})});const v=async()=>{var D,L;c(!0);try{await i.mutateAsync({deal_id:s.id,visibility:"private",require_onboarding:!0,client_name:s.contact?`${s.contact.first_name} ${s.contact.last_name}`:void 0,client_email:((D=s.contact)==null?void 0:D.email)||void 0,client_phone:((L=s.contact)==null?void 0:L.phone)||void 0}),ae.success("Client portal enabled!")}catch{ae.error("Failed to create portal")}finally{c(!1)}},j=async D=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:D}),ae.success(D?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update portal")}},_=()=>{if(!r)return;const D=Ew(r.slug);navigator.clipboard.writeText(D),ae.success("Portal link copied!")},S=()=>{if(!r)return;const D=Ew(r.slug);window.open(D,"_blank")};if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 border-dashed",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Create a beautiful portal so your client can track their deal progress in real-time."}),e.jsxs(B,{onClick:v,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const A=Ew(r.slug),T=(n==null?void 0:n.id)||"";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(ze,{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(vn,{checked:r.is_enabled,onCheckedChange:j})]}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Visibility:"}),e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:r.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:r.require_onboarding?"Required":"Disabled"})]}),r.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:r.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:A})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:_,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(ta,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:S,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(tr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>g(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(cr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Invite"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 w-full",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>p(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(rw,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(Vo,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(Ln,{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(Bi,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(S8e,{open:d,onOpenChange:u,portal:r,dealOwnerId:T}),e.jsx(C8e,{open:h,onOpenChange:p,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(T8e,{open:f,onOpenChange:g,portal:r,dealName:s.deal_name})]})}const jXs=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function NXs(s){return lt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_contacts").select(` id, deal_id, contact_id, role, created_at, contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("deal_id",s).order("created_at");if(n)throw n;return t||[]},enabled:!!s})}function kXs(){const s=Gt();return gt({mutationFn:async({dealId:t,contactId:n,role:r})=>{const{data:a,error:i}=await q.from("deal_contacts").insert({deal_id:t,contact_id:n,role:r}).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ae.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?ae.error("This contact is already linked to this deal"):ae.error("Failed to link contact")}})}function SXs(){const s=Gt();return gt({mutationFn:async({id:t,dealId:n})=>{const{error:r}=await q.from("deal_contacts").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ae.success("Contact removed from deal")},onError:()=>{ae.error("Failed to remove contact")}})}function CXs({dealId:s,primaryContactId:t}){const n=In(),{data:r,isLoading:a}=NXs(s),{data:i}=lx(),l=kXs(),o=SXs(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState("Client"),g=new Set((r==null?void 0:r.map(S=>S.contact_id))||[]);t&&g.add(t);const b=i==null?void 0:i.filter(S=>{var T,D,L;if(g.has(S.id))return!1;if(!u.trim())return!0;const A=u.toLowerCase();return((T=S.first_name)==null?void 0:T.toLowerCase().includes(A))||((D=S.last_name)==null?void 0:D.toLowerCase().includes(A))||((L=S.email)==null?void 0:L.toLowerCase().includes(A))}).slice(0,8),v=S=>{l.mutate({dealId:s,contactId:S,role:p}),d(!1),h("")},j=S=>{o.mutate({id:S,dealId:s})},_={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(_n,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(Wo,{open:c,onOpenChange:d,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(zo,{className:"w-80 p-3",align:"start",children:e.jsx(xXe,{search:u,setSearch:h,selectedRole:p,setSelectedRole:f,filteredContacts:b,onAdd:v})})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(_n,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx(ze,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(Wo,{open:c,onOpenChange:d,children:[e.jsx(Ko,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(As,{className:"h-3.5 w-3.5"})})}),e.jsx(zo,{className:"w-80 p-3",align:"end",children:e.jsx(xXe,{search:u,setSearch:h,selectedRole:p,setSelectedRole:f,filteredContacts:b,onAdd:v})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(S=>{var A,T,D,L,M,F,z,V;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(aa,{className:"h-7 w-7",children:e.jsxs(ia,{className:"text-[10px] bg-primary/10 text-primary",children:[(T=(A=S.contact)==null?void 0:A.first_name)==null?void 0:T[0],(L=(D=S.contact)==null?void 0:D.last_name)==null?void 0:L[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>n(`/mission-control/contacts/${S.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(M=S.contact)==null?void 0:M.first_name," ",(F=S.contact)==null?void 0:F.last_name]})}),e.jsx(ze,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${_[S.role]||_.Other}`,children:S.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((z=S.contact)==null?void 0:z.phone)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${S.contact.phone}`,children:e.jsx(Pr,{className:"h-3 w-3"})})}),((V=S.contact)==null?void 0:V.email)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${S.contact.email}`,children:e.jsx(Hs,{className:"h-3 w-3"})})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>j(S.id),children:e.jsx(bn,{className:"h-3 w-3"})})]})]},S.id)})})]})}function xXe({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(cs,{className:"h-8 text-sm",children:e.jsx(hs,{placeholder:"Role"})}),e.jsx(ds,{children:jXs.map(l=>e.jsx(Ze,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ge,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(mi,{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 P7=[{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"}],TXs=[{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 EXs(){const s=Gt();return gt({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 q.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 AXs(){return lt({queryKey:["tc-playbooks"],queryFn:async()=>{const{data:s,error:t}=await q.from("tc_playbooks").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;const{data:n,error:r}=await q.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 MXs(){const s=fa(),t=Gt();return gt({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([q.from("deal_pipeline").select("*").eq("id",r).single(),q.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 q.from("deal_tasks").select("title").eq("deal_id",r),d=new Set((c||[]).map(g=>String(g.title).toLowerCase())),u=a,h=(g,b)=>{const v=g==="stage_entry"?null:u[g],j=v?new Date(`${v}T12:00:00`):new Date;return j.setDate(j.getDate()+(b||0)),j.toISOString().split("T")[0]},p=l.filter(g=>!d.has(String(g.title).toLowerCase())).map((g,b)=>({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:b}));if(p.length===0)return 0;const{error:f}=await q.from("deal_tasks").insert(p);if(f)throw f;return p.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function IXs(){const s=fa(),t=Gt();return gt({mutationFn:async({playbookId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a},{data:i,error:l}]=await Promise.all([q.from("tc_playbooks").select("deal_type").eq("id",n).single(),q.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 q.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,p)=>({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:p}));if(d.length===0)return 0;const{error:u}=await q.from("deal_task_templates").insert(d);if(u)throw u;return d.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function PXs(){const s=fa();return lt({queryKey:["tc-dashboard",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.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 q.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 E8e(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 V_(s){const t=E8e(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 LXs(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const DXs={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 RXs(s){const t=E8e(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function gXe(s){return s===null?"Not set":s===0?"Today":s<0?`${Math.abs(s)}d overdue`:`in ${s}d`}function OXs({deal:s,compact:t=!1}){const n=EXs(),[r,a]=N.useState(!1),[i,l]=N.useState({}),o=()=>{const g={};P7.forEach(b=>{g[b.key]=(s==null?void 0:s[b.key])??""}),l(g),a(!0)},c=async()=>{try{await n.mutateAsync({dealId:s.id,dates:i}),ae.success("Transaction dates updated"),a(!1)}catch(g){ae.error((g==null?void 0:g.message)||"Could not save dates")}},d=N.useMemo(()=>P7.map(g=>{const b=(s==null?void 0:s[g.key])??null,v=V_(b);return{...g,value:b,days:v,urgency:LXs(v)}}),[s]),u=d.filter(g=>g.value).length,h=V_(s==null?void 0:s.target_close_date),p=d.filter(g=>g.value&&g.days!==null&&g.days>=0).sort((g,b)=>(g.days??0)-(b.days??0))[0],f=d.filter(g=>g.urgency==="overdue");return 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(cm,{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:h!==null?h>=0?`${h} day${h===1?"":"s"} to closing`:`Closing was ${Math.abs(h)} day${Math.abs(h)===1?"":"s"} ago`:`${u} of ${P7.length} key dates set`})]})]}),e.jsxs(Wo,{open:r,onOpenChange:g=>g?o():a(!1),children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"shrink-0 gap-1.5",children:[e.jsx(ja,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(zo,{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:P7.map(g=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{htmlFor:`kd-${g.key}`,className:"text-xs text-muted-foreground",children:g.label}),e.jsx(ge,{id:`kd-${g.key}`,type:"date",value:i[g.key]??"",onChange:b=>l(v=>({...v,[g.key]:b.target.value})),className:"h-9"})]},g.key))}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:c,disabled:n.isPending,children:[n.isPending?e.jsx(ss,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Lr,{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:d.map(g=>e.jsxs("div",{className:Et("rounded-lg border px-2.5 py-2 transition-colors",DXs[g.urgency]),children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide opacity-70 truncate",children:g.short}),e.jsx("p",{className:"text-sm font-semibold leading-tight truncate",children:RXs(g.value)??"—"}),g.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:gXe(g.days)})]},g.key))}),(f.length>0||p)&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-xs",children:[f.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(Dl,{className:"h-3 w-3"}),f.length," date",f.length===1?"":"s"," past due"]}),p&&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: ",p.label," · ",gXe(p.days)]})]}),u===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 FXs={Home:zr,FileSignature:Zk,Handshake:fb,CalendarClock:cm,Sparkles:un,ClipboardCheck:W2},zXs={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 BXs(s,t){var a;const n=((a=TXs.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 P2t({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=AXs(),{data:l}=ZU(),o=MXs(),c=IXs(),[d,u]=N.useState(null),[h,p]=N.useState({}),f=v=>{if(h[v.id])return h[v.id];const j=l==null?void 0:l.find(_=>{var S,A;return((S=_.name)==null?void 0:S.toLowerCase())===((A=v.target_stage_name)==null?void 0:A.toLowerCase())});return(j==null?void 0:j.id)??""},g=async v=>{if(n){u(v.id);try{const j=await o.mutateAsync({playbookId:v.id,dealId:n});ae.success(j>0?`Added ${j} task${j===1?"":"s"} to this deal`:"All tasks already exist on this deal"),j>0&&t(!1)}catch(j){ae.error((j==null?void 0:j.message)||"Could not apply playbook")}finally{u(null)}}},b=async v=>{const j=f(v);if(!j){ae.error("Pick which stage this playbook should trigger on");return}u(`install-${v.id}`);try{const _=await c.mutateAsync({playbookId:v.id,stageId:j});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(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx(ws,{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($u,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx(_s,{children:"Transaction Playbooks"}),e.jsx(Qn,{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(mi,{className:"flex-1",children:e.jsx("div",{className:"p-6 pt-4",children:i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(jIe,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(v=>{const j=FXs[v.icon||"ClipboardCheck"]||W2,_=v.accent_color||"hsl(var(--primary))";return e.jsxs(pve,{value:v.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(fve,{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(j,{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:v.name}),e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:[v.tasks.length," steps"]}),v.deal_type&&e.jsx(ze,{variant:"outline",className:"text-[10px] capitalize",children:v.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.description})]})]})}),e.jsxs(xve,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:v.tasks.map((S,A)=>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:A+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:S.title}),S.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:S.description}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:BXs(S.due_anchor,S.due_offset_days)})]}),e.jsx("span",{className:Et("text-[10px] px-1.5 py-0.5 rounded-full shrink-0 capitalize",zXs[S.priority]),children:S.priority})]},S.id))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 pt-2 border-t",children:[n&&e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>g(v),disabled:d===v.id,children:[d===v.id?e.jsx(ss,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ph,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(us,{value:f(v),onValueChange:S=>p(A=>({...A,[v.id]:S})),children:[e.jsx(cs,{className:"h-9 text-xs flex-1",children:e.jsx(hs,{placeholder:"Trigger stage"})}),e.jsx(ds,{children:(l||[]).map(S=>e.jsx(Ze,{value:S.id,children:S.name},S.id))})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>b(v),disabled:d===`install-${v.id}`,children:[d===`install-${v.id}`?e.jsx(ss,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(vL,{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(xr,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},v.id)})})})})]})})}const $Xs={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"}},UXs={note:Ci,call:Pr,email:Hs,meeting:yr,stage_change:tr,task_completed:xr,document:zr,system:gr};function qXs({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Fe,qe;const l=In(),{data:o,isLoading:c}=cQs((s==null?void 0:s.id)||""),{data:d,isLoading:u}=uQs((s==null?void 0:s.id)||""),h=dQs(),p=mQs(),f=hQs(),g=lQs(),{data:b,isLoading:v}=hXs((s==null?void 0:s.id)||""),j=mXs(),_=pXs(),S=fXs(),A=N.useRef(null),[T,D]=N.useState(""),[L,M]=N.useState(""),[F,z]=N.useState(!1),[V,W]=N.useState(!1),[K,Y]=N.useState(!1);if(!s)return null;const ee=$Xs[s.deal_type],ne=(()=>{var we;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const ve=((we=s.listing)==null?void 0:we.created_at)||s.listing_date;if(!ve)return null;const Je=s.contract_date?ll(s.contract_date):new Date;return Yv(Je,ll(ve))})(),oe=ve=>ve?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(ve):"-",pe=async()=>{if(T.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:T}),D(""),ae.success("Note added")}catch{ae.error("Failed to add note")}},ce=async()=>{if(L.trim())try{await p.mutateAsync({deal_id:s.id,title:L,sort_order:((d==null?void 0:d.length)||0)+1}),M(""),ae.success("Task added")}catch{ae.error("Failed to add task")}},de=async(ve,Je)=>{try{await f.mutateAsync({id:ve,is_completed:Je,deal_id:s.id})}catch{ae.error("Failed to update task")}},ie=async()=>{try{await g.mutateAsync(s.id),ae.success("Deal deleted"),n(!1)}catch{ae.error("Failed to delete deal")}},ye=(d==null?void 0:d.filter(ve=>ve.is_completed).length)||0,_e=(d==null?void 0:d.length)||0,Me=(b==null?void 0:b.length)||0,Te=ve=>ve<1024?`${ve} B`:ve<1024*1024?`${(ve/1024).toFixed(1)} KB`:`${(ve/(1024*1024)).toFixed(1)} MB`,Ce=ve=>ve?ve.startsWith("image/")?nl:ve.includes("pdf")?Nr:rL:rL,Ee=async ve=>{const Je=ve.target.files;if(!(!Je||!s)){Y(!0);try{for(const we of Array.from(Je)){if(we.size>20*1024*1024){ae.error(`${we.name} exceeds 20MB limit`);continue}await j.mutateAsync({dealId:s.id,file:we})}ae.success("File(s) uploaded")}catch{ae.error("Failed to upload file")}finally{Y(!1),A.current&&(A.current.value="")}}},De=async(ve,Je)=>{if(s)try{await _.mutateAsync({fileId:ve,storagePath:Je,dealId:s.id}),ae.success("File deleted")}catch{ae.error("Failed to delete file")}},Ie=async(ve,Je)=>{try{const we=await xXs(ve),it=document.createElement("a");it.href=we,it.download=Je,it.target="_blank",document.body.appendChild(it),it.click(),document.body.removeChild(it)}catch{ae.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(ug,{open:t,onOpenChange:n,children:e.jsxs(ox,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(r0,{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(ze,{variant:"outline",className:Et("text-xs",ee.color),children:ee.label}),e.jsxs(ze,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(a0,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(uXs,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(Tu,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>W(!0),children:e.jsx(bn,{className:"h-4 w-4"})})]})]})}),e.jsx(mi,{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(aa,{className:"h-10 w-10",children:e.jsxs(ia,{className:"bg-primary/10 text-primary",children:[(Fe=s.contact.first_name)==null?void 0:Fe[0],(qe=s.contact.last_name)==null?void 0:qe[0]]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium group-hover:text-primary group-hover:underline truncate",children:[s.contact.first_name," ",s.contact.last_name]}),s.contact.email&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.contact.email})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.contact.phone&&e.jsx(B,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(Pr,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx(B,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(Hs,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"outline",size:"icon",title:"Open contact record",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},children:e.jsx(tr,{className:"h-4 w-4"})})]})]}),e.jsx(CXs,{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(zr,{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:oe(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:oe(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?` (${oe(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:oe(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:oe(s.net_commission)})]})})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs(B,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(vo,{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(xr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),ne!==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:Et("text-lg font-bold",ne>90?"text-red-600":ne>60?"text-amber-600":"text-foreground"),children:[ne," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",ks(ll(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Zl,{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(OXs,{deal:s}),e.jsx(wXs,{deal:s}),e.jsxs($r,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(Ur,{className:"w-full grid grid-cols-3",children:[e.jsxs(Zt,{value:"tasks",className:"gap-1",children:[e.jsx(xr,{className:"h-4 w-4"}),"Tasks ",_e>0&&`(${ye}/${_e})`]}),e.jsxs(Zt,{value:"files",className:"gap-1",children:[e.jsx(r4,{className:"h-4 w-4"}),"Files ",Me>0&&`(${Me})`]}),e.jsxs(Zt,{value:"activity",className:"gap-1",children:[e.jsx(gr,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(ls,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{placeholder:"Add a new task...",value:L,onChange:ve=>M(ve.target.value),onKeyDown:ve=>ve.key==="Enter"&&ce()}),e.jsx(B,{onClick:ce,disabled:!L.trim(),children:e.jsx(As,{className:"h-4 w-4"})}),e.jsxs(B,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>z(!0),children:[e.jsx($u,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(ve=>e.jsxs("div",{className:Et("flex items-center gap-3 p-3 rounded-lg border transition-colors",ve.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(hi,{checked:ve.is_completed,onCheckedChange:Je=>de(ve.id,!!Je)}),e.jsx("span",{className:Et("flex-1 text-sm",ve.is_completed&&"line-through text-muted-foreground"),children:ve.title}),ve.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:ks(new Date(ve.due_date),"MMM d")})]},ve.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(ls,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:A,className:"hidden",multiple:!0,onChange:Ee,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs(B,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var ve;return(ve=A.current)==null?void 0:ve.click()},disabled:K,children:[K?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-2"}),K?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[b==null?void 0:b.map(ve=>{const Je=Ce(ve.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(Je,{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:ve.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Te(ve.file_size)," · ",ks(new Date(ve.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Kw,{children:e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${ve.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>S.mutate({fileId:ve.id,visible:!ve.visible_on_portal,dealId:s.id}),children:ve.visible_on_portal?e.jsx(Ir,{className:"h-4 w-4"}):e.jsx(gf,{className:"h-4 w-4"})})}),e.jsx(yc,{side:"top",children:ve.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Ie(ve.storage_path,ve.file_name),children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>De(ve.id,ve.storage_path),children:e.jsx(Fn,{className:"h-4 w-4"})})]})]},ve.id)}),(b==null?void 0:b.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(ls,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ts,{placeholder:"Add a note...",value:T,onChange:ve=>D(ve.target.value),rows:2}),e.jsxs(B,{onClick:pe,disabled:!T.trim(),size:"sm",className:"w-full",children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(ve=>{const Je=UXs[ve.activity_type]||gr;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(Je,{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:ve.title}),ve.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:ve.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Go(new Date(ve.created_at),{addSuffix:!0})})]})]},ve.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(P2t,{open:F,onOpenChange:z,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(Oo,{open:V,onOpenChange:W,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Deal?"}),e.jsxs(Mo,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:ie,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function VXs({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=Wye(),i=S2t(),{data:l}=KM(),{data:o}=Cy(),[c,d]=N.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:ks(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});N.useEffect(()=>{if(n&&s){const p=n.deal_type==="seller"?"seller":"buyer",f=n.expected_price||0,g=n.commission_percentage||3,b=n.expected_commission||f*g/100;d({property_address:n.property_address||n.deal_name||"",city:n.city||"",state:n.state||"",zip:n.zip_code||"",transaction_type:p,close_date:n.actual_close_date||n.target_close_date||ks(new Date,"yyyy-MM-dd"),sale_price:f,commission_amount:b,lead_source_id:"",client_type_id:"",notes:n.notes||""})}},[n,s]);const u=async p=>{if(p.preventDefault(),!!n)try{const f=await a.mutateAsync({property_address:c.property_address,city:c.city||null,state:c.state||null,zip:c.zip||null,transaction_type:c.transaction_type,close_date:c.close_date,sale_price:c.sale_price,commission_amount:c.commission_amount||null,brokerage_split_pct:n.brokerage_split_pct||null,team_split_pct:n.team_split_pct||null,franchise_fee_pct:n.franchise_fee_pct||null,referral_fee_pct:n.referral_fee_pct||null,transaction_fee:n.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:n.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:n.id,scorecard_transaction_id:f.id,actual_close_date:c.close_date}),ae.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(f){console.error("Error syncing to scorecard:",f),ae.error("Failed to add to scorecard")}},h=p=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(p);return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{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(vo,{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(Qn,{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(se,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(zr,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(ge,{id:"property_address",value:c.property_address,onChange:p=>d(f=>({...f,property_address:p.target.value})),placeholder:"123 Main St",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(ge,{id:"city",value:c.city,onChange:p=>d(f=>({...f,city:p.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ge,{id:"state",value:c.state,onChange:p=>d(f=>({...f,state:p.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zip",children:"Zip"}),e.jsx(ge,{id:"zip",value:c.zip,onChange:p=>d(f=>({...f,zip:p.target.value})),placeholder:"75001"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Transaction Type *"}),e.jsxs(us,{value:c.transaction_type,onValueChange:p=>d(f=>({...f,transaction_type:p})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(ge,{id:"close_date",type:"date",value:c.close_date,onChange:p=>d(f=>({...f,close_date:p.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(Zl,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(ge,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:p=>d(f=>({...f,sale_price:Number(p.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(i4,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(ge,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:p=>d(f=>({...f,commission_amount:Number(p.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Lead Source"}),e.jsxs(us,{value:c.lead_source_id,onValueChange:p=>d(f=>({...f,lead_source_id:p})),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select source"})}),e.jsx(ds,{children:l==null?void 0:l.map(p=>e.jsx(Ze,{value:p.id,children:p.name},p.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Client Type"}),e.jsxs(us,{value:c.client_type_id,onValueChange:p=>d(f=>({...f,client_type_id:p})),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select type"})}),e.jsx(ds,{children:o==null?void 0:o.map(p=>e.jsx(Ze,{value:p.id,children:p.name},p.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Ts,{id:"notes",value:c.notes,onChange:p=>d(f=>({...f,notes:p.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(Xn,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx(B,{type:"submit",disabled:a.isPending||i.isPending,className:"bg-green-600 hover:bg-green-700",children:a.isPending?"Adding...":e.jsxs(e.Fragment,{children:["Add to Scorecard",e.jsx(za,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const HXs={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"}},yXe={urgent:0,high:1,medium:2,low:3};function GXs({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=N.useState("target_close_date"),[l,o]=N.useState("asc"),c=f=>{a===f?o(g=>g==="asc"?"desc":"asc"):(i(f),o("asc"))},d=N.useMemo(()=>[...s].sort((f,g)=>{var v,j;let b=0;switch(a){case"deal_name":b=f.deal_name.localeCompare(g.deal_name);break;case"stage":{const _=((v=t.find(A=>A.id===f.stage_id))==null?void 0:v.sort_order)||0,S=((j=t.find(A=>A.id===g.stage_id))==null?void 0:j.sort_order)||0;b=_-S;break}case"expected_price":b=(f.expected_price||0)-(g.expected_price||0);break;case"expected_commission":b=(f.expected_commission||0)-(g.expected_commission||0);break;case"target_close_date":{const _=f.target_close_date?ll(f.target_close_date).getTime():1/0,S=g.target_close_date?ll(g.target_close_date).getTime():1/0;b=_-S;break}case"priority":b=yXe[f.priority]-yXe[g.priority];break}return l==="asc"?b:-b}),[s,t,a,l]),u=f=>f?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(f):"—",h=f=>f?t.find(g=>g.id===f):null,p=({field:f,children:g})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(f),children:[g,a===f?l==="asc"?e.jsx(Bu,{className:"ml-2 h-4 w-4"}):e.jsx(om,{className:"ml-2 h-4 w-4"}):e.jsx(sm,{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(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{className:"bg-muted/50",children:[e.jsx(Ct,{className:"w-[250px]",children:e.jsx(p,{field:"deal_name",children:"Deal Name"})}),e.jsx(Ct,{className:"w-[150px]",children:e.jsx(p,{field:"stage",children:"Stage"})}),e.jsx(Ct,{className:"w-[100px]",children:"Type"}),e.jsx(Ct,{className:"w-[120px]",children:e.jsx(p,{field:"expected_price",children:"Price"})}),e.jsx(Ct,{className:"w-[120px]",children:e.jsx(p,{field:"expected_commission",children:"GCI"})}),e.jsx(Ct,{className:"w-[130px]",children:e.jsx(p,{field:"target_close_date",children:"Close Date"})}),e.jsx(Ct,{className:"w-[100px]",children:e.jsx(p,{field:"priority",children:"Priority"})})]})}),e.jsx(pa,{children:d.map(f=>{h(f.stage_id);const g=HXs[f.deal_type],b=f.target_close_date?Yv(ll(f.target_close_date),new Date):null,v=b!==null&&b<0,j=b!==null&&b<=7&&b>=0;return e.jsxs(Gs,{className:Et("cursor-pointer hover:bg-muted/50 transition-colors",v&&"bg-red-50/50"),onClick:()=>n(f),children:[e.jsx(ut,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:f.deal_name}),f.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[f.contact.first_name," ",f.contact.last_name]})]})}),e.jsx(ut,{onClick:_=>_.stopPropagation(),children:e.jsx(A2t,{stages:t,currentStageId:f.stage_id||"",onStageSelect:(_,S)=>r(f.id,_,S)})}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",className:Et("text-xs",g.color),children:g.label})}),e.jsx(ut,{children:e.jsx("span",{className:"font-medium",children:u(f.expected_price)})}),e.jsx(ut,{children:e.jsx("span",{className:"text-emerald-600",children:u(f.expected_commission)})}),e.jsx(ut,{children:f.target_close_date?e.jsxs("div",{className:Et("flex items-center gap-1 text-sm",v&&"text-red-600",j&&!v&&"text-amber-600"),children:[v&&e.jsx(Gi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:ks(ll(f.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",className:Et("text-xs capitalize",f.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",f.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",f.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",f.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:f.priority})})]},f.id)})})]})})}function WXs(){const s=fa();return lt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name), stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function KXs(s){const t=fa();return lt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:n,error:r}=await q.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return n},enabled:!!t&&!!s})}function YXs(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_tasks").insert({owner_user_id:s,title:n.title,description:n.description||null,deal_id:n.deal_id||null,contact_id:n.contact_id||null,stage_id:n.stage_id||null,priority:n.priority||"medium",status:n.status||"todo",due_date:n.due_date||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function ZXs(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("deal_tasks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function QXs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("deal_tasks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function dbe(){const s=Gt();return gt({mutationFn:async({id:t,status:n})=>{const{data:r,error:a}=await q.from("deal_tasks").update({status:n,completed_at:n==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function XXs(){const s=Gt();return gt({mutationFn:async t=>{if(t.length===0)return;const{error:n}=await q.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function JXs(s){const t=fa();return lt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let n=q.from("deal_task_templates").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});s&&(n=n.eq("stage_id",s));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function eJs(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_task_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title,description:n.description||null,priority:n.priority||"medium",default_due_offset_days:n.default_due_offset_days||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function tJs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("deal_task_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function sJs(){const s=fa(),t=Gt();return gt({mutationFn:async({dealId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",r).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await q.from("deal_tasks").select("title, stage_id").eq("deal_id",n).eq("stage_id",r),o=new Set((l||[]).map(h=>h.title)),c=a.filter(h=>!o.has(h.title)).map((h,p)=>({owner_user_id:s,deal_id:n,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_date:h.default_due_offset_days?new Date(Date.now()+h.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:p,status:"todo"}));if(c.length===0)return[];const{data:d,error:u}=await q.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const nJs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function rJs({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=KXs(s?n:void 0),u=XXs(),h=sJs(),[p,f]=N.useState(new Set),[g,b]=N.useState(!1),v=(c||[]).filter(A=>A.status!=="done");N.useEffect(()=>{v.length>0&&f(new Set(v.map(A=>A.id)))},[c]);const j=A=>{f(T=>{const D=new Set(T);return D.has(A)?D.delete(A):D.add(A),D})},_=async()=>{b(!0);try{const A=Array.from(p);A.length>0&&await u.mutateAsync(A),await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(A){console.error("Stage move failed:",A),ae.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{b(!1)}},S=async()=>{b(!0);try{await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(A){console.error("Stage move (skip) failed:",A),ae.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{b(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[480px]",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Move Deal"}),e.jsxs(Qn,{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(ze,{variant:"outline",className:"text-sm",children:a}),e.jsx(za,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ze,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["You have ",e.jsx("span",{className:"font-medium text-foreground",children:v.length})," incomplete task",v.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(mi,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:v.map(A=>e.jsxs("label",{className:"flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",children:[e.jsx(hi,{checked:p.has(A.id),onCheckedChange:()=>j(A.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[nJs[A.priority]," ",A.title]}),A.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:A.stage.color+"20",color:A.stage.color},children:A.stage.name})]},A.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{p.size===v.length?f(new Set):f(new Set(v.map(A=>A.id)))},children:p.size===v.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:S,disabled:g,children:"Skip"}),e.jsxs(B,{size:"sm",onClick:_,disabled:g,children:[g&&e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}),p.size>0?`Complete ${p.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(xr,{className:"h-8 w-8 text-emerald-500 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All tasks completed! Ready to move."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:_,disabled:g,children:[g&&e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const aJs=[{name:"ReLevelUp",brand:"#406E71",accent:"#2a4c64"},{name:"Slate",brand:"#0f172a",accent:"#475569"},{name:"Midnight",brand:"#111827",accent:"#3b82f6"},{name:"Forest",brand:"#14532d",accent:"#65a30d"},{name:"Burgundy",brand:"#7f1d1d",accent:"#b45309"},{name:"Royal",brand:"#1e3a8a",accent:"#7c3aed"}];function L2t({open:s,onOpenChange:t}){const n=fa(),{data:r,isLoading:a}=Hht(),i=GJt(),[l,o]=N.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null}),[c,d]=N.useState(null);N.useEffect(()=>{s&&o({logo_url:(r==null?void 0:r.logo_url)??null,cover_photo_url:(r==null?void 0:r.cover_photo_url)??null,brand_color:(r==null?void 0:r.brand_color)??null,accent_color:(r==null?void 0:r.accent_color)??null,tagline:(r==null?void 0:r.tagline)??null,welcome_message:(r==null?void 0:r.welcome_message)??null})},[s,r]);const u=f=>o(g=>({...g,...f})),h=async(f,g)=>{if(n){if(f.size>5*1024*1024){ae.error("Image must be under 5MB");return}d(g);try{const b=await Ght(n,f,g);u(g==="logo"?{logo_url:b}:{cover_photo_url:b})}catch(b){ae.error(`Upload failed: ${b.message||b}`)}finally{d(null)}}},p=async()=>{try{await i.mutateAsync(l),ae.success("Portal branding saved"),t(!1)}catch{ae.error("Failed to save branding")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(xl,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Qn,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(mi,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(ss,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(iJs,{draft:l}),e.jsx(vXe,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:f=>h(f,"logo"),onClear:()=>u({logo_url:null}),aspect:"square"}),e.jsx(vXe,{label:"Cover Photo",hint:"Hero background at the top of the portal. Wide landscape works best.",value:l.cover_photo_url,uploading:c==="cover",onUpload:f=>h(f,"cover"),onClear:()=>u({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{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:aJs.map(f=>{const g=l.brand_color===f.brand&&l.accent_color===f.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:f.brand,accent_color:f.accent}),className:Et("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:f.brand}}),e.jsx("div",{className:"flex-1",style:{background:f.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:f.name})]},f.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(bXe,{label:"Brand",value:l.brand_color,onChange:f=>u({brand_color:f})}),e.jsx(bXe,{label:"Accent",value:l.accent_color,onChange:f=>u({accent_color:f})})]})]}),e.jsxs("div",{children:[e.jsx(se,{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(ge,{value:l.tagline||"",onChange:f=>u({tagline:f.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Default Welcome Message"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown on the portal hero. Per-deal welcome messages override this."}),e.jsx("textarea",{value:l.welcome_message||"",onChange:f=>u({welcome_message:f.target.value}),placeholder:"Welcome! Here's everything you need for your transaction.",className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[70px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",maxLength:300})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:p,disabled:i.isPending,children:[i.isPending?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function iJs({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 vXe({label:s,hint:t,value:n,uploading:r,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(se,{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:Et("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(nl,{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(ss,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Sa,{className:"h-3.5 w-3.5"}),n?"Replace":"Upload"]})]}),n&&e.jsx(B,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})]})}function bXe({label:s,value:t,onChange:n}){const r=t||"#000000";return e.jsxs("div",{children:[e.jsx(se,{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(ge,{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 oJs(){const s=fa();return lt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("client_portals").select("*").eq("owner_user_id",s);if(n)throw n;return t||[]},enabled:!!s})}function lJs({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=NLe(),d=SR(),u=ewt(),h=twt(),[p,f]=N.useState(!1),g=!!(r!=null&&r.archived_at),b=async()=>{f(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),ae.success("Portal enabled!")}catch{ae.error("Failed to create portal")}finally{f(!1)}},v=async T=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:T}),ae.success(T?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update portal")}},j=()=>{r&&(navigator.clipboard.writeText(Ew(r.slug)),ae.success("Link copied!"))},_=()=>{r&&window.open(Ew(r.slug),"_blank")},S=async()=>{if(r)try{await u.mutateAsync(r.id),ae.success("Portal archived")}catch{ae.error("Failed to archive portal")}},A=async()=>{if(r)try{await h.mutateAsync(r.id),ae.success("Portal restored")}catch{ae.error("Failed to restore portal")}};return r?g?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(Ln,{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(ze,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:A,className:"text-xs gap-1",children:[e.jsx(XP,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>o(r),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(bn,{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(Ln,{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(ze,{variant:"outline",className:r.is_enabled?"text-[10px] bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-[10px] bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"}),e.jsx(ga,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:j,title:"Copy link",children:e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:_,title:"Preview",children:e.jsx(tr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(r,t),title:"Invite client",children:e.jsx(cr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(r),title:"Post update",children:e.jsx(rw,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(r),title:"Settings",children:e.jsx(Vo,{className:"h-3.5 w-3.5"})}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Xf,{className:"h-3.5 w-3.5"})})}),e.jsx(cc,{align:"end",children:e.jsxs(Xr,{onClick:S,children:[e.jsx(im,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(vn,{checked:r.is_enabled,onCheckedChange:v,className:"ml-1"})]})]}):e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg border-dashed bg-muted/20",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n||"No contact"})]}),e.jsxs(B,{size:"sm",onClick:b,disabled:p,className:"shrink-0 ml-4",children:[p?e.jsx(ss,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(un,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function D2t(){const{data:s,isLoading:t}=cbe(),{data:n,isLoading:r}=oJs(),[a,i]=N.useState(""),[l,o]=N.useState("all"),c=swt(),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,g]=N.useState(null),[b,v]=N.useState(null),[j,_]=N.useState(!1),S=fa(),A=t||r,T=new Map;n==null||n.forEach(W=>T.set(W.deal_id,W));const L=[...(s||[]).filter(W=>{var oe,pe,ce,de,ie;const K=T.get(W.id),Y=a.toLowerCase(),ee=!Y||W.deal_name.toLowerCase().includes(Y)||((pe=(oe=W.contact)==null?void 0:oe.first_name)==null?void 0:pe.toLowerCase().includes(Y))||((de=(ce=W.contact)==null?void 0:ce.last_name)==null?void 0:de.toLowerCase().includes(Y))||((ie=K==null?void 0:K.client_name)==null?void 0:ie.toLowerCase().includes(Y));let ne=!0;return l==="active"?ne=!!(K!=null&&K.is_enabled)&&!(K!=null&&K.archived_at):l==="disabled"?ne=!!K&&!K.is_enabled&&!K.archived_at:l==="archived"?ne=!!(K!=null&&K.archived_at):l==="none"?ne=!K:l==="all"&&(ne=!(K!=null&&K.archived_at)||!K),ee&&ne})].sort((W,K)=>{const Y=T.get(W.id),ee=T.get(K.id);if(Y!=null&&Y.archived_at&&!(ee!=null&&ee.archived_at))return 1;if(!(Y!=null&&Y.archived_at)&&(ee!=null&&ee.archived_at)||Y&&!ee)return-1;if(!Y&&ee)return 1;if(Y&&ee){if(Y.is_enabled&&!ee.is_enabled)return-1;if(!Y.is_enabled&&ee.is_enabled)return 1}return 0}),M=(n==null?void 0:n.filter(W=>!W.archived_at).length)||0,F=(n==null?void 0:n.filter(W=>W.is_enabled&&!W.archived_at).length)||0,z=(n==null?void 0:n.filter(W=>W.archived_at).length)||0,V=async()=>{if(b)try{await c.mutateAsync({id:b.id,dealId:b.deal_id}),ae.success("Portal permanently deleted"),v(null)}catch{ae.error("Failed to delete portal")}};return A?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[M," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[F," active · ",M-F," disabled",z>0&&` · ${z} archived`]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>_(!0),className:"gap-1.5",children:[e.jsx(xl,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search deals or clients...",value:a,onChange:W=>i(W.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(Fn,{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(W=>e.jsx(B,{variant:l===W?"secondary":"ghost",size:"sm",onClick:()=>o(W),className:"text-xs px-3 capitalize",children:W==="none"?"No Portal":W},W))})]}),e.jsx(mi,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[L.map(W=>{const K=T.get(W.id)||null,Y=W.contact?`${W.contact.first_name||""} ${W.contact.last_name||""}`.trim():"";return e.jsx(lJs,{dealId:W.id,dealName:W.deal_name,contactName:Y,portal:K,onSettingsOpen:u,onComposerOpen:ee=>p(ee),onInviteOpen:(ee,ne)=>g({portal:ee,dealName:ne}),onDeleteConfirm:v},W.id)}),L.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-muted rounded-full flex items-center justify-center",children:e.jsx(un,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm font-medium",children:"No matching deals"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Try adjusting your search or filters"})]})]})})]}),d&&e.jsx(S8e,{open:!!d,onOpenChange:W=>!W&&u(null),portal:d,dealOwnerId:S||""}),h&&e.jsx(C8e,{open:!!h,onOpenChange:W=>!W&&p(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),f&&e.jsx(T8e,{open:!!f,onOpenChange:W=>!W&&g(null),portal:f.portal,dealName:f.dealName}),e.jsx(L2t,{open:j,onOpenChange:_}),e.jsx(Oo,{open:!!b,onOpenChange:W=>!W&&v(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Permanently delete this portal?"}),e.jsx(Mo,{children:"This will permanently remove the portal and all its updates. The client will no longer be able to access their portal page. This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:V,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}class cJs extends N.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("DealPipeline error:",t,n)}render(){return this.state.hasError?e.jsx(Cs,{children:e.jsxs("div",{className:"flex flex-col items-center justify-center h-[60vh] gap-4 text-center px-4",children:[e.jsx("div",{className:"w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center",children:e.jsx("span",{className:"text-2xl",children:"⚠️"})}),e.jsx("h2",{className:"text-xl font-semibold",children:"Something went wrong"}),e.jsx("p",{className:"text-muted-foreground max-w-md",children:"There was an error in the deal pipeline. Click below to try again."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),className:"px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90",children:"Try Again"}),e.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 border border-border rounded-md text-sm font-medium hover:bg-muted",children:"Refresh Page"})]})]})}):this.props.children}}const $F="deal-pipeline-detail-sheet";function dJs(){var Ss;const s=kR(),{data:t,isLoading:n}=ZU(),{data:r,isLoading:a,refetch:i}=cbe(),{data:l,isLoading:o}=pQs(),c=N2t(),d=oQs(),[u,h]=N.useState("board"),[p,f]=N.useState(!1),[g,b]=N.useState(!1),[v,j]=N.useState(null),[_,S]=N.useState(null),[A,T]=N.useState(null),[D,L]=N.useState(null),[M,F]=N.useState(!1),[z,V]=N.useState(null),[W,K]=N.useState(""),[Y,ee]=N.useState("all"),[ne,oe]=N.useState("all"),[pe,ce]=N.useState("all"),{data:de}=sXs(),[ie,ye]=N.useState(!1),[_e,Me]=N.useState(!1),[Te,Ce]=N.useState(new Set),Ee=N.useRef(!1),[De,Ie]=N.useState(null),{data:Fe}=Xv(),{isTeamLeader:qe,teamMembers:ve}=eXs(),Je=N.useMemo(()=>Array.from(Te),[Te]),{data:we}=tXs(Je),it=N.useMemo(()=>{const Bs=new Map;return ve.forEach(Us=>Bs.set(Us.id,{name:Us.name,avatar_url:Us.avatar_url,color:Us.color})),Bs},[ve]),Ne=N.useCallback(Bs=>Bs.owner_user_id&&it.get(Bs.owner_user_id)||null,[it]),He=N.useCallback(Bs=>{Ce(Us=>{const sn=new Set(Us);return sn.has(Bs)?sn.delete(Bs):sn.add(Bs),sn})},[]);N.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[$e,Ye]=yl(),Ke=N.useRef(!1);N.useEffect(()=>{const Bs=$e.get("deal");if(Bs&&r&&r.length>0&&!Ke.current){const Us=r.find(sn=>sn.id===Bs);Us&&(Ke.current=!0,j(Us),b(!0),$e.delete("deal"),Ye($e,{replace:!0}))}},[r,$e]);const rt=N.useMemo(()=>{if(!we||!t)return[];const Bs=new Map(t.map(Us=>[Us.name,Us.id]));return we.map(Us=>{const sn=Us._stage_name&&Bs.get(Us._stage_name)||null;return{...Us,stage_id:sn||Us.stage_id}})},[we,t]),tt=N.useMemo(()=>[...r||[],...rt],[r,rt]);N.useEffect(()=>{if(Ee.current||tt.length===0)return;Ee.current=!0;const Bs=sessionStorage.getItem($F);if(Bs)try{const Us=JSON.parse(Bs);if(!Us.open||!Us.dealId)return;const sn=tt.find(Jn=>Jn.id===Us.dealId);sn&&(j(sn),b(!0))}catch{sessionStorage.removeItem($F)}},[tt]),N.useEffect(()=>{g&&(v!=null&&v.id)?sessionStorage.setItem($F,JSON.stringify({dealId:v.id,open:!0})):sessionStorage.removeItem($F)},[g,v==null?void 0:v.id]);const at=(de==null?void 0:de.byDeal)||{},Ge=(de==null?void 0:de.unique)||[],dt=tt.filter(Bs=>{var Ms,bi,Rr,er,lr,Fs;const Us=W.toLowerCase(),sn=at[Bs.id]||[],Jn=!Us||Bs.deal_name.toLowerCase().includes(Us)||((bi=(Ms=Bs.contact)==null?void 0:Ms.first_name)==null?void 0:bi.toLowerCase().includes(Us))||((er=(Rr=Bs.contact)==null?void 0:Rr.last_name)==null?void 0:er.toLowerCase().includes(Us))||((lr=Bs.property_address)==null?void 0:lr.toLowerCase().includes(Us))||((Fs=Bs.city)==null?void 0:Fs.toLowerCase().includes(Us))||sn.some($n=>$n.toLowerCase().includes(Us)),fn=Y==="all"||Bs.deal_type===Y,Sn=ne==="all"||sn.includes(ne),Gn=Bs.actual_close_date||Bs.target_close_date||Bs.contract_date||Bs.created_at,Hr=Gn?String(Gn).slice(0,4):null;return Jn&&fn&&Sn&&(pe==="all"||Hr===pe)}),Bt=N.useMemo(()=>{const Bs=new Set;return Bs.add(String(new Date().getFullYear())),tt.forEach(Us=>{const sn=Us.actual_close_date||Us.target_close_date||Us.contract_date||Us.created_at;sn&&Bs.add(String(sn).slice(0,4))}),Array.from(Bs).sort((Us,sn)=>Number(sn)-Number(Us))},[tt]),kt=N.useMemo(()=>{if(!t)return l||null;const Bs=new Set(t.filter(Gn=>Gn.is_won_stage).map(Gn=>Gn.id)),Us=new Set(t.filter(Gn=>Gn.is_lost_stage).map(Gn=>Gn.id)),sn=tt.filter(Gn=>Gn.stage_id&&!Bs.has(Gn.stage_id)&&!Us.has(Gn.stage_id)),Jn=tt.filter(Gn=>Gn.stage_id&&Bs.has(Gn.stage_id)),fn=new Date().getFullYear(),Sn=Jn.filter(Gn=>Gn.actual_close_date?new Date(Gn.actual_close_date).getFullYear()===fn:!0);return{totalDeals:tt.length,activeDeals:sn.length,wonDeals:Jn.length,pipelineValue:sn.reduce((Gn,Hr)=>Gn+(Hr.expected_price||0),0),expectedCommission:sn.reduce((Gn,Hr)=>Gn+(Hr.expected_commission||0),0),expectedNetToAgent:sn.reduce((Gn,Hr)=>Gn+(Ev(Hr)||0),0),wonValue:Jn.reduce((Gn,Hr)=>Gn+(Hr.expected_price||0),0),weightedGCI:sn.reduce((Gn,Hr)=>Gn+(Hr.expected_commission||0)*((Hr.probability??50)/100),0),weightedNet:sn.reduce((Gn,Hr)=>Gn+(Ev(Hr)||0)*((Hr.probability??50)/100),0),ytdWonDeals:Sn.length,ytdWonGCI:Sn.reduce((Gn,Hr)=>Gn+(Hr.expected_commission||0),0),ytdWonNet:Sn.reduce((Gn,Hr)=>Gn+(Ev(Hr)||0),0),projectedAnnualNet:Sn.reduce((Gn,Hr)=>Gn+(Ev(Hr)||0),0)+sn.reduce((Gn,Hr)=>Gn+(Ev(Hr)||0)*((Hr.probability??50)/100),0)}},[tt,t,l]),Qt=Bs=>{j(Bs),b(!0)},ns=Bs=>{S(Bs||null),j(null),f(!0)},$s=Bs=>{j(Bs),b(!1),f(!0)},Ds=Bs=>{b(Bs),Bs||sessionStorage.removeItem($F)},Dt=(Bs,Us)=>{T(Bs)},St=(Bs,Us)=>{Bs.preventDefault(),Bs.dataTransfer.dropEffect="move",L(Us)},$t=async(Bs,Us)=>{if(Bs.preventDefault(),L(null),!A)return;const sn=r==null?void 0:r.find(Sn=>Sn.id===A),Jn=t==null?void 0:t.find(Sn=>Sn.id===Us),fn=t==null?void 0:t.find(Sn=>Sn.id===(sn==null?void 0:sn.stage_id));if(!sn||!Jn||sn.stage_id===Us){T(null);return}Ie({dealId:A,dealName:sn.deal_name,fromStageName:(fn==null?void 0:fn.name)||"Unknown",toStageName:Jn.name,toStageId:Us,isWonStage:Jn.is_won_stage,deal:sn}),T(null)},ht=async()=>{if(!De)return;const{dealId:Bs,toStageId:Us,toStageName:sn,isWonStage:Jn,deal:fn}=De;if(await d.mutateAsync({dealId:Bs,stageId:Us,stageName:sn}),ae.success(`Moved to ${sn}`),Jn&&!fn.scorecard_transaction_id){const Sn={...fn,stage_id:Us};V(Sn),F(!0)}},Ut=N.useCallback(async(Bs,Us,sn)=>{const Jn=r==null?void 0:r.find(Gn=>Gn.id===Bs),fn=t==null?void 0:t.find(Gn=>Gn.id===Us),Sn=t==null?void 0:t.find(Gn=>Gn.id===(Jn==null?void 0:Jn.stage_id));!Jn||!fn||Jn.stage_id===Us||Ie({dealId:Bs,dealName:Jn.deal_name,fromStageName:(Sn==null?void 0:Sn.name)||"Unknown",toStageName:sn,toStageId:Us,isWonStage:fn.is_won_stage,deal:Jn})},[r,t]),Es=Bs=>dt.filter(Us=>Us.stage_id===Bs),Xt=n||a,Ys=s?"list":u;return e.jsxs(Cs,{children:[e.jsxs("div",{className:"flex flex-col h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"shrink-0 p-4 md:p-6 pb-0 space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Deal Pipeline"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Track and manage your active deals"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>i(),className:"shrink-0",children:e.jsx(Ai,{className:"h-4 w-4"})}),!s&&e.jsx(Kw,{children:e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsxs(B,{variant:u==="board"?"secondary":"ghost",size:"sm",onClick:()=>h("board"),className:"px-3 gap-1.5",children:[e.jsx(vf,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Board"})]})}),e.jsx(yc,{children:"Kanban board view"})]}),e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsxs(B,{variant:u==="list"?"secondary":"ghost",size:"sm",onClick:()=>h("list"),className:"px-3 gap-1.5",children:[e.jsx(Ep,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"List"})]})}),e.jsx(yc,{children:"Grouped list view"})]}),e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsxs(B,{variant:u==="table"?"secondary":"ghost",size:"sm",onClick:()=>h("table"),className:"px-3 gap-1.5",children:[e.jsx(_L,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Table"})]})}),e.jsx(yc,{children:"Sortable table view"})]}),e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsxs(B,{variant:u==="portals"?"secondary":"ghost",size:"sm",onClick:()=>h("portals"),className:"px-3 gap-1.5",children:[e.jsx(un,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Portals"})]})}),e.jsx(yc,{children:"Client portal management"})]})]})}),Fe&&!qe&&e.jsxs(B,{variant:"outline",onClick:()=>ye(!0),children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Team"]}),e.jsxs(B,{onClick:()=>ns(),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Deal"]})]})]}),Ys!=="portals"&&e.jsx(iXs,{stats:kt,isLoading:o}),Ys!=="portals"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search deals, contacts, addresses, tags...",value:W,onChange:Bs=>K(Bs.target.value),className:"pl-9 pr-8"}),W&&e.jsx("button",{onClick:()=>K(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(Fn,{className:"h-4 w-4"})})]}),e.jsxs(us,{value:Y,onValueChange:ee,children:[e.jsx(cs,{className:"w-[140px]",children:e.jsx(hs,{placeholder:"All Types"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"}),e.jsx(Ze,{value:"dual",children:"Dual"}),e.jsx(Ze,{value:"referral",children:"Referral"}),e.jsx(Ze,{value:"lease",children:"Lease"})]})]}),e.jsxs(us,{value:pe,onValueChange:ce,children:[e.jsx(cs,{className:"w-[120px]",children:e.jsx(hs,{placeholder:"Year"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Years"}),Bt.map(Bs=>e.jsx(Ze,{value:Bs,children:Bs},Bs))]})]}),e.jsxs(us,{value:ne,onValueChange:oe,children:[e.jsxs(cs,{className:"w-[160px]",children:[e.jsx(mh,{className:"h-3.5 w-3.5 mr-1.5 text-muted-foreground"}),e.jsx(hs,{placeholder:"All Tags"})]}),e.jsxs(ds,{className:"max-h-[300px]",children:[e.jsx(Ze,{value:"all",children:"All Tags"}),Ge.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),Ge.map(Bs=>e.jsx(Ze,{value:Bs,children:Bs},Bs))]})]}),ne!=="all"&&e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(mh,{className:"h-3 w-3"}),ne,e.jsx("button",{onClick:()=>oe("all"),className:"ml-1 hover:text-foreground","aria-label":"Clear tag filter",children:e.jsx(Fn,{className:"h-3 w-3"})})]}),(W||Y!=="all"||ne!=="all"||pe!=="all")&&e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[dt.length," of ",(r==null?void 0:r.length)||0," deals"]})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[qe&&!s&&ve.length>0&&e.jsx(JQs,{members:ve,enabledMembers:Te,onToggleMember:He,isOpen:_e,onToggleOpen:()=>Me(Bs=>!Bs)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:Xt?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(Bs=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(Ws,{className:"h-full rounded-xl"})},Bs))}):Ys==="board"?e.jsxs(mi,{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(Bs=>e.jsx(aXs,{stage:Bs,deals:Es(Bs.id),onDealClick:Qt,onAddDeal:ns,onDragStart:Dt,onDragOver:St,onDrop:$t,isDragOver:D===Bs.id,isWonStage:Bs.is_won_stage,getOwnerInfo:Ne},Bs.id))}),e.jsx(cU,{orientation:"horizontal"})]}):Ys==="table"?e.jsx(mi,{className:"h-full",children:e.jsx(GXs,{deals:dt,stages:t||[],onDealClick:Qt,onStageChange:Ut})}):Ys==="portals"?e.jsx(D2t,{}):e.jsx(mi,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(Bs=>{const Us=Es(Bs.id);return Us.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:Bs.color}}),e.jsx("h3",{className:"font-semibold",children:Bs.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",Us.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:Us.map(sn=>e.jsx(M2t,{deal:sn,onClick:()=>Qt(sn),stages:t,onStageChange:Ut,showStagePicker:!0,isWonStage:Bs.is_won_stage,ownerInfo:Ne(sn)},sn.id))})]},Bs.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(vf,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start tracking your opportunities by adding your first deal"}),e.jsxs(B,{onClick:()=>ns(),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&dt.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(_r,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No matching deals"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Try adjusting your search or filters"}),e.jsx(B,{variant:"outline",onClick:()=>{K(""),ee("all"),oe("all"),ce("all")},children:"Clear Filters"})]})]})})})]})]}),e.jsx(dXs,{open:p,onOpenChange:f,deal:v,defaultStageId:_}),e.jsx(qXs,{deal:v,open:g,onOpenChange:Ds,onEdit:$s,isWonStage:v?(Ss=t==null?void 0:t.find(Bs=>Bs.id===v.stage_id))==null?void 0:Ss.is_won_stage:!1,onAddToScorecard:Bs=>{V(Bs),F(!0),b(!1)}}),e.jsx(VXs,{open:M,onOpenChange:F,deal:z,onComplete:()=>{i(),V(null)}}),De&&e.jsx(rJs,{open:!!De,onOpenChange:Bs=>{Bs||Ie(null)},dealId:De.dealId,dealName:De.dealName,fromStageName:De.fromStageName,toStageName:De.toStageName,toStageId:De.toStageId,onConfirm:ht}),e.jsx(QQs,{open:ie,onOpenChange:ye})]})}function uJs(){return e.jsx(cJs,{children:e.jsx(dJs,{})})}function R2t({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var K;const i=YXs(),l=ZXs(),{data:o}=cbe(),c=fa(),{data:d}=lt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:Y,error:ee}=await q.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(ee)throw ee;return Y},enabled:!!c&&s}),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,b]=N.useState("none"),[v,j]=N.useState("none"),[_,S]=N.useState("medium"),[A,T]=N.useState("todo"),[D,L]=N.useState(),[M,F]=N.useState(!1),[z,V]=N.useState(!1);N.useEffect(()=>{n?(h(n.title),f(n.description||""),b(n.deal_id||"none"),j(n.contact_id||"none"),S(n.priority),T(n.status),L(n.due_date?Lu(n.due_date):void 0)):(h(""),f(""),b(r||"none"),j("none"),S("medium"),T("todo"),L(void 0))},[n,s,r]);const W=async()=>{if(!u.trim()){ae.error("Task title is required");return}try{const Y={title:u.trim(),description:p.trim()||null,deal_id:g==="none"?null:g,contact_id:v==="none"?null:v,stage_id:a||null,priority:_,status:A,due_date:D?ks(D,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...Y}),ae.success("Task updated")):(await i.mutateAsync(Y),ae.success("Task created")),t(!1)}catch{ae.error("Failed to save task")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[480px]",children:[e.jsx(ws,{children:e.jsx(_s,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(ge,{value:u,onChange:Y=>h(Y.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{value:p,onChange:Y=>f(Y.target.value),placeholder:"Optional details...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Priority"}),e.jsxs(us,{value:_,onValueChange:Y=>S(Y),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"low",children:"🟢 Low"}),e.jsx(Ze,{value:"medium",children:"🟡 Medium"}),e.jsx(Ze,{value:"high",children:"🟠 High"}),e.jsx(Ze,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(us,{value:A,onValueChange:Y=>T(Y),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"todo",children:"To Do"}),e.jsx(Ze,{value:"in_progress",children:"In Progress"}),e.jsx(Ze,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due Date"}),e.jsxs(Wo,{children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!D&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),D?ks(D,"PPP"):"Pick a date"]})}),e.jsx(zo,{className:"w-auto p-0",align:"start",children:e.jsx(ag,{mode:"single",selected:D,onSelect:L,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Link to Deal"}),e.jsxs(Wo,{open:M,onOpenChange:F,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(Ga,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),g!=="none"?((K=o==null?void 0:o.find(Y=>Y.id===g))==null?void 0:K.deal_name)||"Select deal":"No Deal"]}),e.jsx(Hg,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(zo,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search deals..."}),e.jsxs(e0,{children:[e.jsx(t0,{children:"No deals found."}),e.jsxs(s0,{children:[e.jsxs(ex,{value:"no-deal",onSelect:()=>{b("none"),F(!1)},children:[e.jsx(Lr,{className:Et("mr-2 h-4 w-4",g==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(Y=>e.jsxs(ex,{value:Y.deal_name,onSelect:()=>{b(Y.id),F(!1)},children:[e.jsx(Lr,{className:Et("mr-2 h-4 w-4",g===Y.id?"opacity-100":"opacity-0")}),Y.deal_name]},Y.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Link to Contact"}),e.jsxs(Wo,{open:z,onOpenChange:V,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(Xi,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),v!=="none"?(()=>{const Y=d==null?void 0:d.find(ee=>ee.id===v);return Y?`${Y.first_name} ${Y.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(Hg,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(zo,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search contacts..."}),e.jsxs(e0,{children:[e.jsx(t0,{children:"No contacts found."}),e.jsxs(s0,{children:[e.jsxs(ex,{value:"no-contact",onSelect:()=>{j("none"),V(!1)},children:[e.jsx(Lr,{className:Et("mr-2 h-4 w-4",v==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(Y=>e.jsxs(ex,{value:`${Y.first_name} ${Y.last_name}`,onSelect:()=>{j(Y.id),V(!1)},children:[e.jsx(Lr,{className:Et("mr-2 h-4 w-4",v===Y.id?"opacity-100":"opacity-0")}),Y.first_name," ",Y.last_name]},Y.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:W,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const hJs={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 mJs({tasks:s}){const t=dbe(),n=QXs(),r=In(),[a,i]=N.useState(null),l=async u=>{const h=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:h})}catch{ae.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),ae.success("Task deleted")}catch{ae.error("Failed to delete task")}};if(s.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx(xr,{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(_Xe,{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(Ga,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs(ze,{variant:"secondary",className:"ml-auto text-xs",children:[h.tasks.filter(p=>p.status==="done").length,"/",h.tasks.length]}),e.jsx(ga,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),h.tasks.map(p=>e.jsx(_Xe,{task:p,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:f=>r(`/mission-control/pipeline?deal=${f}`)},p.id))]},u)),a&&e.jsx(R2t,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function _Xe({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&jw(Lu(s.due_date))&&!df(Lu(s.due_date)),o=!i&&s.due_date&&df(Lu(s.due_date)),c=hJs[s.priority];return e.jsxs("div",{className:Et("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(xr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(dm,{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:Et("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(Xi,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(ze,{variant:"outline",className:Et("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Et("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(gr,{className:"h-3 w-3"}),ks(Lu(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(Tu,{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(bn,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const pJs=[{status:"todo",label:"To Do",icon:dm,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:Pu,color:"border-t-blue-500"},{status:"done",label:"Done",icon:xr,color:"border-t-emerald-500"}],fJs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function xJs({tasks:s}){const t=dbe(),n=N.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),r=(i,l)=>{i.dataTransfer.setData("taskId",l)},a=async(i,l)=>{i.preventDefault();const o=i.dataTransfer.getData("taskId");if(!o)return;const c=s.find(d=>d.id===o);if(!(!c||c.status===l))try{await t.mutateAsync({id:o,status:l})}catch{ae.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:pJs.map(i=>e.jsxs("div",{className:Et("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(ze,{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(gJs,{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 gJs({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&jw(Lu(s.due_date))&&!df(Lu(s.due_date)),a=!n&&s.due_date&&df(Lu(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Et("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:fJs[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Et("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(Ga,{className:"h-2.5 w-2.5"}),s.deal.deal_name]}),s.contact&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(Xi,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Et("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(gr,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",ks(Lu(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 wXe={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function yJs({tasks:s}){const[t,n]=N.useState(new Date),r=dbe(),a=Bd(t),i=H0(t),l=Km(a),o=k8(i),c=B4e({start:l,end:o}),d=N.useMemo(()=>{const p=new Map;return s.forEach(f=>{if(!f.due_date)return;const g=f.due_date,b=p.get(g)||[];b.push(f),p.set(g,b)}),p},[s]),u=N.useMemo(()=>s.filter(p=>!p.due_date),[s]),h=async p=>{const f=p.status==="done"?"todo":"done";try{await r.mutateAsync({id:p.id,status:f})}catch{ae.error("Failed to update task")}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>n(WE(t,1)),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:ks(t,"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>n(kf(t,1)),children:e.jsx(ga,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(p=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:p},p))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(p=>{const f=ks(p,"yyyy-MM-dd"),g=d.get(f)||[],b=aU(p,t),v=df(p);return e.jsxs("div",{className:Et("border-r border-b min-h-[100px] p-1",!b&&"bg-muted/30",v&&"bg-primary/5"),children:[e.jsx("div",{className:Et("text-xs font-medium mb-1 text-right px-1",!b&&"text-muted-foreground/40",v&&"text-primary font-bold"),children:ks(p,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[g.slice(0,3).map(j=>e.jsxs("button",{onClick:()=>h(j),className:Et("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",j.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[j.status==="done"?e.jsx(xr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(dm,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[wXe[j.priority]," ",j.title]})]},j.id)),g.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",g.length-3," more"]})]})]},f)})}),u.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",u.length,")"]}),e.jsx("div",{className:"space-y-1",children:u.map(p=>e.jsxs("button",{onClick:()=>h(p),className:Et("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",p.status==="done"&&"opacity-50 line-through"),children:[p.status==="done"?e.jsx(xr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(dm,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[wXe[p.priority]," ",p.title]}),p.deal&&e.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",p.deal.deal_name]})]},p.id))})]})]})}const vJs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function bJs({open:s,onOpenChange:t,stages:n}){var j;const[r,a]=N.useState(((j=n[0])==null?void 0:j.id)||""),{data:i,isLoading:l}=JXs(r||void 0),o=eJs(),c=tJs(),[d,u]=N.useState(""),[h,p]=N.useState("medium"),[f,g]=N.useState(""),b=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:f?parseInt(f):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),g(""),ae.success("Template added")}catch{ae.error("Failed to add template")}},v=async _=>{try{await c.mutateAsync(_),ae.success("Template deleted")}catch{ae.error("Failed to delete template")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[560px]",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(r9,{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(se,{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:Et("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(mi,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((_,S)=>e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border rounded-lg group",children:[e.jsx("span",{className:"text-xs",children:vJs[_.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:_.title}),_.default_due_offset_days&&e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:["+",_.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>v(_.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(bn,{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(se,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{placeholder:"Task title...",value:d,onChange:_=>u(_.target.value),className:"flex-1",onKeyDown:_=>_.key==="Enter"&&b()}),e.jsxs(us,{value:h,onValueChange:_=>p(_),children:[e.jsx(cs,{className:"w-[100px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"low",children:"🟢 Low"}),e.jsx(Ze,{value:"medium",children:"🟡 Med"}),e.jsx(Ze,{value:"high",children:"🟠 High"}),e.jsx(Ze,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(ge,{type:"number",placeholder:"e.g., 7",value:f,onChange:_=>g(_.target.value)})]}),e.jsxs(B,{onClick:b,disabled:!d.trim()||o.isPending,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function _Js(){const{data:s,isLoading:t}=WXs(),{data:n}=ZU(),[r,a]=N.useState("list"),[i,l]=N.useState(""),[o,c]=N.useState("active"),[d,u]=N.useState("all"),[h,p]=N.useState("all"),[f,g]=N.useState(!1),[b,v]=N.useState(!1),j=N.useMemo(()=>{if(!s)return[];const A=new Map;return s.forEach(T=>{T.deal&&A.set(T.deal.id,T.deal.deal_name)}),Array.from(A,([T,D])=>({id:T,name:D}))},[s]),_=N.useMemo(()=>s?s.filter(A=>{var z,V,W,K;const T=i.toLowerCase(),D=!T||A.title.toLowerCase().includes(T)||((V=(z=A.deal)==null?void 0:z.deal_name)==null?void 0:V.toLowerCase().includes(T))||`${((W=A.contact)==null?void 0:W.first_name)||""} ${((K=A.contact)==null?void 0:K.last_name)||""}`.toLowerCase().includes(T),L=o==="all"||o==="active"&&A.status!=="done"||o==="todo"&&A.status==="todo"||o==="in_progress"&&A.status==="in_progress"||o==="done"&&A.status==="done"||o==="overdue"&&A.status!=="done"&&A.due_date&&jw(Lu(A.due_date))&&!df(Lu(A.due_date)),M=d==="all"||A.priority===d,F=h==="all"||h==="no_deal"&&!A.deal_id||A.deal_id===h;return D&&L&&M&&F}):[],[s,i,o,d,h]),S=N.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const A=s.filter(T=>T.status!=="done");return{total:A.length,overdue:A.filter(T=>T.due_date&&jw(Lu(T.due_date))&&!df(Lu(T.due_date))).length,dueToday:A.filter(T=>T.due_date&&df(Lu(T.due_date))).length,dueThisWeek:A.filter(T=>T.due_date&&WUt(Lu(T.due_date))).length,completed:s.filter(T=>T.status==="done").length}},[s]);return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>v(!0),children:[e.jsx(Fv,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(B,{size:"sm",onClick:()=>g(!0),children:[e.jsx(As,{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(Ep,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.total})]}),e.jsxs("button",{onClick:()=>c("overdue"),className:`p-3 rounded-lg border text-left transition-colors ${o==="overdue"?"border-destructive bg-destructive/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-destructive text-xs font-medium",children:[e.jsx(Dl,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:S.overdue})]}),e.jsxs("button",{onClick:()=>{c("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs font-medium",children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.dueToday})]}),e.jsxs("button",{onClick:()=>{c("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 text-blue-600 text-xs font-medium",children:[e.jsx(Tl,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.dueThisWeek})]}),e.jsxs("button",{onClick:()=>c("done"),className:`p-3 rounded-lg border text-left transition-colors ${o==="done"?"border-emerald-500 bg-emerald-500/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 text-xs font-medium",children:[e.jsx(xr,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.completed})]})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 items-start md:items-center",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search tasks...",value:i,onChange:A=>l(A.target.value),className:"pl-9"})]}),e.jsxs(us,{value:d,onValueChange:u,children:[e.jsx(cs,{className:"w-[130px]",children:e.jsx(hs,{placeholder:"Priority"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Priorities"}),e.jsx(Ze,{value:"urgent",children:"🔴 Urgent"}),e.jsx(Ze,{value:"high",children:"🟠 High"}),e.jsx(Ze,{value:"medium",children:"🟡 Medium"}),e.jsx(Ze,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(cs,{className:"w-[160px]",children:e.jsx(hs,{placeholder:"Deal"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Deals"}),e.jsx(Ze,{value:"no_deal",children:"No Deal"}),j.map(A=>e.jsx(Ze,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[e.jsx("button",{onClick:()=>a("list"),className:`p-1.5 rounded-md transition-colors ${r==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(Ep,{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(Q2,{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(Tl,{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(mJs,{tasks:_}),r==="kanban"&&e.jsx(xJs,{tasks:_}),r==="calendar"&&e.jsx(yJs,{tasks:_})]}),e.jsx(R2t,{open:f,onOpenChange:g}),e.jsx(bJs,{open:b,onOpenChange:v,stages:n||[]})]})})}function wJs(s){const t=E8e(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function jJs({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 IG({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:Et("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 NJs(){const s=In(),{data:t,isLoading:n}=PXs(),r=dbe(),[a,i]=N.useState(""),[l,o]=N.useState(!1),[c,d]=N.useState("all"),u=N.useMemo(()=>{let _=t||[];c==="contract"&&(_=_.filter(A=>!!A.contract_date));const S=a.trim().toLowerCase();return S&&(_=_.filter(A=>{var T,D,L,M;return((T=A.deal_name)==null?void 0:T.toLowerCase().includes(S))||((D=A.property_address)==null?void 0:D.toLowerCase().includes(S))||`${((L=A.contact)==null?void 0:L.first_name)??""} ${((M=A.contact)==null?void 0:M.last_name)??""}`.toLowerCase().includes(S)})),_},[t,a,c]),h=N.useMemo(()=>{const _=[];return(u||[]).forEach(S=>{P7.forEach(A=>{const T=S[A.key],D=V_(T);T&&D!==null&&D<=30&&_.push({id:`${S.id}-${A.key}`,kind:"date",label:A.label,dealId:S.id,dealName:S.deal_name,date:T,days:D})}),S.tasks.filter(A=>A.status!=="done"&&A.due_date).forEach(A=>{const T=V_(A.due_date);T!==null&&T<=30&&_.push({id:A.id,kind:"task",label:A.title,dealId:S.id,dealName:S.deal_name,date:A.due_date,days:T,priority:A.priority})})}),_.sort((S,A)=>S.days-A.days)},[u]),p=N.useMemo(()=>({overdue:h.filter(_=>_.days<0),today:h.filter(_=>_.days===0),week:h.filter(_=>_.days>0&&_.days<=7),later:h.filter(_=>_.days>7)}),[h]),f=N.useMemo(()=>{const _=t||[],S=_.filter(D=>{const L=V_(D.target_close_date);return L!==null&&L>=0&&L<=7}).length,A=_.reduce((D,L)=>D+L.tasks.filter(M=>{const F=V_(M.due_date);return M.status!=="done"&&F!==null&&F<0}).length,0),T=_.reduce((D,L)=>D+(Number(L.expected_price)||0),0);return{active:_.length,closingSoon:S,overdueTasks:A,volume:T}},[t]),g=_=>_.tasks.length===0?0:_.tasks.filter(S=>S.status==="done").length/_.tasks.length*100,b=_=>s(`/mission-control/pipeline?deal=${_}`),v=async _=>{try{await r.mutateAsync({id:_,status:"done"}),ae.success("Task completed")}catch{ae.error("Could not update task")}},j=({title:_,items:S,tone:A})=>{if(S.length===0)return null;const T=A==="danger"?"bg-destructive":A==="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:Et("h-1.5 w-1.5 rounded-full",T)}),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:["(",S.length,")"]})]}),S.slice(0,12).map(D=>e.jsxs("div",{className:Et("group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors hover:bg-muted/50",A==="danger"&&"border-destructive/30 bg-destructive/5"),children:[D.kind==="task"?e.jsx(hi,{className:"shrink-0",onCheckedChange:()=>v(D.id),"aria-label":`Complete ${D.label}`}):e.jsx(cm,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>b(D.dealId),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium leading-tight truncate",children:D.label}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[D.dealName," · ",wJs(D.date)]})]}),e.jsx("span",{className:Et("text-[11px] font-semibold shrink-0 tabular-nums",D.days<0?"text-destructive":D.days<=3?"text-amber-600":"text-muted-foreground"),children:D.days<0?`${Math.abs(D.days)}d late`:D.days===0?"Today":`${D.days}d`})]},D.id))]})};return e.jsxs(Cs,{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(B,{onClick:()=>o(!0),className:"gap-2 shrink-0",children:[e.jsx($u,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(IG,{icon:Ov,label:"Active transactions",value:f.active}),e.jsx(IG,{icon:_c,label:"Closing within 7 days",value:f.closingSoon,tone:"warn"}),e.jsx(IG,{icon:Dl,label:"Overdue tasks",value:f.overdueTasks,tone:f.overdueTasks>0?"danger":"good"}),e.jsx(IG,{icon:mo,label:"Pipeline volume",value:f.volume>=1e6?`$${(f.volume/1e6).toFixed(1)}M`:`$${Math.round(f.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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{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(B,{size:"sm",variant:c==="all"?"default":"ghost",onClick:()=>d("all"),className:"h-8",children:"All active"}),e.jsx(B,{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(ss,{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(cm,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Deadline Radar"}),e.jsx(ze,{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(xr,{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(j,{title:"Overdue",items:p.overdue,tone:"danger"}),e.jsx(j,{title:"Today",items:p.today,tone:"warn"}),e.jsx(j,{title:"This week",items:p.week,tone:"warn"}),e.jsx(j,{title:"Coming up",items:p.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(zr,{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(B,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/pipeline"),children:"Go to Deal Pipeline"})]}):u.map(_=>{const S=g(_),A=V_(_.target_close_date),T=_.tasks.filter(M=>M.status!=="done"),D=T.filter(M=>{const F=V_(M.due_date);return F!==null&&F<0}),L=T.filter(M=>M.due_date).sort((M,F)=>(V_(M.due_date)??0)-(V_(F.due_date)??0))[0];return e.jsx("button",{type:"button",onClick:()=>b(_.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(jJs,{value:S}),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(ga,{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(ze,{variant:"outline",className:"text-[10px] capitalize",children:_.deal_type}),A!==null&&e.jsx(ze,{variant:"secondary",className:Et("text-[10px]",A<0&&"bg-destructive/10 text-destructive",A>=0&&A<=7&&"bg-amber-500/10 text-amber-700 dark:text-amber-400"),children:A<0?`Closing ${Math.abs(A)}d overdue`:`Closes in ${A}d`}),D.length>0&&e.jsxs(ze,{className:"text-[10px] bg-destructive/10 text-destructive hover:bg-destructive/10",children:[D.length," overdue"]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(xi,{value:S,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(M=>M.status==="done").length," of"," ",_.tasks.length," steps complete"]}),L&&e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[55%]",children:["Next: ",L.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(P2t,{open:l,onOpenChange:o})]})}function O2t(){const s=fa();return lt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function kJs(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("portal_referrals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function SJs(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("portal_referrals").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const CJs=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),HNe=[{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"}],TJs={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function F2t(){const{data:s=[],isLoading:t}=O2t(),n=kJs(),r=SJs(),[a,i]=N.useState("all"),[l,o]=N.useState({}),c=N.useMemo(()=>a==="all"?s:s.filter(f=>f.status===a),[s,a]),d=N.useMemo(()=>({total:s.length,new:s.filter(f=>f.status==="new").length,converted:s.filter(f=>f.status==="converted").length}),[s]),u=(f,g)=>{n.mutate({id:f.id,status:g}),ae.success("Status updated")},h=f=>{const g=l[f.id];n.mutate({id:f.id,agent_notes:g}),o(b=>{const{[f.id]:v,...j}=b;return j}),ae.success("Notes saved")},p=f=>{confirm(`Delete referral for ${f.friend_name}?`)&&r.mutate(f.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(Yo,{children:e.jsx("title",{children:"Client Portal Referrals"})}),e.jsxs("div",{className:"flex items-start justify-between mb-6 flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Bi,{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"},...HNe.map(f=>({v:f.value,l:f.label}))].map(f=>e.jsx("button",{onClick:()=>i(f.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===f.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:f.l},f.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center",children:[e.jsx(Bi,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once your closed clients refer friends from their portal, they'll show up here."})]})}):e.jsx("div",{className:"space-y-3",children:c.map(f=>{var j,_;const g=HNe.find(S=>S.value===f.status),b=(j=f.client_portals)==null?void 0:j.slug,v=f.referrer_name||((_=f.client_portals)==null?void 0:_.client_name)||"Anonymous client";return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(Pt,{className:"text-lg",children:f.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(yr,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:v})," ·"," ",CJs(f.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"outline",className:g==null?void 0:g.className,children:(g==null?void 0:g.label)||f.status}),e.jsxs(us,{value:f.status,onValueChange:S=>u(f,S),children:[e.jsx(cs,{className:"h-8 w-[130px] text-xs",children:e.jsx(hs,{})}),e.jsx(ds,{children:HNe.map(S=>e.jsx(Ze,{value:S.value,className:"text-xs",children:S.label},S.value))})]})]})]})}),e.jsxs(Ae,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.friend_interest&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:TJs[f.friend_interest]||f.friend_interest}),f.friend_email&&e.jsxs("a",{href:`mailto:${f.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Hs,{className:"h-3 w-3"}),f.friend_email]}),f.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Pr,{className:"h-3 w-3"}),f.friend_phone]}),e.jsxs("a",{href:`sms:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ql,{className:"h-3 w-3"}),"Text"]})]})]}),f.friend_message&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 text-sm",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Note from referrer"}),e.jsxs("p",{className:"italic text-foreground",children:['"',f.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[f.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ts,{value:l[f.id],onChange:S=>o(A=>({...A,[f.id]:S.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:()=>h(f),children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>o(S=>{const{[f.id]:A,...T}=S;return T}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(S=>({...S,[f.id]:f.agent_notes||""})),className:"text-sm text-left w-full p-2 rounded border border-dashed border-input hover:border-primary/50 hover:bg-muted/30 transition-colors",children:f.agent_notes||e.jsx("span",{className:"text-muted-foreground italic",children:"Click to add notes..."})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[b&&e.jsxs("a",{href:`/portal/${b}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(tr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>p(f),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})]},f.id)})})]})}function z2t({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=ZD.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(fe,{className:"p-4 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-muted flex items-center justify-center overflow-hidden shrink-0",children:s.logo_url?e.jsx("img",{src:s.logo_url,alt:s.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-lg font-semibold text-muted-foreground",children:s.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:s.name}),s.is_required&&e.jsx(Rc,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(ua,{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(ze,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(ze,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(ze,{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(Pr,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Hs,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.email})]}),s.website&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(lc,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.website})]}),s.booking_url&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(yr,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:"Booking link"})]}),s.address&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ca,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.address})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t",children:[r&&e.jsxs(B,{size:"sm",variant:a?"default":"outline",onClick:()=>r(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(Ir,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(gf,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx(B,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(Tu,{className:"w-3.5 h-3.5"})}),n&&e.jsx(B,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(bn,{className:"w-3.5 h-3.5"})})]})]})}function B2t({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=LJt(),[c,d]=N.useState({}),[u,h]=N.useState(!1),p=N.useRef(null),f=async v=>{if(!v.type.startsWith("image/")){ae.error("Please select an image");return}if(v.size>5*1024*1024){ae.error("Image must be under 5MB");return}h(!0);try{const j=v.name.split(".").pop()||"png",_=`${r}/${a||i||"misc"}/${Date.now()}.${j}`,{error:S}=await q.storage.from("vendor-logos").upload(_,v,{upsert:!0,contentType:v.type});if(S)throw S;const{data:A}=q.storage.from("vendor-logos").getPublicUrl(_);d(T=>({...T,logo_url:A.publicUrl})),ae.success("Logo uploaded")}catch(j){ae.error(j.message||"Upload failed")}finally{h(!1)}};N.useEffect(()=>{s&&d(n||{owner_type:r,owner_brokerage_id:r==="brokerage"&&a||null,owner_user_id:r==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,n,r,a,i]);const g=(v,j)=>d(_=>({..._,[v]:j})),b=async()=>{var v;if(!((v=c.name)!=null&&v.trim())){ae.error("Name is required");return}try{await o.mutateAsync(c),ae.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(j){ae.error(j.message||"Failed to save vendor")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Contact Name *"}),e.jsx(ge,{value:c.name||"",onChange:v=>g("name",v.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Company"}),e.jsx(ge,{value:c.company||"",onChange:v=>g("company",v.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(us,{value:c.category,onValueChange:v=>g("category",v),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:ZD.map(v=>e.jsx(Ze,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ge,{value:c.phone||"",onChange:v=>g("phone",v.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ge,{type:"email",value:c.email||"",onChange:v=>g("email",v.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Website"}),e.jsx(ge,{value:c.website||"",onChange:v=>g("website",v.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Logo"}),e.jsx("input",{ref:p,type:"file",accept:"image/*",className:"hidden",onChange:v=>{var _;const j=(_=v.target.files)==null?void 0:_[0];j&&f(j),v.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>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(Fn,{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(Sa,{className:"h-5 w-5"})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=p.current)==null?void 0:v.click()},disabled:u,children:[u?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Address"}),e.jsx(ge,{value:c.address||"",onChange:v=>g("address",v.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{rows:3,value:c.description||"",onChange:v=>g("description",v.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Primary Action"}),e.jsxs(us,{value:c.action_type,onValueChange:v=>g("action_type",v),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:MJt.map(v=>e.jsx(Ze,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Booking URL (Calendly etc.)"}),e.jsx(ge,{value:c.booking_url||"",onChange:v=>g("booking_url",v.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Compliance Disclosure (optional)"}),e.jsx(Ts,{rows:2,value:c.disclosure_text||"",onChange:v=>g("disclosure_text",v.target.value),placeholder:"e.g. Agent receives no compensation for this referral."})]}),e.jsxs("div",{className:"flex items-center justify-between md:col-span-2 border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(vn,{checked:!!c.is_active,onCheckedChange:v=>g("is_active",v)})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(vn,{checked:!!c.is_featured,onCheckedChange:v=>g("is_featured",v)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(vn,{checked:!!c.is_required,onCheckedChange:v=>g("is_required",v)})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:b,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function $2t({embedded:s=!1}={}){const t=fa(),{brokerageId:n}=gs(),{data:r,isLoading:a}=PJt(),{data:i={}}=$ht("agent",t),l=zht(),o=DJt(),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(""),[g,b]=N.useState("all"),v=(r==null?void 0:r.vendors)||[],j=(r==null?void 0:r.selections)||[],_=N.useMemo(()=>{const z=new Map;return j.forEach(V=>z.set(V.vendor_id,V.is_visible)),z},[j]),S=N.useMemo(()=>v.filter(z=>!(g!=="all"&&z.category!==g||p&&!`${z.name} ${z.company||""}`.toLowerCase().includes(p.toLowerCase()))),[v,p,g]),A=S.filter(z=>z.owner_type==="agent"),T=S.filter(z=>z.owner_type==="brokerage"),D=async z=>{if(confirm("Delete this vendor?"))try{await l.mutateAsync(z),ae.success("Vendor deleted")}catch(V){ae.error(V.message)}},L=async(z,V)=>{try{await o.mutateAsync({vendorId:z,isVisible:V})}catch(W){ae.error(W.message)}},M=z=>z.is_required?!0:_.get(z.id)??z.owner_type==="agent",F=e.jsxs("div",{className:s?"space-y-6":"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Vm,{className:"w-6 h-6 text-primary"}),"My Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Curate trusted partners that show up in your client portals — inspector, lender, movers and more."})]}),e.jsxs(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(As,{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(_r,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ge,{className:"pl-9",placeholder:"Search vendors...",value:p,onChange:z=>f(z.target.value)})]}),e.jsxs("select",{value:g,onChange:z=>b(z.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),ZD.map(z=>e.jsx("option",{value:z.value,children:z.label},z.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs($r,{defaultValue:n?"all":"personal",children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"all",children:["All (",S.length,")"]}),n&&e.jsxs(Zt,{value:"brokerage",children:["From Brokerage (",T.length,")"]}),e.jsxs(Zt,{value:"personal",children:["My Personal (",A.length,")"]})]}),e.jsx(ls,{value:"all",className:"mt-4",children:e.jsx(GNe,{vendors:S,isVisibleInPortals:M,onToggle:L,onEdit:z=>{d(z),h(!0)},onDelete:D,userId:t,clicks:i})}),n&&e.jsx(ls,{value:"brokerage",className:"mt-4",children:T.length===0?e.jsx(jXe,{icon:e.jsx(un,{className:"w-12 h-12"}),title:"No brokerage vendors yet",desc:"Your brokerage hasn't added any vendors. Ask your manager to set them up."}):e.jsx(GNe,{vendors:T,isVisibleInPortals:M,onToggle:L,userId:t,clicks:i})}),e.jsx(ls,{value:"personal",className:"mt-4",children:A.length===0?e.jsx(jXe,{icon:e.jsx(Vm,{className:"w-12 h-12"}),title:"No personal vendors yet",desc:"Add your trusted inspector, lender, mover — they'll show in every client portal you create.",action:e.jsxs(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(As,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(GNe,{vendors:A,isVisibleInPortals:M,onToggle:L,onEdit:z=>{d(z),h(!0)},onDelete:D,userId:t,clicks:i})})]}),e.jsx(B2t,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?F:e.jsx(Cs,{children:F})}function GNe({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(z2t,{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 jXe({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 EJs(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=gs(),{data:a=[],isLoading:i}=IJt(s),{data:l={}}=$ht("brokerage",s),o=zht(),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(""),[g,b]=N.useState("all");if(r)return e.jsx(Cs,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(Cs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const v=a.filter(_=>!(g!=="all"&&_.category!==g||p&&!`${_.name} ${_.company||""}`.toLowerCase().includes(p.toLowerCase()))),j=async _=>{if(confirm("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(_),ae.success("Vendor deleted")}catch(S){ae.error(S.message)}};return e.jsx(Cs,{children:e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Ga,{className:"w-6 h-6 text-primary"}),"Brokerage Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Manage preferred vendors that all agents in your brokerage can offer to their clients."})]}),e.jsxs(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(As,{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(_r,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ge,{className:"pl-9",placeholder:"Search vendors...",value:p,onChange:_=>f(_.target.value)})]}),e.jsxs("select",{value:g,onChange:_=>b(_.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),ZD.map(_=>e.jsx("option",{value:_.value,children:_.label},_.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):v.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(Ga,{className:"w-12 h-12 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4",children:"Add preferred lenders, inspectors, title companies, and more."}),e.jsxs(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(As,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(_=>e.jsx(z2t,{vendor:_,onEdit:()=>{d(_),h(!0)},onDelete:()=>j(_.id),clickCount:l[_.id]},_.id))}),e.jsx(B2t,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const AJs=[{value:"overview",label:"Portals",icon:vf},{value:"vendors",label:"Vendors",icon:fb},{value:"referrals",label:"Referrals",icon:Bi},{value:"branding",label:"Branding",icon:xl},{value:"questions",label:"Onboarding",icon:pu}];function MJs(){const[s,t]=yl(),n=s.get("tab")||"overview",[r,a]=N.useState(n),[i,l]=N.useState(!1),[o,c]=N.useState(!1);return N.useEffect(()=>{t(d=>{const u=new URLSearchParams(d);return u.set("tab",r),u},{replace:!0})},[r,t]),e.jsxs(Cs,{children:[e.jsx(Yo,{children:e.jsx("title",{children:"Client Portals"})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{className:"flex items-start justify-between flex-wrap gap-4",children:e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(un,{className:"w-6 h-6 text-primary"}),"Client Portals"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:"Your central hub for everything client-facing — manage active portals, curate trusted vendors, tune branding, and inbox referrals from happy clients."})]})}),e.jsx("div",{className:"border rounded-xl p-5 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(H9,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Create portals from Deal Pipeline"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-3xl",children:"This page is for managing portals after they’ve been created. To create a new client portal, open the deal inside Deal Pipeline and enable the portal from that deal."})]}),e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(Ln,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs($r,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(Ur,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:AJs.map(d=>e.jsxs(Zt,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(ls,{value:"overview",className:"mt-6",children:e.jsx(D2t,{})}),e.jsx(ls,{value:"vendors",className:"mt-6",children:e.jsx(IJs,{})}),e.jsx(ls,{value:"referrals",className:"mt-6",children:e.jsx(PJs,{})}),e.jsx(ls,{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(xl,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Portal Branding Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-xl",children:"Set the default logo, colors, cover photo and welcome message that appear at the top of every client portal you create. You can still override per-portal in any deal's settings."}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(Vo,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(ls,{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(pu,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Custom Onboarding Questions"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-xl",children:"Questions you want every new client to answer when they first open their portal — preferred contact times, kids/pets, must-have features, and anything else that helps you serve them better."}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(Vo,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(L2t,{open:i,onOpenChange:l}),e.jsx(I2t,{open:o,onOpenChange:c})]})}function IJs(){return e.jsx($2t,{embedded:!0})}function PJs(){return e.jsx(F2t,{})}const qI=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function LJs(s){return lt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return{portal:null,deal:null};const{data:r,error:a}=await q.from("deal_pipeline").select("deal_name, contact_id").eq("id",t.deal_id).maybeSingle();if(a)throw a;let i=null;if(r!=null&&r.contact_id){const{data:l,error:o}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",r.contact_id).maybeSingle();if(o)throw o;i=l}return{portal:t,deal:r?{deal_name:r.deal_name,contact_id:r.contact_id,contact:i}:null}},enabled:!!s})}function DJs(){const{portalId:s}=_i(),t=In(),n=fa(),{data:r,isLoading:a}=LJs(s),{data:i=[]}=zWs(s),{data:l=[]}=O2t(),o=SR(),c=ewt(),d=twt(),u=swt(),[h,p]=N.useState(!1),[f,g]=N.useState(!1),[b,v]=N.useState(!1),[j,_]=N.useState(!1),S=(r==null?void 0:r.portal)??null,A=(r==null?void 0:r.deal)??null,T=N.useMemo(()=>S?l.filter(ne=>ne.portal_id===S.id):[],[l,S==null?void 0:S.id]);if(a)return e.jsx(Cs,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!S)return e.jsx(Cs,{children:e.jsxs("div",{className:"max-w-3xl mx-auto p-8 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold mb-2",children:"Portal not found"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"This portal may have been deleted or you don't have access to it."}),e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs(Ln,{to:"/mission-control/client-portals",children:[e.jsx(Wr,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const D=Ew(S.slug),L=(A==null?void 0:A.deal_name)||"Untitled deal",M=A==null?void 0:A.contact,F=M?`${M.first_name||""} ${M.last_name||""}`.trim():"",z=!!S.archived_at,V=()=>{navigator.clipboard.writeText(D),ae.success("Portal link copied!")},W=async ne=>{try{await o.mutateAsync({id:S.id,is_enabled:ne}),ae.success(ne?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update")}},K=async()=>{try{await c.mutateAsync(S.id),ae.success("Portal archived")}catch{ae.error("Failed to archive")}},Y=async()=>{try{await d.mutateAsync(S.id),ae.success("Portal restored")}catch{ae.error("Failed to restore")}},ee=async()=>{try{await u.mutateAsync({id:S.id,dealId:S.deal_id}),ae.success("Portal deleted"),t("/mission-control/client-portals")}catch{ae.error("Failed to delete")}};return e.jsxs(Cs,{children:[e.jsx(Yo,{children:e.jsxs("title",{children:[L," — Client Portal"]})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{children:e.jsx(B,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(Ln,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(Wr,{className:"w-4 h-4 mr-1"})," All Client Portals"]})})}),e.jsxs("div",{className:"border rounded-xl p-6 bg-gradient-to-br from-card to-muted/30",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx(un,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:L}),e.jsx(ze,{variant:"outline",className:z?"bg-muted text-muted-foreground":S.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:z?"Archived":S.is_enabled?"Active":"Disabled"}),e.jsx(ze,{variant:"outline",className:"capitalize text-xs",children:S.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(Xi,{className:"w-3.5 h-3.5"}),S.client_name||F||"No client name set",(M==null?void 0:M.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Hs,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:M.email})]}),(M==null?void 0:M.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Pr,{className:"w-3.5 h-3.5"}),M.phone]})]}),e.jsx("div",{className:"mt-3 flex items-center gap-2 bg-background/60 border rounded-md px-3 py-1.5 max-w-full",children:e.jsx("code",{className:"text-xs font-mono text-muted-foreground truncate flex-1",children:D})})]}),!z&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(vn,{checked:S.is_enabled,onCheckedChange:W})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{onClick:V,variant:"outline",size:"sm",children:[e.jsx(ta,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(B,{onClick:()=>window.open(D,"_blank"),variant:"outline",size:"sm",children:[e.jsx(tr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(B,{onClick:()=>v(!0),size:"sm",children:[e.jsx(cr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(B,{onClick:()=>g(!0),variant:"outline",size:"sm",children:[e.jsx(rw,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(B,{onClick:()=>p(!0),variant:"outline",size:"sm",children:[e.jsx(Vo,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[z?e.jsxs(B,{onClick:Y,variant:"outline",size:"sm",children:[e.jsx(XP,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(B,{onClick:K,variant:"ghost",size:"sm",children:[e.jsx(im,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(B,{onClick:()=>_(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(PG,{icon:rw,label:"Updates Posted",value:i.length}),e.jsx(PG,{icon:Bi,label:"Referrals",value:T.length}),e.jsx(PG,{icon:yr,label:"Inspection",value:S.inspection_date?qI(S.inspection_date):"—"}),e.jsx(PG,{icon:yr,label:"Appraisal",value:S.appraisal_date?qI(S.appraisal_date):"—"})]}),e.jsxs($r,{defaultValue:"updates",className:"w-full",children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(Zt,{value:"referrals",children:["Referrals (",T.length,")"]}),e.jsx(Zt,{value:"branding",children:"Branding"}),e.jsx(Zt,{value:"details",children:"Details"})]}),e.jsx(ls,{value:"updates",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold",children:"Portal Update Feed"}),e.jsxs(B,{size:"sm",onClick:()=>g(!0),children:[e.jsx(rw,{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(rw,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No updates posted yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Keep your client in the loop — post your first update."})]}):e.jsx("div",{className:"space-y-3",children:i.map(ne=>e.jsx("div",{className:"border rounded-lg p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"font-medium text-sm",children:ne.title}),ne.is_stage_change&&e.jsx(ze,{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:qI(ne.created_at)}),ne.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:ne.content}),ne.video_url&&e.jsxs("a",{href:ne.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(vr,{className:"w-3 h-3"})," View video"]})]})})},ne.id))})]})})}),e.jsx(ls,{value:"referrals",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),T.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(Bi,{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:T.map(ne=>e.jsx(Ln,{to:"/mission-control/client-portals?tab=referrals",className:"block border rounded-lg p-3 hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:ne.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ne.friend_email||ne.friend_phone||"No contact info"," · ",qI(ne.created_at)]})]}),e.jsx(ze,{variant:"outline",className:"text-xs capitalize",children:ne.status})]})},ne.id))})]})})}),e.jsx(ls,{value:"branding",className:"mt-4",children:e.jsx(fe,{children:e.jsx(Ae,{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(xl,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold mb-1",children:"Portal Branding"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4 max-w-xl",children:"Override your default branding for this specific portal — custom logo, colors, cover photo, and welcome message just for this client."}),e.jsxs(B,{onClick:()=>p(!0),children:[e.jsx(Vo,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(ls,{value:"details",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6 space-y-4",children:[e.jsx(Ik,{label:"Visibility",value:S.visibility}),e.jsx(Ik,{label:"Onboarding Required",value:S.require_onboarding?"Yes":"No"}),e.jsx(Ik,{label:"Allow Spouse",value:S.allow_spouse?"Yes":"No"}),e.jsx(Ik,{label:"Notify Client on Updates",value:S.notify_client?"Yes":"No"}),e.jsx(Ik,{label:"Show Post-Close Tips",value:S.show_post_close_tips?"Yes":"No"}),e.jsx(Ik,{label:"Slug",value:S.slug,mono:!0}),e.jsx(Ik,{label:"Created",value:qI(S.created_at)}),e.jsx(Ik,{label:"Last Updated",value:qI(S.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(B,{variant:"outline",onClick:()=>p(!0),children:[e.jsx(Vo,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(S8e,{open:h,onOpenChange:p,portal:S,dealOwnerId:n||""}),e.jsx(C8e,{open:f,onOpenChange:g,portalId:S.id,portalSlug:S.slug,notifyClient:S.notify_client}),e.jsx(T8e,{open:b,onOpenChange:v,portal:S,dealName:L}),e.jsx(Oo,{open:j,onOpenChange:_,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Permanently delete this portal?"}),e.jsx(Mo,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:ee,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function PG({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 Ik({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 ETe=[{value:"video_intro",label:"Video Intro",icon:vr,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:_w,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:mh,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:El,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:Hl,description:"Links to your social profiles"}],RJs=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],OJs={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function U2t({cardId:s}){const{data:t,isLoading:n}=Dzt(s),r=Rzt(),a=Ozt(),i=Fzt(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(null);if(n)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ws,{className:"h-16 w-full"}),e.jsx(Ws,{className:"h-16 w-full"})]});const p=()=>{c&&r.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:OJs[c]||{}},{onSuccess:()=>{o(!1),d("")}})},f=_=>{a.mutate({id:_.id,is_visible:!_.is_visible})},g=(_,S)=>{if(!t)return;const A=t.findIndex(L=>L.id===_.id),T=S==="up"?A-1:A+1;if(T<0||T>=t.length)return;const D=t[T];a.mutate({id:_.id,sort_order:D.sort_order}),a.mutate({id:D.id,sort_order:_.sort_order})},b=_=>{confirm("Remove this block from this card?")&&i.mutate(_.id)},v=(_,S)=>{a.mutate({id:_.id,config:S},{onSuccess:()=>h(null)})},j=_=>ETe.find(S=>S.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(B,{size:"sm",onClick:()=>o(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((_,S)=>{const A=j(_.block_type),T=(A==null?void 0:A.icon)||mh;return e.jsx(fe,{className:_.is_visible?"":"opacity-50",children:e.jsx(Ae,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Uu,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(T,{className:"h-4 w-4 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs",children:(A==null?void 0:A.label)||_.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:FJs(_)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(_,"up"),disabled:S===0,children:e.jsx(Bu,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(_,"down"),disabled:S===t.length-1,children:e.jsx(om,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(_),children:_.is_visible?e.jsx(Ir,{className:"h-3 w-3"}):e.jsx(gf,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(_),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>b(_),children:e.jsx(bn,{className:"h-3 w-3"})})]})]})})},_.id)}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:ETe.map(_=>{const S=_.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(S,{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(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{onClick:p,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(zJs,{block:u,onSave:_=>v(u,_),onClose:()=>h(null)})]})}function FJs(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 zJs({block:s,onSave:t,onClose:n}){const[r,a]=N.useState(s.config),i=ETe.find(l=>l.value===s.block_type);return e.jsx(bs,{open:!0,onOpenChange:n,children:e.jsxs(vs,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(BJs,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx($Js,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(UJs,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(qJs,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(VJs,{config:r,onChange:a}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(B,{onClick:()=>t(r),children:"Save"})]})]})})}function BJs({config:s,onChange:t,cardId:n}){var f,g;const[r,a]=N.useState(""),[i,l]=N.useState((f=s.video_url)!=null&&f.includes("youtube")||(g=s.video_url)!=null&&g.includes("youtu.be")?"youtube":"library"),{data:o}=lt({queryKey:["card-owner",n],queryFn:async()=>{const{data:b}=await q.from("agent_cards").select("user_id").eq("id",n).single();return b==null?void 0:b.user_id},enabled:!!n}),{data:c,isLoading:d}=lt({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:b,error:v}=await q.from("agent_videos").select("id, title, bunny_video_id, thumbnail_url, playback_url, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(v)throw v;return b||[]},enabled:!!o}),u=(c==null?void 0:c.filter(b=>!r||(b.title||"").toLowerCase().includes(r.toLowerCase())))||[],h=s.bunny_video_id,p=b=>{var S;const v=(S=b.playback_url)==null?void 0:S.match(/\/(?:play|embed)\/(\d+)\//),_=`https://iframe.mediadelivery.net/embed/${v?v[1]:"570924"}/${b.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:_,bunny_video_id:b.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs($r,{value:i,onValueChange:l,children:[e.jsxs(Ur,{className:"w-full",children:[e.jsx(Zt,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Zt,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(ls,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search videos...",value:r,onChange:b=>a(b.target.value),className:"pl-9"})]}),e.jsx(mi,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ws,{className:"h-14 w-full"}),e.jsx(Ws,{className:"h-14 w-full"})]}):u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:(c==null?void 0:c.length)===0?"No videos in library yet":"No matching videos"}):e.jsx("div",{className:"space-y-1.5 pr-3",children:u.map(b=>e.jsxs("button",{onClick:()=>p(b),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${h===b.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[b.thumbnail_url?e.jsx("img",{src:b.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:v=>{var j;v.currentTarget.style.display="none",(j=v.currentTarget.nextElementSibling)==null||j.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${b.thumbnail_url?"hidden":""}`,children:e.jsx(vr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:b.title||"Untitled Video"}),h===b.bunny_video_id&&e.jsx(Lr,{className:"h-4 w-4 text-primary flex-shrink-0"})]},b.id))})})]}),e.jsx(ls,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(se,{children:"YouTube URL"}),e.jsx(ge,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:b=>t({...s,video_url:b.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 $Js({config:s,onChange:t}){const n=s.testimonials||[],r=(l,o,c)=>{const d=[...n];d[l]={...d[l],[o]:c},t({...s,testimonials:d})},a=()=>t({...s,testimonials:[...n,{name:"",quote:"",role:""}]}),i=l=>t({...s,testimonials:n.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-4",children:[n.map((l,o)=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),n.length>1&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(bn,{className:"h-3 w-3"})})]}),e.jsx(ge,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(ge,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>r(o,"role",c.target.value)}),e.jsx("textarea",{className:"w-full min-h-[60px] rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Their testimonial quote...",value:l.quote,onChange:c=>r(o,"quote",c.target.value)})]})},o)),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function UJs({config:s,onChange:t}){const n=s.tags||[],[r,a]=N.useState(""),i=o=>{t({...s,tags:n.includes(o)?n.filter(c=>c!==o):[...n,o]})},l=()=>{r.trim()&&!n.includes(r.trim())&&(t({...s,tags:[...n,r.trim()]}),a(""))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:RJs.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(se,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{placeholder:"Add your own...",value:r,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx(B,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),n.length>0&&e.jsxs("div",{children:[e.jsxs(se,{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 qJs({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(ge,{placeholder:"Button label",value:l.label,onChange:c=>r(o,"label",c.target.value)}),e.jsx(ge,{placeholder:"https://...",value:l.url,onChange:c=>r(o,"url",c.target.value)})]}),n.length>1&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(bn,{className:"h-3 w-3"})})]},o)),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const NXe=[{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 VJs({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=NXe.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=F4e[c],u=NXe.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(ge,{placeholder:`Your ${u.label} profile URL`,value:c.url,onChange:h=>a(d,h.target.value)})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(se,{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=F4e[c.value];return e.jsxs("button",{onClick:()=>r(c.value),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full border border-border bg-muted hover:bg-muted/80 transition-colors",children:[(d==null?void 0:d.icon)&&e.jsx("svg",{viewBox:"0 0 24 24",width:12,height:12,fill:d.color,children:e.jsx("path",{d:d.icon})}),c.label]},c.value)})})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Tap a platform above to add your social media profile."})]})}var HJs=Object.defineProperty,Qge=Object.getOwnPropertySymbols,q2t=Object.prototype.hasOwnProperty,V2t=Object.prototype.propertyIsEnumerable,kXe=(s,t,n)=>t in s?HJs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,ATe=(s,t)=>{for(var n in t||(t={}))q2t.call(t,n)&&kXe(s,n,t[n]);if(Qge)for(var n of Qge(t))V2t.call(t,n)&&kXe(s,n,t[n]);return s},MTe=(s,t)=>{var n={};for(var r in s)q2t.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&Qge)for(var r of Qge(s))t.indexOf(r)<0&&V2t.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var zM;(s=>{const t=class hl{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],chl.MAX_VERSION)throw new RangeError("Version value out of range");if(h<-1||h>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let p=[];for(let g=0;g7)throw new RangeError("Invalid value");let g,b;for(g=u;;g++){const S=hl.getNumDataCodewords(g,d)*8,A=l.getTotalBits(c,g);if(A<=S){b=A;break}if(g>=h)throw new RangeError("Data too long")}for(const S of[hl.Ecc.MEDIUM,hl.Ecc.QUARTILE,hl.Ecc.HIGH])f&&b<=hl.getNumDataCodewords(g,S)*8&&(d=S);let v=[];for(const S of c){n(S.mode.modeBits,4,v),n(S.numChars,S.mode.numCharCountBits(g),v);for(const A of S.getData())v.push(A)}a(v.length==b);const j=hl.getNumDataCodewords(g,d)*8;a(v.length<=j),n(0,Math.min(4,j-v.length),v),n(0,(8-v.length%8)%8,v),a(v.length%8==0);for(let S=236;v.length_[A>>>3]|=S<<7-(A&7)),new hl(g,d,_,p)}getModule(c,d){return 0<=c&&c>>9)*1335;const h=(d<<10|u)^21522;a(h>>>15==0);for(let p=0;p<=5;p++)this.setFunctionModule(8,p,r(h,p));this.setFunctionModule(8,7,r(h,6)),this.setFunctionModule(8,8,r(h,7)),this.setFunctionModule(7,8,r(h,8));for(let p=9;p<15;p++)this.setFunctionModule(14-p,8,r(h,p));for(let p=0;p<8;p++)this.setFunctionModule(this.size-1-p,8,r(h,p));for(let p=8;p<15;p++)this.setFunctionModule(8,this.size-15+p,r(h,p));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let u=0;u<12;u++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let u=0;u<18;u++){const h=r(d,u),p=this.size-11+u%3,f=Math.floor(u/3);this.setFunctionModule(p,f,h),this.setFunctionModule(f,p,h)}}drawFinderPattern(c,d){for(let u=-4;u<=4;u++)for(let h=-4;h<=4;h++){const p=Math.max(Math.abs(h),Math.abs(u)),f=c+h,g=d+u;0<=f&&f{(S!=b-p||T>=g)&&_.push(A[S])});return a(_.length==f),_}drawCodewords(c){if(c.length!=Math.floor(hl.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,b),f||(c+=this.finderPenaltyCountPatterns(b)*hl.PENALTY_N3),f=this.modules[p][v],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,b)*hl.PENALTY_N3}for(let p=0;p5&&c++):(this.finderPenaltyAddHistory(g,b),f||(c+=this.finderPenaltyCountPatterns(b)*hl.PENALTY_N3),f=this.modules[v][p],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,b)*hl.PENALTY_N3}for(let p=0;pf+(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*hl.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.lengthhl.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(hl.getNumRawDataModules(c)/8)-hl.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*hl.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c]}static reedSolomonComputeDivisor(c){if(c<1||c>255)throw new RangeError("Degree out of range");let d=[];for(let h=0;h0);for(const h of c){const p=h^u.shift();u.push(0),d.forEach((f,g)=>u[g]^=hl.reedSolomonMultiply(f,p))}return u}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let u=0;for(let h=7;h>=0;h--)u=u<<1^(u>>>7)*285,u^=(d>>>h&1)*c;return a(u>>>8==0),u}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const u=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(u&&c[0]>=d*4&&c[6]>=d?1:0)+(u&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,u){return c&&(this.finderPenaltyAddHistory(d,u),d=0),d+=this.size,this.finderPenaltyAddHistory(d,u),this.finderPenaltyCountPatterns(u)}finderPenaltyAddHistory(c,d){d[0]==0&&(c+=this.size),d.pop(),d.unshift(c)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],s.QrCode=t;function n(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let u=c-1;u>=0;u--)d.push(o>>>u&1)}function r(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class sh{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 sh(sh.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!sh.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={}))})(zM||(zM={}));(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={}))})(zM||(zM={}));var UP=zM;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var GJs={L:UP.QrCode.Ecc.LOW,M:UP.QrCode.Ecc.MEDIUM,Q:UP.QrCode.Ecc.QUARTILE,H:UP.QrCode.Ecc.HIGH},H2t=128,G2t="L",W2t="#FFFFFF",K2t="#000000",Y2t=!1,Z2t=1,WJs=4,KJs=0,YJs=.1;function Q2t(s,t=0){const n=[];return s.forEach(function(r,a){let i=null;r.forEach(function(l,o){if(!l&&i!==null){n.push(`M${i+t} ${a+t}h${o-i}v1H${i+t}z`),i=null;return}if(o===r.length-1){if(!l)return;i===null?n.push(`M${o+t},${a+t} h1v1H${o+t}z`):n.push(`M${i+t},${a+t} h${o+1-i}v1H${i+t}z`);return}l&&i===null&&(i=o)})}),n.join("")}function X2t(s,t){return s.slice().map((n,r)=>r=t.y+t.h?n:n.map((a,i)=>i=t.x+t.w?a:!1))}function ZJs(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*YJs),l=a/t,o=(r.width||i)*l,c=(r.height||i)*l,d=r.x==null?s.length/2-o/2:r.x*l,u=r.y==null?s.length/2-c/2:r.y*l,h=r.opacity==null?1:r.opacity;let p=null;if(r.excavate){let g=Math.floor(d),b=Math.floor(u),v=Math.ceil(o+d-g),j=Math.ceil(c+u-b);p={x:g,y:b,w:v,h:j}}const f=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:p,opacity:h,crossOrigin:f}}function QJs(s,t){return t!=null?Math.max(Math.floor(t),0):s?WJs:KJs}function J2t({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Nt.useMemo(()=>{const g=(Array.isArray(s)?s:[s]).reduce((b,v)=>(b.push(...UP.QrSegment.makeSegments(v)),b),[]);return UP.QrCode.encodeSegments(g,GJs[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:p}=Nt.useMemo(()=>{let f=c.getModules();const g=QJs(r,a),b=f.length+g*2,v=ZJs(f,l,g,i);return{cells:f,margin:g,numCells:b,calculatedImageSettings:v}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:p}}var XJs=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),JJs=Nt.forwardRef(function(t,n){const r=t,{value:a,size:i=H2t,level:l=G2t,bgColor:o=W2t,fgColor:c=K2t,includeMargin:d=Y2t,minVersion:u=Z2t,boostLevel:h,marginSize:p,imageSettings:f}=r,b=MTe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:v}=b,j=MTe(b,["style"]),_=f==null?void 0:f.src,S=Nt.useRef(null),A=Nt.useRef(null),T=Nt.useCallback(Y=>{S.current=Y,typeof n=="function"?n(Y):n&&(n.current=Y)},[n]),[D,L]=Nt.useState(!1),{margin:M,cells:F,numCells:z,calculatedImageSettings:V}=J2t({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:p,imageSettings:f,size:i});Nt.useEffect(()=>{if(S.current!=null){const Y=S.current,ee=Y.getContext("2d");if(!ee)return;let ne=F;const oe=A.current,pe=V!=null&&oe!==null&&oe.complete&&oe.naturalHeight!==0&&oe.naturalWidth!==0;pe&&V.excavation!=null&&(ne=X2t(F,V.excavation));const ce=window.devicePixelRatio||1;Y.height=Y.width=i*ce;const de=i/z*ce;ee.scale(de,de),ee.fillStyle=o,ee.fillRect(0,0,z,z),ee.fillStyle=c,XJs?ee.fill(new Path2D(Q2t(ne,M))):F.forEach(function(ie,ye){ie.forEach(function(_e,Me){_e&&ee.fillRect(Me+M,ye+M,1,1)})}),V&&(ee.globalAlpha=V.opacity),pe&&ee.drawImage(oe,V.x+M,V.y+M,V.w,V.h)}}),Nt.useEffect(()=>{L(!1)},[_]);const W=ATe({height:i,width:i},v);let K=null;return _!=null&&(K=Nt.createElement("img",{src:_,key:_,style:{display:"none"},onLoad:()=>{L(!0)},ref:A,crossOrigin:V==null?void 0:V.crossOrigin})),Nt.createElement(Nt.Fragment,null,Nt.createElement("canvas",ATe({style:W,height:i,width:i,ref:T,role:"img"},j)),K)});JJs.displayName="QRCodeCanvas";var QU=Nt.forwardRef(function(t,n){const r=t,{value:a,size:i=H2t,level:l=G2t,bgColor:o=W2t,fgColor:c=K2t,includeMargin:d=Y2t,minVersion:u=Z2t,boostLevel:h,title:p,marginSize:f,imageSettings:g}=r,b=MTe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:v,cells:j,numCells:_,calculatedImageSettings:S}=J2t({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:f,imageSettings:g,size:i});let A=j,T=null;g!=null&&S!=null&&(S.excavation!=null&&(A=X2t(j,S.excavation)),T=Nt.createElement("image",{href:g.src,height:S.h,width:S.w,x:S.x+v,y:S.y+v,preserveAspectRatio:"none",opacity:S.opacity,crossOrigin:S.crossOrigin}));const D=Q2t(A,v);return Nt.createElement("svg",ATe({height:i,width:i,viewBox:`0 0 ${_} ${_}`,ref:n,role:"img"},b),!!p&&Nt.createElement("title",null,p),Nt.createElement("path",{fill:o,d:`M0,0 h${_}v${_}H0z`,shapeRendering:"crispEdges"}),Nt.createElement("path",{fill:c,d:D,shapeRendering:"crispEdges"}),T)});QU.displayName="QRCodeSVG";function een({slug:s,agentName:t}){const n=N.useRef(null),r=`https://cards.relevelup.com/${s}`,a=N.useCallback(()=>{var h;const i=(h=n.current)==null?void 0:h.querySelector("svg");if(!i)return;const l=document.createElement("canvas"),o=1024;l.width=o,l.height=o;const c=l.getContext("2d");if(!c)return;const d=new XMLSerializer().serializeToString(i),u=new Image;u.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(u,0,0,o,o);const p=document.createElement("a");p.download=`${s}-qr-code.png`,p.href=l.toDataURL("image/png"),p.click(),ae.success("QR code downloaded!")},u.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(d)))},[s]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{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(QU,{value:r,size:120,level:"H",bgColor:"#ffffff",fgColor:"#000000"})}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Download this QR code to use on business cards, flyers, signs, or any print materials. Scanning it opens your digital card instantly."}),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function WNe(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 ten(){const{user:s}=gs(),{data:t,isLoading:n}=Izt(s==null?void 0:s.id),r=kR(),[a,i]=N.useState(null),l=N.useMemo(()=>a||(t?WNe(t):null),[a,t]);if(n)return e.jsx(Cs,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(Ws,{className:"h-8 w-48"}),e.jsx(Ws,{className:"h-32 w-full"}),e.jsx(Ws,{className:"h-32 w-full"})]})});if(!t)return e.jsx(Cs,{children:e.jsx(nen,{userId:s==null?void 0:s.id})});const o=l||WNe(t),c=d=>{i(u=>{const h=u||WNe(t);return typeof d=="function"?d(h):d})};return e.jsx(Cs,{children:e.jsxs("div",{className:"flex gap-6 items-start",children:[e.jsxs("div",{className:`${r?"w-full":"flex-1 min-w-0"} max-w-2xl p-4 space-y-6 animate-fade-in`,children:[e.jsx(ren,{card:t}),e.jsx(len,{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(gb,{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(sen,{card:t,form:o})})]})})]})})}function sen({card:s,form:t}){const{data:n}=lt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage_id").eq("id",s.user_id).single();let i=(a==null?void 0:a.avatar_url)||null;if(!i){const{data:l}=await q.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),r=N.useMemo(()=>({...s,is_published:t.is_published,theme:t.theme,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,custom_cta_url:s.custom_cta_url,show_photo:t.show_photo,show_bio:t.show_bio,show_video:s.show_video,show_credentials:t.show_credentials,show_social_links:t.show_social_links,show_save_contact:t.show_save_contact,show_leave_review:t.show_leave_review,show_refer_friend:t.show_refer_friend,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,display_email:t.display_email||null,social_links:s.social_links||[],profile:{name:(n==null?void 0:n.name)||null,email:t.display_email||(n==null?void 0:n.email)||null,phone:(n==null?void 0:n.phone)||null,brokerage_id:(n==null?void 0:n.brokerage_id)||null},brokerage_name:t.brokerage_display_name||null,avatar_url:(n==null?void 0:n.avatar_url)||null}),[s,t,n]);return e.jsx("div",{className:"transform scale-[0.85] origin-top",children:e.jsx(aMe,{card:r})})}function nen({userId:s}){var c;const[t,n]=N.useState(""),r=Nct(),{data:a}=lt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await q.from("profiles").select("name").eq("id",s).single();return d},enabled:!!s}),i=((c=a==null?void 0:a.name)==null?void 0:c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||"",l=()=>{if(!s)return;const d=(t.trim()||i).toLowerCase().replace(/[^a-z0-9-]/g,"-");if(!d){ae.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>ae.success("Your digital card has been created!")})},o=[{icon:lc,title:"Shareable Link",desc:"One link that works everywhere"},{icon:ph,title:"Lead Capture",desc:"Collect leads automatically"},{icon:hh,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:xl,title:"Fully Customizable",desc:"Themes, colors, and content blocks"}];return e.jsxs("div",{className:"max-w-2xl mx-auto p-4 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/90 via-primary to-primary/80 p-8 md:p-12 mb-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,rgba(255,255,255,0.15),transparent_50%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_80%_80%,rgba(0,0,0,0.1),transparent_50%)]"}),e.jsxs("div",{className:"relative z-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm text-sm font-medium mb-4",children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"New Feature"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3 tracking-tight",children:"Your Digital Business Card"}),e.jsx("p",{className:"text-primary-foreground/80 text-lg max-w-md leading-relaxed",children:"Ditch the paper. Share a beautiful, interactive card that captures leads and makes a lasting impression."})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-8",children:o.map(d=>e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-xl border bg-card hover:shadow-md transition-shadow",children:[e.jsx("div",{className:"mt-0.5 p-2 rounded-lg bg-primary/10 shrink-0",children:e.jsx(d.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:d.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.desc})]})]},d.title))}),e.jsxs(fe,{className:"shadow-lg border-2",children:[e.jsxs(Mt,{className:"text-center pb-2",children:[e.jsx(Pt,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(Hn,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Ae,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{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(ge,{value:t||i,onChange:d=>n(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs(B,{onClick:l,disabled:r.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function ren({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(ze,{variant:s.is_published?"default":"secondary",className:"text-[10px] uppercase tracking-wider",children:s.is_published?"Live":"Draft"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(lc,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(ta,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx(B,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function aen({userId:s}){const t=Gt(),n=N.useRef(null),[r,a]=N.useState(!1),[i,l]=N.useState(""),{data:o,isLoading:c}=lt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:V}=await q.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let W=(V==null?void 0:V.avatar_url)||null;if(!W){const{data:K}=await q.storage.from("avatars").list(`${s}`);if(K&&K.length>0){const{data:Y}=q.storage.from("avatars").getPublicUrl(`${s}/${K[0].name}`);W=`${Y.publicUrl}?t=${Date.now()}`,await q.from("profiles").update({avatar_url:W}).eq("id",s)}}return{...V,avatar_url:W}}}),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,g]=N.useState(null),[b,v]=N.useState(!1),j=d??(o==null?void 0:o.name)??"",_=h??(o==null?void 0:o.phone)??"",S=f??(o==null?void 0:o.email)??"",A=o==null?void 0:o.avatar_url,T=((o==null?void 0:o.name)||"A").split(" ").map(V=>V[0]).join("").toUpperCase().slice(0,2),D=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),L=gt({mutationFn:async V=>{const{error:W}=await q.from("profiles").update(V).eq("id",s);if(W)throw W},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")}),M=()=>{const V={};if(d!==null&&d!==(o==null?void 0:o.name)&&(V.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&(V.phone=h||null),f!==null&&f!==(o==null?void 0:o.email)&&(V.email=f),Object.keys(V).length===0){ae.info("No changes to save");return}L.mutate(V)},F=V=>{var Y;const W=(Y=V.target.files)==null?void 0:Y[0];if(!W)return;if(!W.type.startsWith("image/")){ae.error("Please select an image file");return}const K=new FileReader;K.onloadend=()=>{l(K.result),a(!0)},K.readAsDataURL(W),V.target.value=""},z=async V=>{v(!0);try{const{data:W}=await q.storage.from("avatars").list(`${s}`);W&&W.length>0&&await q.storage.from("avatars").remove(W.map(oe=>`${s}/${oe.name}`));const K=`${s}/avatar.jpg`,{error:Y}=await q.storage.from("avatars").upload(K,V,{upsert:!0,contentType:"image/jpeg"});if(Y)throw Y;const{data:ee}=q.storage.from("avatars").getPublicUrl(K),ne=ee.publicUrl+"?t="+Date.now();await q.from("profiles").update({avatar_url:ne}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ae.success("Photo updated!")}catch{ae.error("Failed to upload photo")}finally{v(!1)}};return c?e.jsx(Ws,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:D?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Ae,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(se,{className:"text-sm font-semibold",children:"Profile Info"}),D&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(Gi,{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 V;return(V=n.current)==null?void 0:V.click()},children:[e.jsxs(aa,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(ri,{src:A||void 0,alt:j}),e.jsx(ia,{className:"text-lg font-semibold bg-primary/10 text-primary",children:T})]}),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(pf,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:F})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:b?"Uploading...":A?"Tap to change photo":"Add a profile photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo appears on your card, profile, and community posts"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(ge,{value:j,onChange:V=>u(V.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(se,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(ge,{value:_,onChange:V=>p(V.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(ge,{value:S,onChange:V=>g(V.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:M,disabled:L.isPending,className:"w-full",children:L.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(xIe,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:z,aspectRatio:1})]})}function ien({form:s,setForm:t,userId:n}){const[r,a]=N.useState(null),[i,l]=N.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=N.useState(s.team_logo_url?"logo":"name"),d=f=>{l(f),t(f==="name"?g=>({...g,brokerage_logo_url:""}):g=>({...g,brokerage_display_name:""}))},u=f=>{c(f),t(f==="name"?g=>({...g,team_logo_url:""}):g=>({...g,team_name:""}))},h=async(f,g)=>{var v;const b=(v=f.target.files)==null?void 0:v[0];if(b){if(!b.type.startsWith("image/")){ae.error("Please select an image file");return}a(g);try{const j=b.name.split(".").pop()||"png",S=`${n}/${g==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${j}`,{error:A}=await q.storage.from("card-logos").upload(S,b,{upsert:!0});if(A)throw A;const{data:T}=q.storage.from("card-logos").getPublicUrl(S),D=T.publicUrl+"?t="+Date.now();t(g==="brokerage_logo_url"?L=>({...L,[g]:D,brokerage_display_name:""}):L=>({...L,[g]:D,team_name:""})),ae.success("Logo uploaded!")}catch{ae.error("Failed to upload logo")}finally{a(null),f.target.value=""}}},p=f=>{t(g=>({...g,[f]:""}))};return e.jsx(fe,{children:e.jsxs(Ae,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{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(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx(B,{type:"button",variant:i==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("logo"),children:"Use Logo"})]}),i==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(ge,{value:s.brokerage_display_name,onChange:f=>t(g=>({...g,brokerage_display_name:f.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.brokerage_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>p("brokerage_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(pf,{className:"h-3.5 w-3.5"}),r==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f=>h(f,"brokerage_logo_url"),disabled:r!==null})]})]}),s.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{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($m,{value:[s.brokerage_logo_size||56],onValueChange:([f])=>t(g=>({...g,brokerage_logo_size:f})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("name"),children:"Use Name"}),e.jsx(B,{type:"button",variant:o==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("logo"),children:"Use Logo"})]}),o==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(ge,{value:s.team_name,onChange:f=>t(g=>({...g,team_name:f.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Team Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.team_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.team_logo_url,alt:"Team logo",style:{height:`${s.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>p("team_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(pf,{className:"h-3.5 w-3.5"}),r==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f=>h(f,"team_logo_url"),disabled:r!==null})]})]}),s.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{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($m,{value:[s.team_logo_size||56],onValueChange:([f])=>t(g=>({...g,team_logo_size:f})),min:24,max:120,step:4})]})]})]})]})})}function oen({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(se,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(xl,{className:"h-4 w-4"})," Brand Colors"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Customize colors to match your brand"})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:i,children:"Reset to Default"})]}),e.jsx("div",{className:"grid gap-3",children:l.map(({key:o,label:c,desc:d})=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"relative shrink-0",children:[e.jsx("input",{type:"color",value:r[o],onChange:u=>a(o,u.target.value),className:"sr-only"}),e.jsx("div",{className:"h-10 w-10 rounded-lg border-2 border-border cursor-pointer shadow-sm hover:scale-105 transition-transform",style:{backgroundColor:r[o]}})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:c}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsx(ge,{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 len({card:s,form:t,setForm:n}){var b;const r=kct(),a=Gt(),{data:i}=Sct(s.id),[l,o]=N.useState(s.slug),[c,d]=N.useState(!1),[u,h]=N.useState("idle"),p=N.useRef(JSON.stringify(t)),f=N.useRef(null);N.useEffect(()=>{const v=JSON.stringify(t);if(v!==p.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{h("saving"),r.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{p.current=v,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{f.current&&clearTimeout(f.current)}},[t]);const g=async()=>{const v=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!v){ae.error("Please enter a valid URL");return}if(v===s.slug){ae.info("No changes to save");return}d(!0);try{const{data:j}=await q.from("agent_cards").select("id").eq("slug",v).neq("id",s.id).maybeSingle();if(j){ae.error("This URL is already taken. Try another one.");return}const{error:_}=await q.from("agent_cards").update({slug:v}).eq("id",s.id);if(_)throw _;o(v),a.invalidateQueries({queryKey:["agent-card"]}),ae.success("Card address updated!")}catch{ae.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs($r,{defaultValue:"content",children:[e.jsxs(Ur,{className:"w-full h-11 p-1",children:[e.jsxs(Zt,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ff,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Zt,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Zt,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ph,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Zt,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ly,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Zt,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(oc,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(ls,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(aen,{userId:s.user_id}),e.jsx(ien,{form:t,setForm:n,userId:s.user_id}),e.jsx(fe,{children:e.jsxs(Ae,{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(se,{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(vn,{checked:t.is_published,onCheckedChange:v=>n(j=>({...j,is_published:v}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{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(ge,{value:l,onChange:v=>o(v.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick: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(se,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(ge,{value:t.display_email,onChange:v=>n(j=>({...j,display_email:v.target.value})),placeholder:"you@yourbusiness.com",className:"h-11",type:"email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional — use a different email on your card instead of your sign-in email."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(us,{value:t.theme,onValueChange:v=>n(j=>({...j,theme:v})),children:[e.jsx(cs,{className:"h-11",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(Ze,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(Ze,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(Ze,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(oen,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(ge,{value:t.title,onChange:v=>n(j=>({...j,title:v.target.value})),placeholder:"e.g. Luxury Real Estate Specialist",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown below your name on the card"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(ge,{value:t.positioning_statement,onChange:v=>n(j=>({...j,positioning_statement:v.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Ts,{value:t.bio,onChange:v=>n(j=>({...j,bio:v.target.value})),placeholder:"A short intro about you and what makes you different...",rows:3})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(ge,{value:t.review_snippet,onChange:v=>n(j=>({...j,review_snippet:v.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(ge,{value:t.review_source_url,onChange:v=>n(j=>({...j,review_source_url:v.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(ge,{value:t.booking_url,onChange:v=>n(j=>({...j,booking_url:v.target.value})),placeholder:"https://calendly.com/your-link",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to show a built-in lead form instead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(ge,{value:t.custom_cta_label,onChange:v=>n(j=>({...j,custom_cta_label:v.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(ls,{value:"sections",className:"mt-4",children:e.jsx(fe,{children:e.jsx(Ae,{className:"p-5 divide-y",children:[{key:"show_photo",label:"Photo",desc:"Uses the photo from your Profile Info above"},{key:"show_bio",label:"Bio Section",desc:"Display your bio on the card"},{key:"show_credentials",label:"Credentials",desc:"Show star rating and reviews"},{key:"show_social_links",label:"Social Links",desc:"Display your social media links"},{key:"show_save_contact",label:"Save Contact",desc:"Let visitors save you as a contact"},{key:"show_leave_review",label:"Leave Review",desc:"Link to your review page"},{key:"show_refer_friend",label:"Refer a Friend",desc:"Enable referral submissions"}].map(({key:v,label:j,desc:_})=>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(se,{className:"text-sm font-medium",children:j}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_})]}),e.jsx(vn,{checked:t[v],onCheckedChange:S=>n(A=>({...A,[v]:S}))})]},v))})})}),e.jsx(ls,{value:"blocks",className:"mt-4",children:e.jsx(U2t,{cardId:s.id})}),e.jsx(ls,{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:Ir,color:"text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-900/30"},{label:"Clicks",value:(i==null?void 0:i.clicks)??0,icon:oc,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((b=i==null?void 0:i.leads)==null?void 0:b.length)??0,icon:Fo,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(v=>e.jsx(fe,{className:"overflow-hidden",children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`p-1.5 rounded-md ${v.color}`,children:e.jsx(v.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:v.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:v.value})]})},v.label))}),i&&i.leads.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(Pt,{className:"text-base",children:"Recent Leads"})}),e.jsx(Ae,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(v=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:v.name}),v.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:v.phone})]}),v.intent&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:v.intent})]},v.id))})]}),(!i||i.leads.length===0)&&e.jsx(fe,{children:e.jsxs(Ae,{className:"p-8 text-center",children:[e.jsx(oc,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"No analytics data yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Share your card link to start tracking"})]})})]})}),e.jsx(ls,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(fe,{children:e.jsx(Ae,{className:"p-6",children:e.jsx(een,{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 cen(){const s=Gt(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,g]=N.useState(null),[b,v]=N.useState(null),[j,_]=N.useState(0),[S,A]=N.useState(""),[T,D]=N.useState(!1),{data:L,isLoading:M}=lt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ce,error:de}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(de)throw de;return ce}}),F=gt({mutationFn:async ce=>{const{data:de,error:ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ce}});if(ie)throw ie;if(de!=null&&de.error)throw new Error(de.error);return de},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),ae.success("BoldTrail connected successfully!")},onError:ce=>{ae.error(ce.message||"Failed to connect BoldTrail")}}),z=gt({mutationFn:async()=>{const{data:ce,error:de}=await q.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(de)throw de;return ce},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("BoldTrail disconnected")},onError:()=>ae.error("Failed to disconnect")}),V=gt({mutationFn:async ce=>{const{data:de,error:ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ce}});if(ie)throw ie;if(de!=null&&de.error)throw new Error(de.error);return de},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("Sync direction saved")},onError:ce=>{ae.error(ce.message||"Failed to save sync direction")}}),W=gt({mutationFn:async()=>{const{data:ce,error:de}=await q.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(de)throw de;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:ce=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),ce.kvcore_user_id){const de=ce.detected_name||ce.detected_email||`ID ${ce.kvcore_user_id}`;ae.success(`Detected your BoldTrail account: ${de}`)}else if(ce.candidates&&ce.candidates.length>0){const de=ce.candidates.slice(0,5).map(ie=>`${ie.id} (${ie.count} contacts)`).join(", ");ae.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${de}. Pick yours and enter it below.`,{duration:12e3}),D(!0)}else ae.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),D(!0)},onError:ce=>ae.error(ce.message||"Detection failed")}),K=gt({mutationFn:async ce=>{const{data:de,error:ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ce}});if(ie)throw ie;if(de!=null&&de.error)throw new Error(de.error);return de},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("Settings saved"),D(!1)},onError:ce=>ae.error(ce.message||"Failed to save settings")}),Y=gt({mutationFn:async()=>{const{data:ce,error:de}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(de)throw de;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:ce=>{g(null),c(ce),a(!0)},onError:ce=>{ae.error(ce.message||"Failed to generate sync preview")}}),ee=gt({mutationFn:async()=>{v("Initializing sync..."),_(5);const{data:ce,error:de}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:pe}});if(de)throw de;if(ce!=null&&ce.error)throw new Error(ce.error);const ie=ce;let ye=ie.sync_log_id,_e=ie.next_phase,Me=ie.next_offset,Te=ie.push_total||0,Ce=ie.pull_total||0,Ee=0,De=0;for(;_e!=="finalize";){const qe=Te+Ce;_e==="fetch_bt"?v("Fetching BoldTrail contacts..."):_e==="analyze"?(v("Analyzing contacts..."),_(15)):_e==="push"?(v(`Pushing contacts to BoldTrail... (${Ee}/${Te})`),_(qe>0?Ee/qe*100:0)):_e==="pull"&&(v(`Pulling contacts from BoldTrail... (${De}/${Ce})`),_(qe>0?(Te+De)/qe*100:0));const{data:ve,error:Je}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:_e,offset:Me,sync_log_id:ye,sync_direction:pe}});if(Je)throw Je;if(ve!=null&&ve.error)throw new Error(ve.error);const we=ve;Ee+=we.chunk_pushed||0,De+=we.chunk_pulled||0,we.push_total!==void 0&&(Te=we.push_total||0),we.pull_total!==void 0&&(Ce=we.pull_total||0),we.progress&&v(we.progress),_e==="pull"&&Ce>0?_(Math.min(95,De/Ce*100)):_e==="push"&&Te>0&&_(Math.min(95,Ee/Te*100)),_e=we.next_phase,Me=we.next_offset}v("Finalizing sync..."),_(95);const{data:Ie,error:Fe}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:ye,sync_direction:pe}});if(Fe)throw Fe;return _(100),Ie},onSuccess:ce=>{v(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 ${ce.contacts_pushed||0}, pulled ${ce.contacts_pulled||0}, skipped ${ce.contacts_skipped||0} duplicates.`)},onError:ce=>{v(null),_(0),ae.error(ce.message||"Sync failed")}}),ne=L==null?void 0:L.connected,oe=(L==null?void 0:L.sync_direction)||"bidirectional",pe=f??oe;return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-emerald-500/10 flex items-center justify-center",children:e.jsx(sm,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:["BoldTrail",ne&&e.jsx(ze,{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(Pu,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(Hn,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Ae,{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(zi,{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(zi,{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(zi,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Syncs name, email, phone, address, notes, and lead source"})]}),ne?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"BoldTrail Connected"}),(L==null?void 0:L.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(L.last_sync_at).toLocaleString(),L.last_sync_status&&e.jsx(ze,{variant:L.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:L.last_sync_status})]}),(L==null?void 0:L.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[L.boldtrail_contact_count," contacts in BoldTrail"]}),(L==null?void 0:L.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:L.last_sync_message})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect BoldTrail?"}),e.jsx(Mo,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>z.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]})}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(_b,{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(vn,{checked:!!(L!=null&&L.sync_only_owned),onCheckedChange:ce=>K.mutate({sync_only_owned:ce}),disabled:K.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Your BoldTrail Agent ID"}),T?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{type:"number",placeholder:"e.g. 12345",value:S,onChange:ce=>A(ce.target.value),className:"h-8 text-sm"}),e.jsx(B,{size:"sm",onClick:()=>{const ce=S.trim()===""?null:Number(S);K.mutate({kvcore_user_id:ce})},disabled:K.isPending,children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>D(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(L==null?void 0:L.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>W.mutate(),disabled:W.isPending,children:[W.isPending?e.jsx(Ai,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var ce;A(((ce=L==null?void 0:L.kvcore_user_id)==null?void 0:ce.toString())??""),D(!0)},children:"Edit"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Your numeric BoldTrail (kvCORE) user ID. To find it: log into BoldTrail → click your avatar (top right) → ",e.jsx("strong",{children:"My Profile"}),". The ID appears in the page URL after ",e.jsx("code",{children:"/users/"})," (e.g. ",e.jsxs("code",{children:[".../users/",e.jsx("strong",{children:"12345"})]}),"). You can also open any contact you own in BoldTrail and look at the URL — your ID is shown as the assigned agent. Auto-detect tries to find it via your API token first."]})]})]}),e.jsx("div",{className:"rounded-lg border p-3",children:e.jsx(nTe,{value:oe,onChange:ce=>V.mutate(ce)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(B,{onClick:()=>Y.mutate(),disabled:Y.isPending||ee.isPending,variant:"outline",className:"gap-2",children:[Y.isPending?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(Ir,{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(ge,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:ce=>n(ce.target.value),className:"flex-1"}),e.jsxs(B,{onClick:()=>F.mutate(t),disabled:!t||t.length<10||F.isPending,children:[F.isPending?e.jsx(Ai,{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(bs,{open:r,onOpenChange:ce=>{ee.isPending||a(ce)},children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(sm,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Qn,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const ce=pe==="pull_only"?0:o.to_push,de=pe==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(nTe,{value:pe,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(_b,{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 ${pe==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:ce}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Bu,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${pe==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:de}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(om,{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(_n,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",o.agent_os_total," contacts · BoldTrail: ",o.boldtrail_total," contacts"]}),ee.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(xi,{value:j||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:b||"Sync in progress..."})]}),ce>0&&e.jsxs(uy,{open:d,onOpenChange:u,children:[e.jsx(hy,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bu,{className:"h-3 w-3 text-emerald-600"}),ce," contacts to push to BoldTrail"]}),e.jsx(io,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(my,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((ie,ye)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ie.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ie.email})]},ye)),o.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_push-20," more"]})]})})]}),de>0&&e.jsxs(uy,{open:h,onOpenChange:p,children:[e.jsx(hy,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(om,{className:"h-3 w-3 text-blue-600"}),de," contacts to pull from BoldTrail"]}),e.jsx(io,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(my,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((ie,ye)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ie.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ie.email})]},ye)),o.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_pull-20," more"]})]})})]}),ce===0&&de===0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer."}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),disabled:ee.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>ee.mutate(),disabled:ee.isPending||ce===0&&de===0,className:"gap-2",children:[ee.isPending?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(sm,{className:"h-4 w-4"}),ee.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(ws,{className:"p-6 pb-0",children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(sm,{className:"h-5 w-5 text-emerald-600"}),"How BoldTrail Sync Works"]})}),e.jsx("div",{className:"px-6 pb-6",children:e.jsx("video",{src:"/videos/BoldTrailIntegration.mp4",controls:!0,autoPlay:!0,className:"w-full rounded-lg",controlsList:"nodownload"})})]})})]})}function den(){const s=Gt(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(null),{data:d,isLoading:u}=lt({queryKey:["fub-status"],queryFn:async()=>{const{data:b,error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"status"}});if(v)throw v;return b}}),h=gt({mutationFn:async b=>{const{data:v,error:j}=await q.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:b}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{ae.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:b=>ae.error(b.message)}),p=gt({mutationFn:async()=>{const{error:b}=await q.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(b)throw b},onSuccess:()=>{ae.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),f=gt({mutationFn:async b=>{const{error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:b}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from FUB…");let b=0,v=0,j=0,_=0;try{for(;;){const{data:D,error:L}=await q.functions.invoke("followupboss-sync",{body:{action:"sync",offset:b}});if(L)throw L;if(D!=null&&D.error)throw new Error(D.error);v+=D.chunk_created||0,j+=D.chunk_updated||0,_+=D.chunk_skipped||0,b=D.next_offset;const M=D.total?Math.min(100,Math.round(b/D.total*100)):100;if(l(M),c(`Pulling · ${b} / ${D.total||"?"}`),D.done)break;await new Promise(F=>setTimeout(F,400))}let S=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let D=0;for(l(0),c("Pushing to FUB…");;){const{data:L,error:M}=await q.functions.invoke("followupboss-sync",{body:{action:"push",offset:D}});if(M)throw M;if(L!=null&&L.error)throw new Error(L.error);S+=L.chunk_pushed||0,A+=L.chunk_failed||0,D=L.next_offset;const F=L.total?Math.min(100,Math.round(D/L.total*100)):100;if(l(F),c(`Pushing · ${D} / ${L.total||"?"}`),L.done)break;await new Promise(z=>setTimeout(z,400))}}const T=S||A?` · pushed ${S}${A?`, ${A} failed`:""}`:"";ae.success(`Sync complete · ${v} new, ${j} updated${_?`, ${_} skipped`:""}${T}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(S){ae.error(S.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(J2,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(ze,{variant:"default",className:"ml-1",children:[e.jsx(zi,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Hn,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Ae,{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(vn,{checked:d.sync_direction==="bidirectional",onCheckedChange:b=>f.mutate(b?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(xi,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:g,disabled:r,children:[e.jsx(Ai,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(bn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Follow Up Boss?"}),e.jsx(Mo,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>p.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(ge,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:b=>n(b.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:["Find your key in FUB → Admin → API.",e.jsxs("a",{href:"https://app.followupboss.com/2/api",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-0.5 text-primary hover:underline",children:["Open ",e.jsx(tr,{className:"h-3 w-3"})]})]})]}),e.jsx(B,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function uen(){var Y;const s=Gt(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState(!1),[o,c]=N.useState(0),[d,u]=N.useState(null),[h,p]=N.useState(!1),[f,g]=N.useState(null),[b,v]=N.useState(!1),[j,_]=N.useState(new Set),{data:S,isLoading:A}=lt({queryKey:["cloze-status"],queryFn:async()=>{const{data:ee,error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"status"}});if(ne)throw ne;return ee}}),T=gt({mutationFn:async()=>{const{data:ee,error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(ne)throw ne;if(ee!=null&&ee.error)throw new Error(ee.error);return ee},onSuccess:()=>{ae.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:ee=>ae.error(ee.message)}),D=gt({mutationFn:async()=>{const{error:ee}=await q.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(ee)throw ee},onSuccess:()=>{ae.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),L=gt({mutationFn:async ee=>{const{error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:ee}});if(ne)throw ne},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),M=gt({mutationFn:async ee=>{const{error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"set_scope",...ee}});if(ne)throw ne},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),F=async()=>{v(!0);try{const{data:ee,error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(ne)throw ne;if(ee!=null&&ee.error)throw new Error(ee.error);g(ee.segments||[]),_(new Set((S==null?void 0:S.selected_segments)||[])),p(!0)}catch(ee){ae.error(ee.message||"Failed to load segments")}finally{v(!1)}},z=async()=>{const ee=Array.from(j);await M.mutateAsync({sync_scope:"segments",selected_segments:ee}),ae.success(`Saved · ${ee.length} segment(s) selected`),p(!1)},V=async()=>{const ee=(S==null?void 0:S.sync_direction)||"pull_only";l(!0),c(0);try{if(ee==="pull_only"||ee==="bidirectional"){u("Pulling from Cloze…");let ne=0,oe=0,pe=0;for(;;){const{data:ce,error:de}=await q.functions.invoke("cloze-sync",{body:{action:"sync",offset:ne}});if(de)throw de;if(ce!=null&&ce.error)throw new Error(ce.error);if(oe+=ce.chunk_created||0,pe+=ce.chunk_updated||0,ne=ce.next_offset,u(`Pulling · ${oe+pe} contacts processed`),c(ce.done?100:Math.min(95,(oe+pe)%200/2)),ce.done)break;await new Promise(ie=>setTimeout(ie,300))}ae.success(`Pulled · ${oe} new, ${pe} updated`)}if(ee==="push_only"||ee==="bidirectional"){c(0),u("Pushing to Cloze…");let ne=0,oe=0,pe=0;for(;;){const{data:ce,error:de}=await q.functions.invoke("cloze-sync",{body:{action:"push",offset:ne}});if(de)throw de;if(ce!=null&&ce.error)throw new Error(ce.error);oe+=ce.chunk_pushed||0,pe+=ce.chunk_failed||0,ne=ce.next_offset;const ie=ce.total?Math.min(100,Math.round(ne/ce.total*100)):100;if(c(ie),u(`Pushing · ${ne} / ${ce.total||"?"}`),ce.done)break;await new Promise(ye=>setTimeout(ye,300))}ae.success(`Pushed · ${oe}${pe?`, ${pe} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(ne){ae.error(ne.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},W=(S==null?void 0:S.sync_scope)||"all",K=((Y=S==null?void 0:S.selected_segments)==null?void 0:Y.length)||0;return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(J2,{className:"h-5 w-5 text-primary"}),"Cloze",(S==null?void 0:S.connected)&&e.jsxs(ze,{variant:"default",className:"ml-1",children:[e.jsx(zi,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Hn,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Ae,{className:"space-y-4",children:A?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):S!=null&&S.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Account"}),e.jsx("p",{className:"font-medium break-all",children:S.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:S.last_sync_at?new Date(S.last_sync_at).toLocaleString():"Never"})]})]}),S.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:S.last_sync_message}),e.jsx("div",{className:"rounded-lg border px-3 py-2 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sync direction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which way contacts should flow."})]}),e.jsxs(us,{value:S.sync_direction||"pull_only",onValueChange:ee=>L.mutate(ee),disabled:i||L.isPending,children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(Ze,{value:"push_only",children:"Push to Cloze"}),e.jsx(Ze,{value:"bidirectional",children:"Two-way sync"})]})]})]})}),e.jsxs("div",{className:"rounded-lg border px-3 py-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"What to sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:W==="all"?"All Cloze contacts.":`${K} segment${K===1?"":"s"} selected.`})]}),e.jsxs(us,{value:W,onValueChange:ee=>{ee==="all"?M.mutate({sync_scope:"all",selected_segments:[]}):(M.mutate({sync_scope:"segments",selected_segments:S.selected_segments||[]}),F())},disabled:i||M.isPending,children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All contacts"}),e.jsx(Ze,{value:"segments",children:"Selected segments"})]})]})]}),W==="segments"&&e.jsxs("div",{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:F,disabled:b,children:[e.jsx(L9,{className:"h-4 w-4 mr-2"}),b?"Loading segments…":"Choose segments"]}),h&&f&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"max-h-96 overflow-y-auto rounded-md border divide-y",children:[f.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),f.map(ee=>{const ne=j.has(ee.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(hi,{checked:ne,onCheckedChange:oe=>{const pe=new Set(j);oe?pe.add(ee.id):pe.delete(ee.id),_(pe)}}),e.jsx("span",{className:"flex-1 text-sm",children:ee.name}),ee.count!=null&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:ee.count})]},ee.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:z,disabled:M.isPending,children:["Save selection (",j.size,")"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(xi,{value:o}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsxs(B,{disabled:i,children:[e.jsx(Ai,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Preview sync"}),e.jsx(Mo,{asChild:!0,children:e.jsx(hen,{segments:f})})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:V,children:"Start Sync"})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:i,children:[e.jsx(bn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Cloze?"}),e.jsx(Mo,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>D.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(ge,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:r,onChange:ee=>a(ee.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(ge,{id:"cloze-key",type:"password",placeholder:"Your personal Cloze API key",value:t,onChange:ee=>n(ee.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:["Generate one in Cloze → Settings → API Keys.",e.jsxs("a",{href:"https://app.cloze.com/app/#/settings/apikeys",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-0.5 text-primary hover:underline",children:["Open ",e.jsx(tr,{className:"h-3 w-3"})]})]})]}),e.jsx(B,{onClick:()=>T.mutate(),disabled:!t.trim()||!r.trim()||T.isPending,children:T.isPending?"Connecting…":"Connect Cloze"})]})})]})}function hen({segments:s}){var h;const[t,n]=N.useState(!0),[r,a]=N.useState(null),[i,l]=N.useState(null);if(N.useEffect(()=>{(async()=>{try{const{data:p,error:f}=await q.functions.invoke("cloze-sync",{body:{action:"preview"}});if(f)throw f;if(p!=null&&p.error)throw new Error(p.error);a(p)}catch(p){l(p.message||"Could not load preview")}finally{n(!1)}})()},[]),t)return e.jsx("span",{className:"text-sm",children:"Calculating…"});if(i)return e.jsx("span",{className:"text-sm text-destructive",children:i});const o=new Map((s||[]).map(p=>[p.id,p.name])),c=r.total_incoming??0,d=r.already_synced??0,u=Math.max(0,c-d);return e.jsxs("div",{className:"space-y-3 text-sm text-foreground",children:[e.jsxs("div",{className:"rounded-md border p-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{children:["Contacts in Cloze (",r.scope==="segments"?"selected segments":"all",")"]}),e.jsx("strong",{children:c.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Already linked to Cloze in your CRM"}),e.jsx("span",{children:d.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Estimated new contacts"}),e.jsxs("strong",{children:["~",u.toLocaleString()]})]})]}),r.scope==="segments"&&((h=r.segment_counts)==null?void 0:h.length)>0&&e.jsx("div",{className:"rounded-md border p-3 space-y-1 max-h-40 overflow-auto",children:r.segment_counts.map(p=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:o.get(p.id)||p.id}),e.jsx("span",{className:"text-muted-foreground",children:p.total})]},p.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.note})]})}function men(){const s=Gt(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(null),{data:d,isLoading:u}=lt({queryKey:["boomtown-status"],queryFn:async()=>{const{data:b,error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"status"}});if(v)throw v;return b}}),h=gt({mutationFn:async b=>{const{data:v,error:j}=await q.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:b}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{ae.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:b=>ae.error(b.message)}),p=gt({mutationFn:async()=>{const{error:b}=await q.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(b)throw b},onSuccess:()=>{ae.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),f=gt({mutationFn:async b=>{const{error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:b}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let b=0,v=0,j=0,_=0;try{for(;;){const{data:D,error:L}=await q.functions.invoke("boomtown-sync",{body:{action:"sync",offset:b}});if(L)throw L;if(D!=null&&D.error)throw new Error(D.error);v+=D.chunk_created||0,j+=D.chunk_updated||0,_+=D.chunk_skipped||0,b=D.next_offset;const M=D.total?Math.min(100,Math.round(b/D.total*100)):100;if(l(M),c(`Pulling · ${b} / ${D.total||"?"}`),D.done)break;await new Promise(F=>setTimeout(F,400))}let S=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let D=0;for(l(0),c("Pushing to Boomtown…");;){const{data:L,error:M}=await q.functions.invoke("boomtown-sync",{body:{action:"push",offset:D}});if(M)throw M;if(L!=null&&L.error)throw new Error(L.error);S+=L.chunk_pushed||0,A+=L.chunk_failed||0,D=L.next_offset;const F=L.total?Math.min(100,Math.round(D/L.total*100)):100;if(l(F),c(`Pushing · ${D} / ${L.total||"?"}`),L.done)break;await new Promise(z=>setTimeout(z,400))}}const T=S||A?` · pushed ${S}${A?`, ${A} failed`:""}`:"";ae.success(`Sync complete · ${v} new, ${j} updated${_?`, ${_} skipped`:""}${T}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(S){ae.error(S.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(J2,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs(ze,{variant:"default",className:"ml-1",children:[e.jsx(zi,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Hn,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Ae,{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(vn,{checked:d.sync_direction==="bidirectional",onCheckedChange:b=>f.mutate(b?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(xi,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:g,disabled:r,children:[e.jsx(Ai,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(bn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Boomtown?"}),e.jsx(Mo,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>p.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(ge,{id:"boomtown-key",type:"password",placeholder:"Paste your Boomtown Ambassador API key",value:t,onChange:b=>n(b.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Requires a Boomtown Ambassador/Partner API key with contact access."})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"How to get your API key"}),e.jsxs("ol",{className:"text-xs text-muted-foreground space-y-1 list-decimal list-inside",children:[e.jsx("li",{children:"Log in to Boomtown as an admin or manager."}),e.jsxs("li",{children:["Go to ",e.jsx("strong",{children:"Settings → Integrations → API Keys"}),"."]}),e.jsxs("li",{children:["Generate a key with ",e.jsx("strong",{children:"Contact read/write"})," scope."]}),e.jsx("li",{children:"Copy the key and paste it above, then click Connect."})]}),e.jsxs("a",{href:"https://backoffice.boomtownroi.com/#/settings/integrations",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:["Open Boomtown settings ",e.jsx(tr,{className:"h-3 w-3"})]})]}),e.jsx(B,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function eNt(){const s=In(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState("Test from ReLevelUp"),[o,c]=N.useState(!1),{data:d,isLoading:u}=lt({queryKey:["ses-config"],queryFn:async()=>{const{data:{session:f}}=await q.auth.getSession();if(!f)throw new Error("Not authenticated");return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f.access_token}`},body:JSON.stringify({action:"check_config"})})).json()}}),h=async()=>{if(!t||!r){ae.error("Please fill in From and To email addresses");return}c(!0);try{const{data:{session:f}}=await q.auth.getSession();if(!f)throw new Error("Not authenticated");const b=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f.access_token}`},body:JSON.stringify({action:"test_send",to:t,from_email:r,subject:i,body_html:"

Test Email

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

If you received this, SES is configured correctly! 🎉

"})})).json();b.success?ae.success(`Test email sent! Message ID: ${b.messageId}`):ae.error(b.error||"Failed to send test email")}catch(f){ae.error(f.message||"Failed to send test email")}finally{c(!1)}},p=(d==null?void 0:d.configured)===!0;return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-orange-500/10 flex items-center justify-center",children:e.jsx(Hs,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(Hn,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(ze,{variant:p?"default":"secondary",children:u?"Checking...":p?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zi,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gi,{className:"h-3 w-3"})," Not Configured"]})})]})}),p&&e.jsxs(Ae,{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(se,{className:"text-xs",children:"From Email"}),e.jsx(ge,{placeholder:"notifications@mail.relevelup.com",value:r,onChange:f=>a(f.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"To Email"}),e.jsx(ge,{placeholder:"your@email.com",value:t,onChange:f=>n(f.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(ge,{value:i,onChange:f=>l(f.target.value),className:"text-sm"})]})]}),e.jsxs(B,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(B,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(qd,{className:"h-4 w-4 mr-2"})," Launch Campaign Composer"]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Region:"})," ",d==null?void 0:d.region]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Domain:"})," send.relevelup.com (verified)"]})]})]}),!p&&!u&&e.jsx(Ae,{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 KNe(s){const{data:{session:t}}=await q.auth.getSession();if(!t)throw new Error("Not authenticated");const n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function pen({status:s}){return s==="verified"?e.jsxs(ze,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(ze,{variant:"secondary",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(ze,{variant:"destructive",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(ze,{variant:"outline",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"})," Not started"]})}function tNt({brokerageId:s,onVerifiedSelect:t}){const n=Gt(),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),{data:f,isLoading:g}=lt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:_,error:S}=await q.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(S)throw S;return _||[]}}),b=gt({mutationFn:async()=>KNe({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)}),v=async _=>{var S,A;u(_.id);try{const T=await KNe({action:"check_status",sender_id:_.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((S=T.sender)==null?void 0:S.status)==="verified"?ae.success(`${_.email} is verified! 🎉`):ae.info(`Status: ${((A=T.sender)==null?void 0:A.status)||"unknown"}`)}catch(T){ae.error(T.message)}finally{u(null)}},j=gt({mutationFn:async _=>KNe({action:"delete",sender_id:_}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ae.success("Sender removed"),p(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…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.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(Hs,{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(pen,{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(B,{size:"sm",variant:"outline",onClick:()=>t(_.email),children:"Use"}),_.status!=="verified"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>v(_),disabled:d===_.id,title:"Refresh status from AWS",children:d===_.id?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(Ai,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(_),className:"text-destructive hover:text-destructive",children:e.jsx(bn,{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(se,{className:"text-xs",children:"Email Address *"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(ge,{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(B,{size:"sm",onClick:()=>b.mutate(),disabled:!r.trim()||b.isPending,children:[b.isPending?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Oo,{open:!!h,onOpenChange:_=>!_&&p(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove this sender?"}),e.jsxs(Mo,{children:['"',h==null?void 0:h.email,`" will be removed from your verified senders and from Amazon SES. You'd need to verify it again to use it.`]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h&&j.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function YNe(s){const{data:{session:t}}=await q.auth.getSession();if(!t)throw new Error("Not authenticated");const n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function fen({status:s}){return s==="verified"?e.jsxs(ze,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(ze,{variant:"secondary",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(ze,{variant:"destructive",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(ze,{variant:"outline",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"})," Not started"]})}function xen({userId:s,onVerifiedSelect:t}){const n=Gt(),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),{data:f,isLoading:g}=lt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:_,error:S}=await q.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(S)throw S;return _||[]}}),b=gt({mutationFn:async()=>YNe({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)}),v=async _=>{var S,A;u(_.id);try{const T=await YNe({action:"check_status",sender_id:_.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((S=T.sender)==null?void 0:S.status)==="verified"?ae.success(`${_.email} is verified! 🎉`):ae.info(`Status: ${((A=T.sender)==null?void 0:A.status)||"unknown"}`)}catch(T){ae.error(T.message)}finally{u(null)}},j=gt({mutationFn:async _=>YNe({action:"delete",sender_id:_}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ae.success("Sender removed"),p(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…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.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(Hs,{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(fen,{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(B,{size:"sm",variant:"outline",onClick:()=>t(_.email),children:"Use"}),_.status!=="verified"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>v(_),disabled:d===_.id,title:"Refresh status from AWS",children:d===_.id?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(Ai,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(_),className:"text-destructive hover:text-destructive",children:e.jsx(bn,{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(se,{className:"text-xs",children:"Email Address *"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(ge,{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(B,{size:"sm",onClick:()=>b.mutate(),disabled:!r.trim()||b.isPending,children:[b.isPending?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Oo,{open:!!h,onOpenChange:_=>!_&&p(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove this sender?"}),e.jsxs(Mo,{children:['"',h==null?void 0:h.email,`" will be removed from your verified senders and from Amazon. You'd need to verify it again to use it.`]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h&&j.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function gen(){var A,T,D,L,M;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=gs(),i=a||((A=r==null?void 0:r[0])==null?void 0:A.id)||null,l=(t||n)&&!!i,o=Gt(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(""),{data:g}=lt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:F,error:z}=await q.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(z)throw z;return F}}),{data:b}=lt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:F,error:z}=await q.from("profiles").select("email, name").eq("id",s.id).single();if(z)throw z;return F}}),v=((T=g==null?void 0:g.reply_to_email)==null?void 0:T.trim())||((D=b==null?void 0:b.email)==null?void 0:D.trim())||"",j=((L=g==null?void 0:g.display_name)==null?void 0:L.trim())||((M=b==null?void 0:b.name)==null?void 0:M.trim())||"";N.useEffect(()=>{c||(h(v),f(j))},[c,v,j]);const _=gt({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const F={reply_to_email:u.trim(),display_name:p.trim()||null,updated_at:new Date().toISOString()};if(g){const{error:z}=await q.from("mass_email_settings").update(F).eq("user_id",s.id);if(z)throw z}else{const{error:z}=await q.from("mass_email_settings").insert({user_id:s.id,...F});if(z)throw z}},onSuccess:()=>{o.invalidateQueries({queryKey:["mass-email-settings",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-ready",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-settings-check",s==null?void 0:s.id]}),ae.success("Reply-to email saved!"),d(!1)},onError:F=>ae.error(F.message)}),S=!!v;return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-orange-500/10 flex items-center justify-center",children:e.jsx(cr,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:["Mass Email",S?e.jsxs(ze,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(zi,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(Hn,{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(Ae,{className:"space-y-3",children:[S&&!c?e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:j||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(ja,{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(se,{className:"text-xs",children:"Display Name"}),e.jsx(ge,{placeholder:"e.g. 🏡 Karen Hall",value:p,onChange:F=>f(F.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"How your name appears in the recipient's inbox"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(ge,{type:"email",placeholder:"your@email.com",value:u,onChange:F=>h(F.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>_.mutate(),disabled:_.isPending||!u.trim(),children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(v),f(j)},children:[e.jsx(Fn,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(cl,{className:"my-2"}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(ng,{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(xen,{userId:s.id,onVerifiedSelect:F=>{h(F),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(cl,{className:"my-2"}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(ng,{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(tNt,{brokerageId:i})]})]})]})]})}function yen({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 ven(){const s=In(),{isAdmin:t,user:n}=gs(),{actingAsAgent:r,effectiveUserId:a}=Y0e(),i=Gt(),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState(!1),{scopeUserId:p,isDelegated:f}=yen({authUserId:n==null?void 0:n.id,actingAsUserId:(r==null?void 0:r.id)??a}),{data:g,isLoading:b}=lt({queryKey:["gmail-integration",p],enabled:!!p&&!f,queryFn:async()=>{const{data:z,error:V}=await q.from("gmail_integrations").select("*").eq("user_id",p).maybeSingle();if(V)throw V;return z}}),{data:v}=lt({queryKey:["social-accounts",p],enabled:!!p&&!f,queryFn:async()=>{const{data:z,error:V}=await q.from("social_accounts").select("*").eq("user_id",p).order("created_at",{ascending:!1});if(V)throw V;return z}}),j=async()=>{if(f){ae.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:z,error:V}=await q.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(V)throw V;if(z!=null&&z.authUrl)window.location.href=z.authUrl;else throw new Error("Failed to get authorization URL")}catch(z){console.error("Gmail OAuth error:",z),ae.error("Failed to start Gmail connection"),o(!1)}},_=async z=>{if(f){ae.error("Account connections must be made by the agent from their own login.");return}d(!0);try{const{data:V,error:W}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:z}});if(W)throw W;if(V!=null&&V.authUrl)window.location.href=V.authUrl;else throw new Error("Failed to get authorization URL")}catch(V){console.error("Meta OAuth error:",V),ae.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},S=async()=>{if(f){ae.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:z,error:V}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(V)throw V;if(z!=null&&z.authUrl)window.location.href=z.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(z){console.error("LinkedIn OAuth error:",z),ae.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},A=gt({mutationFn:async z=>{const{error:V}=await q.from("gmail_integrations").delete().eq("id",z).eq("user_id",p);if(V)throw V},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",p]}),ae.success("Gmail disconnected")},onError:()=>{ae.error("Failed to disconnect Gmail")}}),T=gt({mutationFn:async z=>{const{error:V}=await q.from("social_accounts").delete().eq("id",z).eq("user_id",p);if(V)throw V},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",p]}),ae.success("Account disconnected")},onError:()=>{ae.error("Failed to disconnect account")}}),D=!f&&!!(g!=null&&g.is_active),L=(v==null?void 0:v.filter(z=>z.platform==="facebook"))||[],M=(v==null?void 0:v.filter(z=>z.platform==="instagram"))||[],F=(v==null?void 0:v.filter(z=>z.platform==="linkedin"))||[];return e.jsx(Cs,{children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Integrations"}),e.jsx("p",{className:"text-muted-foreground",children:"Connect third-party services to supercharge your Agent OS workflow."})]}),f&&e.jsx(fe,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Mt,{className:"flex flex-row items-start gap-3 space-y-0",children:[e.jsx(Rc,{className:"h-5 w-5 text-amber-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-base",children:"Connected accounts are hidden"}),e.jsxs(Hn,{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(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(ZS,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-lg",children:"ChatGPT"}),e.jsx(Hn,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]})]})}),e.jsx(Ae,{children:e.jsxs(B,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(za,{className:"h-4 w-4 ml-1"})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-destructive/10 flex items-center justify-center",children:e.jsx(Hs,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:["Gmail",D&&e.jsx(ze,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Hn,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),e.jsx(Ae,{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(zi,{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(zi,{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(zi,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Quick compose from any contact detail page"})]}),D?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(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Gmail?"}),e.jsx(Mo,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>A.mutate(g.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:j,disabled:l||b,children:[l?e.jsx(Ai,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Hs,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(za,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center",children:e.jsx(Oh,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:["Facebook",L.length>0&&e.jsx(ze,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Hn,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(Ae,{className:"space-y-3",children:[L.length>0&&e.jsx("div",{className:"space-y-2",children:L.map(z=>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(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:z.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(Oh,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:z.page_name||z.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Facebook?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>T.mutate(z.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},z.id))}),e.jsxs(B,{onClick:()=>_("facebook"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(As,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-pink-500/10 flex items-center justify-center",children:e.jsx(mu,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:["Instagram",M.length>0&&e.jsx(ze,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Hn,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(Ae,{className:"space-y-3",children:[M.length>0&&e.jsx("div",{className:"space-y-2",children:M.map(z=>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(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:z.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(mu,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",z.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Instagram?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>T.mutate(z.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},z.id))}),e.jsxs(B,{onClick:()=>_("instagram"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(As,{className:"h-4 w-4"}),"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Uses Instagram's professional login for Business or Creator accounts. Personal accounts cannot post via Meta's API — convert your account in the Instagram app (Profile → Menu → Settings → Account type → Switch to Professional)."})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-700/10 flex items-center justify-center",children:e.jsx(bf,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:["LinkedIn",F.length>0&&e.jsx(ze,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Hn,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(Ae,{className:"space-y-3",children:[F.length>0&&e.jsx("div",{className:"space-y-2",children:F.map(z=>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(aa,{className:"h-8 w-8",children:[e.jsx(ri,{src:z.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(bf,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:z.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect LinkedIn?"}),e.jsx(Mo,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>T.mutate(z.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},z.id))}),e.jsxs(B,{onClick:S,disabled:u,variant:"outline",className:"gap-2",children:[u?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(As,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(cen,{}),e.jsx(den,{}),e.jsx(uen,{}),e.jsx(men,{}),e.jsx(gen,{}),t&&e.jsx(eNt,{})]})})}const ben="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function _en(){const[s,t]=N.useState(null),[n,r]=N.useState(!1),[a,i]=N.useState(0),[l,o]=N.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",u=window.location.hostname.startsWith("id-preview--"),h=async v=>{const j=new Uint8Array(await v.slice(0,4).arrayBuffer());return j[0]===80&&j[1]===75&&j[2]===3&&j[3]===4||j[0]===80&&j[1]===75&&j[2]===5&&j[3]===6||j[0]===80&&j[1]===75&&j[2]===7&&j[3]===8},p=v=>{const j=document.createElement("a");j.href=v,j.download="levelup-extension.zip",j.rel="noopener noreferrer",j.target="_blank",document.body.appendChild(j),j.click(),j.remove()},f=async()=>{o(!0);try{if(u){p(`${d}?v=${Date.now()}`);return}const v=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!v.ok)throw new Error(`Download failed (${v.status})`);const j=await v.blob();if(!await h(j)){p(`${d}?v=${Date.now()}`);return}const _=new Blob([j],{type:"application/zip"}),S=URL.createObjectURL(_),A=document.createElement("a");A.href=S,A.download="levelup-extension.zip",document.body.appendChild(A),A.click(),A.remove(),setTimeout(()=>URL.revokeObjectURL(S),1e3)}catch(v){ae.error(v.message||"Download failed")}finally{o(!1)}},g=async()=>{r(!0);try{await q.auth.refreshSession();const{data:v}=await q.auth.getSession();if(!v.session){ae.error("Your session has expired. Please sign in again.");return}const{data:j,error:_}=await q.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${v.session.access_token}`}});if(_)throw _;t(j.code),i(j.expires_in||300);const S=setInterval(()=>{i(A=>A<=1?(clearInterval(S),t(null),0):A-1)},1e3)}catch(v){console.error("generateCode error",v),ae.error("We couldn't generate a pairing code",{description:"Please refresh the page and try again. If it still fails, sign out and sign back in, then click Generate pairing code.",duration:8e3})}finally{r(!1)}},b=()=>{s&&(navigator.clipboard.writeText(s),ae.success("Copied"))};return e.jsx(Cs,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"Browser Extension | LevelUp"}),e.jsx("meta",{name:"description",content:"Install the LevelUp browser extension to add contacts and import listings from any webpage."})]}),e.jsx("header",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-primary text-primary-foreground flex items-center justify-center",children:e.jsx(kA,{className:"w-6 h-6"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Browser Extension"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts and import listings from anywhere on the web."})]})]})}),e.jsxs(fe,{className:"p-6 space-y-4 border-2 border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"1"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Install from the Chrome Web Store"})]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Quick-add contacts from any webpage with one click or right-click"}),e.jsx("li",{children:"Import listings from Zillow, Realtor.com, and Redfin as drafts"}),e.jsx("li",{children:'"Add to LevelUp" button on Gmail threads and LinkedIn profiles'}),e.jsx("li",{children:"Toolbar launcher with shortcuts to Dashboard, ReelFlow, Card Studio, and more"})]}),e.jsxs(B,{size:"lg",className:"w-full",onClick:()=>window.open(ben,"_blank","noopener,noreferrer"),children:[e.jsx(kA,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(tr,{className:"w-3.5 h-3.5 ml-2 opacity-70"})]}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Works in Chrome, Edge, Brave, and Arc. Free to install."})]}),e.jsxs(fe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"2"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Pair the extension"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a one-time pairing code, then enter it inside the extension popup."}),s?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-muted rounded-xl p-6 text-center",children:[e.jsx("div",{className:"text-4xl font-mono font-bold tracking-[0.4em] text-primary",children:s}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Expires in ",Math.floor(a/60),":",String(a%60).padStart(2,"0")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{onClick:b,variant:"outline",className:"flex-1",children:[e.jsx(ta,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(B,{onClick:g,variant:"outline",className:"flex-1",children:[e.jsx(Ai,{className:"w-4 h-4 mr-2"})," New code"]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground bg-muted/50 rounded-lg p-3",children:[e.jsx(Lr,{className:"w-4 h-4 mt-0.5 text-primary"}),e.jsx("span",{children:"Click the LevelUp icon in your browser toolbar and paste this code. You only need to do this once per browser."})]})]}):e.jsx(B,{onClick:g,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(Ai,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(fe,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oc,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h2",{className:"text-base font-semibold text-muted-foreground",children:"Manual install (advanced)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you prefer to load the extension unpacked, or the Web Store is unavailable, download the ZIP below."}),e.jsxs("ol",{className:"text-sm space-y-2 list-decimal list-inside text-muted-foreground",children:[e.jsx("li",{children:e.jsx(B,{variant:"link",className:"h-auto p-0 text-sm",onClick:f,disabled:l,children:"Download the extension ZIP"})}),e.jsx("li",{children:"Unzip the downloaded file"}),e.jsxs("li",{children:["Open"," ",e.jsx("code",{className:"px-1.5 py-0.5 rounded bg-muted text-foreground",children:"chrome://extensions"})," ","in Chrome, Edge, Brave, or Arc"]}),e.jsxs("li",{children:["Turn on ",e.jsx("b",{className:"text-foreground",children:"Developer mode"})," (top-right toggle)"]}),e.jsxs("li",{children:["Click ",e.jsx("b",{className:"text-foreground",children:"Load unpacked"})," and pick the unzipped folder"]}),e.jsx("li",{children:"Pin the LevelUp icon to your toolbar"})]})]})]})})}function wen(){const[s]=yl(),t=In(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your Gmail account...");return N.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:h,error:p}=await q.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:u}});if(p)throw p;if(h!=null&&h.success)r("success"),i(h.message||"Gmail connected successfully!"),ae.success("Gmail connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Gmail OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Gmail"),ae.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[n==="loading"&&e.jsx(ss,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(zi,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Gc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Pt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Hn,{children:a})]}),e.jsx(Ae,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function jen(){const s=In();return N.useEffect(()=>{const t=setTimeout(()=>{s("/mission-control/integrations",{replace:!0})},1500);return()=>clearTimeout(t)},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Finishing Canva connection…"})]})})}function Nen(){const[s]=yl(),t=In(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing your connection...");return N.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:f}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u,callbackPath:"/mission-control/integrations/meta/callback"}});if(p&&p.success===!1)throw new Error(p.error||"Failed to connect accounts");if(f){let g=f.message||"Failed to connect accounts";try{const b=f.context;if(b&&typeof b.json=="function"){const v=await b.json();v!=null&&v.error&&(g=v.error)}}catch{}throw new Error(g)}if(p!=null&&p.success)r("success"),i(`Successfully connected ${((h=p.accounts)==null?void 0:h.length)||0} account(s)!`),ae.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),r("error"),i(p instanceof Error?p.message:"Failed to connect accounts"),ae.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[n==="loading"&&e.jsx(ss,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(zi,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Gc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Pt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Hn,{children:a})]}),e.jsx(Ae,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const sNt=new Date().getFullYear(),ken=Array.from({length:5},(s,t)=>sNt-t);function Sen(){const[s,t]=N.useState(sNt),n=In(),{data:r,isLoading:a}=ras();return a?e.jsx(Cs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(Ws,{className:"h-24"},i))}),e.jsx(Ws,{className:"h-96"})]})}):e.jsx(Cs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Scorecard Admin"}),e.jsx("p",{className:"text-muted-foreground",children:"View agent performance and scorecards"})]}),e.jsxs(us,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(cs,{className:"w-[120px]",children:e.jsx(hs,{})}),e.jsx(ds,{children:ken.map(i=>e.jsx(Ze,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_n,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Agents Tracking"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(r==null?void 0:r.length)||0})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(yo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(r==null?void 0:r.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with transactions"})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Agents with Scorecards"}),e.jsx(Hn,{children:"Click to view individual agent scorecards"})]}),e.jsx(Ae,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(yo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:r.map(i=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:i.name}),e.jsx(ut,{className:"text-muted-foreground",children:i.email}),e.jsx(ut,{className:"text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const nNt=new Date().getFullYear(),Cen=Array.from({length:10},(s,t)=>nNt-t);function SXe(){var b;const{userId:s}=_i(),t=In(),r=Jl().pathname.startsWith("/mission-control"),[a,i]=N.useState(nNt),{data:l,isLoading:o}=lt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:v,error:j}=await q.from("profiles").select("id, name, email").eq("id",s).single();if(j)throw j;return v},enabled:!!s}),{data:c,isLoading:d}=S6e(a,s),{yearStats:u,lifetimeStats:h,isLoading:p,showCommission:f}=_pt(a,s),{data:g}=bpt(a,s);return o?e.jsx(Cs,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(v=>e.jsx(Ws,{className:"h-24"},v))})]})}):e.jsx(Cs,{title:`${l==null?void 0:l.name}'s Scorecard`,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t(r?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(Wr,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:l==null?void 0:l.name}),e.jsx("p",{className:"text-muted-foreground",children:l==null?void 0:l.email})]})]}),e.jsxs(us,{value:String(a),onValueChange:v=>i(Number(v)),children:[e.jsx(cs,{className:"w-[120px]",children:e.jsx(hs,{})}),e.jsx(ds,{children:Cen.map(v=>e.jsx(Ze,{value:String(v),children:v},v))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(zr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:u.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.totalTransactions," lifetime"]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_n,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[u.buyerCount,"/",u.sellerCount]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:gc(u.totalVolume,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(mo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:gc(u.averagePrice,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(vc,{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=u.topLeadSource)==null?void 0:b.name)||"-"})]})})]}),g&&e.jsx(d2t,{goals:g,stats:u,year:a,showCommission:f}),e.jsxs($r,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"transactions",children:"Transactions"}),e.jsx(Zt,{value:"charts",children:"Charts"}),e.jsxs(Zt,{value:"map",children:[e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(ls,{value:"transactions",children:e.jsx(b8e,{transactions:c||[],showCommission:f,isLoading:d})}),e.jsx(ls,{value:"charts",children:e.jsx(_8e,{stats:u,year:a})}),e.jsx(ls,{value:"map",children:e.jsx(w8e,{transactions:c||[],isLoading:d})})]})]})})}function Ten(){const s=Gt(),[t,n]=N.useState(""),[r,a]=N.useState("all"),[i,l]=N.useState(null);emt();const{data:o,refetch:c}=lt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:F}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(F==null?void 0:F.enabled)??!1}}),{data:d,isLoading:u}=lt({queryKey:["admin-listings"],queryFn:async()=>{const{data:F,error:z}=await q.from("listings").select(` *, agent:profiles!listings_agent_id_fkey(id, name, email), photos:listing_photos(id, photo_url, is_primary) `).order("created_at",{ascending:!1});if(z)throw z;return F}}),{data:h}=lt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:F}=await q.from("listings").select("id, is_approved, status"),{data:z}=await q.from("listing_shares").select("id"),{data:V}=await q.from("listing_views").select("id"),{count:W}=await q.from("listing_leads").select("id",{count:"exact",head:!0}),K=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:Y}=await q.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",K);return{total:(F==null?void 0:F.length)||0,pending:(F==null?void 0:F.filter(ee=>!ee.is_approved).length)||0,active:(F==null?void 0:F.filter(ee=>ee.status==="active").length)||0,totalShares:(z==null?void 0:z.length)||0,totalViews:(V==null?void 0:V.length)||0,totalLeads:W||0,leadsLast7:Y||0}}}),{data:p}=lt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const F={};let z=0;const V=1e3;for(;;){const{data:W,error:K}=await q.from("listing_leads").select("listing_id").range(z,z+V-1);if(K)throw K;if(!W||W.length===0)break;for(const Y of W)Y.listing_id&&(F[Y.listing_id]=(F[Y.listing_id]||0)+1);if(W.length{const{data:F,error:z}=await q.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(z)throw z;return F}}),b=async(F,z,V="submit_url")=>{try{const{data:{session:W}}=await q.auth.getSession();if(!W)return;const{data:K,error:Y}=await q.functions.invoke("google-indexing",{body:{action:V,listing_id:F,listing_slug:z}});if(Y)throw Y;if((K==null?void 0:K.configured)===!1)return;K!=null&&K.success&&ae.success("Submitted to Google for indexing")}catch(W){console.error("Google indexing submission failed:",W)}},v=gt({mutationFn:async()=>{const{data:{session:F}}=await q.auth.getSession();if(!F)throw new Error("Not authenticated");const{data:z,error:V}=await q.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(V)throw V;return z},onSuccess:F=>{if((F==null?void 0:F.configured)===!1){ae.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}ae.success(`Submitted ${(F==null?void 0:F.succeeded)||0} URLs to Google (${(F==null?void 0:F.failed)||0} failed)`)},onError:F=>{ae.error("Failed to submit to Google"),console.error(F)}}),j=gt({mutationFn:async({id:F,approved:z,slug:V})=>{const{error:W}=await q.from("listings").update({is_approved:z}).eq("id",F);if(W)throw W;return{id:F,approved:z,slug:V}},onSuccess:F=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ae.success(F.approved?"Listing approved":"Listing unapproved"),F.approved?b(F.id,F.slug||null,"submit_url"):b(F.id,F.slug||null,"remove_url")}}),_=gt({mutationFn:async({id:F,featured:z})=>{const{error:V}=await q.from("listings").update({is_featured:z}).eq("id",F);if(V)throw V},onSuccess:(F,{featured:z})=>{s.invalidateQueries({queryKey:["admin-listings"]}),ae.success(z?"Listing featured":"Listing unfeatured")}}),S=gt({mutationFn:async F=>{const{error:z}=await q.from("listings").delete().eq("id",F);if(z)throw z},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ae.success("Listing deleted")}}),A=gt({mutationFn:async F=>{const{error:z}=await q.from("feature_flags").update({enabled:F}).eq("key","listing_exchange_enabled");if(z)throw z},onSuccess:()=>{c(),ae.success("Feature flag updated")}}),T=o??!1,D=d==null?void 0:d.filter(F=>{var W,K,Y,ee;const z=((W=F.city)==null?void 0:W.toLowerCase().includes(t.toLowerCase()))||((Y=(K=F.agent)==null?void 0:K.name)==null?void 0:Y.toLowerCase().includes(t.toLowerCase()))||((ee=F.property_address)==null?void 0:ee.toLowerCase().includes(t.toLowerCase())),V=r==="all"||r==="pending"&&!F.is_approved||r==="approved"&&F.is_approved;return z&&V}),L=F=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(F),M=F=>{const z={active:"bg-green-500/10 text-green-600 border-green-200",coming_soon:"bg-blue-500/10 text-blue-600 border-blue-200",price_improvement:"bg-amber-500/10 text-amber-600 border-amber-200",under_contract:"bg-purple-500/10 text-purple-600 border-purple-200",sold:"bg-gray-500/10 text-gray-600 border-gray-200"};return z[F]||z.active};return e.jsxs(Cs,{title:"Listing Exchange Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending,className:"gap-2",children:[v.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(lc,{className:"h-4 w-4"}),"Submit All to Google"]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Feature visible to agents"}),e.jsx(vn,{checked:T,onCheckedChange:F=>A.mutate(F)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Listings"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.total)||0})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mo,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.active)||0})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Pending Review"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.pending)||0})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Views"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalViews)||0})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hl,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Shares"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalShares)||0})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalLeads)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[(h==null?void 0:h.leadsLast7)||0," in last 7 days"]})]})})]}),e.jsx(fe,{children:e.jsx(Ae,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by city, address, or agent...",value:t,onChange:F=>n(F.target.value),className:"pl-9"})]}),e.jsx($r,{value:r,onValueChange:F=>a(F),children:e.jsxs(Ur,{children:[e.jsx(Zt,{value:"all",children:"All"}),e.jsx(Zt,{value:"pending",children:"Pending"}),e.jsx(Zt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{children:["Listings (",(D==null?void 0:D.length)||0,")"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Property"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Price"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-center",children:"Approved"}),e.jsx(Ct,{className:"text-center",children:"Featured"}),e.jsx(Ct,{children:"Views"}),e.jsx(Ct,{children:"Shares"}),e.jsx(Ct,{children:"Leads"}),e.jsx(Ct,{children:"Date"}),e.jsx(Ct,{})]})}),e.jsx(pa,{children:u?e.jsx(Gs,{children:e.jsx(ut,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(D==null?void 0:D.length)===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):D==null?void 0:D.map(F=>{var z,V,W,K,Y;return e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(V=(z=F.photos)==null?void 0:z[0])!=null&&V.photo_url?e.jsx("img",{src:F.photos[0].photo_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(Ga,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:F.property_address||`${F.city}, ${F.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(W=F.property_type)==null?void 0:W.replace("_"," ")})]})]})}),e.jsx(ut,{children:e.jsx("p",{className:"text-sm",children:((K=F.agent)==null?void 0:K.name)||"Unknown"})}),e.jsx(ut,{className:"font-medium",children:L(F.price)}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",className:M(F.status),children:(Y=F.status)==null?void 0:Y.replace("_"," ")})}),e.jsx(ut,{className:"text-center",children:e.jsx(vn,{checked:F.is_approved??!1,onCheckedChange:ee=>j.mutate({id:F.id,approved:ee,slug:F.slug})})}),e.jsx(ut,{className:"text-center",children:e.jsx(vn,{checked:F.is_featured??!1,onCheckedChange:ee=>_.mutate({id:F.id,featured:ee})})}),e.jsx(ut,{children:F.view_count||0}),e.jsx(ut,{children:F.share_count||0}),e.jsx(ut,{children:((p==null?void 0:p[F.id])??0)>0?e.jsx(B,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:F.id,label:F.property_address||`${F.city}, ${F.state}`}),children:p==null?void 0:p[F.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:ks(new Date(F.created_at),"MMM d, yyyy")}),e.jsx(ut,{children:e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(Xf,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[e.jsxs(Xr,{onClick:()=>window.open(`/mission-control/listings/${F.id}`,"_blank"),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(Xr,{onClick:()=>_.mutate({id:F.id,featured:!F.is_featured}),children:[e.jsx(ua,{className:"h-4 w-4 mr-2"}),F.is_featured?"Unfeature":"Feature"]}),e.jsxs(Xr,{className:"text-destructive",onClick:()=>{confirm("Are you sure you want to delete this listing?")&&S.mutate(F.id)},children:[e.jsx(Fn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},F.id)})})]})})})]})]}),e.jsx(bs,{open:!!i,onOpenChange:F=>!F&&l(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Leads from listing"}),e.jsx(Qn,{children:i==null?void 0:i.label})]}),g?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ss,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!f||f.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Phone"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Captured"})]})}),e.jsx(pa,{children:f.map(F=>{var z;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:[F.first_name,F.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(ut,{children:F.email}),e.jsx(ut,{children:F.phone||"—"}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",children:(z=F.lead_type)==null?void 0:z.replace("_"," ")})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:ks(new Date(F.created_at),"MMM d, yyyy h:mm a")})]},F.id)})})]})]})})]})}function Een(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function Aen(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),{data:l,isLoading:o}=lt({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let p=0;const f=1e3;for(;;){const{data:g,error:b}=await q.from("listing_leads").select(` id, listing_id, agent_id, referred_by_agent_id, first_name, last_name, email, phone, lead_type, showing_mode, preferred_date, preferred_time, message, created_at, listing:listings!listing_leads_listing_id_fkey(id, slug, property_address, city, state, price), agent:profiles!listing_leads_agent_id_fkey(id, name, email), referrer:profiles!listing_leads_referred_by_agent_id_fkey(id, name, email) `).order("created_at",{ascending:!1}).range(p,p+f-1);if(b)throw b;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,p=s.trim().toLowerCase();return l.filter(f=>{var b,v,j,_,S,A;return h&&new Date(f.created_at).getTime(){const h=c.length,p=c.filter(b=>b.lead_type==="showing_request").length,f=new Set(c.map(b=>b.agent_id)).size,g=new Set(c.map(b=>b.listing_id)).size;return{total:h,showings:p,uniqueAgents:f,uniqueListings:g}},[c]),u=()=>{const p=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(v=>{var j,_,S,A,T,D;return[ks(new Date(v.created_at),"yyyy-MM-dd HH:mm"),`${v.first_name||""} ${v.last_name||""}`.trim(),v.email,v.phone||"",v.lead_type,v.preferred_date?`${v.preferred_date} ${v.preferred_time||""}`:"",((j=v.listing)==null?void 0:j.property_address)||"",((_=v.listing)==null?void 0:_.city)||"",(S=v.listing)!=null&&S.price?String(v.listing.price):"",((A=v.agent)==null?void 0:A.name)||"",((T=v.agent)==null?void 0:T.email)||"",((D=v.referrer)==null?void 0:D.name)||"",(v.message||"").replace(/[\r\n]+/g," ")]})].map(v=>v.map(j=>`"${String(j).replace(/"/g,'""')}"`).join(",")).join(` `),f=new Blob([p],{type:"text/csv"}),g=URL.createObjectURL(f),b=document.createElement("a");b.href=g,b.download=`listing-leads-${ks(new Date,"yyyy-MM-dd")}.csv`,b.click(),URL.revokeObjectURL(g)};return e.jsx(Cs,{title:"Listing Leads",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Leads"}),e.jsx("p",{className:"text-muted-foreground",children:"All leads submitted through the public listings site"})]}),e.jsxs(B,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(Da,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.total})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-purple-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing Requests"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.showings})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Properties"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueListings})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4 text-amber-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Agents w/ Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueAgents})]})})]}),e.jsx(fe,{children:e.jsx(Ae,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(us,{value:a,onValueChange:h=>i(h),children:[e.jsx(cs,{className:"w-full sm:w-48",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),e.jsx(Ze,{value:"info_request",children:"Info Request"}),e.jsx(Ze,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(us,{value:n,onValueChange:h=>r(h),children:[e.jsx(cs,{className:"w-full sm:w-40",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Time"}),e.jsx(Ze,{value:"7",children:"Last 7 days"}),e.jsx(Ze,{value:"30",children:"Last 30 days"}),e.jsx(Ze,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{children:["Leads (",c.length,")"]})}),e.jsx(Ae,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Date"}),e.jsx(Ct,{children:"Lead"}),e.jsx(Ct,{children:"Contact"}),e.jsx(Ct,{children:"Property"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Assigned To"}),e.jsx(Ct,{children:"Referred By"}),e.jsx(Ct,{children:"Message"})]})}),e.jsx(pa,{children:o?e.jsx(Gs,{children:e.jsx(ut,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(h=>{var p,f;return e.jsxs(Gs,{children:[e.jsxs(ut,{className:"whitespace-nowrap text-sm",children:[ks(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:ks(new Date(h.created_at),"h:mm a")})]}),e.jsx(ut,{children:e.jsx("div",{className:"font-medium",children:`${h.first_name||""} ${h.last_name||""}`.trim()||"—"})}),e.jsx(ut,{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(Hs,{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(Pr,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(ut,{children:h.listing?e.jsxs(Ln,{to:`/public/listing/${h.listing.slug||h.listing.id}`,target:"_blank",className:"group",children:[e.jsxs("div",{className:"font-medium text-sm group-hover:underline flex items-center gap-1",children:[h.listing.property_address||"Untitled",e.jsx(tr,{className:"h-3 w-3 opacity-60"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[[h.listing.city,h.listing.state].filter(Boolean).join(", ")," · ",Een(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(ut,{children:[e.jsx(ze,{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(ut,{children:[e.jsx("div",{className:"text-sm font-medium",children:((p=h.agent)==null?void 0:p.name)||"—"}),((f=h.agent)==null?void 0:f.email)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:h.agent.email})]}),e.jsx(ut,{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(ut,{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(Ci,{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 VI={new_listing_alerts:{label:"New Listing Alerts",icon:lm,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:DA,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:yi,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:_r,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:$u,color:"bg-emerald-100 text-emerald-800"}},CXe=[{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 TXe(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function Men(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState("30d"),[l,o]=N.useState("all"),[c,d]=N.useState("");N.useEffect(()=>{let f=!1;return(async()=>{r(!0);let g=q.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const b=CXe.find(_=>_.key===a);if(b&&b.days>0){const _=new Date(Date.now()-b.days*864e5).toISOString();g=g.gte("created_at",_)}const{data:v,error:j}=await g;f||(j?(console.error(j),t([])):t(v||[]),r(!1))})(),()=>{f=!0}},[a]);const u=N.useMemo(()=>s.filter(f=>{if(l!=="all"&&f.lead_type!==l)return!1;if(c){const g=c.toLowerCase();if(![f.email,f.first_name,f.last_name,f.phone,f.source_page,f.referrer].filter(Boolean).join(" ").toLowerCase().includes(g))return!1}return!0}),[s,l,c]),h=N.useMemo(()=>{const f=u.length,g=new Set(u.map(v=>v.email.toLowerCase())).size,b={};return u.forEach(v=>{b[v.lead_type]=(b[v.lead_type]||0)+1}),{total:f,uniqueEmails:g,byType:b}},[u]),p=()=>{const g=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(_=>{var A;const S=[TXe(_.created_at),((A=VI[_.lead_type])==null?void 0:A.label)||_.lead_type,_.email,_.first_name||"",_.last_name||"",_.phone||"",_.listing_id||"",_.source_page||"",_.referrer||"",_.criteria?JSON.stringify(_.criteria):""].map(T=>`"${String(T).replace(/"/g,'""')}"`);g.push(S.join(","))});const b=new Blob([g.join(` `)],{type:"text/csv"}),v=URL.createObjectURL(b),j=document.createElement("a");j.href=v,j.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,j.click(),URL.revokeObjectURL(v)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(Yo,{children:e.jsx("title",{children:"Public Site Leads — Admin"})}),e.jsx("div",{className:"border-b bg-white",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ln,{to:"/admin",children:e.jsxs(B,{variant:"ghost",size:"sm",children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Public Site Leads"}),e.jsx("p",{className:"text-xs text-slate-500",children:"listings.relevelup.com — alerts, exit intent & saved homes"})]})]}),e.jsxs(B,{onClick:p,variant:"outline",size:"sm",children:[e.jsx(Da,{className:"h-4 w-4 mr-1"})," Export CSV"]})]})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(fe,{children:e.jsxs(Ae,{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(VI).map(f=>{const g=VI[f],b=g.icon;return e.jsx(fe,{children:e.jsxs(Ae,{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(b,{className:"h-3.5 w-3.5"}),g.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[f]||0})]})},f)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(us,{value:a,onValueChange:f=>i(f),children:[e.jsx(cs,{className:"w-[160px] bg-white",children:e.jsx(hs,{})}),e.jsx(ds,{children:CXe.map(f=>e.jsx(Ze,{value:f.key,children:f.label},f.key))})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(cs,{className:"w-[200px] bg-white",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All lead types"}),Object.keys(VI).map(f=>e.jsx(Ze,{value:f,children:VI[f].label},f))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ge,{placeholder:"Search name, email, phone…",value:c,onChange:f=>d(f.target.value),className:"pl-9 bg-white"})]}),e.jsxs("div",{className:"ml-auto text-sm text-slate-500",children:[u.length," ",u.length===1?"lead":"leads"]})]}),e.jsx(fe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500",children:[e.jsx("th",{className:"px-4 py-3",children:"Date"}),e.jsx("th",{className:"px-4 py-3",children:"Type"}),e.jsx("th",{className:"px-4 py-3",children:"Contact"}),e.jsx("th",{className:"px-4 py-3",children:"Phone"}),e.jsx("th",{className:"px-4 py-3",children:"Details"}),e.jsx("th",{className:"px-4 py-3",children:"Source"})]})}),e.jsx("tbody",{children:n?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"Loading…"})}):u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"No leads yet in this range."})}):u.map(f=>{const g=VI[f.lead_type],b=g==null?void 0:g.icon,v=[f.first_name,f.last_name].filter(Boolean).join(" ")||"—";return e.jsxs("tr",{className:"border-b hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-slate-600 text-xs",children:TXe(f.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(ze,{className:`${(g==null?void 0:g.color)||""} font-normal`,variant:"secondary",children:[b?e.jsx(b,{className:"h-3 w-3 mr-1"}):null,(g==null?void 0:g.label)||f.lead_type]})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium text-slate-900",children:v}),e.jsxs("a",{href:`mailto:${f.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(Hs,{className:"h-3 w-3"}),f.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:f.phone?e.jsxs("a",{href:`tel:${f.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(Pr,{className:"h-3 w-3"}),f.phone]}):e.jsx("span",{className:"text-slate-400 text-xs",children:"—"})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-600 max-w-xs",children:[f.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[f.listing_id.slice(0,8),"…"]})]}),f.criteria&&Object.keys(f.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(f.criteria).map(([j,_])=>`${j}: ${_}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[f.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(tr,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f.source_page})]}),f.referrer&&e.jsxs("div",{className:"text-slate-400 truncate",children:["from ",f.referrer]})]})]},f.id)})})]})})})]})]})}const Ien=()=>{var h,p;const[s,t]=N.useState(""),[n,r]=N.useState(null),{data:a,isLoading:i}=lt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:f,error:g}=await q.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(g)throw g;const b=(f==null?void 0:f.map(_=>_.user_id))||[],{data:v}=await q.from("profiles").select("id, name, email").in("id",b);return f==null?void 0:f.map(_=>({..._,profiles:(v==null?void 0:v.find(S=>S.id===_.user_id))||null}))}}),l=a==null?void 0:a.filter(f=>{var b,v,j,_,S;const g=s.toLowerCase();return((v=(b=f.profiles)==null?void 0:b.name)==null?void 0:v.toLowerCase().includes(g))||((_=(j=f.profiles)==null?void 0:j.email)==null?void 0:_.toLowerCase().includes(g))||((S=f.review_text)==null?void 0:S.toLowerCase().includes(g))}),o=a!=null&&a.length?(a.reduce((f,g)=>f+g.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((f,g)=>(f[g.rating]=(f[g.rating]||0)+1,f),{}),d=(a==null?void 0:a.filter(f=>f.posted_to_google).length)||0,u=f=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(g=>e.jsx(ua,{className:Et("h-4 w-4",f>=g?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},g))});return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Membership Reviews",description:"View and manage feedback from LevelUp members"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Hn,{children:"Total Reviews"}),e.jsx(Pt,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Hn,{children:"Average Rating"}),e.jsxs(Pt,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(ua,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Hn,{children:"5-Star Reviews"}),e.jsx(Pt,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Hn,{children:"Posted to Google"}),e.jsxs(Pt,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(tr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name, email, or review...",value:s,onChange:f=>t(f.target.value),className:"pl-9"})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Member"}),e.jsx(Ct,{children:"Rating"}),e.jsx(Ct,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Ct,{children:"Google"}),e.jsx(Ct,{children:"Date"})]})}),e.jsx(pa,{children:i?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(f=>{var g,b;return e.jsxs(Gs,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(f),children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((g=f.profiles)==null?void 0:g.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(b=f.profiles)==null?void 0:b.email})]})}),e.jsx(ut,{children:u(f.rating)}),e.jsx(ut,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:f.review_text||"-"})}),e.jsx(ut,{children:f.posted_to_google?e.jsx(ze,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(ze,{variant:"outline",children:"No"})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:ks(new Date(f.created_at),"MMM d, yyyy")})]},f.id)})})]})})}),e.jsx(bs,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{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"}),((p=n.profiles)==null?void 0:p.email)&&e.jsxs("a",{href:`mailto:${n.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(Hs,{className:"h-3 w-3"}),n.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[u(n.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[n.rating," out of 5 stars"]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Review"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:n.review_text||"No written review provided."})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(yr,{className:"h-4 w-4"}),ks(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs(ze,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(tr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(ze,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},EXe={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},Pen={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 Len(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),[l,o]=N.useState("7"),{data:c,isLoading:d}=lt({queryKey:["lead-notification-log",l],queryFn:async()=>{const p=new Date(Date.now()-Number(l)*864e5).toISOString(),{data:f,error:g}=await q.from("lead_notification_log").select("*").gte("created_at",p).order("created_at",{ascending:!1}).limit(2e3);if(g)throw g;return f||[]}}),u=N.useMemo(()=>{const p=s.trim().toLowerCase();return(c||[]).filter(f=>n!=="all"&&f.source!==n||a!=="all"&&f.status!==a?!1:p?[f.agent_name,f.agent_email,f.lead_name,f.lead_email,f.lead_phone,f.subject].some(g=>(g||"").toLowerCase().includes(p)):!0)},[c,s,n,a]),h=N.useMemo(()=>{const p=u.length,f=u.filter(v=>v.status==="sent"||v.status==="backfilled").length,g=u.filter(v=>v.status==="failed").length,b=new Set(u.map(v=>v.agent_user_id).filter(Boolean)).size;return{total:p,sent:f,failed:g,agents:b}},[u]);return e.jsx(Cs,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(Vd,{title:"Lead Notifications",description:"Every new-lead notification sent to agents — agent cards, listings, lead sites, guest book sign-ins, landing pages, connect pages, and bookings."}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"}),e.jsx("div",{className:"text-2xl font-bold",children:h.total})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sent"}),e.jsx("div",{className:"text-2xl font-bold text-green-600",children:h.sent})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Failed"}),e.jsx("div",{className:"text-2xl font-bold text-red-600",children:h.failed})]})}),e.jsx(fe,{children:e.jsxs(Ae,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:p=>t(p.target.value),className:"pl-9"})]}),e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(cs,{className:"w-full md:w-48",children:e.jsx(hs,{placeholder:"Source"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Sources"}),Object.entries(EXe).map(([p,f])=>e.jsx(Ze,{value:p,children:f},p))]})]}),e.jsxs(us,{value:a,onValueChange:i,children:[e.jsx(cs,{className:"w-full md:w-40",children:e.jsx(hs,{placeholder:"Status"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),e.jsx(Ze,{value:"sent",children:"Sent"}),e.jsx(Ze,{value:"backfilled",children:"Backfilled"}),e.jsx(Ze,{value:"failed",children:"Failed"})]})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(cs,{className:"w-full md:w-36",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"1",children:"Last 24h"}),e.jsx(Ze,{value:"7",children:"Last 7 days"}),e.jsx(Ze,{value:"14",children:"Last 14 days"}),e.jsx(Ze,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"When"}),e.jsx(Ct,{children:"Source"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Lead"}),e.jsx(Ct,{children:"Status"})]})}),e.jsx(pa,{children:d?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No notifications match the current filters."})}):u.map(p=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"whitespace-nowrap text-sm",children:ks(new Date(p.created_at),"MMM d, yyyy h:mm a")}),e.jsx(ut,{children:e.jsx(ze,{variant:"secondary",children:EXe[p.source]||p.source})}),e.jsxs(ut,{children:[e.jsx("div",{className:"font-medium",children:p.agent_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:p.agent_email||"—"})]}),e.jsxs(ut,{children:[e.jsx("div",{className:"font-medium",children:p.lead_name||"—"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap gap-x-3 gap-y-1",children:[p.lead_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hs,{className:"h-3 w-3"}),p.lead_email]}),p.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pr,{className:"h-3 w-3"}),p.lead_phone]})]})]}),e.jsxs(ut,{children:[e.jsx(ze,{className:Pen[p.status]||"",children:p.status}),p.error_message&&e.jsx("div",{className:"text-xs text-red-600 mt-1 max-w-[220px] truncate",title:p.error_message,children:p.error_message})]})]},p.id))})]})})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Historical entries (before this feature was enabled) are marked as ",e.jsx("em",{children:"backfilled"})," and reconstructed from the underlying lead records. New leads are logged automatically going forward."]})]})})}const Den=[{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"}],Ren=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 Oen(){const s=Gt(),{user:t}=gs(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),{data:c,isLoading:d}=lt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:M,error:F}=await q.from("weekly_digest_settings").select("*").single();if(F)throw F;return M}}),{data:u,isLoading:h}=lt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:M,error:F}=await q.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(F)throw F;return M}}),{data:p}=lt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:M,error:F}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(F)throw F;return M||0}}),{data:f,refetch:g}=lt({queryKey:["digest-queue-status"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const[F,z,V,W]=await Promise.all([q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",M.toISOString())]);return{pending:F.count||0,processing:z.count||0,sent:V.count||0,failed:W.count||0,total:(F.count||0)+(z.count||0)+(V.count||0)+(W.count||0)}},refetchInterval:5e3});N.useEffect(()=>{if(f&&(f.pending>0||f.processing>0)){const M=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(M)}},[f,g,s]);const{data:b=0}=lt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const{count:F,error:z}=await q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString());if(z)throw z;return F||0}}),v=gt({mutationFn:async M=>{const{error:F}=await q.from("weekly_digest_settings").update(M).eq("id",c==null?void 0:c.id);if(F)throw F},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),ae.success("Settings updated")},onError:M=>{ae.error("Failed to update settings: "+M.message)}}),j=async()=>{r(!0);try{const{data:M,error:F}=await q.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(F)throw F;M.queued?ae.success(`${M.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):M.sent!==void 0&&ae.success(`Digest sent! ${M.sent} emails delivered, ${M.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(M){ae.error("Failed to send digest: "+M.message)}finally{r(!1)}},_=async()=>{var M,F,z,V,W,K;if(!(t!=null&&t.email)){ae.error("No email found for your account");return}i(!0);try{const{data:Y,error:ee}=await q.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(ee)throw ee;const ne=Y==null?void 0:Y.resendId,oe=Y==null?void 0:Y.resendDetails,pe=oe==null?void 0:oe.status,ce=((M=oe==null?void 0:oe.body)==null?void 0:M.status)||((z=(F=oe==null?void 0:oe.body)==null?void 0:F.data)==null?void 0:z.status),de=((W=(V=oe==null?void 0:oe.body)==null?void 0:V.error)==null?void 0:W.message)||((K=oe==null?void 0:oe.body)==null?void 0:K.message);ae.success(ne?`Preview accepted by email provider (id: ${ne})${pe?`, status check: ${pe}`:""}${ce?`, provider: ${ce}`:""}${de?` (${de})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(Y){ae.error("Failed to send preview: "+Y.message)}finally{i(!1)}},S=async()=>{o(!0);try{const{data:M,error:F}=await q.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(F)throw F;M.queued===0||M.sent===0&&M.failed===0&&!M.queued?ae.info("No failed emails to retry"):M.queued?ae.success(`${M.queued} emails queued for retry!`):ae.success(`Retry complete! ${M.sent} emails delivered, ${M.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(M){ae.error("Failed to retry: "+M.message)}finally{o(!1)}},A=f!=null&&f.total?Math.round((f.sent+f.failed)/f.total*100):0,T=((f==null?void 0:f.pending)||0)>0||((f==null?void 0:f.processing)||0)>0,{data:D}=lt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var K,Y;const M=new Date;M.setUTCHours(0,0,0,0);const[F,z,V,W]=await Promise.all([q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:F.count||0,totalFailed:z.count||0,agentOsEngaged:V.count||0,lastSent:((Y=(K=W.data)==null?void 0:K[0])==null?void 0:Y.sent_at)||null}},refetchInterval:T?5e3:!1}),L={totalSent:(D==null?void 0:D.totalSent)||0,totalFailed:(D==null?void 0:D.totalFailed)||0,lastSent:D==null?void 0:D.lastSent,agentOsEngaged:(D==null?void 0:D.agentOsEngaged)||0};return d?e.jsx(Cs,{title:"Weekly Digest",description:"Manage automated weekly email digests",children:e.jsxs("div",{className:"animate-pulse space-y-4",children:[e.jsx("div",{className:"h-32 bg-muted rounded-lg"}),e.jsx("div",{className:"h-64 bg-muted rounded-lg"})]})}):e.jsx(Cs,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs($r,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(Vo,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Zt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(yo,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(ls,{value:"settings",className:"space-y-6",children:[T&&f&&e.jsx(fe,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Ae,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(ss,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Sending emails..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f.sent.toLocaleString()," sent, ",f.pending.toLocaleString()," pending",f.failed>0&&`, ${f.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[A,"%"]})]}),e.jsx(xi,{value:A,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Processing ~80 emails per minute. Estimated time remaining: ~",Math.ceil(f.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsx(Ae,{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(_n,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:p}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(fe,{children:e.jsx(Ae,{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(xr,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:L.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(fe,{children:e.jsx(Ae,{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(Gc,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:L.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(fe,{children:e.jsx(Ae,{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(gr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:L.lastSent?ks(new Date(L.lastSent),"MMM d"):"Never"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last Sent"})]})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Hn,{children:"Configure when the digest is sent"})]}),e.jsxs(Ae,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(vn,{checked:c==null?void 0:c.is_enabled,onCheckedChange:M=>v.mutate({is_enabled:M})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Cron Frequency"}),e.jsxs(us,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:M=>v.mutate({cron_frequency:M}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(Ze,{value:"hourly",children:"Hourly (checks every hour)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(c==null?void 0:c.cron_frequency)==="hourly"?"Cron runs every hour; digest sends when day & hour match.":"Cron runs once daily at the selected hour (UTC)."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Day of Week"}),e.jsxs(us,{value:String(c==null?void 0:c.send_day),onValueChange:M=>v.mutate({send_day:parseInt(M)}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:Den.map(M=>e.jsx(Ze,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Time (UTC)"}),e.jsxs(us,{value:String(c==null?void 0:c.send_hour),onValueChange:M=>v.mutate({send_hour:parseInt(M)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:Ren.map(M=>e.jsx(Ze,{value:M.value,children:M.label},M.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{onClick:_,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(B,{onClick:j,disabled:n,className:"flex-1",children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),b>0&&e.jsxs(B,{onClick:S,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(Ai,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${b} Failed`]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(Nr,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Hn,{children:"Choose what to include in the digest"})]}),e.jsxs(Ae,{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(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"New Resources"})]}),e.jsx(vn,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:M=>v.mutate({include_new_resources:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Community Highlights"})]}),e.jsx(vn,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:M=>v.mutate({include_community_posts:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Agent OS Stats"})]}),e.jsx(vn,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:M=>v.mutate({include_agent_os_stats:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Upcoming Events"})]}),e.jsx(vn,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:M=>v.mutate({include_upcoming_events:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Goals Progress"})]}),e.jsx(vn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:M=>v.mutate({include_goals_progress:M})})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Custom Introduction"}),e.jsx(Hn,{children:"Personalize the intro message (optional)"})]}),e.jsx(Ae,{children:e.jsx(Ts,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:M=>v.mutate({custom_intro_text:M.target.value||null}),rows:3})})]})]}),e.jsx(ls,{value:"stats",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Hn,{children:"Recent digest emails sent to members"})]}),e.jsx(Ae,{children:h?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(M=>e.jsx("div",{className:"h-12 bg-muted rounded"},M))}):u&&u.length>0?e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Sent At"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Resources"}),e.jsx(Ct,{children:"Agent OS"})]})}),e.jsx(pa,{children:u.map(M=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:M.email_sent_to}),e.jsx(ut,{children:ks(new Date(M.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(ut,{children:e.jsx(ze,{variant:M.delivery_status==="sent"?"default":"destructive",children:M.delivery_status})}),e.jsx(ut,{children:M.resources_count}),e.jsx(ut,{children:M.has_agent_os_activity?e.jsx(ze,{variant:"secondary",children:"Active"}):e.jsx(ze,{variant:"outline",children:"Not Started"})})]},M.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Hs,{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 Fen={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 zen(){var ye,_e,Me;const s=Gt(),[t,n]=N.useState(""),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(!0),[b,v]=N.useState(!1),[j,_]=N.useState(""),[S,A]=N.useState(null),{data:T,isLoading:D}=lt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:Te,error:Ce}=await q.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(Ce)throw Ce;const Ee=(Te==null?void 0:Te.map(Fe=>Fe.user_id))||[],{data:De}=await q.from("profiles").select("id, name, email").in("id",Ee),Ie=new Map((De==null?void 0:De.map(Fe=>[Fe.id,{name:Fe.name,email:Fe.email}]))||[]);return Te==null?void 0:Te.map(Fe=>({...Fe,profile:Ie.get(Fe.user_id)||null}))}}),{data:L}=lt({queryKey:["all-profiles-for-points",T],queryFn:async()=>{const Ce=[];let Ee=0;for(;;){const{data:De,error:Ie}=await q.from("profiles").select("id, name, email").order("name").range(Ee,Ee+1e3-1);if(Ie)throw Ie;if(Ce.push(...De),!De||De.length<1e3)break;Ee+=1e3}return Ce}}),F=((L==null?void 0:L.filter(Te=>!(T!=null&&T.some(Ce=>Ce.user_id===Te.id))))||[]).filter(Te=>{var Ee,De;if(!j)return!0;const Ce=j.toLowerCase();return((Ee=Te.name)==null?void 0:Ee.toLowerCase().includes(Ce))||((De=Te.email)==null?void 0:De.toLowerCase().includes(Ce))}),{data:z,isLoading:V}=lt({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:Te,error:Ce}=await q.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(Ce)throw Ce;return Te},enabled:!!(r!=null&&r.user_id)&&o}),{data:W}=lt({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:Te,error:Ce}=await q.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(Ce)throw Ce;return Te},enabled:!!(r!=null&&r.user_id)}),K=gt({mutationFn:async({userId:Te,points:Ce,reason:Ee})=>{const{error:De}=await q.from("agent_points").insert({user_id:Te,points:Ce,reason:Ee});if(De)throw De;const{data:Ie}=await q.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",Te).maybeSingle(),Fe=((Ie==null?void 0:Ie.total_points)||0)+Ce,qe=((Ie==null?void 0:Ie.spendable_points)||0)+Ce,{error:ve}=await q.from("agent_attendance_stats").upsert({user_id:Te,total_points:Math.max(0,Fe),spendable_points:Math.max(0,qe),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(ve)throw ve},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),p(""),ae.success(f?"Points awarded successfully!":"Points deducted successfully!")},onError:Te=>{console.error("Error modifying points:",Te),ae.error("Failed to modify points")}}),Y=()=>{if(!r||!d||!h){ae.error("Please fill in all fields");return}const Te=parseInt(d);if(isNaN(Te)||Te<=0){ae.error("Please enter a valid positive number");return}K.mutate({userId:r.user_id,points:f?Te:-Te,reason:h})},ee=()=>{if(!S||!d||!h){ae.error("Please fill in all fields");return}const Te=parseInt(d);if(isNaN(Te)||Te<=0){ae.error("Please enter a valid positive number");return}K.mutate({userId:S.id,points:Te,reason:h},{onSuccess:()=>{v(!1),A(null),_("")}})},ne=(Te,Ce)=>{a(Te),g(Ce),l(!0)},oe=Te=>{a(Te),c(!0)},pe=T==null?void 0:T.filter(Te=>{var Ie,Fe,qe,ve;const Ce=((Fe=(Ie=Te.profile)==null?void 0:Ie.name)==null?void 0:Fe.toLowerCase())||"",Ee=((ve=(qe=Te.profile)==null?void 0:qe.email)==null?void 0:ve.toLowerCase())||"",De=t.toLowerCase();return Ce.includes(De)||Ee.includes(De)}),ce=(T==null?void 0:T.reduce((Te,Ce)=>Te+Ce.total_points,0))||0,de=(T==null?void 0:T.length)||0,ie=de>0?Math.round(ce/de):0;return D?e.jsx(Cs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(Te=>e.jsx(Ws,{className:"h-24"},Te))}),e.jsx(Ws,{className:"h-96"})]})}):e.jsx(Cs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Agent Points Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Track, view, and manage agent gamification points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_n,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:de}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(vo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ce.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(mo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Average Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ie}),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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search agents...",value:t,onChange:Te=>n(Te.target.value),className:"pl-10"})]}),e.jsxs(B,{onClick:()=>v(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Agent Leaderboard"}),e.jsx(Hn,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Ae,{children:!pe||pe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(vo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-12",children:"#"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{className:"text-center",children:"Total Points"}),e.jsx(Ct,{className:"text-center",children:"Spendable"}),e.jsx(Ct,{className:"text-center",children:"Events"}),e.jsx(Ct,{className:"text-center",children:"Streak"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:pe.map((Te,Ce)=>{var Ee,De,Ie,Fe;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:Ce<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${Ce===0?"bg-yellow-100 text-yellow-700":Ce===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:Ce+1}):e.jsx("span",{className:"text-muted-foreground",children:Ce+1})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(aa,{className:"h-8 w-8",children:e.jsx(ia,{children:((De=(Ee=Te.profile)==null?void 0:Ee.name)==null?void 0:De.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Ie=Te.profile)==null?void 0:Ie.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Fe=Te.profile)==null?void 0:Fe.email})]})]})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(ua,{className:"h-3 w-3 mr-1"}),Te.total_points]})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Bi,{className:"h-3 w-3 mr-1"}),Te.spendable_points||0]})}),e.jsx(ut,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"}),Te.total_events_attended]})}),e.jsx(ut,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(_c,{className:"h-3 w-3 text-orange-500"}),Te.current_streak]})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ne(Te,!0),title:"Award points",children:e.jsx(As,{className:"h-4 w-4 text-green-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ne(Te,!1),title:"Deduct points",children:e.jsx(xb,{className:"h-4 w-4 text-red-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>oe(Te),title:"View history",children:e.jsx(IA,{className:"h-4 w-4"})})]})})]},Te.user_id)})})]})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:f?"Award Points":"Deduct Points"}),e.jsxs(Qn,{children:[f?"Award":"Deduct"," points ",f?"to":"from"," ",((ye=r==null?void 0:r.profile)==null?void 0:ye.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"points",children:"Points Amount"}),e.jsx(ge,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Te=>u(Te.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"reason",children:"Reason"}),e.jsx(Ts,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:Te=>p(Te.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:Y,disabled:K.isPending,className:f?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:K.isPending?"Saving...":f?"Award Points":"Deduct Points"})]})]})}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:["Point History: ",(_e=r==null?void 0:r.profile)==null?void 0:_e.name]}),e.jsx(Qn,{children:"View all point transactions and badges for this agent"})]}),e.jsxs($r,{defaultValue:"history",className:"w-full",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"history",children:"Point History"}),e.jsx(Zt,{value:"badges",children:"Badges"})]}),e.jsx(ls,{value:"history",className:"mt-4",children:V?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(Te=>e.jsx(Ws,{className:"h-12"},Te))}):!z||z.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(IA,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No point history yet"})]}):e.jsx("div",{className:"max-h-80 overflow-y-auto space-y-2",children:z.map(Te=>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:Te.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ks(new Date(Te.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(ze,{variant:Te.points>=0?"default":"destructive",className:Te.points>=0?"bg-green-100 text-green-800":"",children:[Te.points>=0?"+":"",Te.points]})]},Te.id))})}),e.jsx(ls,{value:"badges",className:"mt-4",children:!W||W.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(vc,{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:W.map(Te=>e.jsxs("div",{className:`p-3 rounded-lg ${Fen[Te.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vc,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:Te.badge_name})]}),Te.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:Te.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",ks(new Date(Te.earned_at),"MMM d, yyyy")]})]},Te.id))})})]})]})}),e.jsx(bs,{open:b,onOpenChange:Te=>{v(Te),Te||(A(null),_(""),u(""),p(""))},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Award Points to New Agent"}),e.jsx(Qn,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:S?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(aa,{className:"h-10 w-10",children:e.jsx(ia,{children:((Me=S.name)==null?void 0:Me.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:S.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.email})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>A(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(ge,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Te=>u(Te.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Ts,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:Te=>p(Te.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name or email...",value:j,onChange:Te=>_(Te.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:F.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(_n,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:j?"No matching agents found":"All agents already have points"})]}):F.slice(0,20).map(Te=>{var Ce;return e.jsxs("button",{onClick:()=>A(Te),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(aa,{className:"h-8 w-8",children:e.jsx(ia,{children:((Ce=Te.name)==null?void 0:Ce.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Te.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Te.email})]})]},Te.id)})})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),S&&e.jsxs(B,{onClick:ee,disabled:K.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function Ben(){const{data:s,isLoading:t}=Mzt(),[n,r]=N.useState(null),[a,i]=N.useState(!1),[l,o]=N.useState(""),[c,d]=N.useState("all"),[u,h]=N.useState("newest"),[p,f]=N.useState("table"),g=N.useMemo(()=>(s==null?void 0:s.map(S=>S.user_id))||[],[s]),b=N.useMemo(()=>(s==null?void 0:s.map(S=>S.id))||[],[s]),{data:v}=lt({queryKey:["card-profiles-lookup",g],queryFn:async()=>{if(g.length===0)return{};const{data:S}=await q.from("profiles").select("id, name, email").in("id",g),A={};return S==null||S.forEach(T=>{A[T.id]={name:T.name||"",email:T.email||""}}),A},enabled:g.length>0}),{data:j}=lt({queryKey:["card-stats-all",b],queryFn:async()=>{if(b.length===0)return{};const S={};b.forEach(D=>{S[D]={views:0,leads:0}});const{data:A}=await q.from("agent_card_interactions").select("card_id").in("card_id",b).eq("interaction_type","card_view");A==null||A.forEach(D=>{S[D.card_id]&&S[D.card_id].views++});const{data:T}=await q.from("agent_card_leads").select("card_id").in("card_id",b);return T==null||T.forEach(D=>{S[D.card_id]&&S[D.card_id].leads++}),S},enabled:b.length>0}),_=N.useMemo(()=>{if(!s)return[];let S=[...s];if(c==="live"?S=S.filter(A=>A.is_published):c==="draft"&&(S=S.filter(A=>!A.is_published)),l.trim()){const A=l.toLowerCase();S=S.filter(T=>{var L,M;const D=v==null?void 0:v[T.user_id];return T.slug.toLowerCase().includes(A)||((L=D==null?void 0:D.name)==null?void 0:L.toLowerCase().includes(A))||((M=D==null?void 0:D.email)==null?void 0:M.toLowerCase().includes(A))})}return u==="newest"?S.sort((A,T)=>new Date(T.created_at).getTime()-new Date(A.created_at).getTime()):u==="oldest"?S.sort((A,T)=>new Date(A.created_at).getTime()-new Date(T.created_at).getTime()):u==="name"?S.sort((A,T)=>{var D,L;return(((D=v==null?void 0:v[A.user_id])==null?void 0:D.name)||"").localeCompare(((L=v==null?void 0:v[T.user_id])==null?void 0:L.name)||"")}):u==="slug"?S.sort((A,T)=>A.slug.localeCompare(T.slug)):u==="views_desc"?S.sort((A,T)=>{var D,L;return(((D=j==null?void 0:j[T.id])==null?void 0:D.views)||0)-(((L=j==null?void 0:j[A.id])==null?void 0:L.views)||0)}):u==="views_asc"?S.sort((A,T)=>{var D,L;return(((D=j==null?void 0:j[A.id])==null?void 0:D.views)||0)-(((L=j==null?void 0:j[T.id])==null?void 0:L.views)||0)}):u==="leads_desc"?S.sort((A,T)=>{var D,L;return(((D=j==null?void 0:j[T.id])==null?void 0:D.leads)||0)-(((L=j==null?void 0:j[A.id])==null?void 0:L.leads)||0)}):u==="leads_asc"&&S.sort((A,T)=>{var D,L;return(((D=j==null?void 0:j[A.id])==null?void 0:D.leads)||0)-(((L=j==null?void 0:j[T.id])==null?void 0:L.leads)||0)}),S},[s,c,l,u,v]);return e.jsxs(Cs,{title:"Digital Agent Cards",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Digital Agent Cards"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage agent digital business cards"})]}),e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(As,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name, email, or slug...",value:l,onChange:S=>o(S.target.value),className:"pl-9"})]}),e.jsxs(us,{value:c,onValueChange:d,children:[e.jsx(cs,{className:"w-full sm:w-36",children:e.jsx(hs,{placeholder:"Status"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All Status"}),e.jsx(Ze,{value:"live",children:"Live"}),e.jsx(Ze,{value:"draft",children:"Draft"})]})]}),e.jsxs(us,{value:u,onValueChange:h,children:[e.jsx(cs,{className:"w-full sm:w-44",children:e.jsx(hs,{placeholder:"Sort by"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"newest",children:"Newest First"}),e.jsx(Ze,{value:"oldest",children:"Oldest First"}),e.jsx(Ze,{value:"name",children:"Name A–Z"}),e.jsx(Ze,{value:"slug",children:"Slug A–Z"}),e.jsx(Ze,{value:"views_desc",children:"Most Views"}),e.jsx(Ze,{value:"views_asc",children:"Fewest Views"}),e.jsx(Ze,{value:"leads_desc",children:"Most Leads"}),e.jsx(Ze,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(B,{variant:p==="table"?"default":"ghost",size:"sm",onClick:()=>f("table"),className:"rounded-r-none",children:e.jsx(_L,{className:"h-4 w-4"})}),e.jsx(B,{variant:p==="grid"?"default":"ghost",size:"sm",onClick:()=>f("grid"),className:"rounded-l-none",children:e.jsx(vf,{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(S=>e.jsx(Ws,{className:"h-48"},S))}):_.length>0?p==="table"?e.jsx($en,{cards:_,cardProfiles:v,cardStats:j,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:_.map(S=>e.jsx(Uen,{card:S,onEdit:()=>r(S),stats:j==null?void 0:j[S.id]},S.id))}):s&&s.length>0?e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(_r,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No matching cards"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Try adjusting your search or filters"})]})}):e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(_n,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No cards yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first digital agent card"}),e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(qen,{open:a,onOpenChange:i}),n&&e.jsx(Ven,{card:n,open:!!n,onOpenChange:S=>!S&&r(null)})]})}function $en({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(om,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Bu,{className:"h-3 w-3"}):e.jsx(sm,{className:"h-3 w-3 opacity-40"});return e.jsx(fe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"text-left p-3 font-medium",children:e.jsxs("button",{onClick:()=>{i(a==="name"?"newest":"name")},className:"flex items-center gap-1 hover:text-foreground text-muted-foreground",children:["Agent ",a==="name"&&e.jsx(Bu,{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(ze,{variant:c.is_published?"default":"secondary",className:"text-xs",children:c.is_published?"Live":"Draft"})}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.views)??0}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.leads)??0}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>r(c),className:"h-8 w-8 p-0",children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(h),ae.success("Link copied!")},children:e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",asChild:!0,children:e.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function Uen({card:s,onEdit:t,stats:n}){const[r,a]=N.useState(null);N.useEffect(()=>{(async()=>{const{data:c}=await q.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await q.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${u[0].name}`);d=h.publicUrl}}catch{}a({name:(c==null?void 0:c.name)||"Unknown",avatar_url:d})})()},[s.user_id]);const i=`https://cards.relevelup.com/${s.slug}`,l=()=>{navigator.clipboard.writeText(i),ae.success("Link copied!")};return e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:(r==null?void 0:r.avatar_url)||void 0}),e.jsx(ia,{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(ze,{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(Ir,{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(_n,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(ja,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:l,children:e.jsx(ta,{className:"h-3 w-3"})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(tr,{className:"h-3 w-3"})})})]})]})})}function qen({open:s,onOpenChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(!1),u=Nct(),h=l.trim(),{data:p}=lt({queryKey:["profiles-search-for-cards",h],queryFn:async()=>{let _=q.from("profiles").select("id, name, email").order("name").limit(50);h.length>=2&&(_=_.or(`name.ilike.%${h}%,email.ilike.%${h}%`));const{data:S}=await _;return S||[]},enabled:s}),[f,g]=N.useState(null),b=(p==null?void 0:p.find(_=>_.id===n))||f,v=()=>{if(!n||!a.trim()){ae.error("Select an agent and enter a slug");return}u.mutate({user_id:n,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),r(""),i(""),o("")}})},j=_=>{var A;r(_),d(!1);const S=p==null?void 0:p.find(T=>T.id===_);S&&(g(S),i(((A=S.name)==null?void 0:A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create Agent Card"}),e.jsx(Qn,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Agent"}),e.jsxs(Wo,{open:c,onOpenChange:d,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[b?`${b.name} (${b.email})`:"Search for an agent...",e.jsx(Hg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(zo,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Xg,{shouldFilter:!1,children:[e.jsx(Jg,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(e0,{children:[e.jsx(t0,{children:"No agents found."}),e.jsx(s0,{children:(p||[]).map(_=>e.jsxs(ex,{value:_.id,onSelect:j,children:[e.jsx(Lr,{className:Et("mr-2 h-4 w-4",n===_.id?"opacity-100":"opacity-0")}),_.name," (",_.email,")"]},_.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(se,{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(ge,{value:a,onChange:_=>i(_.target.value),placeholder:"john-doe"})]})]}),e.jsx(B,{onClick:v,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function Ven({card:s,open:t,onOpenChange:n}){const r=kct(),{data:a}=Sct(s.id),i=Gt(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState(""),[g,b]=N.useState(s.slug),[v,j]=N.useState(!1),[_,S]=N.useState({is_published:s.is_published,theme:s.theme,title:s.title||"",positioning_statement:s.positioning_statement||"",bio:s.bio||"",review_snippet:s.review_snippet||"",review_source_url:s.review_source_url||"",booking_url:s.booking_url||"",custom_cta_label:s.custom_cta_label||"",custom_cta_url:s.custom_cta_url||"",show_photo:s.show_photo,show_bio:s.show_bio,show_credentials:s.show_credentials,show_social_links:s.show_social_links,show_save_contact:s.show_save_contact,show_leave_review:s.show_leave_review,show_refer_friend:s.show_refer_friend,brokerage_display_name:s.brokerage_display_name||"",brokerage_logo_url:s.brokerage_logo_url||"",brokerage_logo_size:s.brokerage_logo_size||56,team_name:s.team_name||"",team_logo_url:s.team_logo_url||"",team_logo_size:s.team_logo_size||56});N.useEffect(()=>{t&&(async()=>{try{const{data:z}=await q.storage.from("avatars").list(`${s.user_id}`);if(z&&z.length>0){const{data:V}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${z[0].name}`);o(`${V.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const A=F=>{var W;const z=(W=F.target.files)==null?void 0:W[0];if(!z)return;if(!z.type.startsWith("image/")){ae.error("Please select an image file");return}if(z.size>5*1024*1024){ae.error("Image must be under 5MB");return}const V=new FileReader;V.onloadend=()=>{f(V.result),h(!0)},V.readAsDataURL(z),F.target.value=""},T=async F=>{d(!0);try{const{data:z}=await q.storage.from("avatars").list(`${s.user_id}`);z&&z.length>0&&await q.storage.from("avatars").remove(z.map(ee=>`${s.user_id}/${ee.name}`));const V=`${s.user_id}/avatar.jpg`,{error:W}=await q.storage.from("avatars").upload(V,F,{upsert:!0,contentType:"image/jpeg"});if(W)throw W;const{data:K}=q.storage.from("avatars").getPublicUrl(V),Y=`${K.publicUrl}?t=${Date.now()}`;o(Y),await q.from("profiles").update({avatar_url:Y}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),ae.success("Photo updated!")}catch(z){ae.error(z.message||"Upload failed")}finally{d(!1)}},D=async()=>{const F=g.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!F){ae.error("Please enter a valid URL");return}if(F===s.slug){ae.info("No changes to save");return}j(!0);try{const{data:z}=await q.from("agent_cards").select("id").eq("slug",F).neq("id",s.id).maybeSingle();if(z){ae.error("This URL is already taken. Try another one.");return}const{error:V}=await q.from("agent_cards").update({slug:F}).eq("id",s.id);if(V)throw V;b(F),i.invalidateQueries({queryKey:["agent-cards-admin"]}),ae.success("Card address updated!")}catch{ae.error("Failed to update card address")}finally{j(!1)}},L=async(F,z)=>{var W;const V=(W=F.target.files)==null?void 0:W[0];if(V){if(!V.type.startsWith("image/")){ae.error("Please select an image file");return}try{const K=V.name.split(".").pop()||"png",Y=z==="brokerage_logo_url"?"brokerage-logo":"team-logo",ee=`${s.user_id}/${Y}.${K}`,{error:ne}=await q.storage.from("card-logos").upload(ee,V,{upsert:!0});if(ne)throw ne;const{data:oe}=q.storage.from("card-logos").getPublicUrl(ee),pe=oe.publicUrl+"?t="+Date.now();S(z==="brokerage_logo_url"?ce=>({...ce,[z]:pe,brokerage_display_name:""}):ce=>({...ce,[z]:pe,team_name:""})),ae.success("Logo uploaded!")}catch{ae.error("Failed to upload logo")}finally{F.target.value=""}}},M=()=>{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(bs,{open:t,onOpenChange:n,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Agent Card"}),e.jsxs(Qn,{children:["/card/",s.slug]})]}),e.jsxs($r,{defaultValue:"content",children:[e.jsxs(Ur,{className:"w-full",children:[e.jsx(Zt,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Zt,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Zt,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Zt,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(ls,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Published"}),e.jsx(vn,{checked:_.is_published,onCheckedChange:F=>S(z=>({...z,is_published:F}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(aa,{className:"h-16 w-16",children:[e.jsx(ri,{src:l||void 0}),e.jsx(ia,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:A,disabled:c}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{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(ge,{value:g,onChange:F=>b(F.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:D,disabled:v||g===s.slug,className:"shrink-0",children:v?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Theme"}),e.jsxs(us,{value:_.theme,onValueChange:F=>S(z=>({...z,theme:F})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(Ze,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(Ze,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(Ze,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Title / Tagline"}),e.jsx(ge,{value:_.title,onChange:F=>S(z=>({...z,title:F.target.value})),placeholder:"e.g. Luxury Real Estate Specialist"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Shown below the agent's name on the card"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Positioning Statement"}),e.jsx(ge,{value:_.positioning_statement,onChange:F=>S(z=>({...z,positioning_statement:F.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Bio"}),e.jsx(Ts,{value:_.bio,onChange:F=>S(z=>({...z,bio:F.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review Snippet"}),e.jsx(ge,{value:_.review_snippet,onChange:F=>S(z=>({...z,review_snippet:F.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review Source URL"}),e.jsx(ge,{value:_.review_source_url,onChange:F=>S(z=>({...z,review_source_url:F.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(ge,{value:_.booking_url,onChange:F=>S(z=>({...z,booking_url:F.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Custom CTA Label (optional)"}),e.jsx(ge,{value:_.custom_cta_label,onChange:F=>S(z=>({...z,custom_cta_label:F.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Custom CTA URL (optional)"}),e.jsx(ge,{value:_.custom_cta_url,onChange:F=>S(z=>({...z,custom_cta_url:F.target.value})),placeholder:"https://example.com/landing"})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{value:_.brokerage_display_name,onChange:F=>S(z=>({...z,brokerage_display_name:F.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!_.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:()=>S(F=>({...F,brokerage_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Sa,{className:"h-3.5 w-3.5"}),_.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:F=>L(F,"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(se,{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($m,{value:[_.brokerage_logo_size||56],onValueChange:([F])=>S(z=>({...z,brokerage_logo_size:F})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{value:_.team_name,onChange:F=>S(z=>({...z,team_name:F.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:()=>S(F=>({...F,team_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Sa,{className:"h-3.5 w-3.5"}),_.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:F=>L(F,"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(se,{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($m,{value:[_.team_logo_size||56],onValueChange:([F])=>S(z=>({...z,team_logo_size:F})),min:24,max:120,step:4})]})]})]})]}),e.jsx(ls,{value:"sections",className:"space-y-4 mt-4",children:[{key:"show_photo",label:"Show Photo",hint:"Photo is pulled from the agent's profile."},{key:"show_bio",label:"Show Bio"},{key:"show_credentials",label:"Show Credentials"},{key:"show_social_links",label:"Show Social Links"},{key:"show_save_contact",label:"Save Contact Button"},{key:"show_leave_review",label:"Leave Review Button"},{key:"show_refer_friend",label:"Refer a Friend Button"}].map(({key:F,label:z,hint:V})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(se,{children:z}),V&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[V," ",F==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(vn,{checked:_[F],onCheckedChange:W=>S(K=>({...K,[F]:W}))})]},F))}),e.jsx(ls,{value:"blocks",className:"mt-4",children:e.jsx(U2t,{cardId:s.id})}),e.jsx(ls,{value:"analytics",className:"mt-4",children:a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.views}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Views"})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.clicks}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clicks"})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.leads.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Leads"})]})})]}),a.leads.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Recent Leads"}),e.jsx("div",{className:"space-y-2",children:a.leads.slice(0,5).map(F=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:F.name}),F.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",F.phone]}),F.intent&&e.jsx(ze,{variant:"secondary",className:"ml-2 text-xs",children:F.intent})]},F.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx(B,{onClick:M,disabled:r.isPending,className:"w-full mt-4",children:r.isPending?"Saving...":"Save Changes"})]})}),e.jsx(xIe,{open:u,onClose:()=>h(!1),imageSrc:p,onCropComplete:T,aspectRatio:1})]})}const KL={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"},A8e={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 M8e(s=!0){return lt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=q.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:n,error:r}=await t;if(r)throw r;return n}})}function Hen(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category created successfully")},onError:t=>{ae.error("Failed to create category: "+t.message)}})}function Gen(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("marketplace_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category updated successfully")},onError:t=>{ae.error("Failed to update category: "+t.message)}})}function Wen(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("marketplace_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category deleted successfully")},onError:t=>{ae.error("Failed to delete category: "+t.message)}})}function rNt(s,t=!0){return lt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let n=q.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});s&&(n=n.eq("category_id",s)),t&&(n=n.eq("is_active",!0));const{data:r,error:a}=await n;if(a)throw a;return r}})}function Ken(s){return lt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function Yen(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_products").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ae.success("Product created successfully")},onError:t=>{ae.error("Failed to create product: "+t.message)}})}function Zen(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("marketplace_products").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.id]}),ae.success("Product updated successfully")},onError:t=>{ae.error("Failed to update product: "+t.message)}})}function Qen(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("marketplace_products").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ae.success("Product deleted successfully")},onError:t=>{ae.error("Failed to delete product: "+t.message)}})}function Xen(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_product_images").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]})}})}function Jen(){const s=Gt();return gt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_images").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Image deleted successfully")},onError:t=>{ae.error("Failed to delete image: "+t.message)}})}function etn(){const s=Gt();return gt({mutationFn:async({imageId:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",n);if(r)throw r;const{error:a}=await q.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Primary image updated")},onError:t=>{ae.error("Failed to set primary image: "+t.message)}})}function ttn(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_product_variants").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]}),ae.success("Variant added successfully")}})}function stn(){const s=Gt();return gt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_variants").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Variant deleted successfully")}})}function ntn(){const s=Gt();return gt({mutationFn:async({productId:t,videoUrl:n})=>{await q.from("marketplace_product_videos").delete().eq("product_id",t);const{data:r,error:a}=await q.from("marketplace_product_videos").insert({product_id:t,video_url:n}).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.productId]}),ae.success("Video updated successfully")}})}function rtn(s){const{isAdmin:t}=gs();return lt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let n=q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:r,error:a}=await n;if(a)throw a;if(t&&r){const i=[...new Set(r.map(c=>c.user_id))],{data:l}=await q.from("profiles").select("id, name, email").in("id",i),o=new Map((l==null?void 0:l.map(c=>[c.id,c]))||[]);return r.map(c=>({...c,user:o.get(c.user_id)}))}return r}})}function atn(){const{user:s}=gs();return lt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function itn(s){return lt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function otn(){const s=Gt(),{user:t}=gs();return gt({mutationFn:async({orderId:n,status:r,notes:a,trackingNumber:i,trackingUrl:l,previousStatus:o})=>{const c={status:r};i!==void 0&&(c.tracking_number=i),l!==void 0&&(c.tracking_url=l);const{error:d}=await q.from("marketplace_orders").update(c).eq("id",n);if(d)throw d;const{error:u}=await q.from("marketplace_order_status_history").insert({order_id:n,status:r,notes:a,created_by:t==null?void 0:t.id});if(u)throw u;if(["shipped","in_production","processing","completed"].includes(r)&&r!==o)try{await q.functions.invoke("marketplace-order-notify",{body:{orderId:n,notificationType:r==="shipped"?"shipped":"status_update",newStatus:r,trackingNumber:i,trackingUrl:l}})}catch(p){console.error("Failed to send notification email:",p)}},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",r.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Order status updated")},onError:n=>{ae.error("Failed to update order: "+n.message)}})}function ltn(){const s=Gt();return gt({mutationFn:async({itemId:t,proofUrl:n,proofNotes:r,orderId:a})=>{const{error:i}=await q.from("marketplace_order_items").update({proof_url:n,proof_notes:r,proof_status:"pending"}).eq("id",t);if(i)throw i;await q.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await q.functions.invoke("marketplace-order-notify",{body:{orderId:a,notificationType:"proof_ready"}})}catch(l){console.error("Failed to send proof notification:",l)}return a},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof uploaded & customer notified")}})}function ctn(){const s=Gt();return gt({mutationFn:async({itemId:t,orderId:n})=>{const{error:r}=await q.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof approved")}})}function dtn(){const s=Gt();return gt({mutationFn:async({itemId:t,orderId:n,reason:r})=>{const{error:a}=await q.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof rejected - please upload a new proof")}})}function utn(){const{data:s,isLoading:t}=M8e(!1),n=Hen(),r=Gen(),a=Wen(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),h=()=>{u({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},p=b=>{c(b),u({name:b.name,description:b.description||"",image_url:b.image_url||"",sort_order:b.sort_order,is_active:b.is_active}),l(!0)},f=async b=>{b.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},g=async b=>{confirm("Are you sure you want to delete this category?")&&await a.mutateAsync(b)};return t?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Ws,{className:"h-8 w-48"})}),e.jsx(Ae,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(b=>e.jsx(Ws,{className:"h-12 w-full"},b))})})]}):e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Pt,{children:"Categories"}),e.jsxs(bs,{open:i,onOpenChange:b=>{l(b),b||h()},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:f,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ge,{id:"name",value:d.name,onChange:b=>u({...d,name:b.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{id:"description",value:d.description,onChange:b=>u({...d,description:b.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"image_url",children:"Image URL"}),e.jsx(ge,{id:"image_url",value:d.image_url,onChange:b=>u({...d,image_url:b.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(ge,{id:"sort_order",type:"number",value:d.sort_order,onChange:b=>u({...d,sort_order:parseInt(b.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{id:"is_active",checked:d.is_active,onCheckedChange:b=>u({...d,is_active:b})}),e.jsx(se,{htmlFor:"is_active",children:"Active"})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:n.isPending||r.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(Ae,{children:s&&s.length>0?e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{children:"Sort Order"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:s.map(b=>e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium",children:b.name}),e.jsx(ut,{className:"max-w-xs truncate",children:b.description}),e.jsx(ut,{children:b.sort_order}),e.jsx(ut,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${b.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:b.is_active?"Active":"Inactive"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(b),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(b.id),disabled:a.isPending,children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function htn(){var ie,ye;const{data:s,isLoading:t}=rNt(void 0,!1),{data:n}=M8e(!1),r=Yen(),a=Zen(),i=Qen(),l=Xen(),o=Jen(),c=etn(),d=ttn(),u=stn(),h=ntn(),[p,f]=N.useState(!1),[g,b]=N.useState(!1),[v,j]=N.useState(!1),[_,S]=N.useState(null),[A,T]=N.useState(null),[D,L]=N.useState(!1),[M,F]=N.useState({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),[z,V]=N.useState({name:"",price_adjustment:0}),[W,K]=N.useState(""),Y=()=>{F({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),S(null)},ee=_e=>{S(_e),F({name:_e.name,description:_e.description||"",base_price:Number(_e.base_price),shipping_fee:Number(_e.shipping_fee),category_id:_e.category_id||"",allow_artwork_upload:_e.allow_artwork_upload,requires_proof_approval:_e.requires_proof_approval,is_active:_e.is_active,sort_order:_e.sort_order}),f(!0)},ne=async _e=>{_e.preventDefault();const Me={...M,category_id:M.category_id||null};_?await a.mutateAsync({id:_.id,...Me}):await r.mutateAsync(Me),f(!1),Y()},oe=async _e=>{confirm("Are you sure you want to delete this product?")&&await i.mutateAsync(_e)},pe=async _e=>{if(!A||!_e.target.files||_e.target.files.length===0)return;L(!0);const Me=_e.target.files[0],Te=Me.name.split(".").pop(),Ce=`products/${A.id}/${Date.now()}.${Te}`;try{const{error:Ee}=await q.storage.from("marketplace").upload(Ce,Me);if(Ee)throw Ee;const{data:{publicUrl:De}}=q.storage.from("marketplace").getPublicUrl(Ce);await l.mutateAsync({product_id:A.id,image_url:De,is_primary:!A.images||A.images.length===0}),ae.success("Image uploaded successfully")}catch(Ee){ae.error("Failed to upload image: "+Ee.message)}finally{L(!1)}},ce=async _e=>{_e.preventDefault(),A&&(await d.mutateAsync({product_id:A.id,name:z.name,price_adjustment:z.price_adjustment}),V({name:"",price_adjustment:0}))},de=async()=>{!A||!W||(await h.mutateAsync({productId:A.id,videoUrl:W}),K(""))};return t?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Ws,{className:"h-8 w-48"})}),e.jsx(Ae,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(_e=>e.jsx(Ws,{className:"h-64 w-full"},_e))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Pt,{children:"Products"}),e.jsxs(bs,{open:p,onOpenChange:_e=>{f(_e),_e||Y()},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:_?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:ne,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Product Name"}),e.jsx(ge,{id:"name",value:M.name,onChange:_e=>F({...M,name:_e.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"category",children:"Category"}),e.jsxs(us,{value:M.category_id,onValueChange:_e=>F({...M,category_id:_e}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select category"})}),e.jsx(ds,{children:n==null?void 0:n.map(_e=>e.jsx(Ze,{value:_e.id,children:_e.name},_e.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ts,{id:"description",value:M.description,onChange:_e=>F({...M,description:_e.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(se,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(ge,{id:"base_price",type:"number",step:"0.01",min:"0",value:M.base_price,onChange:_e=>F({...M,base_price:parseFloat(_e.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(ge,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:M.shipping_fee,onChange:_e=>F({...M,shipping_fee:parseFloat(_e.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(ge,{id:"sort_order",type:"number",value:M.sort_order,onChange:_e=>F({...M,sort_order:parseInt(_e.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{id:"allow_artwork_upload",checked:M.allow_artwork_upload,onCheckedChange:_e=>F({...M,allow_artwork_upload:_e})}),e.jsx(se,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{id:"requires_proof_approval",checked:M.requires_proof_approval,onCheckedChange:_e=>F({...M,requires_proof_approval:_e})}),e.jsx(se,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{id:"is_active",checked:M.is_active,onCheckedChange:_e=>F({...M,is_active:_e})}),e.jsx(se,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:r.isPending||a.isPending,children:_?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Ae,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(_e=>{var Me,Te;return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[_e.images&&_e.images.length>0?e.jsx("img",{src:((Me=_e.images.find(Ce=>Ce.is_primary))==null?void 0:Me.image_url)||_e.images[0].image_url,alt:_e.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"}),!_e.is_active&&e.jsx(ze,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Ae,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:_e.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((Te=_e.category)==null?void 0:Te.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(_e.base_price).toFixed(2)]}),Number(_e.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(_e.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[_e.allow_artwork_upload&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),_e.requires_proof_approval&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Proof Required"}),_e.variants&&_e.variants.length>0&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:[_e.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>ee(_e),children:[e.jsx(ja,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{T(_e),b(!0)},children:[e.jsx(ay,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{T(_e),j(!0)},children:[e.jsx(mh,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>oe(_e.id),children:e.jsx(bn,{className:"h-3 w-3 text-destructive"})})]})]})]},_e.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(bs,{open:g,onOpenChange:b,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Manage Images - ",A==null?void 0:A.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(ie=A==null?void 0:A.images)==null?void 0:ie.map(_e=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:_e.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),_e.is_primary&&e.jsx(ze,{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:[!_e.is_primary&&e.jsx(B,{variant:"secondary",size:"icon",onClick:async()=>{var Me;await c.mutateAsync({imageId:_e.id,productId:A.id}),T({...A,images:(Me=A.images)==null?void 0:Me.map(Te=>({...Te,is_primary:Te.id===_e.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(ua,{className:"h-4 w-4"})}),e.jsx(B,{variant:"destructive",size:"icon",onClick:async()=>{var Te;await o.mutateAsync({id:_e.id,productId:A.id});const Me=s==null?void 0:s.find(Ce=>Ce.id===A.id);Me&&T({...Me,images:(Te=Me.images)==null?void 0:Te.filter(Ce=>Ce.id!==_e.id)})},disabled:o.isPending,children:e.jsx(bn,{className:"h-4 w-4"})})]})]},_e.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:pe,className:"hidden",id:"image-upload",disabled:D}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(ay,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(se,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(ge,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:W,onChange:_e=>K(_e.target.value)}),e.jsxs(B,{onClick:de,disabled:!W,children:[e.jsx(vr,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(A==null?void 0:A.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",A.video.video_url]})]})]})]})}),e.jsx(bs,{open:v,onOpenChange:j,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Manage Variants - ",A==null?void 0:A.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:ce,className:"flex gap-2",children:[e.jsx(ge,{placeholder:"Variant name (e.g., 500 count)",value:z.name,onChange:_e=>V({...z,name:_e.target.value}),required:!0}),e.jsx(ge,{type:"number",step:"0.01",placeholder:"Price adj.",value:z.price_adjustment,onChange:_e=>V({...z,price_adjustment:parseFloat(_e.target.value)||0}),className:"w-32"}),e.jsx(B,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(ye=A==null?void 0:A.variants)==null?void 0:ye.map(_e=>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:_e.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(_e.price_adjustment)>=0?"+":"","$",Number(_e.price_adjustment).toFixed(2)]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:_e.id,productId:A.id}),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]},_e.id)),(!(A!=null&&A.variants)||A.variants.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:'No variants yet. Add variants like "250 count", "500 count", etc.'})]})]})]})})]})}const mtn=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function ptn(){var b,v,j;const{data:s,isLoading:t}=rtn(),n=otn(),r=ltn(),[a,i]=N.useState(null),[l,o]=N.useState(!1),[c,d]=N.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,h]=N.useState(!1),p=_=>{i(_),d({status:_.status,notes:"",trackingNumber:_.tracking_number||"",trackingUrl:_.tracking_url||""}),o(!0)},f=async()=>{a&&(await n.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},g=async(_,S)=>{if(!a||!_.target.files||_.target.files.length===0)return;h(!0);const A=_.target.files[0],T=A.name.split(".").pop(),D=`proofs/${a.id}/${S}/${Date.now()}.${T}`;try{const{error:L}=await q.storage.from("marketplace").upload(D,A);if(L)throw L;const{data:{publicUrl:M}}=q.storage.from("marketplace").getPublicUrl(D);await r.mutateAsync({itemId:S,proofUrl:M,orderId:a.id}),ae.success("Proof uploaded successfully")}catch(L){ae.error("Failed to upload proof: "+L.message)}finally{h(!1)}};return t?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Ws,{className:"h-8 w-48"})}),e.jsx(Ae,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(_=>e.jsx(Ws,{className:"h-16 w-full"},_))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Orders"})}),e.jsx(Ae,{children:s&&s.length>0?e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Order #"}),e.jsx(Ct,{children:"Customer"}),e.jsx(Ct,{children:"Date"}),e.jsx(Ct,{children:"Total"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:s.map(_=>{var S,A;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-mono",children:_.order_number}),e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((S=_.user)==null?void 0:S.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(A=_.user)==null?void 0:A.email})]})}),e.jsx(ut,{children:ks(new Date(_.created_at),"MMM d, yyyy")}),e.jsxs(ut,{className:"font-bold",children:["$",Number(_.total).toFixed(2)]}),e.jsx(ut,{children:e.jsx(ze,{className:A8e[_.status],children:KL[_.status]})}),e.jsx(ut,{className:"text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>p(_),children:[e.jsx(Ir,{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(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{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:(b=a.user)==null?void 0:b.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(v=a.user)==null?void 0:v.email})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Shipping Address"}),e.jsx("p",{children:a.shipping_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.shipping_address,e.jsx("br",{}),a.shipping_city,", ",a.shipping_state," ",a.shipping_zip]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Order Items"}),e.jsx("div",{className:"space-y-3",children:(j=a.items)==null?void 0:j.map(_=>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(ze,{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:S=>g(S,_.id),className:"hidden",id:`proof-${_.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${_.id}`,children:e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Sa,{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(se,{children:"Status"}),e.jsxs(us,{value:c.status,onValueChange:_=>d({...c,status:_}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:mtn.map(_=>e.jsx(Ze,{value:_,children:KL[_]},_))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Tracking Number"}),e.jsx(ge,{value:c.trackingNumber,onChange:_=>d({...c,trackingNumber:_.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Tracking URL"}),e.jsx(ge,{value:c.trackingUrl,onChange:_=>d({...c,trackingUrl:_.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes (optional)"}),e.jsx(Ts,{value:c.notes,onChange:_=>d({...c,notes:_.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(B,{onClick:f,disabled:n.isPending,className:"w-full",children:[e.jsx(Oc,{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(ze,{variant:"outline",children:KL[_.status]}),_.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:_.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:ks(new Date(_.created_at),"MMM d, h:mm a")})]},_.id))})]})]})]})})]})}function ftn(){const[s,t]=N.useState("products"),n=In();return e.jsx(Cs,{title:"Marketplace Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Marketplace Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage products, categories, and orders"})]}),e.jsxs(B,{variant:"outline",onClick:()=>n("/marketplace"),children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs($r,{value:s,onValueChange:t,children:[e.jsxs(Ur,{className:"grid w-full grid-cols-3",children:[e.jsxs(Zt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(Oc,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Zt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(yf,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Zt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(zg,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(ls,{value:"products",children:e.jsx(htn,{})}),e.jsx(ls,{value:"categories",children:e.jsx(utn,{})}),e.jsx(ls,{value:"orders",children:e.jsx(ptn,{})})]})]})})}function aNt(){return lt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await q.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function xtn(s){return lt({queryKey:["reward-items",s],queryFn:async()=>{let t=q.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:n,error:r}=await t;if(r)throw r;return n}})}function gtn(s){return lt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=q.from("reward_store_items").select(` *, category:reward_store_categories(*) `).eq("is_active",!0).order("created_at",{ascending:!1});s&&(t=t.eq("category_id",s));const{data:n,error:r}=await t;if(r)throw r;return n}})}function ytn(s){return lt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).eq("user_id",s).order("purchased_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function vtn(){return lt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await q.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).order("purchased_at",{ascending:!1});if(t)throw t;if(!s||s.length===0)return[];const n=[...new Set(s.map(l=>l.user_id))],{data:r,error:a}=await q.from("profiles").select("id, name, email").in("id",n);if(a)throw a;const i=new Map((r==null?void 0:r.map(l=>[l.id,l]))||[]);return s.map(l=>({...l,user:i.get(l.user_id)||null}))}})}function btn(s){return lt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:n}=await q.from("agent_attendance_stats").select("spendable_points").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return(t==null?void 0:t.spendable_points)||0},enabled:!!s})}function _tn(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("purchase_reward_item",{p_item_id:t});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error||"Purchase failed");return a},onSuccess:()=>{s.invalidateQueries({queryKey:["user-purchases"]}),s.invalidateQueries({queryKey:["spendable-points"]}),s.invalidateQueries({queryKey:["active-reward-items"]}),s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["homereel-credits"]})}})}function wtn(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("reward_store_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function jtn(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("reward_store_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function Ntn(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("reward_store_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function ktn(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("reward_store_items").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function Stn(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("reward_store_items").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function Ctn(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("reward_store_items").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function Ttn(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function ZNe(s,t){const n=Ttn(s);if(n)try{const{data:r,error:a}=await q.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),ae.error("Failed to download file");return}const i=URL.createObjectURL(r),l=document.createElement("a");l.href=i,l.download=t||n.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("Download error:",r),ae.error("Failed to download file")}else try{const a=await(await fetch(s)).blob(),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=t||s.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("External download error:",r),ae.error("Failed to download file")}}function iNt(){return lt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await q.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function Etn(){const s=Gt();return gt({mutationFn:async({id:t,points:n,is_active:r})=>{const a={points:n};r!==void 0&&(a.is_active=r);const{data:i,error:l}=await q.from("point_reward_settings").update(a).eq("id",t).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["point-reward-settings"]})}})}function Atn(){const{user:s}=gs(),[t,n]=N.useState("items"),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(null),[b,v]=N.useState(!1),[j,_]=N.useState(null),[S,A]=N.useState(""),[T,D]=N.useState(""),[L,M]=N.useState(null),[F,z]=N.useState(""),[V,W]=N.useState("file"),[K,Y]=N.useState(""),[ee,ne]=N.useState(""),[oe,pe]=N.useState(""),[ce,de]=N.useState(!0),[ie,ye]=N.useState(null),[_e,Me]=N.useState(!1),[Te,Ce]=N.useState(!1),Ee=N.useRef(null),De=N.useRef(null),{data:Ie,isLoading:Fe}=aNt(),{data:qe,isLoading:ve}=xtn(),{data:Je,isLoading:we}=vtn(),{data:it,isLoading:Ne}=iNt(),He=wtn(),$e=jtn(),Ye=Ntn(),Ke=ktn(),rt=Stn(),tt=Ctn(),at=Etn(),[Ge,dt]=N.useState({}),Bt=ht=>{ht?(l(ht),c(ht.name),u(ht.description||""),p(ht.icon||"")):(l(null),c(""),u(""),p("")),a(!0)},kt=async()=>{if(!o.trim()){ae.error("Please enter a category name");return}try{i?(await $e.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),ae.success("Category updated successfully")):(await He.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Ie==null?void 0:Ie.length)||0)+1}),ae.success("Category created successfully")),a(!1)}catch(ht){console.error("Error saving category:",ht),ae.error("Failed to save category")}},Qt=async()=>{if(f)try{await Ye.mutateAsync(f),ae.success("Category deleted successfully"),g(null)}catch(ht){console.error("Error deleting category:",ht),ae.error("Failed to delete category")}},ns=ht=>{var Ut;ht?(_(ht),A(ht.name),D(ht.description||""),M(ht.category_id),z(ht.points_cost.toString()),W(ht.item_type),Y(ht.file_url||""),ne(ht.preview_image_url||""),pe(((Ut=ht.max_quantity)==null?void 0:Ut.toString())||""),de(ht.is_active)):(_(null),A(""),D(""),M(null),z(""),W("file"),Y(""),ne(""),pe(""),de(!0)),v(!0)},$s=async(ht,Ut)=>{Ut==="file"?Me(!0):Ce(!0);try{const Es=ht.name.split(".").pop(),Xt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Es}`,Ys=`${Ut==="file"?"items":"previews"}/${Xt}`,{error:Ss}=await q.storage.from("reward-store").upload(Ys,ht);if(Ss)throw Ss;const{data:{publicUrl:Bs}}=q.storage.from("reward-store").getPublicUrl(Ys);Ut==="file"?Y(Bs):ne(Bs),ae.success("File uploaded successfully")}catch(Es){console.error("Error uploading file:",Es),ae.error("Failed to upload file")}finally{Ut==="file"?Me(!1):Ce(!1)}},Ds=async()=>{if(!S.trim()){ae.error("Please enter an item name");return}if(!F||parseInt(F)<0){ae.error("Please enter a valid points cost");return}try{const ht={name:S,description:T||null,category_id:L,points_cost:parseInt(F),item_type:V,file_url:K||null,preview_image_url:ee||null,max_quantity:oe?parseInt(oe):null,current_quantity:oe?parseInt(oe):null,is_active:ce,created_by:s==null?void 0:s.id};j?(await rt.mutateAsync({id:j.id,...ht,current_quantity:j.max_quantity!==(oe?parseInt(oe):null)?oe?parseInt(oe):null:j.current_quantity}),ae.success("Item updated successfully")):(await Ke.mutateAsync(ht),ae.success("Item created successfully")),v(!1)}catch(ht){console.error("Error saving item:",ht),ae.error("Failed to save item")}},Dt=async()=>{if(ie)try{await tt.mutateAsync(ie),ae.success("Item deleted successfully"),ye(null)}catch(ht){console.error("Error deleting item:",ht),ae.error("Failed to delete item")}},St=async(ht,Ut)=>{const Es=Ge[ht];if(Es===void 0||Es===Ut.toString())return;const Xt=parseInt(Es);if(isNaN(Xt)||Xt<0){ae.error("Please enter a valid positive number");return}try{await at.mutateAsync({id:ht,points:Xt}),ae.success("Points updated successfully"),dt(Ys=>{const Ss={...Ys};return delete Ss[ht],Ss})}catch(Ys){console.error("Error updating points:",Ys),ae.error("Failed to update points")}};return Fe||ve||we||Ne?e.jsx(Cs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx(Ws,{className:"h-96"})]})}):e.jsxs(Cs,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Reward Store Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage store items that agents can purchase with their points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Oc,{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:(qe==null?void 0:qe.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(qe==null?void 0:qe.filter(ht=>ht.is_active).length)||0," active"]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(yf,{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(fe,{children:e.jsxs(Ae,{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:"Avg. Cost"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[qe&&qe.length>0?Math.round(qe.reduce((ht,Ut)=>ht+Ut.points_cost,0)/qe.length):0," pts"]})]})})]}),e.jsxs($r,{value:t,onValueChange:n,children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"items",children:"Items"}),e.jsx(Zt,{value:"categories",children:"Categories"}),e.jsx(Zt,{value:"purchases",children:"Purchases"}),e.jsx(Zt,{value:"point-settings",children:"Point Settings"})]}),e.jsx(ls,{value:"items",className:"mt-4",children:e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Store Items"}),e.jsx(Hn,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(B,{onClick:()=>ns(),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Ae,{children:!qe||qe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Bi,{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(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Item"}),e.jsx(Ct,{children:"Category"}),e.jsx(Ct,{className:"text-center",children:"Cost"}),e.jsx(Ct,{className:"text-center",children:"Type"}),e.jsx(Ct,{className:"text-center",children:"Quantity"}),e.jsx(Ct,{className:"text-center",children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:qe.map(ht=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ht.preview_image_url?e.jsx("img",{src:ht.preview_image_url,alt:ht.name,className:"h-10 w-10 rounded object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Bi,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ht.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:ht.description||"No description"})]})]})}),e.jsx(ut,{children:ht.category?e.jsx(ze,{variant:"outline",children:ht.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(ua,{className:"h-3 w-3 mr-1"}),ht.points_cost]})}),e.jsx(ut,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[ht.item_type==="file"?e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:ht.item_type})]})}),e.jsx(ut,{className:"text-center",children:ht.max_quantity!==null?e.jsxs("span",{className:ht.current_quantity===0?"text-red-500":"",children:[ht.current_quantity,"/",ht.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(ut,{className:"text-center",children:e.jsx(ze,{variant:ht.is_active?"default":"secondary",children:ht.is_active?"Active":"Inactive"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ns(ht),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ye(ht.id),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},ht.id))})]})})]})}),e.jsx(ls,{value:"categories",className:"mt-4",children:e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Categories"}),e.jsx(Hn,{children:"Organize your store items into categories"})]}),e.jsxs(B,{onClick:()=>Bt(),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Ae,{children:!Ie||Ie.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(yf,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{className:"text-center",children:"Items"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(pa,{children:Ie.map(ht=>e.jsxs(Gs,{children:[e.jsxs(ut,{className:"font-medium",children:[ht.icon&&e.jsx("span",{className:"mr-2",children:ht.icon}),ht.name]}),e.jsx(ut,{className:"text-muted-foreground",children:ht.description||"—"}),e.jsx(ut,{className:"text-center",children:(qe==null?void 0:qe.filter(Ut=>Ut.category_id===ht.id).length)||0}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Bt(ht),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>g(ht.id),children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})})]})})]},ht.id))})]})})]})}),e.jsx(ls,{value:"purchases",className:"mt-4",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(zg,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Hn,{children:"View all reward redemptions by agents"})]}),e.jsx(Ae,{children:!Je||Je.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(zg,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Date"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Item"}),e.jsx(Ct,{className:"text-center",children:"Points Spent"})]})}),e.jsx(pa,{children:Je.map(ht=>{var Ut,Es,Xt,Ys;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"text-muted-foreground",children:ks(new Date(ht.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(ut,{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(Xi,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Ut=ht.user)==null?void 0:Ut.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((Es=ht.user)==null?void 0:Es.email)||"—"})]})]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(Xt=ht.item)!=null&&Xt.preview_image_url?e.jsx("img",{src:ht.item.preview_image_url,alt:ht.item.name,className:"h-8 w-8 rounded object-cover"}):e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center",children:e.jsx(Bi,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((Ys=ht.item)==null?void 0:Ys.name)||"Deleted item"})]})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(ua,{className:"h-3 w-3 mr-1"}),ht.points_spent]})})]},ht.id)})})]})})]})})]})]}),e.jsx(bs,{open:r,onOpenChange:a,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:i?"Edit Category":"Add Category"}),e.jsx(Qn,{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(se,{htmlFor:"categoryName",children:"Name"}),e.jsx(ge,{id:"categoryName",value:o,onChange:ht=>c(ht.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Ts,{id:"categoryDescription",value:d,onChange:ht=>u(ht.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(ge,{id:"categoryIcon",value:h,onChange:ht=>p(ht.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{onClick:kt,disabled:He.isPending||$e.isPending,children:He.isPending||$e.isPending?"Saving...":"Save"})]})]})}),e.jsx(bs,{open:b,onOpenChange:v,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:j?"Edit Item":"Add Item"}),e.jsx(Qn,{children:j?"Update the item details":"Create a new reward item for agents to purchase"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemName",children:"Name *"}),e.jsx(ge,{id:"itemName",value:S,onChange:ht=>A(ht.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemDescription",children:"Description"}),e.jsx(Ts,{id:"itemDescription",value:T,onChange:ht=>D(ht.target.value),placeholder:"Describe the item..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(us,{value:L||"none",onValueChange:ht=>M(ht==="none"?null:ht),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select category"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No category"}),Ie==null?void 0:Ie.map(ht=>e.jsxs(Ze,{value:ht.id,children:[ht.icon&&`${ht.icon} `,ht.name]},ht.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(ge,{id:"itemPointsCost",type:"number",min:"0",value:F,onChange:ht=>z(ht.target.value),placeholder:"e.g., 100"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemType",children:"Type"}),e.jsxs(us,{value:V,onValueChange:W,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"file",children:"File Download"}),e.jsx(Ze,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(ge,{id:"itemMaxQuantity",type:"number",min:"1",value:oe,onChange:ht=>pe(ht.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:K,onChange:ht=>Y(ht.target.value),placeholder:V==="file"?"Upload a file or paste URL":"Paste external link"}),V==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var ht;return(ht=Ee.current)==null?void 0:ht.click()},disabled:_e,children:e.jsx(Sa,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ee,type:"file",className:"hidden",onChange:ht=>{var Es;const Ut=(Es=ht.target.files)==null?void 0:Es[0];Ut&&$s(Ut,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:ee,onChange:ht=>ne(ht.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var ht;return(ht=De.current)==null?void 0:ht.click()},disabled:Te,children:e.jsx(nl,{className:"h-4 w-4"})}),e.jsx("input",{ref:De,type:"file",accept:"image/*",className:"hidden",onChange:ht=>{var Es;const Ut=(Es=ht.target.files)==null?void 0:Es[0];Ut&&$s(Ut,"preview")}})]}),ee&&e.jsx("img",{src:ee,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{id:"itemIsActive",checked:ce,onCheckedChange:de}),e.jsx(se,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(B,{onClick:Ds,disabled:Ke.isPending||rt.isPending,children:Ke.isPending||rt.isPending?"Saving...":"Save"})]})]})}),e.jsx(Oo,{open:!!f,onOpenChange:()=>g(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Category"}),e.jsx(Mo,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:Qt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Oo,{open:!!ie,onOpenChange:()=>ye(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Item"}),e.jsx(Mo,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:Dt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(fe,{className:"mt-4",children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vo,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(Pt,{children:"Point Reward Settings"}),e.jsx(Hn,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Ae,{children:!it||it.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Vo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Action"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{className:"text-center w-32",children:"Points"}),e.jsx(Ct,{className:"text-right w-24",children:"Save"})]})}),e.jsx(pa,{children:it.map(ht=>e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsx("p",{className:"font-medium",children:ht.action_name})}),e.jsx(ut,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:ht.description})}),e.jsx(ut,{className:"text-center",children:e.jsx(ge,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:Ge[ht.id]??ht.points.toString(),onChange:Ut=>dt(Es=>({...Es,[ht.id]:Ut.target.value}))})}),e.jsx(ut,{className:"text-right",children:e.jsx(B,{size:"sm",variant:"outline",disabled:Ge[ht.id]===void 0||Ge[ht.id]===ht.points.toString()||at.isPending,onClick:()=>St(ht.id,ht.points),children:e.jsx(Ho,{className:"h-4 w-4"})})})]},ht.id))})]})})]})]})}const AXe=()=>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"})]}),MXe=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function Mtn(){const s=Gt(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:u}=lt({queryKey:["canva-integration"],queryFn:async()=>{const{data:_,error:S}=await q.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(S)throw S;return _}}),{data:h}=lt({queryKey:["brokerages-list"],queryFn:async()=>{const{data:_,error:S}=await q.from("brokerages").select("id, name").order("name");if(S)throw S;return _}}),{data:p}=lt({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:_,error:S}=await q.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(S)throw S;return _}}),f=async()=>{var _;n(!0);try{const{data:S}=await q.auth.getSession(),A=(_=S==null?void 0:S.session)==null?void 0:_.access_token;if(!A)throw new Error("Not authenticated");const L=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"get_auth_url"})}),M=await L.json();if(!L.ok||M!=null&&M.error)throw new Error((M==null?void 0:M.error)||"Failed to get authorization URL");if(M!=null&&M.authUrl){localStorage.setItem("canva_code_verifier",M.codeVerifier),localStorage.setItem("canva_oauth_state",M.state);const F=window.open(M.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!F){ae.error("Popup was blocked. Please allow popups for this site and try again."),n(!1);return}const z=W=>{var K,Y;W.origin===window.location.origin&&(((K=W.data)==null?void 0:K.type)==="canva-oauth-success"?(window.removeEventListener("message",z),ae.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1)):((Y=W.data)==null?void 0:Y.type)==="canva-oauth-error"&&(window.removeEventListener("message",z),ae.error("Canva connection failed: "+(W.data.error||"Unknown error")),n(!1)))};window.addEventListener("message",z);const V=setInterval(()=>{F.closed&&(clearInterval(V),window.removeEventListener("message",z),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(S){console.error("Canva connect error:",S);const A=(S==null?void 0:S.message)||"";A.includes("CANVA_CLIENT_ID")?ae.error("Canva app credentials not configured yet."):ae.error(A||"Failed to start Canva connection"),n(!1)}},g=gt({mutationFn:async _=>{var F;const{data:S}=await q.auth.getSession(),A=(F=S==null?void 0:S.session)==null?void 0:F.access_token;if(!A)throw new Error("Not authenticated");const L=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:_})}),M=await L.json();if(!L.ok||M!=null&&M.error)throw new Error((M==null?void 0:M.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),ae.success("Canva disconnected")},onError:_=>{ae.error(_.message||"Failed to disconnect Canva")}}),b=gt({mutationFn:async _=>{const{error:S}=await q.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:(p==null?void 0:p.length)||0});if(S)throw S},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ae.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>ae.error("Failed to add folder")}),v=gt({mutationFn:async _=>{const{error:S}=await q.from("canva_brokerage_folders").delete().eq("id",_);if(S)throw S},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ae.success("Folder removed")},onError:()=>ae.error("Failed to remove folder")}),j=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-accent flex items-center justify-center",children:e.jsx(AXe,{})}),e.jsxs("div",{children:[e.jsxs(Pt,{className:"text-lg flex items-center gap-2",children:["Canva Connect",j&&e.jsx(ze,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(ze,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(Hn,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Ae,{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(zi,{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(zi,{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(zi,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsx("span",{children:"Multiple folders per brokerage (templates, brand assets, listings)"})]}),e.jsxs("div",{className:"mt-4 p-3 rounded-lg bg-muted border border-dashed",children:[e.jsx("p",{className:"text-xs font-medium text-foreground mb-1",children:"Canva App Redirect URL"}),e.jsx("code",{className:"text-xs text-muted-foreground break-all select-all",children:"https://dashboard.relevelup.com/canva-callback.html"})]}),j?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:d.canva_team_id?`Team: ${d.canva_team_id}`:"Canva Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.expires_at?`Token expires ${new Date(d.expires_at).toLocaleDateString()}`:"Platform integration active"})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Canva?"}),e.jsx(Mo,{children:"This will remove the Canva platform integration. Agents who have already connected will not be affected, but new folder sharing will stop."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{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(yf,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",p&&p.length>0&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:p.length})]}),r?e.jsx(sx,{className:"h-4 w-4"}):e.jsx(io,{className:"h-4 w-4"})]}),r&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[p&&p.length>0?p.map(_=>{var S,A;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md bg-muted/50 text-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium truncate",children:_.folder_name}),e.jsx(ze,{variant:"outline",className:"text-xs shrink-0",children:((S=MXe.find(T=>T.value===_.folder_type))==null?void 0:S.label)||_.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(A=_.brokerages)==null?void 0:A.name," · ID: ",e.jsx("span",{className:"font-mono",children:_.folder_id})]})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>v.mutate(_.id),children:e.jsx(Fn,{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(B,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(As,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:f,disabled:t||u,children:[t?e.jsx(Ai,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(AXe,{})}),"Connect Canva",e.jsx(za,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(ws,{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(se,{children:"Brokerage"}),e.jsxs(us,{value:o.brokerage_id,onValueChange:_=>c(S=>({...S,brokerage_id:_})),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select a brokerage…"})}),e.jsx(ds,{children:h==null?void 0:h.map(_=>e.jsx(Ze,{value:_.id,children:_.name},_.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Canva Folder ID"}),e.jsx(ge,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:_=>c(S=>({...S,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(se,{children:"Folder Display Name"}),e.jsx(ge,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:_=>c(S=>({...S,folder_name:_.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Folder Type"}),e.jsxs(us,{value:o.folder_type,onValueChange:_=>c(S=>({...S,folder_type:_})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:MXe.map(_=>e.jsx(Ze,{value:_.value,children:_.label},_.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(ge,{placeholder:"What's in this folder?",value:o.description,onChange:_=>c(S=>({...S,description:_.target.value}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>b.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||b.isPending,children:[b.isPending?e.jsx(Ai,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function Itn(){const s=In();return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Vd,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(fe,{className:"p-6 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(Hl,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"User Social Connections"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"See which agents have connected Facebook, Instagram, LinkedIn, and Google."})]})]}),e.jsxs(B,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(za,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(Mtn,{}),e.jsx(eNt,{})]})})}const IXe=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(Oh,{className:t}):s==="instagram"?e.jsx(mu,{className:t}):s==="linkedin"?e.jsx(bf,{className:t}):s==="google"?e.jsx(Hs,{className:t}):null},Ptn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function Ltn(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(""),[l,o]=N.useState("all");N.useEffect(()=>{(async()=>{r(!0);const{data:p,error:f}=await q.rpc("admin_get_social_connections");if(f){ae.error(f.message),r(!1);return}t(p||[]),r(!1)})()},[]);const c=N.useMemo(()=>{const p=a.trim().toLowerCase();return s.filter(f=>l!=="all"&&f.platform!==l?!1:p?(f.user_name||"").toLowerCase().includes(p)||(f.user_email||"").toLowerCase().includes(p)||(f.page_name||"").toLowerCase().includes(p)||(f.platform_username||"").toLowerCase().includes(p):!0)},[s,a,l]),d=N.useMemo(()=>{const p=new Map;return s.forEach(f=>{const g=p.get(f.user_id)||{name:f.user_name,email:f.user_email,platforms:new Set,count:0};g.platforms.add(f.platform),g.count+=1,p.set(f.user_id,g)}),Array.from(p.entries()).map(([f,g])=>({user_id:f,...g}))},[s]),u=N.useMemo(()=>{const p=new Map;return s.forEach(f=>p.set(f.platform,(p.get(f.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(p.entries())}},[s,d]),h=p=>p&&new Date(p).getTime()e.jsxs(fe,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[IXe(p)," ",p]}),e.jsx("div",{className:"text-2xl font-bold",children:f})]},p))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(ge,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:p=>i(p.target.value),className:"md:max-w-md"}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(cs,{className:"md:w-48",children:e.jsx(hs,{placeholder:"All platforms"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All platforms"}),e.jsx(Ze,{value:"facebook",children:"Facebook"}),e.jsx(Ze,{value:"instagram",children:"Instagram"}),e.jsx(Ze,{value:"linkedin",children:"LinkedIn"}),e.jsx(Ze,{value:"google",children:"Google"})]})]})]}),e.jsx(fe,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(ss,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"User"}),e.jsx(Ct,{children:"Platform"}),e.jsx(Ct,{children:"Page / Account"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Connected"})]})}),e.jsx(pa,{children:c.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(p=>{const f=h(p.token_expires_at);return e.jsxs(Gs,{children:[e.jsxs(ut,{children:[e.jsx("div",{className:"font-medium",children:p.user_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:p.user_email})]}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[IXe(p.platform)," ",p.platform]})}),e.jsxs(ut,{children:[e.jsx("div",{className:"font-medium",children:p.page_name||p.platform_username||"—"}),p.instagram_business_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["IG Business: ",p.instagram_business_id]})]}),e.jsx(ut,{children:p.is_active?f?e.jsxs(ze,{variant:"destructive",className:"gap-1",children:[e.jsx(Gi,{className:"h-3 w-3"})," Expired"]}):e.jsx(ze,{children:"Active"}):e.jsx(ze,{variant:"secondary",children:"Inactive"})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Ptn(p.created_at)})]},p.id)})})]})})]})})}const Dtn={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 UF(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function Rtn(){var V,W,K,Y,ee;const s=Gt(),[t,n]=N.useState("Test Push"),[r,a]=N.useState("Testing web push notification"),[i,l]=N.useState("/community"),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[f,g]=N.useState(null),[b,v]=N.useState(null),{data:j,isLoading:_}=lt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:ne,error:oe}=await q.from("push_notification_settings").select("*").order("setting_key");if(oe)throw oe;return ne}}),{data:S,isLoading:A}=lt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:ne,error:oe}=await q.from("push_subscriptions").select("*",{count:"exact",head:!0});if(oe)throw oe;return{totalSubscriptions:ne||0}}}),T=gt({mutationFn:async({settingKey:ne,isEnabled:oe})=>{const{error:pe}=await q.from("push_notification_settings").update({is_enabled:oe}).eq("setting_key",ne);if(pe)throw pe},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),ae.success("Notification setting updated")},onError:ne=>{ae.error("Failed to update setting: "+ne.message)}}),D=N.useMemo(()=>{var ne,oe;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((ne=h.serviceWorker)==null?void 0:ne.activeState)??"unknown"} · sub=${(oe=h.subscription)!=null&&oe.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);N.useEffect(()=>{let ne=!0;const oe=async()=>{var ie,ye,_e,Me,Te,Ce,Ee;const ce="serviceWorker"in navigator&&"PushManager"in window,de={isSupported:ce,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((ie=navigator.serviceWorker)!=null&&ie.controller)};if(!ce){ne&&p(de);return}try{const{data:De,error:Ie}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(Ie)throw Ie;de.vapidPublicKey=De==null?void 0:De.vapidPublicKey;const qe=(await navigator.serviceWorker.getRegistrations()).find(ve=>{var we,it,Ne;return(((we=ve.active)==null?void 0:we.scriptURL)||((it=ve.waiting)==null?void 0:it.scriptURL)||((Ne=ve.installing)==null?void 0:Ne.scriptURL)||"").includes("/sw.js")});if(qe){de.pushWorkerScriptUrl=((ye=qe.active)==null?void 0:ye.scriptURL)||((_e=qe.waiting)==null?void 0:_e.scriptURL)||((Me=qe.installing)==null?void 0:Me.scriptURL),de.serviceWorker={scope:qe.scope,activeState:(Te=qe.active)==null?void 0:Te.state};const ve=await qe.pushManager.getSubscription();if(ve){const Je=ve.toJSON();de.subscription={endpoint:Je.endpoint,p256dh:(Ce=Je.keys)==null?void 0:Ce.p256dh,auth:(Ee=Je.keys)==null?void 0:Ee.auth}}}}catch(De){de.error=(De==null?void 0:De.message)||String(De)}ne&&p(de)};oe();const pe=window.setInterval(oe,4e3);return()=>{ne=!1,window.clearInterval(pe)}},[]);const L=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(ne){ae.error(`Local notification failed: ${(ne==null?void 0:ne.message)||String(ne)}`)}},M=async()=>{c(!0),g(null);try{const{data:ne,error:oe}=await q.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(oe)throw oe;g({sent:ne==null?void 0:ne.sent,failed:ne==null?void 0:ne.failed,expiredCleaned:ne==null?void 0:ne.expiredCleaned,vapidPublicKey:ne==null?void 0:ne.vapidPublicKey}),(ne==null?void 0:ne.sent)>0?ae.success(`Test notification sent to ${ne.sent} subscriber(s)`):(ne==null?void 0:ne.failed)>0?ae.warning(`Notification failed for ${ne.failed} subscriber(s). ${ne.expired||0} expired subscriptions cleaned up.`):ae.info("No active subscriptions to send to")}catch(ne){console.error("Error sending test notification:",ne),g({error:(ne==null?void 0:ne.message)||String(ne)}),ae.error("Failed to send test notification: "+(ne.message||"Unknown error"))}finally{c(!1)}},F=async()=>{u(!0),v(null);try{const{data:ne,error:oe}=await q.functions.invoke("generate-vapid-keys",{body:{}});if(oe)throw oe;const pe=ne==null?void 0:ne.publicKey,ce=ne==null?void 0:ne.privateKey;if(!pe||!ce)throw new Error("generate-vapid-keys did not return keys");v({publicKey:pe,privateKey:ce}),ae.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(ne){console.error("Error generating VAPID keys:",ne),ae.error("Failed to generate VAPID keys: "+((ne==null?void 0:ne.message)||"Unknown error"))}finally{u(!1)}},z=gt({mutationFn:async()=>{const{error:ne}=await q.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(ne)throw ne},onSuccess:()=>{ae.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:ne=>{ae.error("Failed to clear subscriptions: "+ne.message)}});return e.jsx(Cs,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(Hn,{children:"Current active push notification subscriptions"})]}),e.jsx(Ae,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:A?"...":(S==null?void 0:S.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(Vo,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(Hn,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Ae,{children:_?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:j==null?void 0:j.map(ne=>{const oe=Dtn[ne.setting_key]||{label:ne.setting_key,icon:"🔔"};return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:oe.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:oe.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:ne.description})]})]}),e.jsx(vn,{checked:ne.is_enabled,onCheckedChange:pe=>T.mutate({settingKey:ne.setting_key,isEnabled:pe}),disabled:T.isPending})]},ne.id)})})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(lm,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Hn,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Client push debug"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:D}),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?UF(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: ",(V=h.serviceWorker)!=null&&V.scope?UF(h.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((W=h.serviceWorker)==null?void 0:W.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: ",(K=h.subscription)!=null&&K.endpoint?UF(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(Y=h.subscription)!=null&&Y.p256dh?UF(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(ee=h.subscription)!=null&&ee.auth?UF(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(B,{variant:"outline",onClick:L,children:"Local notification test"}),e.jsx(B,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(ge,{id:"test-title",value:t,onChange:ne=>n(ne.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Ts,{id:"test-body",value:r,onChange:ne=>a(ne.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(ge,{id:"test-url",value:i,onChange:ne=>l(ne.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs(B,{onClick:M,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),f&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Last send debug"}),f.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",f.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",f.sent??0," sent, ",f.failed??0," failed, ",f.expiredCleaned??0," expired cleaned"]}),f.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:f.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(bn,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Hn,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you've recently updated the VAPID keys, existing subscriptions will no longer work. Use this to clear all subscriptions so users can re-subscribe with the new keys."}),e.jsxs(B,{variant:"destructive",onClick:()=>z.mutate(),disabled:z.isPending,children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),z.isPending?"Clearing...":"Clear All Subscriptions"]}),e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"VAPID key rotation helper"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:"If you suspect the backend public/private keys don’t match, generate a fresh pair, update backend secrets, then clear subscriptions and have users re-enable push."}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(B,{variant:"outline",onClick:F,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),b&&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:b.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:b.privateKey})]})]})]})]})]})]})})}function Otn(){const{toast:s}=Ua(),[t,n]=N.useState([]),[r,a]=N.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=N.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=CU("presentation_count","desc"),h=u(t,{name:g=>{var b;return((b=g.name)==null?void 0:b.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});N.useEffect(()=>{p()},[]);const p=async()=>{try{l(!0);const{data:g,error:b}=await q.rpc("get_admin_presentation_stats");if(b)throw b;if(!g||g.length===0){l(!1);return}const v=g.map(T=>T.owner_user_id),{data:j,error:_}=await q.from("profiles").select("id, name, email, avatar_url").in("id",v);if(_)throw _;const S=new Map((j==null?void 0:j.map(T=>[T.id,T]))||[]),A=g.map(T=>{const D=S.get(T.owner_user_id);return{owner_user_id:T.owner_user_id,name:(D==null?void 0:D.name)||"Unknown",email:(D==null?void 0:D.email)||"",avatar_url:(D==null?void 0:D.avatar_url)||null,presentation_count:Number(T.presentation_count),total_views:Number(T.total_views),total_leads:Number(T.total_leads),total_cta_clicks:Number(T.total_cta_clicks)}});n(A),n(A),a({totalPresentations:A.reduce((T,D)=>T+D.presentation_count,0),totalViews:A.reduce((T,D)=>T+D.total_views,0),totalLeads:A.reduce((T,D)=>T+D.total_leads,0),totalCtaClicks:A.reduce((T,D)=>T+D.total_cta_clicks,0),agentsUsing:A.length})}catch(g){console.error("Error loading presentation stats:",g),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},f=[{label:"Agents Using",value:r.agentsUsing,icon:_n,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:oy,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:Ir,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:Fo,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:oc,color:"text-rose-600"}];return e.jsx(Cs,{title:"Presentation Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Presentation Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track Smart Presentations usage and engagement across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:f.map(g=>e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:g.label}),e.jsx(g.icon,{className:`h-4 w-4 ${g.color}`})]}),e.jsx(Ae,{children:i?e.jsx(Ws,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:g.value.toLocaleString()})})]},g.label))}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(mo,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Ae,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((g,b)=>e.jsx(Ws,{className:"h-12 w-full"},b))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Pc,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Pc,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Pc,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Pc,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Pc,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Pc,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(pa,{children:h.map(g=>{var v,j;const b=g.total_views>0?(g.total_leads/g.total_views*100).toFixed(1):"0.0";return e.jsxs(Gs,{children:[e.jsx(ut,{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:((j=(v=g.name)==null?void 0:v.charAt(0))==null?void 0:j.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:g.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:g.email})]})]})}),e.jsx(ut,{className:"text-center font-medium",children:g.presentation_count}),e.jsx(ut,{className:"text-center",children:g.total_views.toLocaleString()}),e.jsx(ut,{className:"text-center",children:g.total_leads>0?e.jsx(ze,{variant:"secondary",children:g.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ut,{className:"text-center",children:g.total_cta_clicks}),e.jsx(ut,{className:"text-center",children:e.jsxs("span",{className:Number(b)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[b,"%"]})})]},g.owner_user_id)})})]})})]})]})})}function Ftn(){const{toast:s}=Ua(),[t,n]=N.useState([]),[r,a]=N.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=N.useState(!0);N.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await q.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const h=d.map(v=>v.agent_id),{data:p,error:f}=await q.from("profiles").select("id, name, email, avatar_url").in("id",h);if(f)throw f;const g=new Map((p==null?void 0:p.map(v=>[v.id,v]))||[]),b=d.map(v=>{const j=g.get(v.agent_id);return{agent_id:v.agent_id,name:(j==null?void 0:j.name)||"Unknown",email:(j==null?void 0:j.email)||"",avatar_url:(j==null?void 0:j.avatar_url)||null,open_house_count:Number(v.open_house_count),total_visitors:Number(v.total_visitors),total_leads:Number(v.total_leads),active_count:Number(v.active_count)}});b.sort((v,j)=>j.total_visitors-v.total_visitors),n(b),a({totalOpenHouses:b.reduce((v,j)=>v+j.open_house_count,0),totalVisitors:b.reduce((v,j)=>v+j.total_visitors,0),totalLeads:b.reduce((v,j)=>v+j.total_leads,0),activeOpenHouses:b.reduce((v,j)=>v+j.active_count,0),agentsUsing:b.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:_n,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:zr,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:zi,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:Ir,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:Fo,color:"text-rose-600"}];return e.jsx(Cs,{title:"Guest Book Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Guest Book Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track open house sign-in usage and lead generation across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:c.map(d=>e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Pt,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Ae,{children:i?e.jsx(Ws,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(mo,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Ae,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(Ws,{className:"h-12 w-full"},u))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No open houses created yet."}):e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{className:"text-center",children:"Open Houses"}),e.jsx(Ct,{className:"text-center",children:"Active"}),e.jsx(Ct,{className:"text-center",children:"Visitors"}),e.jsx(Ct,{className:"text-center",children:"Leads"}),e.jsx(Ct,{className:"text-center",children:"Conversion"})]})}),e.jsx(pa,{children:t.map(d=>{var h,p;const u=d.total_visitors>0?(d.total_leads/d.total_visitors*100).toFixed(1):"0.0";return e.jsxs(Gs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:d.avatar_url?e.jsx("img",{src:d.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((p=(h=d.name)==null?void 0:h.charAt(0))==null?void 0:p.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email})]})]})}),e.jsx(ut,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(ut,{className:"text-center",children:d.active_count>0?e.jsx(ze,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ut,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(ut,{className:"text-center",children:d.total_leads>0?e.jsx(ze,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ut,{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 ztn(){const[s]=yl(),t=In(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing connection...");return N.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Failed to connect: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("Failed to connect: No authorization code");return}try{const{data:h,error:p}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u}});if(h&&h.success===!1)throw new Error(h.error||"Failed to connect accounts");if(p){let f=p.message||"Failed to connect accounts";try{const g=p.context;if(g&&typeof g.json=="function"){const b=await g.json();b!=null&&b.error&&(f=b.error)}}catch{}throw new Error(f)}if(h!=null&&h.success)r("success"),i(h.message||"Accounts connected successfully!"),ae.success(h.message||"Social accounts connected!");else throw new Error((h==null?void 0:h.error)||"Failed to connect accounts")}catch(h){console.error("Callback error:",h),r("error"),i(h.message||"Failed to complete connection"),ae.error(h.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(ss,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(zi,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(Gc,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(Pt,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Hn,{children:a})]}),e.jsx(Ae,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function Btn(){const s=Gt(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState([]),o=N.useRef(null),{data:c,isLoading:d}=lt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:_,error:S}=await q.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(S)throw S;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},p=gt({mutationFn:async _=>{const{data:S,error:A}=await q.functions.invoke("send-prospect-email",{body:{emails:_}});if(A)throw A;return S},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)}}),f=gt({mutationFn:async()=>{var T,D;const{data:{user:_}}=await q.auth.getUser();if(!(_!=null&&_.email))throw new Error("Could not get your email");const{data:S,error:A}=await q.functions.invoke("send-prospect-email",{body:{emails:[{email:_.email,first_name:(D=(T=_.user_metadata)==null?void 0:T.name)==null?void 0:D.split(" ")[0]}],test_mode:!0}});if(A)throw A;return S},onSuccess:()=>{ae.success("Test email sent to your inbox!")},onError:_=>{ae.error("Failed to send test: "+_.message)}}),g=gt({mutationFn:async()=>{const{data:_,error:S}=await q.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(S)throw S;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)}}),b=()=>{if(!t.trim()){ae.error("Please enter an email address");return}if(c==null?void 0:c.find(S=>S.email.toLowerCase()===t.trim().toLowerCase())){ae.error("This email has already been prospected");return}p.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},v=_=>{var T;const S=(T=_.target.files)==null?void 0:T[0];if(!S)return;const A=new FileReader;A.onload=D=>{var V,W;const M=((V=D.target)==null?void 0:V.result).split(` `).filter(K=>K.trim()),F=[],z=(W=M[0])!=null&&W.toLowerCase().includes("email")?1:0;for(let K=z;Koe.trim().replace(/"/g,"")),ee=Y[0],ne=Y[1];ee&&ee.includes("@")&&F.push({email:ee,first_name:ne||void 0})}l(F),ae.success(`${F.length} entries loaded from CSV`)},A.readAsText(S),o.current&&(o.current.value="")},j=()=>{if(i.length===0){ae.error("No entries to send");return}const _=new Set((c==null?void 0:c.map(A=>A.email.toLowerCase()))||[]),S=i.filter(A=>!_.has(A.email.toLowerCase()));if(S.length===0){ae.error("All emails have already been prospected");return}S.length0&&e.jsxs(fe,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(wf,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx(ze,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(Hn,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Ae,{children:e.jsxs(B,{onClick:()=>g.mutate(),disabled:g.isPending,className:"gap-2",children:[g.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(wc,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(Hn,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>f.mutate(),disabled:f.isPending,className:"gap-2 ml-4 shrink-0",children:[f.isPending?e.jsx(ss,{className:"h-3 w-3 animate-spin"}):e.jsx(Hs,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Ae,{children:e.jsxs($r,{defaultValue:"single",children:[e.jsxs(Ur,{className:"mb-4",children:[e.jsxs(Zt,{value:"single",children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Zt,{value:"bulk",children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(ls,{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(se,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(ge,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:_=>n(_.target.value),onKeyDown:_=>_.key==="Enter"&&b()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(se,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(ge,{id:"prospect-name",placeholder:"First name (optional)",value:r,onChange:_=>a(_.target.value),onKeyDown:_=>_.key==="Enter"&&b()})]}),e.jsxs(B,{onClick:b,disabled:p.isPending,className:"gap-2",children:[p.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(ls,{value:"bulk",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{ref:o,type:"file",accept:".csv",onChange:v,className:"hidden"}),e.jsxs(B,{variant:"outline",onClick:()=>{var _;return(_=o.current)==null?void 0:_.click()},className:"gap-2",children:[e.jsx(Nr,{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(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(_n,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(Fn,{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((_,S)=>e.jsxs("div",{className:"text-muted-foreground",children:[_.email,_.first_name?` — ${_.first_name}`:""]},S)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(B,{onClick:j,disabled:p.isPending,className:"gap-2",children:[p.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Hn,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Ae,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((_,S)=>e.jsx(Ws,{className:"h-12 w-full"},S))}):c&&c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(_=>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:ks(new Date(_.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:_.status==="converted"?e.jsxs(ze,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"}),"Converted"]}):_.status==="live_lead"?e.jsxs(ze,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(wf,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:_.converted_at?ks(new Date(_.converted_at),"MMM d, yyyy"):"—"})]},_.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(wc,{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 XU(s){const t=Gt(),{toast:n}=Ua(),r=lt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=lt({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],u=0,h=!0;for(;h;){const{data:p,error:f}=await q.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(f)throw f;d=d.concat(p),h=p.length===c,u+=c}return d},enabled:!!s}),i=gt({mutationFn:async c=>{const{data:{user:d}}=await q.auth.getUser();if(!d)throw new Error("Not authenticated");const u={first_name:c.first_name||"",last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,current_brokerage:c.current_brokerage||null,license_number:c.license_number||null,experience_years:c.experience_years??null,annual_production:c.annual_production||null,source:c.source||"manual",notes:c.notes||null,stage_id:c.stage_id||null,brokerage_id:s,created_by:d.id,address:c.address||null,city:c.city||null,state:c.state||null,zip_code:c.zip_code||null,last_year_volume:c.last_year_volume||null,last_year_transactions:c.last_year_transactions??null,avg_sale_price:c.avg_sale_price||null,specialties:c.specialties||null,linkedin_url:c.linkedin_url||null,website_url:c.website_url||null,instagram_handle:c.instagram_handle||null,facebook_url:c.facebook_url||null,birthday:c.birthday||null,spouse_name:c.spouse_name||null,interests:c.interests||null,referred_by:c.referred_by||null},{data:h,error:p}=await q.from("recruit_prospects").insert(u).select().single();if(p)throw p;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect added"})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),l=gt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await q.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),o=gt({mutationFn:async c=>{const{error:d}=await q.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect removed"})}});return{stages:r.data||[],prospects:a.data||[],isLoading:r.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function $tn(s){const t=Gt(),{toast:n}=Ua(),r=lt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await q.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=gt({mutationFn:async i=>{const{data:{user:l}}=await q.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await q.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),n({title:"Activity logged"})},onError:i=>n({title:"Error",description:i.message,variant:"destructive"})});return{activities:r.data||[],isLoading:r.isLoading,addActivity:a}}const PXe=(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 oNt({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=N.useState(PXe(r,n)),c=u=>h=>o(p=>({...p,[u]:h.target.value})),d=u=>{u.preventDefault(),a({...l,experience_years:l.experience_years?parseInt(l.experience_years):null,last_year_transactions:l.last_year_transactions?parseInt(l.last_year_transactions):null,stage_id:l.stage_id||null}),o(PXe(r,n)),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs($r,{defaultValue:"basic",className:"w-full",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-4",children:[e.jsx(Zt,{value:"basic",children:"Basic Info"}),e.jsx(Zt,{value:"production",children:"Production"}),e.jsx(Zt,{value:"social",children:"Social & Web"}),e.jsx(Zt,{value:"personal",children:"Personal"})]}),e.jsxs(ls,{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(se,{children:"First Name *"}),e.jsx(ge,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last Name"}),e.jsx(ge,{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(se,{children:"Email"}),e.jsx(ge,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ge,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Current Brokerage"}),e.jsx(ge,{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(se,{children:"License #"}),e.jsx(ge,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Experience (years)"}),e.jsx(ge,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Address"}),e.jsx(ge,{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(se,{children:"City"}),e.jsx(ge,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(ge,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Zip"}),e.jsx(ge,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Pipeline Stage"}),e.jsxs(us,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:n.map(u=>e.jsx(Ze,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Referred By"}),e.jsx(ge,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(ls,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Annual Production Volume"}),e.jsx(ge,{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(se,{children:"Last Year Volume"}),e.jsx(ge,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last Year Transactions"}),e.jsx(ge,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Avg Sale Price"}),e.jsx(ge,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Specialties / Niche"}),e.jsx(ge,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(ls,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"LinkedIn URL"}),e.jsx(ge,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Website URL"}),e.jsx(ge,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Instagram Handle"}),e.jsx(ge,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Facebook URL"}),e.jsx(ge,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(ls,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Birthday"}),e.jsx(ge,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Spouse / Partner Name"}),e.jsx(ge,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Interests / Hobbies"}),e.jsx(ge,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ts,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function ube(){const{user:s}=gs();return lt({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,n]=await Promise.all([q.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),q.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]);return{massEmail:t.data?{email:t.data.email,displayName:t.data.display_name}:null,gmail:n.data?{email:n.data.gmail_email}:null}}})}function I8e({value:s,onChange:t}){const{data:n,isLoading:r}=ube();return e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Send from"}),e.jsxs(us,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(Ze,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Z2,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(Ze,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Hs,{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 lNt({open:s,onOpenChange:t,recruitVideoId:n,brokerageId:r,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState("default"),[b,v]=N.useState(!1),j=Gt(),{data:_}=ube();N.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),p(o||""),g(_!=null&&_.massEmail?"mass_email":_!=null&&_.gmail?"gmail":"default"))},[s,c,o,_==null?void 0:_.massEmail,_==null?void 0:_.gmail]);const S=async()=>{var A,T;if(!i){ae.error("This prospect has no email address on file.");return}v(!0);try{const{data:D,error:L}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[n],brokerage_id:r,subject_override:d.trim()||void 0,message_override:h.trim()||void 0,send_via:f}});if(L)throw L;if(((D==null?void 0:D.sent)??0)>0)ae.success(`Email sent to ${i}`),j.invalidateQueries({queryKey:["recruit-videos"]}),j.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const F=((T=(A=D==null?void 0:D.results)==null?void 0:A[0])==null?void 0:T.error)||"Failed to send";ae.error(F)}}catch(D){ae.error((D==null?void 0:D.message)||"Failed to send email")}finally{v(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"To"}),e.jsx(ge,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(I8e,{value:f,onChange:g}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(ge,{value:d,onChange:A=>u(A.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Ts,{value:h,onChange:A=>p(A.target.value),rows:5,placeholder:`Hi ${c}, wanted to share a quick video...`,className:"mt-1"})]}),l&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Video: ",e.jsx("span",{className:"font-medium",children:l})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs(B,{onClick:S,disabled:b||!i,children:[b?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function cw(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const ITe=[{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 Utn(s){return lt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_videos").select(` *, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function qtn(s){return lt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function cNt(){const s=Gt(),{toast:t}=Ua();return gt({mutationFn:async n=>{const{data:{user:r}}=await q.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("recruit_videos").insert({prospect_id:n.prospect_id,video_id:n.video_id,brokerage_id:n.brokerage_id,message:n.message||null,created_by:r.id}).select("*, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token)").single();if(i)throw i;return a},onSuccess:n=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",n.prospect_id]}),t({title:"Video linked to prospect"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function dNt(){const s=Gt();return gt({mutationFn:async({id:t,sent_via:n})=>{const{error:r}=await q.from("recruit_videos").update({sent_at:new Date().toISOString(),sent_via:n,updated_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-videos"]})}})}function uNt(s){return lt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_video_scripts").select("*").or(`brokerage_id.eq.${s},is_global.eq.true`).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Vtn(){const s=Gt(),{toast:t}=Ua();return gt({mutationFn:async n=>{const{data:{user:r}}=await q.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("recruit_video_scripts").insert({...n,created_by:r.id}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]}),t({title:"Script saved"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function Htn(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("recruit_video_scripts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function Gtn({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var ee;const{data:a=[],isLoading:i}=qtn(s),{data:l=[]}=uNt(r),o=cNt(),c=PN();dNt();const[d,u]=N.useState("idle"),[h,p]=N.useState(0),[f,g]=N.useState(0),[b,v]=N.useState(""),[j,_]=N.useState(""),[S,A]=N.useState(!1),[T,D]=N.useState(null),[L,M]=N.useState(null),[F,z]=N.useState(null),V=((ee=l.find(ne=>ne.id===b))==null?void 0:ee.script_text)||"",W=()=>{u("idle"),p(0),g(0),v(""),_("")},K=N.useCallback(async(ne,oe)=>{u("uploading");try{const pe=`Recruiting: ${t}`,{videoId:ce,libraryId:de}=await l6(pe),{uploadUrl:ie,apiKey:ye}=await c6(ce),_e=new XMLHttpRequest;_e.upload.onprogress=qe=>{qe.lengthComputable&&p(qe.loaded/qe.total*100)},await new Promise((qe,ve)=>{_e.onload=()=>_e.status>=200&&_e.status<300?qe():ve(new Error("Upload failed")),_e.onerror=()=>ve(new Error("Upload failed")),_e.open("PUT",ie),_e.setRequestHeader("AccessKey",ye),_e.send(ne)}),u("processing");let Me=0;const Te=Date.now(),Ce=9e4,Ee=`https://iframe.mediadelivery.net/embed/${de}/${ce}`;for(;Me<4&&(await new Promise(ve=>setTimeout(ve,3e3)),!(Date.now()-Te>Ce));){const qe=await Uw(ce);if(Me=qe.status,g(qe.encodeProgress||0),Me===5||Me===6)throw new Error("Video processing failed")}const De=await Uw(ce),Ie=(De.storageSize||ne.size)/(1024*1024),Fe=await c.mutateAsync({bunny_video_id:ce,playback_url:De.directPlayUrl||Ee,thumbnail_url:De.thumbnailUrl,preview_url:De.previewUrl||null,duration_seconds:De.length||oe,file_size_mb:Ie,title:pe,status:Me>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Fe.id,brokerage_id:r,message:j||void 0}),u("done"),ae.success("Video recorded and linked to prospect!"),setTimeout(()=>{A(!1),W()},1500)}catch(pe){ae.error(pe.message||"Failed to upload video"),u("record")}},[s,t,r,j,c,o]),Y=ne=>{ne&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${ne}`),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(vr,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(bs,{open:S,onOpenChange:ne=>{!ne&&(d==="uploading"||d==="processing")||(A(ne),ne||W())},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{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(se,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(us,{value:b,onValueChange:v,children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{placeholder:"No script — speak freely"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No script"}),l.map(ne=>{var oe;return e.jsx(Ze,{value:ne.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[ne.title,e.jsx(ze,{variant:"outline",className:"text-[9px] ml-1",children:(oe=ITe.find(pe=>pe.value===ne.category))==null?void 0:oe.label})]})},ne.id)})]})]}),V&&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:V})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Ts,{value:j,onChange:ne=>_(ne.target.value),placeholder:`Hi ${t.split(" ")[0]}, I'd love to chat about what we're building here...`,rows:3,className:"mt-1"})]}),e.jsxs(B,{onClick:()=>u("record"),className:"w-full",children:[e.jsx(vr,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(m6,{maxDurationSeconds:600,onRecordingComplete:K,teleprompterContent:V||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(xi,{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(xi,{value:f,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(f),"%"]})]}),d==="done"&&e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(Al,{className:"h-6 w-6 text-emerald-600"})}),e.jsx("p",{className:"font-medium text-emerald-600",children:"Video ready!"})]})]})]})]}),i?e.jsx("div",{className:"text-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent mx-auto"})}):a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos sent yet"}):e.jsx("div",{className:"space-y-2",children:a.map(ne=>{var oe;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md border text-sm",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:cw(ne.video)?e.jsx("img",{src:cw(ne.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(vr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs truncate",children:((oe=ne.video)==null?void 0:oe.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[ne.view_count>0?e.jsxs(ze,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(Ir,{className:"h-2.5 w-2.5 mr-0.5"}),ne.view_count]}):ne.sent_at?e.jsxs(ze,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(cr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(ze,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(gr,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:ks(new Date(ne.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>Y(ne.share_token),title:"Copy link",children:e.jsx(ta,{className:"h-3 w-3"})}),e.jsxs(B,{variant:ne.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var pe;D(ne.id),M(((pe=ne.video)==null?void 0:pe.title)||null),z(ne.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(Hs,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:ne.sent_at?"Resend":"Email"})]})]})]},ne.id)})}),T&&e.jsx(lNt,{open:!!T,onOpenChange:ne=>{ne||D(null)},recruitVideoId:T,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:L,defaultMessage:F})]})}function Wtn({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=lt({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=q.from("recruit_email_templates").select("id,brokerage_id,category,title,subject,body,sort_order").eq("is_active",!0).order("sort_order");s?i=i.or(`brokerage_id.is.null,brokerage_id.eq.${s}`):i=i.is("brokerage_id",null);const{data:l,error:o}=await i;if(o)throw o;return l}}),a=n.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Use Template",e.jsx(io,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(cc,{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(ss,{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(Qg,{}),e.jsx(I4,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(Xr,{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(ze,{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 Ktn({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=gs(),o=(a||"").split(" ")[0]||"there",[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState("default"),[g,b]=N.useState(!1),[v,j]=N.useState(null),[_,S]=N.useState(!1),A=Gt(),{data:T}=ube();N.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const V=T!=null&&T.massEmail?"mass_email":T!=null&&T.gmail?"gmail":"default";f(V),j(null),S(!1)}},[s,o,T==null?void 0:T.massEmail,T==null?void 0:T.gmail]);const{data:D=[],isLoading:L}=lt({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:V,error:W}=await q.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, touch_type, created_at, share_token").eq("owner_user_id",l.id).eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(W)throw W;return V??[]},enabled:s&&!!(l!=null&&l.id)}),M=D.find(V=>V.id===v)||null,F=async()=>{var V,W;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}b(!0);try{if(v){const{data:K}=await q.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",v).maybeSingle();let Y=K==null?void 0:K.id;if(!Y){const{data:pe,error:ce}=await q.from("recruit_videos").insert({prospect_id:n,video_id:v,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(ce)throw ce;Y=pe.id}const{data:ee,error:ne}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[Y],brokerage_id:r,subject_override:c.trim(),message_override:u.trim(),send_via:p}});if(ne)throw ne;if(((ee==null?void 0:ee.sent)??0)>0)ae.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-videos"]}),A.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),A.invalidateQueries({queryKey:["recruit-activities",n]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const pe=((W=(V=ee==null?void 0:ee.results)==null?void 0:V[0])==null?void 0:W.error)||"Failed to send";ae.error(pe)}}else{const{data:K,error:Y}=await q.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:p}});if(Y)throw Y;K!=null&&K.success?(ae.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-activities",n]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):ae.error((K==null?void 0:K.error)||"Failed to send")}}catch(K){ae.error((K==null?void 0:K.message)||"Failed to send email")}finally{b(!1)}},z=V=>{const W=K=>K.replace(/\[First Name\]/gi,o);d(W(V.subject)),h(W(V.body)),ae.success(`Loaded "${V.title}"`)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"To"}),e.jsx(ge,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(I8e,{value:p,onChange:f}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(Wtn,{brokerageId:r,onSelect:z})]}),e.jsx(ge,{value:c,onChange:V=>d(V.target.value)}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Message"}),e.jsx(Ts,{value:u,onChange:V=>h(V.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(se,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(vr,{className:"h-3.5 w-3.5"})," Include a video"]}),M?e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{j(null),S(!1)},children:[e.jsx(Fn,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>S(V=>!V),children:_?"Hide library":"Pick from library"})]}),M&&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:cw(M)?e.jsx("img",{src:cw(M),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(vr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:M.title||"Untitled video"})]}),!M&&_&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:L?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ss,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):D.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos in your library yet. Record one from a prospect to get started."}):D.map(V=>e.jsxs("button",{type:"button",onClick:()=>{j(V.id),S(!1)},className:"w-full flex items-center gap-3 p-2 rounded hover:bg-accent text-left transition-colors",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:cw(V)?e.jsx("img",{src:cw(V),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(vr,{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:V.title||"Untitled video"}),V.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(V.duration_seconds/60),":",String(Math.floor(V.duration_seconds%60)).padStart(2,"0")]})]})]},V.id))}),M&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"A tracked share link with thumbnail will be added to the email automatically."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsxs(B,{onClick:F,disabled:g||!i,children:[g?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function Ytn(s){return lt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_campaign_sends").select("id, prospect_id, subject, email_number, status, sent_at, opened_at, clicked_at, error_message, created_at").eq("prospect_id",s).neq("status","failed").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}const LXe=[{value:"call",label:"Phone Call",icon:Pr},{value:"email",label:"Email",icon:Hs},{value:"text",label:"Text Message",icon:Ci},{value:"meeting",label:"Meeting",icon:yr},{value:"note",label:"Note",icon:Nr},{value:"campaign_email",label:"Campaign Email",icon:cr}];function R0({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 LG({label:s,url:t,icon:n}){return t?e.jsxs("a",{href:t.startsWith("http")?t:`https://${t}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm text-primary hover:underline",children:[e.jsx(n,{className:"h-3.5 w-3.5"})," ",s," ",e.jsx(tr,{className:"h-3 w-3 opacity-50"})]}):null}function Ld({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:s}),e.jsx(ge,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function hNt({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=$tn((s==null?void 0:s.id)||null),{data:d=[]}=Ytn((s==null?void 0:s.id)||null),[u,h]=N.useState({type:"note",title:"",description:""}),[p,f]=N.useState(!1),[g,b]=N.useState(!1),[v,j]=N.useState({}),[_,S]=N.useState(!1);if(!s)return null;const A=()=>{var Y,ee;j({first_name:s.first_name||"",last_name:s.last_name||"",email:s.email||"",phone:s.phone||"",current_brokerage:s.current_brokerage||"",license_number:s.license_number||"",experience_years:((Y=s.experience_years)==null?void 0:Y.toString())||"",notes:s.notes||"",source:s.source||"",address:s.address||"",city:s.city||"",state:s.state||"",zip_code:s.zip_code||"",last_year_volume:s.last_year_volume||"",last_year_transactions:((ee=s.last_year_transactions)==null?void 0:ee.toString())||"",avg_sale_price:s.avg_sale_price||"",specialties:s.specialties||"",annual_production:s.annual_production||"",linkedin_url:s.linkedin_url||"",website_url:s.website_url||"",instagram_handle:s.instagram_handle||"",facebook_url:s.facebook_url||"",birthday:s.birthday||"",spouse_name:s.spouse_name||"",interests:s.interests||"",referred_by:s.referred_by||""}),b(!0)},T=()=>{const Y={id:s.id};for(const[ee,ne]of Object.entries(v))ee==="experience_years"||ee==="last_year_transactions"?Y[ee]=ne?parseInt(ne):null:Y[ee]=ne||null;i(Y),b(!1)},D=()=>b(!1),L=Y=>ee=>j(ne=>({...ne,[Y]:ee})),M=()=>{u.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:u.type,title:u.title,description:u.description||null}),h({type:"note",title:"",description:""}),f(!1))},F=t.find(Y=>Y.id===s.stage_id),z=s.address||s.city||s.state,V=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,W=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,K=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(ug,{open:r,onOpenChange:Y=>{Y||b(!1),a(Y)},children:[e.jsx(ox,{className:"w-full sm:max-w-lg p-0",children:e.jsx(mi,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(r0,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(a0,{className:"text-xl",children:[s.first_name," ",s.last_name]}),F&&e.jsx(ze,{variant:"outline",style:{borderColor:F.color,color:F.color},className:"mt-1",children:F.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[g?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:D,children:e.jsx(Fn,{className:"h-4 w-4"})}),e.jsx(B,{variant:"default",size:"icon",onClick:T,children:e.jsx(Ho,{className:"h-4 w-4"})})]}):e.jsx(B,{variant:"ghost",size:"icon",onClick:A,title:"Edit prospect",children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete prospect?"}),e.jsx(Mo,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{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(Hs,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>S(!0),children:[e.jsx(Hs,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Pr,{className:"h-3.5 w-3.5"})," ",s.phone]}),z&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),[s.address,s.city,s.state,s.zip_code].filter(Boolean).join(", ")]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(us,{value:s.stage_id||"",onValueChange:Y=>i({id:s.id,stage_id:Y}),children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(ds,{children:t.map(Y=>e.jsx(Ze,{value:Y.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:Y.color}}),Y.name]})},Y.id))})]})]}),e.jsxs($r,{defaultValue:"details",className:"w-full",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Zt,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Zt,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Zt,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Zt,{value:"personal",className:"text-xs",children:"Personal"})]}),g?e.jsxs(e.Fragment,{children:[e.jsxs(ls,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Ld,{label:"First Name",value:v.first_name,onChange:L("first_name")}),e.jsx(Ld,{label:"Last Name",value:v.last_name,onChange:L("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Ld,{label:"Email",value:v.email,onChange:L("email"),type:"email"}),e.jsx(Ld,{label:"Phone",value:v.phone,onChange:L("phone")})]}),e.jsx(Ld,{label:"Current Brokerage",value:v.current_brokerage,onChange:L("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Ld,{label:"License #",value:v.license_number,onChange:L("license_number")}),e.jsx(Ld,{label:"Experience (years)",value:v.experience_years,onChange:L("experience_years"),type:"number"})]}),e.jsx(Ld,{label:"Address",value:v.address,onChange:L("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(Ld,{label:"City",value:v.city,onChange:L("city")}),e.jsx(Ld,{label:"State",value:v.state,onChange:L("state")}),e.jsx(Ld,{label:"Zip",value:v.zip_code,onChange:L("zip_code")})]}),e.jsx(Ld,{label:"Source",value:v.source,onChange:L("source")}),e.jsx(Ld,{label:"Referred By",value:v.referred_by,onChange:L("referred_by")}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Notes"}),e.jsx(Ts,{value:v.notes,onChange:Y=>j(ee=>({...ee,notes:Y.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(ls,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(Ld,{label:"Annual Production",value:v.annual_production,onChange:L("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Ld,{label:"Last Year Volume",value:v.last_year_volume,onChange:L("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(Ld,{label:"Last Year Transactions",value:v.last_year_transactions,onChange:L("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(Ld,{label:"Avg Sale Price",value:v.avg_sale_price,onChange:L("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(Ld,{label:"Specialties / Niche",value:v.specialties,onChange:L("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(ls,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(Ld,{label:"LinkedIn URL",value:v.linkedin_url,onChange:L("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(Ld,{label:"Website URL",value:v.website_url,onChange:L("website_url"),type:"url",placeholder:"https://..."}),e.jsx(Ld,{label:"Instagram Handle",value:v.instagram_handle,onChange:L("instagram_handle"),placeholder:"@handle"}),e.jsx(Ld,{label:"Facebook URL",value:v.facebook_url,onChange:L("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(ls,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(Ld,{label:"Birthday",value:v.birthday,onChange:L("birthday"),type:"date"}),e.jsx(Ld,{label:"Spouse / Partner",value:v.spouse_name,onChange:L("spouse_name")}),e.jsx(Ld,{label:"Interests / Hobbies",value:v.interests,onChange:L("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ls,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(R0,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(R0,{label:"License #",value:s.license_number}),e.jsx(R0,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(R0,{label:"Referred By",value:s.referred_by}),e.jsx(R0,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(ls,{value:"production",className:"mt-3",children:V?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(R0,{label:"Annual Production",value:s.annual_production}),e.jsx(R0,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(R0,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(R0,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(R0,{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(ls,{value:"social",className:"mt-3",children:W?e.jsxs("div",{className:"space-y-2",children:[e.jsx(LG,{label:"LinkedIn",url:s.linkedin_url,icon:bf}),e.jsx(LG,{label:"Website",url:s.website_url,icon:lc}),s.instagram_handle&&e.jsx(LG,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:mu}),e.jsx(LG,{label:"Facebook",url:s.facebook_url,icon:Oh})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(ls,{value:"personal",className:"mt-3",children:K?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(R0,{label:"Birthday",value:s.birthday?ks(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Bi}),e.jsx(R0,{label:"Spouse / Partner",value:s.spouse_name,icon:yi}),e.jsx("div",{className:"col-span-2",children:e.jsx(R0,{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(Gtn,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(cl,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Activity Log"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>f(!p),children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),p&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(us,{value:u.type,onValueChange:Y=>h(ee=>({...ee,type:Y})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:LXe.map(Y=>e.jsx(Ze,{value:Y.value,children:Y.label},Y.value))})]}),e.jsx(ge,{placeholder:"Subject / Title",value:u.title,onChange:Y=>h(ee=>({...ee,title:Y.target.value}))}),e.jsx(Ts,{placeholder:"Details (optional)",value:u.description,onChange:Y=>h(ee=>({...ee,description:Y.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{size:"sm",onClick:M,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const Y=[...o.map(ee=>({type:"manual",data:ee,date:ee.created_at})),...d.map(ee=>({type:"campaign_email",data:ee,date:ee.sent_at||ee.created_at}))].sort((ee,ne)=>new Date(ne.date).getTime()-new Date(ee.date).getTime());return Y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):Y.map(ee=>{if(ee.type==="manual"){const oe=ee.data,pe=LXe.find(de=>de.value===oe.activity_type),ce=(pe==null?void 0:pe.icon)||Nr;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(ce,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:oe.title}),oe.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:oe.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:ks(new Date(oe.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${oe.id}`)}const ne=ee.data;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(cr,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium",children:["Campaign Email #",ne.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ne.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[ne.status==="failed"?e.jsx(ze,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(cr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),ne.opened_at?e.jsxs(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(Ir,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",ks(new Date(ne.opened_at),"MMM d, h:mm a")]}):ne.status!=="failed"?e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,ne.clicked_at&&e.jsxs(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(Fm,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",ks(new Date(ne.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:ks(new Date(ne.sent_at||ne.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${ne.id}`)})})()})]})]})})}),e.jsx(Ktn,{open:_,onOpenChange:S,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const Ztn=["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 mNt({open:s,onOpenChange:t,brokerageId:n,stages:r}){var z;const{toast:a}=Ua(),i=Gt(),l=N.useRef(null),[o,c]=N.useState([]),[d,u]=N.useState([]),[h,p]=N.useState({}),[f,g]=N.useState(((z=r[0])==null?void 0:z.id)||""),[b,v]=N.useState(!1),[j,_]=N.useState("upload"),[S,A]=N.useState(0),T=()=>{c([]),u([]),p({}),_("upload"),A(0)},D=V=>{var Y;const W=(Y=V.target.files)==null?void 0:Y[0];if(!W)return;const K=new FileReader;K.onload=ee=>{var ye;const oe=((ye=ee.target)==null?void 0:ye.result).split(/\r?\n/).filter(_e=>_e.trim());if(oe.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const pe=L(oe[0]);u(pe);const ce={},de=new Set;pe.forEach((_e,Me)=>{const Te=_e.toLowerCase().replace(/[^a-z0-9]/g,"");let Ce=null;/^firstname$/.test(Te)||Te==="first"?Ce="first_name":/^lastname$/.test(Te)||Te==="last"?Ce="last_name":/^email$/.test(Te)||Te==="emailaddress"?Ce="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(Te)?Ce="phone":/officename|currentbrokerage|brokerage|company/.test(Te)?Ce="current_brokerage":/membernumber|licensenumber|license/.test(Te)?Ce="license_number":/experienceyears|yearsexperience/.test(Te)?Ce="experience_years":/^totalvolume$|annualproduction/.test(Te)?Ce="annual_production":/^address$/.test(Te)?Ce="address":/^city$/.test(Te)?Ce="city":/^state$/.test(Te)?Ce="state":/^postalcode$|^zip$|^zipcode$/.test(Te)?Ce="zip_code":/listsidevolume|lastyearvolume/.test(Te)?Ce="last_year_volume":/^totalcount$|lastyeartransactions/.test(Te)?Ce="last_year_transactions":/avgsaleprice|averageprice/.test(Te)?Ce="avg_sale_price":/linkedin/.test(Te)?Ce="linkedin_url":/website/.test(Te)?Ce="website_url":/specialt/.test(Te)?Ce="specialties":/referr/.test(Te)?Ce="referred_by":/^notes$|^note$/.test(Te)&&(Ce="notes"),Ce&&!de.has(Ce)&&(ce[String(Me)]=Ce,de.add(Ce))}),p(ce);const ie=oe.slice(1).map(_e=>{const Me=L(_e),Te={};return pe.forEach((Ce,Ee)=>{Te[String(Ee)]=Me[Ee]||""}),Te});c(ie),_("map")},K.readAsText(W)},L=V=>{const W=[];let K="",Y=!1;for(const ee of V)ee==='"'?Y=!Y:ee===","&&!Y?(W.push(K.trim()),K=""):K+=ee;return W.push(K.trim()),W},M=async()=>{v(!0);try{const{data:{user:V}}=await q.auth.getUser();if(!V)throw new Error("Not authenticated");const W=o.map(Y=>{const ee={brokerage_id:n,created_by:V.id,stage_id:f,source:"csv_import",first_name:"Unknown"},ne=ee;return Object.entries(h).forEach(([oe,pe])=>{var de;const ce=(de=Y[oe])==null?void 0:de.trim();ce&&(pe==="experience_years"||pe==="last_year_transactions"?ne[pe]=parseInt(ce.replace(/[^0-9.-]/g,""))||null:pe==="annual_production"||pe==="last_year_volume"||pe==="avg_sale_price"?ne[pe]=ce.replace(/[^0-9.$,.-]/g,""):ne[pe]=ce)}),ee});let K=0;for(let Y=0;Y{const V=`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`,W=new Blob([V],{type:"text/csv"}),K=URL.createObjectURL(W),Y=document.createElement("a");Y.href=K,Y.download="recruit-prospects-template.csv",Y.click(),URL.revokeObjectURL(K)};return e.jsx(bs,{open:s,onOpenChange:V=>{V||T(),t(V)},children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Import Prospects from CSV"})}),j==="upload"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx(yw,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Upload a CSV file with prospect data"}),e.jsx("input",{ref:l,type:"file",accept:".csv",className:"hidden",onChange:D}),e.jsxs(B,{onClick:()=>{var V;return(V=l.current)==null?void 0:V.click()},children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(B,{variant:"link",className:"text-xs",onClick:F,children:"Download CSV template"})]}),j==="map"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," rows found"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:"Import to stage:"}),e.jsxs(us,{value:f,onValueChange:g,children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{})}),e.jsx(ds,{children:r.map(V=>e.jsx(Ze,{value:V.id,children:V.name},V.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Ct,{className:"w-[160px]",children:"Map To"}),e.jsx(Ct,{children:"Preview"})]})}),e.jsx(pa,{children:d.map((V,W)=>{var K;return e.jsxs(Gs,{children:[e.jsx(ut,{className:"font-medium text-xs",children:V}),e.jsx(ut,{children:e.jsxs(us,{value:h[String(W)]||"skip",onValueChange:Y=>p(ee=>({...ee,[String(W)]:Y==="skip"?"":Y})),children:[e.jsx(cs,{className:"h-8 text-xs",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"skip",children:"— Skip —"}),Ztn.map(Y=>e.jsx(Ze,{value:Y,children:Y.replace(/_/g," ")},Y))]})]})}),e.jsx(ut,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((K=o[0])==null?void 0:K[String(W)])||"—"})]},W)})})]})}),!Object.values(h).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(Gi,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>{T()},children:"Back"}),e.jsx(B,{onClick:M,disabled:b||!Object.values(h).includes("first_name"),children:b?"Importing...":`Import ${o.length} Prospects`})]})]}),j==="done"&&e.jsxs("div",{className:"text-center py-6 space-y-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-green-500/10 flex items-center justify-center mx-auto",children:e.jsx(Lr,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[S," prospects imported successfully!"]}),e.jsx(B,{onClick:()=>{T(),t(!1)},children:"Close"})]})]})})}function pNt({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=XU(s),[o,c]=N.useState(!1),[d,u]=N.useState(),[h,p]=N.useState(null),[f,g]=N.useState(!1),[b,v]=N.useState(!1),[j,_]=N.useState(null);if(r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const S=F=>n.filter(z=>z.stage_id===F),A=(F,z)=>{_(z),F.dataTransfer.effectAllowed="move"},T=F=>{F.preventDefault(),F.dataTransfer.dropEffect="move"},D=(F,z)=>{F.preventDefault(),j&&(i.mutate({id:j,stage_id:z}),_(null))},L=F=>{u(F),c(!0)},M=F=>{p(F),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(B,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(As,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(mi,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(F=>{const z=S(F.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:T,onDrop:V=>D(V,F.id),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:F.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:F.name}),e.jsx(ze,{variant:"secondary",className:"text-xs h-5 px-1.5",children:z.length})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>L(F.id),children:e.jsx(As,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"space-y-2 min-h-[200px] bg-muted/30 rounded-lg p-2",children:z.map(V=>e.jsx(fe,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:F.color},draggable:!0,onDragStart:W=>A(W,V.id),onClick:()=>M(V),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Uu,{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(Xi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[V.first_name," ",V.last_name]})]}),V.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ga,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:V.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[V.email&&e.jsx(Hs,{className:"h-3 w-3 text-muted-foreground"}),V.phone&&e.jsx(Pr,{className:"h-3 w-3 text-muted-foreground"}),V.experience_years!=null&&e.jsxs(ze,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[V.experience_years,"yr"]})]})]})]})},V.id))})]},F.id)})}),e.jsx(cU,{orientation:"horizontal"})]}),e.jsx(oNt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:F=>a.mutate(F),isSubmitting:a.isPending}),e.jsx(hNt,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:F=>{i.mutate(F),p(z=>z?{...z,...F}:null)},onDelete:F=>l.mutate(F)}),e.jsx(mNt,{open:b,onOpenChange:v,brokerageId:s,stages:t})]})}function Xge({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=XU(s),{user:o}=gs(),c=Gt(),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,g]=N.useState(!1),[b,v]=N.useState(!1),[j,_]=N.useState(""),[S,A]=N.useState("all"),[T,D]=N.useState("all"),[L,M]=N.useState("all"),[F,z]=N.useState(null),[V,W]=N.useState("asc"),[K,Y]=N.useState(new Set),[ee,ne]=N.useState(!1),[oe,pe]=N.useState(""),ce=N.useMemo(()=>{const ve=new Set;return n.forEach(Je=>{Je.current_brokerage&&ve.add(Je.current_brokerage)}),Array.from(ve).sort()},[n]),{data:de=[]}=lt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:ve,error:Je}=await q.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Je)throw Je;return ve}}),{data:ie=[]}=lt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Je=[],we=0;for(;;){const{data:it,error:Ne}=await q.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(we,we+1e3-1);if(Ne)throw Ne;if(Je=Je.concat(it??[]),!it||it.length<1e3)break;we+=1e3}return Je}}),ye=N.useMemo(()=>{const ve=new Map;return ie.forEach(Je=>{ve.has(Je.prospect_id)||ve.set(Je.prospect_id,new Set),ve.get(Je.prospect_id).add(Je.campaign_id)}),ve},[ie]),_e=ve=>{F===ve?W(Je=>Je==="asc"?"desc":"asc"):(z(ve),W("asc"))},Me=({column:ve})=>F!==ve?e.jsx(sm,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):V==="asc"?e.jsx(Bu,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(om,{className:"h-3.5 w-3.5 ml-1 text-primary"}),Te=ve=>t.find(Je=>Je.id===ve),Ce=N.useMemo(()=>{let ve=n.filter(Je=>{var $e,Ye,Ke;const we=!j||`${Je.first_name} ${Je.last_name}`.toLowerCase().includes(j.toLowerCase())||(($e=Je.email)==null?void 0:$e.toLowerCase().includes(j.toLowerCase()))||((Ye=Je.current_brokerage)==null?void 0:Ye.toLowerCase().includes(j.toLowerCase())),it=S==="all"||Je.stage_id===S,Ne=T==="all"||Je.current_brokerage===T;let He=!0;return L==="in_campaign"?He=ye.has(Je.id):L==="not_in_campaign"?He=!ye.has(Je.id):L!=="all"&&(He=((Ke=ye.get(Je.id))==null?void 0:Ke.has(L))??!1),we&&it&&Ne&&He});return F&&(ve=[...ve].sort((Je,we)=>{var $e,Ye;let it=null,Ne=null;switch(F){case"name":it=`${Je.first_name} ${Je.last_name||""}`.toLowerCase(),Ne=`${we.first_name} ${we.last_name||""}`.toLowerCase();break;case"stage":it=(($e=Te(Je.stage_id))==null?void 0:$e.sort_order)??999,Ne=((Ye=Te(we.stage_id))==null?void 0:Ye.sort_order)??999;break;case"brokerage":it=(Je.current_brokerage||"").toLowerCase(),Ne=(we.current_brokerage||"").toLowerCase();break;case"experience":it=Je.experience_years??-1,Ne=we.experience_years??-1;break;case"production":it=(Je.annual_production||"").toLowerCase(),Ne=(we.annual_production||"").toLowerCase();break;case"source":it=(Je.source||"").toLowerCase(),Ne=(we.source||"").toLowerCase();break;default:return 0}if(it===Ne)return 0;if(it==null)return 1;if(Ne==null)return-1;const He=it0&&Ce.every(ve=>K.has(ve.id)),De=Ce.some(ve=>K.has(ve.id)),Ie=()=>{Y(Ee?new Set:new Set(Ce.map(ve=>ve.id)))},Fe=ve=>{Y(Je=>{const we=new Set(Je);return we.has(ve)?we.delete(ve):we.add(ve),we})},qe=gt({mutationFn:async()=>{if(!oe||!(o!=null&&o.id))throw new Error("Select a campaign");const ve=new Set(ie.filter(it=>it.campaign_id===oe).map(it=>it.prospect_id)),Je=Array.from(K).filter(it=>!ve.has(it)).map(it=>({prospect_id:it,campaign_id:oe,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Je.length===0)throw new Error("All selected prospects are already in this campaign");const{error:we}=await q.from("recruit_campaign_assignments").insert(Je);if(we)throw we;return Je.length},onSuccess:ve=>{ae.success(`${ve} prospect(s) added to campaign`),ne(!1),Y(new Set),pe(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:ve=>ae.error(ve.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(_r,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search prospects...",value:j,onChange:ve=>_(ve.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[K.size>0&&e.jsxs(B,{variant:"secondary",onClick:()=>ne(!0),className:"gap-1.5",children:[e.jsx(cr,{className:"h-4 w-4"})," Add ",K.size," to Campaign"]}),e.jsxs(B,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>u(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Fv,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(us,{value:S,onValueChange:A,children:[e.jsx(cs,{className:"w-[160px] h-8 text-xs",children:e.jsx(hs,{placeholder:"All stages"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All stages"}),t.map(ve=>e.jsx(Ze,{value:ve.id,children:ve.name},ve.id))]})]}),e.jsxs(us,{value:T,onValueChange:D,children:[e.jsxs(cs,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Ga,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(hs,{placeholder:"All brokerages"})]}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All brokerages"}),ce.map(ve=>e.jsx(Ze,{value:ve,children:ve},ve))]})]}),e.jsxs(us,{value:L,onValueChange:M,children:[e.jsxs(cs,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Hs,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(hs,{placeholder:"Campaign status"})]}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All contacts"}),e.jsx(Ze,{value:"in_campaign",children:"In any campaign"}),e.jsx(Ze,{value:"not_in_campaign",children:"Not in any campaign"}),de.map(ve=>e.jsxs(Ze,{value:ve.id,children:["In: ",ve.name]},ve.id))]})]}),(S!=="all"||T!=="all"||L!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{A("all"),D("all"),M("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{className:"w-[40px]",children:e.jsx(hi,{checked:Ee,onCheckedChange:Ie,"aria-label":"Select all",...De&&!Ee?{"data-state":"indeterminate"}:{}})}),e.jsx(Ct,{className:"cursor-pointer select-none",onClick:()=>_e("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(Me,{column:"name"})]})}),e.jsx(Ct,{className:"cursor-pointer select-none",onClick:()=>_e("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(Me,{column:"stage"})]})}),e.jsx(Ct,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>_e("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(Me,{column:"brokerage"})]})}),e.jsx(Ct,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Ct,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>_e("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(Me,{column:"experience"})]})}),e.jsx(Ct,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>_e("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(Me,{column:"production"})]})}),e.jsx(Ct,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Ct,{className:"w-[50px]"})]})}),e.jsx(pa,{children:Ce.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):Ce.map(ve=>{const Je=Te(ve.stage_id),we=ye.get(ve.id),it=(we==null?void 0:we.size)??0;return e.jsxs(Gs,{className:"cursor-pointer",onClick:()=>{p(ve),g(!0)},children:[e.jsx(ut,{onClick:Ne=>Ne.stopPropagation(),children:e.jsx(hi,{checked:K.has(ve.id),onCheckedChange:()=>Fe(ve.id),"aria-label":`Select ${ve.first_name}`})}),e.jsxs(ut,{className:"font-medium",children:[ve.first_name," ",ve.last_name]}),e.jsx(ut,{children:Je?e.jsxs(ze,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Je.color,color:Je.color,backgroundColor:`${Je.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Je.color}}),Je.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(ut,{className:"hidden md:table-cell",children:ve.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Ga,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:ve.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ut,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ve.email&&e.jsx(Hs,{className:"h-3.5 w-3.5 text-muted-foreground"}),ve.phone&&e.jsx(Pr,{className:"h-3.5 w-3.5 text-muted-foreground"}),!ve.email&&!ve.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(ut,{className:"hidden lg:table-cell",children:ve.experience_years!=null?`${ve.experience_years} yr`:"—"}),e.jsx(ut,{className:"hidden lg:table-cell",children:ve.annual_production||"—"}),e.jsx(ut,{className:"hidden lg:table-cell",children:it>0?e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[it," campaign",it>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(ut,{children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Ne=>{Ne.stopPropagation(),l.mutate(ve.id)},children:e.jsx(bn,{className:"h-3.5 w-3.5"})})})]},ve.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[K.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[K.size," selected · "]}),Ce.length," of ",n.length," prospects"]}),e.jsx(bs,{open:ee,onOpenChange:ne,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{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:K.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Campaign"}),e.jsxs(us,{value:oe,onValueChange:pe,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select a campaign..."})}),e.jsx(ds,{children:de.map(ve=>e.jsxs(Ze,{value:ve.id,children:[ve.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",ve.warmth_level,")"]})]},ve.id))})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>qe.mutate(),disabled:!oe||qe.isPending,children:qe.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(oNt,{open:d,onOpenChange:u,stages:t,onSubmit:ve=>a.mutate(ve),isSubmitting:a.isPending}),e.jsx(hNt,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:ve=>{i.mutate(ve),p(Je=>Je?{...Je,...ve}:null)},onDelete:ve=>l.mutate(ve)}),e.jsx(mNt,{open:b,onOpenChange:v,brokerageId:s,stages:t})]})}function fNt({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=XU(s),a=N.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(j=>j.name==="Signed"),o=t.find(j=>j.name==="Onboarded"),c=n.filter(j=>j.stage_id===(l==null?void 0:l.id)||j.stage_id===(o==null?void 0:o.id)).length,d=i>0?(c/i*100).toFixed(1):"0",u=new Date,h=i>0?Math.round(n.reduce((j,_)=>j+Yv(u,new Date(_.created_at)),0)/i):0,p=t.map(j=>({...j,count:n.filter(_=>_.stage_id===j.id).length})),f={};n.forEach(j=>{const _=j.source||"unknown";f[_]=(f[_]||0)+1});const g=Object.entries(f).sort((j,_)=>_[1]-j[1]),b=new Date;b.setDate(b.getDate()-30);const v=n.filter(j=>new Date(j.created_at)>=b).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:p,bySrc:g,recentCount:v}},[t,n]);return r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsx(Ae,{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(_n,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Prospects"})]})]})})}),e.jsx(fe,{children:e.jsx(Ae,{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(mo,{className:"h-5 w-5 text-green-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.conversionRate,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Conversion Rate"})]})]})})}),e.jsx(fe,{children:e.jsx(Ae,{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(gr,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.avgDays,"d"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Days in Pipeline"})]})]})})}),e.jsx(fe,{children:e.jsx(Ae,{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(wc,{className:"h-5 w-5 text-violet-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.recentCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Added (30 days)"})]})]})})})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Ae,{className:"space-y-3",children:a.byStage.map(i=>{const l=a.total>0?i.count/a.total*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:i.color}}),e.jsx("span",{children:i.name})]}),e.jsx("span",{className:"font-medium",children:i.count})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${l}%`,backgroundColor:i.color}})})]},i.id)})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ae,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ze,{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 Qtn=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function xNt({brokerageId:s}){const{toast:t}=Ua(),{user:n}=gs(),r=Gt(),[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),{data:p=[],isLoading:f}=lt({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:A,error:T}=await q.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(T)throw T;return A}}),g=gt({mutationFn:async A=>{if(A.id){const{error:T}=await q.from("recruit_email_templates").update({category:A.category,title:A.title,subject:A.subject,body:A.body}).eq("id",A.id);if(T)throw T}else{const{error:T}=await q.from("recruit_email_templates").insert({brokerage_id:s,category:A.category||"Outreach",title:A.title,subject:A.subject,body:A.body,created_by:n==null?void 0:n.id,sort_order:100});if(T)throw T}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),h(null)},onError:A=>t({title:"Save failed",description:A.message,variant:"destructive"})}),b=gt({mutationFn:async A=>{const{error:T}=await q.from("recruit_email_templates").delete().eq("id",A);if(T)throw T},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:A=>t({title:"Delete failed",description:A.message,variant:"destructive"})}),v=(A,T)=>{navigator.clipboard.writeText(A),i(T),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},j=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},_=A=>{h(A),d(!0)},S=Array.from(new Set(p.map(A=>A.category)));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-built and custom recruiting templates. Built-in templates are global; your custom ones are private to this brokerage."}),e.jsxs(B,{onClick:j,size:"sm",className:"gap-1.5",children:[e.jsx(As,{className:"h-4 w-4"})," New Template"]})]}),f?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ss,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):S.map(A=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(Hs,{className:"h-4 w-4"})," ",A]}),p.filter(T=>T.category===A).map(T=>{const D=T.brokerage_id!==null;return e.jsxs(fe,{className:`transition-all ${l===T.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(Mt,{className:"pb-2 cursor-pointer",onClick:()=>o(l===T.id?null:T.id),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Pt,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:T.title}),!D&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),D&&e.jsx(ze,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",T.subject]})]}),e.jsx(ze,{variant:"outline",className:"text-[10px] shrink-0",children:T.category})]})}),l===T.id&&e.jsxs(Ae,{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:T.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:T.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>v(T.subject,T.id+"-s"),children:[a===T.id+"-s"?e.jsx(Lr,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ta,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>v(T.body,T.id+"-b"),children:[a===T.id+"-b"?e.jsx(Lr,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ta,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),D&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>_(T),children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&b.mutate(T.id)},children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},T.id)})]},A)),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{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(se,{className:"text-xs",children:"Title"}),e.jsx(ge,{value:(u==null?void 0:u.title)||"",onChange:A=>h(T=>({...T,title:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:A=>h(T=>({...T,category:A.target.value})),className:"mt-1 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:Qtn.map(A=>e.jsx("option",{value:A,children:A},A))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(ge,{value:(u==null?void 0:u.subject)||"",onChange:A=>h(T=>({...T,subject:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Body"}),e.jsx(Ts,{value:(u==null?void 0:u.body)||"",onChange:A=>h(T=>({...T,body:A.target.value})),rows:12,className:"mt-1 font-sans",placeholder:`Hi [First Name], ... Best, [Your Name]`}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Available placeholders: [First Name], [Your Name], [Brokerage Name]"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>g.mutate(u||{}),disabled:g.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[g.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const DXe={call:Pr,email:Hs,text:Ci,meeting:yr,note:Nr};function gNt({brokerageId:s}){const{data:t,isLoading:n}=lt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:r,error:a}=await q.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(r==null?void 0:r.map(f=>f.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await q.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...r.map(f=>f.created_by),...(l||[]).map(f=>f.created_by)])],{data:d}=await q.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(f=>[f.id,f])),h=Y9(new Date,30);return{recruiters:c.map(f=>{var _,S;const g=(l||[]).filter(A=>A.created_by===f),b=g.filter(A=>new Date(A.created_at)>=h),v={};b.forEach(A=>{v[A.activity_type]=(v[A.activity_type]||0)+1});const j=r.filter(A=>A.created_by===f).length;return{id:f,name:((_=u[f])==null?void 0:_.name)||"Unknown",email:((S=u[f])==null?void 0:S.email)||"",totalActivities:g.length,recentActivities:b.length,byType:v,prospectsCreated:j}}).sort((f,g)=>g.recentActivities-f.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Ae,{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(Xi,{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=DXe[i]||Nr;return e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(o,{className:"h-2.5 w-2.5"})," ",l," ",i,l!==1?"s":""]},i)})})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.recentActivities}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"activities"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},r.id))})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Recent Activity"})}),e.jsx(Ae,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=DXe[r.activity_type]||Nr;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:ks(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 yNt({brokerageId:s}){const{toast:t}=Ua(),n=Gt(),[r,a]=N.useState(!1),[i,l]=N.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=lt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:v,error:j}=await q.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(j)throw j;return v}}),d=[...new Set(o.map(v=>v.referred_by))],{data:u=[]}=lt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:v}=await q.from("profiles").select("id, name, email").in("id",d);return v||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(v=>[v.id,v])),p=gt({mutationFn:async v=>{const{data:{user:j}}=await q.auth.getUser();if(!j)throw new Error("Not authenticated");const{error:_}=await q.from("recruit_referrals").insert({brokerage_id:s,referred_by:j.id,referee_first_name:v.first_name,referee_last_name:v.last_name||null,referee_email:v.email||null,referee_phone:v.phone||null,referee_current_brokerage:v.current_brokerage||null,notes:v.notes||null});if(_)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:v=>t({title:"Error",description:v.message,variant:"destructive"})}),f=gt({mutationFn:async({id:v,status:j,incentive_status:_})=>{const S={updated_at:new Date().toISOString()};j&&(S.status=j),_&&(S.incentive_status=_);const{error:A}=await q.from("recruit_referrals").update(S).eq("id",v);if(A)throw A},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),g=v=>v==="approved"||v==="signed"?e.jsx(Lr,{className:"h-3 w-3"}):v==="rejected"?e.jsx(Gc,{className:"h-3 w-3"}):e.jsx(gr,{className:"h-3 w-3"}),b=v=>v==="approved"||v==="signed"||v==="paid"?"bg-green-500/10 text-green-600 border-green-200":v==="rejected"?"bg-red-500/10 text-red-600 border-red-200":"bg-amber-500/10 text-amber-600 border-amber-200";return c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," referral",o.length!==1?"s":""]}),e.jsxs(B,{onClick:()=>a(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(fe,{className:"py-12 text-center",children:[e.jsx(Fo,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No referrals yet. Agents can refer potential recruits here."})]}):e.jsx("div",{className:"space-y-3",children:o.map(v=>{var j;return e.jsx(fe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium",children:[v.referee_first_name," ",v.referee_last_name]}),e.jsxs(ze,{variant:"outline",className:b(v.status),children:[g(v.status)," ",v.status]}),v.incentive_status&&e.jsxs(ze,{variant:"outline",className:b(v.incentive_status),children:[e.jsx(Bi,{className:"h-3 w-3 mr-1"})," ",v.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[v.referee_email&&e.jsx("p",{children:v.referee_email}),v.referee_phone&&e.jsx("p",{children:v.referee_phone}),v.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",v.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((j=h[v.referred_by])==null?void 0:j.name)||"Unknown"," • ",ks(new Date(v.created_at),"MMM d, yyyy")]})]}),v.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:v.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(us,{value:v.status,onValueChange:_=>f.mutate({id:v.id,status:_}),children:[e.jsx(cs,{className:"h-7 text-xs w-[110px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"pending",children:"Pending"}),e.jsx(Ze,{value:"contacted",children:"Contacted"}),e.jsx(Ze,{value:"approved",children:"Approved"}),e.jsx(Ze,{value:"signed",children:"Signed"}),e.jsx(Ze,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(us,{value:v.incentive_status||"pending",onValueChange:_=>f.mutate({id:v.id,incentive_status:_}),children:[e.jsx(cs,{className:"h-7 text-xs w-[100px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"pending",children:"Unpaid"}),e.jsx(Ze,{value:"paid",children:"Paid"}),e.jsx(Ze,{value:"n/a",children:"N/A"})]})]})]})]})},v.id)})}),e.jsx(bs,{open:r,onOpenChange:a,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:v=>{v.preventDefault(),p.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"First Name *"}),e.jsx(ge,{required:!0,value:i.first_name,onChange:v=>l(j=>({...j,first_name:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last Name"}),e.jsx(ge,{value:i.last_name,onChange:v=>l(j=>({...j,last_name:v.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ge,{type:"email",value:i.email,onChange:v=>l(j=>({...j,email:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ge,{value:i.phone,onChange:v=>l(j=>({...j,phone:v.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Current Brokerage"}),e.jsx(ge,{value:i.current_brokerage,onChange:v=>l(j=>({...j,current_brokerage:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ts,{value:i.notes,onChange:v=>l(j=>({...j,notes:v.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:p.isPending,children:"Submit"})]})]})]})})]})}function vNt({brokerageId:s}){const{toast:t}=Ua(),n=Gt(),[r,a]=N.useState(!1),{data:i}=lt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:p,error:f}=await q.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(f)throw f;return p}}),{data:l=[]}=lt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:p,error:f}=await q.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(f)throw f;return p}}),o=gt({mutationFn:async p=>{const{error:f}=await q.from("brokerages").update({recruit_form_enabled:p}).eq("id",s);if(f)throw f},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=gt({mutationFn:async({id:p,status:f})=>{const{error:g}=await q.from("recruit_interest_submissions").update({status:f}).eq("id",p);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=p=>p==="contacted"||p==="converted"?"bg-green-500/10 text-green-600":p==="dismissed"?"bg-red-500/10 text-red-600":"bg-blue-500/10 text-blue-600";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(vn,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:p=>o.mutate(p)})]}),(i==null?void 0:i.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg",children:[e.jsx("code",{className:"text-xs flex-1 truncate",children:d}),e.jsx(B,{size:"sm",variant:"outline",onClick:u,children:r?e.jsx(Lr,{className:"h-3.5 w-3.5"}):e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Ae,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Fo,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No submissions yet"})]}):e.jsx("div",{className:"space-y-3",children:l.map(p=>e.jsxs("div",{className:"flex items-start justify-between gap-4 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium text-sm",children:[p.first_name," ",p.last_name]}),e.jsx(ze,{variant:"outline",className:h(p.status),children:p.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[p.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hs,{className:"h-3 w-3"}),p.email]}),p.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pr,{className:"h-3 w-3"}),p.phone]}),p.current_brokerage&&e.jsxs("span",{children:["From: ",p.current_brokerage]}),p.experience_years&&e.jsxs("span",{children:[p.experience_years,"yr exp"]})]}),p.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',p.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:ks(new Date(p.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(us,{value:p.status,onValueChange:f=>c.mutate({id:p.id,status:f}),children:[e.jsx(cs,{className:"h-7 text-xs w-[110px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"new",children:"New"}),e.jsx(Ze,{value:"contacted",children:"Contacted"}),e.jsx(Ze,{value:"converted",children:"Converted"}),e.jsx(Ze,{value:"dismissed",children:"Dismissed"})]})]})]},p.id))})})]})]})}function bNt({brokerageId:s}){const{toast:t}=Ua(),n=Gt(),[r,a]=N.useState(!1),[i,l]=N.useState({prospect_id:"",title:"",description:"",due_date:ks(Ul(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=N.useState("pending"),{data:d=[]}=lt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:T,error:D}=await q.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(D)throw D;return T}}),{data:u=[],isLoading:h}=lt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const T=d.map(M=>M.id);if(!T.length)return[];const{data:D,error:L}=await q.from("recruit_follow_ups").select("*").in("prospect_id",T).order("due_date");if(L)throw L;return D},enabled:d.length>0}),p=Object.fromEntries(d.map(T=>[T.id,T])),f=gt({mutationFn:async T=>{const{data:{user:D}}=await q.auth.getUser();if(!D)throw new Error("Not authenticated");const{error:L}=await q.from("recruit_follow_ups").insert({prospect_id:T.prospect_id,assigned_to:D.id,title:T.title,description:T.description||null,due_date:new Date(T.due_date).toISOString()});if(L)throw L},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:ks(Ul(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:T=>t({title:"Error",description:T.message,variant:"destructive"})}),g=gt({mutationFn:async({id:T,completed:D})=>{const{error:L}=await q.from("recruit_follow_ups").update({completed_at:D?new Date().toISOString():null}).eq("id",T);if(L)throw L},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),b=u.filter(T=>o==="pending"?!T.completed_at:o==="completed"?!!T.completed_at:!0),v=b.filter(T=>!T.completed_at&&jw(new Date(T.due_date))&&!df(new Date(T.due_date))),j=b.filter(T=>!T.completed_at&&df(new Date(T.due_date))),_=b.filter(T=>!T.completed_at&&!jw(new Date(T.due_date))&&!df(new Date(T.due_date))),S=b.filter(T=>!!T.completed_at),A=T=>{const D=p[T.prospect_id],L=!T.completed_at&&jw(new Date(T.due_date))&&!df(new Date(T.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(hi,{checked:!!T.completed_at,onCheckedChange:M=>g.mutate({id:T.id,completed:M}),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${T.completed_at?"line-through text-muted-foreground":""}`,children:T.title}),T.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:T.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[D&&e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:[D.first_name," ",D.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${L?"text-destructive font-medium":""}`,children:[L?e.jsx(Gi,{className:"h-3 w-3"}):e.jsx(yr,{className:"h-3 w-3"}),ks(new Date(T.due_date),"MMM d, h:mm a")]}),T.is_automated&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},T.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(T=>e.jsxs(B,{size:"sm",variant:o===T?"default":"outline",onClick:()=>c(T),className:"capitalize text-xs",children:[T," ",T==="pending"&&v.length+j.length+_.length>0&&`(${v.length+j.length+_.length})`]},T))}),e.jsxs(B,{size:"sm",onClick:()=>a(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&v.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-destructive flex items-center gap-1",children:[e.jsx(Gi,{className:"h-3.5 w-3.5"})," Overdue (",v.length,")"]}),v.map(A)]}),o!=="completed"&&j.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-amber-600 flex items-center gap-1",children:[e.jsx(gr,{className:"h-3.5 w-3.5"})," Today (",j.length,")"]}),j.map(A)]}),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(yr,{className:"h-3.5 w-3.5"})," Upcoming (",_.length,")"]}),_.map(A)]}),o!=="pending"&&S.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(Lr,{className:"h-3.5 w-3.5"})," Completed (",S.length,")"]}),S.map(A)]}),b.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(bs,{open:r,onOpenChange:a,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:T=>{T.preventDefault(),f.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{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:T=>l(D=>({...D,prospect_id:T.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(T=>e.jsxs("option",{value:T.id,children:[T.first_name," ",T.last_name]},T.id))]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Task *"}),e.jsx(ge,{required:!0,value:i.title,onChange:T=>l(D=>({...D,title:T.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Details"}),e.jsx(Ts,{value:i.description,onChange:T=>l(D=>({...D,description:T.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due Date *"}),e.jsx(ge,{type:"datetime-local",required:!0,value:i.due_date,onChange:T=>l(D=>({...D,due_date:T.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:f.isPending,children:"Schedule"})]})]})]})})]})}const Xtn=[{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 _Nt({brokerageId:s}){const{toast:t}=Ua(),n=Gt(),[r,a]=N.useState(null),{data:i,isLoading:l}=lt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:v,error:j}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(j)throw j;return v}}),[o,c]=N.useState({brokerage_id:s,hero_headline:"Join Our Team",hero_subtext:"Take your real estate career to the next level.",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",benefits:Xtn,testimonials:[],gallery_images:[],calculator_enabled:!1,calculator_config:{headline:"See What You Could Earn With Us",subtext:"Confidential 60-second calculator — no signup required.",commission_split_pct:80,cap_amount:16e3,post_cap_split_pct:100,monthly_fee:99,transaction_fee:0,show_email_capture:!0,email_capture_label:"Want the full breakdown? Enter your email."},lead_magnet_enabled:!1,lead_magnet_config:{title:"Get the Full Comp Plan PDF",description:"See exactly how splits, caps, and fees work — no call required.",button_text:"Email Me the PDF",pdf_url:null},form_style:"classic",confidential_messaging:!0});N.useEffect(()=>{i&&c({id:i.id,brokerage_id:i.brokerage_id,hero_headline:i.hero_headline,hero_subtext:i.hero_subtext||"",hero_image_url:i.hero_image_url,logo_url:i.logo_url,primary_color:i.primary_color,accent_color:i.accent_color,benefits:i.benefits||[],testimonials:i.testimonials||[],gallery_images:i.gallery_images||[],calculator_enabled:i.calculator_enabled??!1,calculator_config:i.calculator_config||{},lead_magnet_enabled:i.lead_magnet_enabled??!1,lead_magnet_config:i.lead_magnet_config||{},form_style:i.form_style||"classic",confidential_messaging:i.confidential_messaging??!0})},[i]);const d=gt({mutationFn:async()=>{const v={brokerage_id:s,hero_headline:o.hero_headline,hero_subtext:o.hero_subtext,hero_image_url:o.hero_image_url,logo_url:o.logo_url,primary_color:o.primary_color,accent_color:o.accent_color,benefits:JSON.parse(JSON.stringify(o.benefits)),testimonials:JSON.parse(JSON.stringify(o.testimonials)),gallery_images:JSON.parse(JSON.stringify(o.gallery_images)),calculator_enabled:o.calculator_enabled,calculator_config:JSON.parse(JSON.stringify(o.calculator_config)),lead_magnet_enabled:o.lead_magnet_enabled,lead_magnet_config:JSON.parse(JSON.stringify(o.lead_magnet_config)),form_style:o.form_style,confidential_messaging:o.confidential_messaging,updated_at:new Date().toISOString()};if(o.id){const{error:j}=await q.from("recruit_landing_page_settings").update(v).eq("id",o.id);if(j)throw j}else{const{error:j}=await q.from("recruit_landing_page_settings").insert(v);if(j)throw j}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:v=>t({title:"Error",description:v.message,variant:"destructive"})}),u=async(v,j)=>{const _=v.name.split(".").pop(),S=`${s}/${j}-${Date.now()}.${_}`,{error:A}=await q.storage.from("recruit-landing").upload(S,v);if(A)throw A;const{data:{publicUrl:T}}=q.storage.from("recruit-landing").getPublicUrl(S);return T},h=async(v,j)=>{var S;const _=(S=v.target.files)==null?void 0:S[0];if(_){a(j);try{const A=await u(_,j);c(T=>({...T,[j]:A})),t({title:"Image uploaded!"})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},p=async v=>{var _;const j=(_=v.target.files)==null?void 0:_[0];if(j){a("gallery");try{const S=await u(j,"gallery");c(A=>({...A,gallery_images:[...A.gallery_images,S]})),t({title:"Gallery image added!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},f=async(v,j)=>{var S;const _=(S=v.target.files)==null?void 0:S[0];if(_){a(`testimonial-${j}`);try{const A=await u(_,`testimonial-${j}`);c(T=>{const D=[...T.testimonials];return D[j]={...D[j],photo_url:A},{...T,testimonials:D}})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},{data:g}=lt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:v,error:j}=await q.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(j)throw j;return v}}),b=`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:b}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:b,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Branding"})}),e.jsx(Ae,{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(se,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.logo_url&&e.jsx("img",{src:o.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="logo_url",children:e.jsxs("span",{children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),r==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:v=>h(v,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.primary_color,onChange:v=>c(j=>({...j,primary_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ge,{value:o.primary_color,onChange:v=>c(j=>({...j,primary_color:v.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.accent_color,onChange:v=>c(j=>({...j,accent_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ge,{value:o.accent_color,onChange:v=>c(j=>({...j,accent_color:v.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(ge,{value:o.hero_headline,onChange:v=>c(j=>({...j,hero_headline:v.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Subtext"}),e.jsx(Ts,{value:o.hero_subtext,onChange:v=>c(j=>({...j,hero_subtext:v.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Background Image"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.hero_image_url&&e.jsx("img",{src:o.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),r==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:v=>h(v,"hero_image_url")})]}),o.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(v=>({...v,hero_image_url:null})),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Pt,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,benefits:[...v.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Ae,{className:"space-y-3",children:[o.benefits.map((v,j)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Uu,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(ge,{value:v.icon,onChange:_=>{const S=[...o.benefits];S[j]={...v,icon:_.target.value},c(A=>({...A,benefits:S}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ge,{value:v.title,onChange:_=>{const S=[...o.benefits];S[j]={...v,title:_.target.value},c(A=>({...A,benefits:S}))},placeholder:"Benefit title"}),e.jsx(ge,{value:v.description,onChange:_=>{const S=[...o.benefits];S[j]={...v,description:_.target.value},c(A=>({...A,benefits:S}))},placeholder:"Short description"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(_=>({..._,benefits:_.benefits.filter((S,A)=>A!==j)})),children:e.jsx(bn,{className:"h-3.5 w-3.5 text-destructive"})})]},j)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Pt,{className:"text-base",children:"Testimonials"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,testimonials:[...v.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Ae,{className:"space-y-3",children:[o.testimonials.map((v,j)=>{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:[v.photo_url?e.jsx("img",{src:v.photo_url,alt:v.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center text-xs text-muted-foreground",children:((_=v.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-${j}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:S=>f(S,j)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ge,{value:v.name,onChange:S=>{const A=[...o.testimonials];A[j]={...v,name:S.target.value},c(T=>({...T,testimonials:A}))},placeholder:"Name"}),e.jsx(ge,{value:v.role,onChange:S=>{const A=[...o.testimonials];A[j]={...v,role:S.target.value},c(T=>({...T,testimonials:A}))},placeholder:"Role / Title"})]}),e.jsx(Ts,{value:v.quote,onChange:S=>{const A=[...o.testimonials];A[j]={...v,quote:S.target.value},c(T=>({...T,testimonials:A}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(S=>({...S,testimonials:S.testimonials.filter((A,T)=>T!==j)})),children:e.jsx(bn,{className:"h-3.5 w-3.5 text-destructive"})})]},j)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Pt,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{size:"sm",variant:"outline",asChild:!0,disabled:r==="gallery",children:e.jsxs("span",{children:[e.jsx(nl,{className:"h-3.5 w-3.5 mr-1"}),r==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p})]})]}),e.jsx(Ae,{children:o.gallery_images.length>0?e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:o.gallery_images.map((v,j)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:v,alt:`Gallery ${j+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx(B,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>c(_=>({..._,gallery_images:_.gallery_images.filter((S,A)=>A!==j)})),children:e.jsx(bn,{className:"h-3 w-3"})})]},j))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Application Form Style"}),e.jsxs(us,{value:o.form_style,onValueChange:v=>c(j=>({...j,form_style:v})),children:[e.jsx(cs,{className:"mt-1.5",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(Ze,{value:"multi_step",children:"Multi-Step Wizard — 3-step soft CTA (recommended)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:"Multi-step wizards convert ~30% better than single long forms."})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Rc,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(se,{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(vn,{checked:o.confidential_messaging,onCheckedChange:v=>c(j=>({...j,confidential_messaging:v}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(xw,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(vn,{checked:o.calculator_enabled,onCheckedChange:v=>c(j=>({...j,calculator_enabled:v}))})]}),o.calculator_enabled&&e.jsxs(Ae,{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(se,{className:"text-xs",children:"Calculator Headline"}),e.jsx(ge,{value:o.calculator_config.headline||"",onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,headline:v.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subtext"}),e.jsx(ge,{value:o.calculator_config.subtext||"",onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,subtext:v.target.value}})),placeholder:"Confidential 60-second calculator"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(ge,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,commission_split_pct:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 80 for an 80/20"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(ge,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,cap_amount:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Annual cap to brokerage"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(ge,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,post_cap_split_pct:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 95 for 95/5 after cap, 100 for 100%"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(ge,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,monthly_fee:parseFloat(v.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(ge,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,transaction_fee:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Multiplied by # of transactions"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx(se,{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(vn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,show_email_capture:v}}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(TA,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(vn,{checked:o.lead_magnet_enabled,onCheckedChange:v=>c(j=>({...j,lead_magnet_enabled:v}))})]}),o.lead_magnet_enabled&&e.jsxs(Ae,{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(se,{className:"text-xs",children:"Title"}),e.jsx(ge,{value:o.lead_magnet_config.title||"",onChange:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,title:v.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Description"}),e.jsx(Ts,{rows:2,value:o.lead_magnet_config.description||"",onChange:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,description:v.target.value}})),placeholder:"See exactly how splits, caps, and fees work..."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Button Text"}),e.jsx(ge,{value:o.lead_magnet_config.button_text||"",onChange:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,button_text:v.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ge,{value:o.lead_magnet_config.pdf_url||"",onChange:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,pdf_url:v.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),r==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async v=>{var _;const j=(_=v.target.files)==null?void 0:_[0];if(j){a("lead_magnet_pdf");try{const S=await u(j,"lead-magnet");c(A=>({...A,lead_magnet_config:{...A.lead_magnet_config,pdf_url:S}})),t({title:"PDF uploaded!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(Jtn,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function Jtn({brokerageId:s}){const{data:t=[]}=lt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:n,error:r}=await q.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n}});return t.length===0?null:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Ae,{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:[ks(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function wNt({brokerageId:s,trigger:t,initialProspectId:n,open:r,onOpenChange:a}){const[i,l]=N.useState(!1),o=r??i,c=a??l,[d,u]=N.useState("pick-recipients"),[h,p]=N.useState(new Set(n?[n]:[])),[f,g]=N.useState("all"),[b,v]=N.useState(""),[j,_]=N.useState(null),[S,A]=N.useState(""),[T,D]=N.useState(0),[L,M]=N.useState(0),[F,z]=N.useState(""),[V,W]=N.useState(""),{data:K}=ube(),[Y,ee]=N.useState("default");N.useEffect(()=>{ee(K!=null&&K.massEmail?"mass_email":K!=null&&K.gmail?"gmail":"default")},[K==null?void 0:K.massEmail,K==null?void 0:K.gmail]);const[ne,oe]=N.useState(null),{prospects:pe,stages:ce}=XU(s),de=cNt(),ie=PN(),{data:ye=[]}=lt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:ve,error:Je}=await q.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id, share_token").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Je)throw Je;return ve??[]},enabled:o&&d==="pick-video"}),_e=N.useCallback(()=>{u("pick-recipients"),p(new Set(n?[n]:[])),g("all"),v(""),_(null),A(""),D(0),M(0),z(""),W(""),ee("default"),oe(null)},[n]),Me=ve=>{!ve&&(d==="uploading"||d==="processing"||d==="sending")||(c(ve),ve||setTimeout(_e,200))},Te=N.useMemo(()=>pe.filter(ve=>{if(!ve.email||f!=="all"&&ve.stage_id!==f)return!1;if(b){const Je=b.toLowerCase();if(!`${ve.first_name} ${ve.last_name??""}`.toLowerCase().includes(Je)&&!ve.email.toLowerCase().includes(Je))return!1}return!0}),[pe,f,b]),Ce=ve=>{p(Je=>{const we=new Set(Je);return we.has(ve)?we.delete(ve):we.add(ve),we})},Ee=()=>{h.size===Te.length?p(new Set):p(new Set(Te.map(ve=>ve.id)))},De=N.useCallback(async(ve,Je)=>{u("uploading");try{const we=`Recruiting blast (${h.size} recipients)`,{videoId:it,libraryId:Ne}=await l6(we),{uploadUrl:He,apiKey:$e}=await c6(it),Ye=new XMLHttpRequest;Ye.upload.onprogress=kt=>{kt.lengthComputable&&D(kt.loaded/kt.total*100)},await new Promise((kt,Qt)=>{Ye.onload=()=>Ye.status>=200&&Ye.status<300?kt():Qt(new Error("Upload failed")),Ye.onerror=()=>Qt(new Error("Upload failed")),Ye.open("PUT",He),Ye.setRequestHeader("AccessKey",$e),Ye.send(ve)}),u("processing");const Ke=`https://iframe.mediadelivery.net/embed/${Ne}/${it}`;let rt=0;const tt=Date.now(),at=9e4;for(;rt<4&&(await new Promise(Qt=>setTimeout(Qt,3e3)),!(Date.now()-tt>at));){const kt=await Uw(it);if(rt=kt.status,M(kt.encodeProgress||0),rt===5||rt===6)throw new Error("Video processing failed")}const Ge=await Uw(it),dt=(Ge.storageSize||ve.size)/(1024*1024),Bt=await ie.mutateAsync({bunny_video_id:it,playback_url:Ge.directPlayUrl||Ke,thumbnail_url:Ge.thumbnailUrl,preview_url:Ge.previewUrl||null,duration_seconds:Ge.length||Je,file_size_mb:dt,title:we,status:rt>=4?"ready":"processing",touch_type:"recruiting"});_(Bt.id),A(we),u("compose")}catch(we){ae.error((we==null?void 0:we.message)||"Failed to upload video"),u("pick-video")}},[h.size,ie]),Ie=N.useCallback(async()=>{if(!(!j||h.size===0)){u("sending");try{const ve=[];for(const it of h){const Ne=await de.mutateAsync({prospect_id:it,video_id:j,brokerage_id:s,message:V||void 0});ve.push(Ne.id)}const{data:Je,error:we}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:ve,brokerage_id:s,subject_override:F||void 0,message_override:V||void 0,send_via:Y}});if(we)throw new Error(we.message);oe({sent:(Je==null?void 0:Je.sent)??0,total:(Je==null?void 0:Je.total)??ve.length}),u("done"),ae.success(`Sent ${(Je==null?void 0:Je.sent)??0} of ${(Je==null?void 0:Je.total)??ve.length} videos`)}catch(ve){ae.error((ve==null?void 0:ve.message)||"Failed to send"),u("compose")}}},[j,h,s,V,F,Y,de]),Fe=h.size,qe=pe.filter(ve=>!ve.email).length;return e.jsxs(bs,{open:o,onOpenChange:Me,children:[t&&e.jsx(Di,{asChild:!0,children:t}),e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Fe>0&&e.jsxs(ze,{variant:"secondary",className:"ml-2",children:[e.jsx(_n,{className:"h-3 w-3 mr-1"}),Fe," ",Fe===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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search prospects...",value:b,onChange:ve=>v(ve.target.value),className:"pl-9"})]}),e.jsxs(us,{value:f,onValueChange:g,children:[e.jsx(cs,{className:"w-48",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All stages"}),ce.map(ve=>e.jsx(Ze,{value:ve.id,children:ve.name},ve.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:Ee,className:"hover:underline",children:[h.size===Te.length&&Te.length>0?"Deselect all":"Select all"," ","(",Te.length,")"]}),qe>0&&e.jsxs("span",{children:[qe," prospect(s) hidden — no email on file"]})]}),e.jsx(mi,{className:"flex-1 border rounded-md",children:Te.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:Te.map(ve=>{const Je=h.has(ve.id),we=ce.find(it=>it.id===ve.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(hi,{checked:Je,onCheckedChange:()=>Ce(ve.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[ve.first_name," ",ve.last_name]}),we&&e.jsx(ze,{variant:"outline",className:"text-[10px]",style:{borderColor:we.color,color:we.color},children:we.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ve.email," ",ve.current_brokerage&&`· ${ve.current_brokerage}`]})]})]},ve.id)})})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Me(!1),children:"Cancel"}),e.jsx(B,{disabled:Fe===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($r,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Ur,{className:"self-start",children:[e.jsxs(Zt,{value:"record",children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Zt,{value:"library",children:[e.jsx(Wg,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(ls,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(Ph,{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 ",Fe," ",Fe===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(B,{onClick:()=>u("record"),children:[e.jsx(vr,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(ls,{value:"library",className:"flex-1 overflow-auto",children:ye.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:ye.map(ve=>e.jsxs("button",{onClick:()=>{_(ve.id),A(ve.title||"Untitled"),u("compose")},className:"text-left group rounded-md border overflow-hidden hover:border-primary transition-colors",children:[e.jsx("div",{className:"aspect-video bg-muted relative",children:cw(ve)?e.jsx("img",{src:cw(ve),alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(vr,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsx("div",{className:"p-2",children:e.jsx("p",{className:"text-xs font-medium truncate",children:ve.title||"Untitled"})})]},ve.id))})})]}),e.jsx(Xn,{children:e.jsx(B,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(m6,{maxDurationSeconds:600,onRecordingComplete:De}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>u("pick-video"),children:"← Back"})})]}),(d==="uploading"||d==="processing")&&e.jsxs("div",{className:"py-12 space-y-4 text-center",children:[e.jsx(ss,{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(xi,{value:d==="uploading"?T:L,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?T:L),"%"]})]}),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(xr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:S})," selected · sending to ",e.jsx("strong",{children:Fe})," recipient",Fe===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(ge,{value:F,onChange:ve=>z(ve.target.value),placeholder:"[First Name], I made you a quick video 🎥",className:"mt-1"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Leave blank to use the default personalized subject."})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Ts,{value:V,onChange:ve=>W(ve.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(I8e,{value:Y,onChange:ee}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs(B,{onClick:Ie,disabled:!j||Fe===0,children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send to ",Fe," ",Fe===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(ss,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Fe," recipient",Fe===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&ne&&e.jsxs("div",{className:"py-12 text-center space-y-4",children:[e.jsx("div",{className:`h-16 w-16 rounded-full mx-auto flex items-center justify-center ${ne.sent===ne.total?"bg-primary/10":"bg-muted"}`,children:ne.sent===ne.total?e.jsx(xr,{className:"h-8 w-8 text-primary"}):e.jsx(Gi,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[ne.sent," of ",ne.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx(B,{onClick:()=>Me(!1),children:"Done"})]})]})]})}function esn(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function tsn({video:s}){return s.cta_clicked_at?e.jsx(ze,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(ze,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(ze,{variant:"secondary",children:[e.jsx(cr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(ze,{variant:"outline",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"}),"Draft"]})}function jNt({brokerageId:s}){var S,A,T,D;const{data:t=[],isLoading:n}=Utn(s),{data:r=[]}=uNt(s),a=Vtn(),i=Htn(),l=dNt(),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,p]=N.useState({title:"",script_text:"",category:"general"}),[f,g]=N.useState(null),b=t.filter(L=>{var F,z,V,W;return o?`${((F=L.prospect)==null?void 0:F.first_name)||""} ${((z=L.prospect)==null?void 0:z.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((W=(V=L.video)==null?void 0:V.title)==null?void 0:W.toLowerCase().includes(o.toLowerCase())):!0}),v={total:t.length,sent:t.filter(L=>L.sent_at).length,viewed:t.filter(L=>L.view_count>0).length,ctaClicked:t.filter(L=>L.cta_clicked_at).length},j=N.useCallback(L=>{if(!L)return;const M=`${window.location.origin}/recruit-video/${L}`;navigator.clipboard.writeText(M),ae.success("Share link copied")},[]);N.useCallback((L,M)=>{l.mutate({id:L,sent_via:M})},[l]);const _=()=>{!h.title.trim()||!h.script_text.trim()||a.mutate({brokerage_id:s,...h},{onSuccess:()=>{p({title:"",script_text:"",category:"general"}),u(!1)}})};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Total Videos",value:v.total,icon:vr,color:"text-primary"},{label:"Sent",value:v.sent,icon:cr,color:"text-blue-500"},{label:"Viewed",value:v.viewed,icon:Ir,color:"text-amber-500"},{label:"CTA Clicked",value:v.ctaClicked,icon:xr,color:"text-emerald-500"}].map(L=>e.jsx(fe,{children:e.jsxs(Ae,{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 ${L.color}`,children:e.jsx(L.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:L.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:L.label})]})]})},L.label))}),e.jsxs($r,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"videos",children:[e.jsx(vr,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Zt,{value:"scripts",children:[e.jsx(Nr,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Zt,{value:"analytics",children:[e.jsx(yo,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(ls,{value:"videos",children:e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Pt,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name or title...",value:o,onChange:L=>c(L.target.value),className:"pl-9"})]}),e.jsx(wNt,{brokerageId:s,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(Hs,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Ae,{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"})}):b.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(vr,{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:b.map(L=>{var M,F,z,V,W,K,Y;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:[cw(L.video)?e.jsx("img",{src:cw(L.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(vr,{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:esn(((M=L.video)==null?void 0:M.duration_seconds)??null)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium truncate",children:[(F=L.prospect)==null?void 0:F.first_name," ",(z=L.prospect)==null?void 0:z.last_name]}),e.jsx(tsn,{video:L})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((V=L.video)==null?void 0:V.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[ks(new Date(L.created_at),"MMM d, yyyy"),((W=L.prospect)==null?void 0:W.current_brokerage)&&` · ${L.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>j(L.share_token),title:"Copy share link",children:e.jsx(ta,{className:"h-4 w-4"})}),e.jsxs(B,{variant:L.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>g(L),disabled:!((K=L.prospect)!=null&&K.email),title:(Y=L.prospect)!=null&&Y.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(Hs,{className:"h-4 w-4"}),L.sent_at?"Resend":"Email"]}),L.share_token&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${L.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(tr,{className:"h-4 w-4"})})]})]},L.id)})})})]})}),e.jsx(ls,{value:"scripts",children:e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Pt,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(bs,{open:d,onOpenChange:u,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ge,{value:h.title,onChange:L=>p(M=>({...M,title:L.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(us,{value:h.category,onValueChange:L=>p(M=>({...M,category:L})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:ITe.map(L=>e.jsx(Ze,{value:L.value,children:L.label},L.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Script"}),e.jsx(Ts,{value:h.script_text,onChange:L=>p(M=>({...M,script_text:L.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx(B,{onClick:_,disabled:!h.title.trim()||!h.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Ae,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Nr,{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(L=>{var F;const M=((F=ITe.find(z=>z.value===L.category))==null?void 0:F.label)||L.category;return e.jsx(fe,{className:"relative group",children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(ze,{variant:"outline",className:"text-[10px] mb-2",children:M}),e.jsx("h4",{className:"font-medium text-sm",children:L.title})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(L.id),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:L.script_text}),L.is_global&&e.jsx(ze,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},L.id)})})})]})}),e.jsx(ls,{value:"analytics",children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Ae,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:v.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:v.sent,pct:v.total?Math.round(v.sent/v.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:v.viewed,pct:v.sent?Math.round(v.viewed/v.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:v.ctaClicked,pct:v.viewed?Math.round(v.ctaClicked/v.viewed*100):0,color:"bg-emerald-500"}].map(L=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:L.label}),e.jsxs("span",{className:"font-medium",children:[L.count," (",L.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${L.color} rounded-full transition-all`,style:{width:`${L.pct}%`}})})]},L.label))}),t.filter(L=>L.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(L=>L.view_count>0).sort((L,M)=>M.view_count-L.view_count).slice(0,5).map(L=>{var M,F;return e.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded-md bg-muted/30",children:[e.jsxs("span",{className:"font-medium",children:[(M=L.prospect)==null?void 0:M.first_name," ",(F=L.prospect)==null?void 0:F.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ir,{className:"h-3.5 w-3.5"})," ",L.view_count]}),L.cta_clicked_at&&e.jsx(xr,{className:"h-4 w-4 text-emerald-500"})]})]},L.id)})})]})]})]})})]}),f&&e.jsx(lNt,{open:!!f,onOpenChange:L=>{L||g(null)},recruitVideoId:f.id,brokerageId:s,prospectName:`${((S=f.prospect)==null?void 0:S.first_name)||""} ${((A=f.prospect)==null?void 0:A.last_name)||""}`.trim(),prospectEmail:(T=f.prospect)==null?void 0:T.email,videoTitle:(D=f.video)==null?void 0:D.title,defaultMessage:f.message})]})}function NNt({brokerageId:s}){const{toast:t}=Ua(),n=Gt(),{stages:r,prospects:a}=XU(s),[i,l]=N.useState(!1),[o,c]=N.useState({title:"",target_count:"10",target_stage_id:"",period_start:ks(new Date,"yyyy-MM-dd"),period_end:ks(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=lt({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:g,error:b}=await q.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(b)throw b;return g}}),h=gt({mutationFn:async g=>{const{data:{user:b}}=await q.auth.getUser();if(!b)throw new Error("Not authenticated");const{error:v}=await q.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:b.id});if(v)throw v},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:g=>t({title:"Error",description:g.message,variant:"destructive"})}),p=gt({mutationFn:async g=>{const{error:b}=await q.from("recruit_goals").delete().eq("id",g);if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),f=g=>{const b=r.find(j=>j.id===g.target_stage_id);return{count:a.filter(j=>Q1(new Date(j.created_at),{start:new Date(g.period_start),end:new Date(g.period_end)})?g.target_stage_id?j.stage_id===g.target_stage_id:!0:!1).length,stage:b}};return u?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.length," goal",d.length!==1?"s":""]}),e.jsxs(B,{size:"sm",onClick:()=>l(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(fe,{className:"py-12 text-center",children:[e.jsx(wc,{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:b,stage:v}=f(g),j=Math.min(100,b/g.target_count*100),_=Q1(new Date,{start:new Date(g.period_start),end:new Date(g.period_end)});return e.jsxs(fe,{className:_?"":"opacity-60",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{className:"text-sm",children:g.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[ks(new Date(g.period_start),"MMM d")," – ",ks(new Date(g.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[_?e.jsx(ze,{className:"text-[10px]",children:"Active"}):e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>p.mutate(g.id),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ae,{className:"space-y-2",children:[v&&e.jsxs(ze,{variant:"outline",className:"text-[10px]",style:{borderColor:v.color,color:v.color},children:["Stage: ",v.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:b}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",g.target_count]})]}),e.jsx(xi,{value:j,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[j.toFixed(0),"% complete"]})]})]},g.id)})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(ws,{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(se,{children:"Goal Title *"}),e.jsx(ge,{required:!0,value:o.title,onChange:g=>c(b=>({...b,title:g.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Target Count *"}),e.jsx(ge,{type:"number",min:"1",required:!0,value:o.target_count,onChange:g=>c(b=>({...b,target_count:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{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(b=>({...b,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(se,{children:"Start Date"}),e.jsx(ge,{type:"date",required:!0,value:o.period_start,onChange:g=>c(b=>({...b,period_start:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"End Date"}),e.jsx(ge,{type:"date",required:!0,value:o.period_end,onChange:g=>c(b=>({...b,period_end:g.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:h.isPending,children:"Create Goal"})]})]})]})})]})}const ssn={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function kNt({email:s,mergeValues:t=ssn,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(bs,{open:!0,onOpenChange:()=>r(),children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(ws,{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(ze,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(ze,{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 P8e({brokerageId:s}){const t=Gt(),{user:n}=gs(),[r,a]=N.useState(""),[i,l]=N.useState(!1),[o,c]=N.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=lt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:g,error:b}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(b)throw b;return g}}),{data:u}=lt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:g,error:b}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(b)throw b;return g}});N.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]),N.useEffect(()=>{n!=null&&n.id&&q.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 q.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!")},p=gt({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:b}=await q.from("brokerage_recruit_settings").update(g).eq("id",d.id);if(b)throw b}else{const{error:b}=await q.from("brokerage_recruit_settings").insert(g);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),ae.success("Recruiting email settings saved!")},onError:g=>ae.error(g.message)}),f=(g,b)=>{c(v=>({...v,merge_fields:{...v.merge_fields,[g]:b}}))};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the sender identity and merge fields for recruiting emails sent to this brokerage's prospects."}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Your Scheduling Link"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This URL powers the ",e.jsx("strong",{children:'"Schedule a Conversation"'})," button on every recruiting video page you send. Paste your Calendly, HubSpot Meetings, Google Calendar booking link, etc."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:r,onChange:g=>a(g.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs(B,{onClick:h,disabled:i,size:"sm",children:[e.jsx(Ho,{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(se,{className:"text-xs",children:"Sender Display Name"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Sender Email Address"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(ge,{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(ng,{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(tNt,{brokerageId:s,onVerifiedSelect:g=>{c(b=>({...b,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(se,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(ge,{value:o.merge_fields.brokerage_name||"",onChange:g=>f("brokerage_name",g.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"{{city}}"}),e.jsx(ge,{value:o.merge_fields.city||"",onChange:g=>f("city",g.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(ge,{value:o.merge_fields.sender_name||"",onChange:g=>f("sender_name",g.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(B,{onClick:()=>p.mutate(),disabled:p.isPending,className:"w-full",children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const nsn=Ab.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",xu(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()}}}),RXe=[{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 Xp({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(Ac,{children:[e.jsx(Mc,{asChild:!0,children:e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:s,disabled:n,className:`h-8 w-8 p-0 ${t?"bg-accent text-accent-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(r,{className:"h-4 w-4"})})}),e.jsx(yc,{side:"bottom",className:"text-xs",children:a})]})}function rsn({content:s,onChange:t}){const n=eIe({extensions:[sIe.configure({heading:{levels:[1,2,3]}}),nsn,hIe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),mIe.configure({types:["heading","paragraph"]}),pIe,C_t],content:s,editorProps:{attributes:{class:"prose prose-sm max-w-none focus:outline-none min-h-[350px] px-5 py-4",style:"font-size: 15px; line-height: 1.75; color: #1a1a1a;"}},onUpdate:({editor:i})=>{t(i.getHTML())}});N.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const r=N.useCallback(()=>{if(!n)return;const i=n.getAttributes("link").href,l=window.prompt("Enter URL",i);if(l!==null){if(l===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:l}).run()}},[n]),a=N.useCallback(i=>{n&&n.chain().focus().insertContent(`{{${i}}}`).run()},[n]);return n?e.jsx(Kw,{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(Xp,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:YS,tooltip:"Bold"}),e.jsx(Xp,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:e4,tooltip:"Italic"}),e.jsx(Xp,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:NL,tooltip:"Underline"}),e.jsx(Xp,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:P9,tooltip:"Strikethrough"}),e.jsx(cl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Xp,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:aL,tooltip:"Heading 1"}),e.jsx(Xp,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:iL,tooltip:"Heading 2"}),e.jsx(Xp,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:d9,tooltip:"Heading 3"}),e.jsx(cl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Xp,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:Ep,tooltip:"Bullet List"}),e.jsx(Xp,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:zv,tooltip:"Numbered List"}),e.jsx(Xp,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:yb,tooltip:"Blockquote"}),e.jsx(Xp,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:xb,tooltip:"Divider"}),e.jsx(cl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Xp,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:wA,tooltip:"Align Left"}),e.jsx(Xp,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:_A,tooltip:"Align Center"}),e.jsx(Xp,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:jA,tooltip:"Align Right"}),e.jsx(cl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Xp,{onClick:r,active:n.isActive("link"),icon:tl,tooltip:"Insert Link"}),e.jsx(cl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Xp,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:u4,tooltip:"Undo"}),e.jsx(Xp,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:l4,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",onClick:()=>{n&&n.chain().focus().insertContent('

Learn More About Us

').run()},children:"🔘 CTA Button"}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(kL,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(cc,{align:"end",className:"w-56",children:RXe.map(i=>e.jsxs(Xr,{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(X6e,{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:"}),RXe.map(i=>e.jsx(ze,{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 asn({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(bs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(vs,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(mo,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(Qn,{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(cr,{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(DG,{icon:Hs,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(DG,{icon:Ir,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(DG,{icon:oc,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(DG,{icon:Dl,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(gr,{className:"h-3 w-3"})," Last sent: ",ks(new Date(r.lastSentAt),"MMM d, yyyy h:mm a")]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 mt-4",children:"Per-Email Performance"}),e.jsx("div",{className:"space-y-2",children:r.byEmail.map(a=>{const i=a.sent_count>0?a.opened_count/a.sent_count*100:0,l=a.sent_count>0?a.clicked_count/a.sent_count*100:0;return e.jsx(fe,{className:"overflow-hidden",children:e.jsxs(Ae,{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(ze,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Hs,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(Ir,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(oc,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(Dl,{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 DG({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(fe,{children:e.jsx(Ae,{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 SNt(s){return lt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await q.from("recruit_campaign_email_stats").select("*").eq("brokerage_id",s);if(n)throw n;const r=t??[],a={};for(const i of r){a[i.campaign_id]||(a[i.campaign_id]={campaign_id:i.campaign_id,sent:0,opened:0,clicked:0,failed:0,openRate:0,clickRate:0,byEmail:[],lastSentAt:null});const l=a[i.campaign_id];l.sent+=i.sent_count,l.opened+=i.opened_count,l.clicked+=i.clicked_count,l.failed+=i.failed_count,l.byEmail.push(i),i.last_sent_at&&(!l.lastSentAt||i.last_sent_at>l.lastSentAt)&&(l.lastSentAt=i.last_sent_at)}return Object.values(a).forEach(i=>{i.openRate=i.sent>0?i.opened/i.sent*100:0,i.clickRate=i.sent>0?i.clicked/i.sent*100:0,i.byEmail.sort((l,o)=>l.email_number-o.email_number)}),a}})}const OXe={cold:{icon:Mv,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:vb,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:_c,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function CNt({brokerageId:s}){var Ee,De,Ie,Fe;const{user:t}=gs(),n=Gt(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,g]=N.useState("editor"),[b,v]=N.useState(null),[j,_]=N.useState(null),{data:S={}}=SNt(s),[A,T]=N.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:D}=lt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:qe,error:ve}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(ve)throw ve;return qe}}),{data:L}=lt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:qe,error:ve}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(ve)throw ve;return qe}}),M={first_name:"Sarah",brokerage_name:((Ee=L==null?void 0:L.merge_fields)==null?void 0:Ee.brokerage_name)||(D==null?void 0:D.name)||"Your Brokerage",city:((De=L==null?void 0:L.merge_fields)==null?void 0:De.city)||(D==null?void 0:D.city)||"Your City",sender_name:((Ie=L==null?void 0:L.merge_fields)==null?void 0:Ie.sender_name)||(L==null?void 0:L.sender_name)||"Your Name"},F=qe=>qe.replace(/\{\{first_name\}\}/g,M.first_name).replace(/\{\{brokerage_name\}\}/g,M.brokerage_name).replace(/\{\{city\}\}/g,M.city).replace(/\{\{sender_name\}\}/g,M.sender_name),{data:z=[],isLoading:V}=lt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:qe,error:ve}=await q.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(ve)throw ve;return qe}}),{data:W={}}=lt({queryKey:["recruit-campaign-emails",s],enabled:z.length>0,queryFn:async()=>{const qe=z.map(it=>it.id),{data:ve,error:Je}=await q.from("recruit_campaign_emails").select("*").in("campaign_id",qe).order("email_number");if(Je)throw Je;const we={};return ve.forEach(it=>{we[it.campaign_id]||(we[it.campaign_id]=[]),we[it.campaign_id].push(it)}),we}}),K=Object.values(W).flat().map(qe=>qe.id),{data:Y=[]}=lt({queryKey:["recruit-subject-overrides",s],enabled:K.length>0,queryFn:async()=>{const{data:qe,error:ve}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(ve)throw ve;return qe}}),ee={};Y.forEach(qe=>{ee[qe.campaign_email_id]=qe.selected_subject_index});const ne=gt({mutationFn:async({campaignEmailId:qe,selectedIndex:ve})=>{const{error:Je}=await q.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:qe,selected_subject_index:ve,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Je)throw Je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),ae.success("Subject line updated for your brokerage")},onError:qe=>ae.error(qe.message)}),oe=gt({mutationFn:async qe=>{const{error:ve}=await q.from("recruit_campaign_emails").update({title:qe.title,subject_line:qe.subject_line,subject_line_options:qe.subject_line_options,body_html:qe.body_html,body_text:qe.body_text,delay_days:qe.delay_days,updated_at:new Date().toISOString()}).eq("id",qe.id);if(ve)throw ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email template saved!"),l(null)},onError:qe=>ae.error(qe.message)}),pe=gt({mutationFn:async()=>{const qe=A.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:ve,error:Je}=await q.from("recruit_campaigns").insert({name:A.name,slug:qe,description:A.description||null,theme:A.theme||null,goal:A.goal||null,primary_cta:A.primary_cta||"Learn more",warmth_level:A.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:A.sender_name||null,sender_email:A.sender_email||null,reply_to_email:A.reply_to_email||null,is_active:!0,sort_order:z.length+1}).select().single();if(Je)throw Je;const we=[{email_number:1,title:"Introduction",subject_line:"Hey {{first_name}}, quick question",delay_days:0},{email_number:2,title:"Follow Up",subject_line:"Following up, {{first_name}}",delay_days:7},{email_number:3,title:"Value Add",subject_line:"{{first_name}}, thought you'd want to see this",delay_days:14},{email_number:4,title:"Final Touch",subject_line:"Last note, {{first_name}}",delay_days:21}],{error:it}=await q.from("recruit_campaign_emails").insert(we.map(Ne=>({campaign_id:ve.id,...Ne,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(it)throw it;return ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Campaign created with 4 starter emails!"),p(!1),T({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:qe=>ae.error(qe.message)}),ce=gt({mutationFn:async qe=>{const{error:ve}=await q.from("recruit_campaigns").update({name:qe.name,description:qe.description,theme:qe.theme,goal:qe.goal,primary_cta:qe.primary_cta,warmth_level:qe.warmth_level,sender_name:qe.sender_name,sender_email:qe.sender_email,reply_to_email:qe.reply_to_email,updated_at:new Date().toISOString()}).eq("id",qe.id);if(ve)throw ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),ae.success("Campaign settings saved!"),v(null)},onError:qe=>ae.error(qe.message)}),de=gt({mutationFn:async qe=>{var He,$e;const{data:ve}=await q.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",qe).order("email_number",{ascending:!1}).limit(1),Je=((He=ve==null?void 0:ve[0])==null?void 0:He.email_number)??0,we=(($e=ve==null?void 0:ve[0])==null?void 0:$e.delay_days)??0,it=Je+1,{error:Ne}=await q.from("recruit_campaign_emails").insert({campaign_id:qe,email_number:it,title:`Email ${it}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:we+7,is_active:!0});if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email added to campaign!")},onError:qe=>ae.error(qe.message)}),ie=gt({mutationFn:async qe=>{const{error:ve}=await q.from("recruit_campaigns").delete().eq("id",qe);if(ve)throw ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Campaign deleted")},onError:qe=>ae.error(qe.message)}),ye=gt({mutationFn:async qe=>{const{error:ve}=await q.from("recruit_campaign_emails").delete().eq("id",qe);if(ve)throw ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email removed from campaign")},onError:qe=>ae.error(qe.message)}),_e=gt({mutationFn:async({emailId:qe,delay_days:ve})=>{const{error:Je}=await q.from("recruit_campaign_emails").update({delay_days:ve,updated_at:new Date().toISOString()}).eq("id",qe);if(Je)throw Je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Send delay updated")},onError:qe=>ae.error(qe.message)});if(V)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 Me=z.filter(qe=>!qe.brokerage_id),Te=z.filter(qe=>qe.brokerage_id===s);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Recruiting Campaigns"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"System campaigns + custom campaigns · Each can have its own email settings"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-1.5",children:[e.jsx(Vo,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(B,{size:"sm",onClick:()=>p(!0),className:"gap-1.5",children:[e.jsx(As,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(fe,{className:"border-primary/20 bg-primary/5",children:e.jsx(Ae,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(un,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-semibold",children:"Per-Campaign Email Settings"}),e.jsxs("p",{className:"text-muted-foreground",children:["Each campaign can override the default sender name, email, and reply-to. Click the ",e.jsx(Vo,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),Te.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(m9,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Te.map(qe=>Ce(qe,!0))})]}),Me.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Me.map(qe=>Ce(qe,!1))})]}),z.length===0&&e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Hs,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No campaigns yet. Create your first campaign to start automated outreach."}),e.jsxs(B,{className:"mt-4",onClick:()=>p(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(asn,{open:!!j,onClose:()=>_(null),campaignName:(j==null?void 0:j.name)||"",stat:j&&S[j.id]||null}),o&&e.jsx(kNt,{email:o,mergeValues:M,selectedSubjectIndex:ee[o.id],onClose:()=>c(null)}),e.jsx(bs,{open:!!i,onOpenChange:qe=>!qe&&l(null),children:e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(ws,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(JS,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Qn,{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(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(ge,{value:i.title,onChange:qe=>l({...i,title:qe.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(ge,{type:"number",min:0,max:90,value:i.delay_days,onChange:qe=>l({...i,delay_days:parseInt(qe.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(ge,{value:i.subject_line,onChange:qe=>l({...i,subject_line:qe.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{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(Ts,{value:((Fe=i.subject_line_options)==null?void 0:Fe.join(` `))||"",onChange:qe=>l({...i,subject_line_options:qe.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(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx($r,{value:f,onValueChange:qe=>g(qe),children:e.jsxs(Ur,{className:"h-7",children:[e.jsx(Zt,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Zt,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),f==="editor"?e.jsx(rsn,{content:i.body_html,onChange:qe=>l({...i,body_html:qe})}):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:[M.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:[M.first_name," "]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium w-12 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:F(i.subject_line)})]})]}),e.jsx("div",{className:"bg-white p-6",children:e.jsx("div",{className:"prose prose-sm max-w-none",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:F(i.body_html)}})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changes are saved to this campaign's templates"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:()=>oe.mutate(i),disabled:oe.isPending,className:"gap-1.5",children:[e.jsx(Ho,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(bs,{open:h,onOpenChange:p,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(As,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Qn,{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(se,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(ge,{value:A.name,onChange:qe=>T({...A,name:qe.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(se,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(us,{value:A.warmth_level,onValueChange:qe=>T({...A,warmth_level:qe}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(Ze,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(Ze,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(ge,{value:A.primary_cta,onChange:qe=>T({...A,primary_cta:qe.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Description"}),e.jsx(Ts,{value:A.description,onChange:qe=>T({...A,description:qe.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Goal"}),e.jsx(ge,{value:A.goal,onChange:qe=>T({...A,goal:qe.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(uy,{children:[e.jsx(hy,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs font-medium text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Hs,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(io,{className:"h-3.5 w-3.5"})]})}),e.jsxs(my,{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(se,{className:"text-xs",children:"Sender Name"}),e.jsx(ge,{value:A.sender_name,onChange:qe=>T({...A,sender_name:qe.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Sender Email"}),e.jsx(ge,{value:A.sender_email,onChange:qe=>T({...A,sender_email:qe.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(se,{className:"text-xs",children:"Reply-To Email"}),e.jsx(ge,{value:A.reply_to_email,onChange:qe=>T({...A,reply_to_email:qe.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(B,{className:"w-full",disabled:!A.name.trim()||pe.isPending,onClick:()=>pe.mutate(),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(bs,{open:!!b,onOpenChange:qe=>!qe&&v(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vo,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Qn,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),b&&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(se,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(ge,{value:b.name,onChange:qe=>v({...b,name:qe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(us,{value:b.warmth_level,onValueChange:qe=>v({...b,warmth_level:qe}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"cold",children:"❄️ Cold"}),e.jsx(Ze,{value:"warm",children:"☀️ Warm"}),e.jsx(Ze,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Goal"}),e.jsx(ge,{value:b.goal||"",onChange:qe=>v({...b,goal:qe.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(Hs,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Sender Name"}),e.jsx(ge,{value:b.sender_name||"",onChange:qe=>v({...b,sender_name:qe.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Sender Email"}),e.jsx(ge,{value:b.sender_email||"",onChange:qe=>v({...b,sender_email:qe.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(se,{className:"text-xs",children:"Reply-To Email"}),e.jsx(ge,{value:b.reply_to_email||"",onChange:qe=>v({...b,reply_to_email:qe.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(B,{className:"w-full",onClick:()=>ce.mutate(b),disabled:ce.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(bs,{open:d,onOpenChange:u,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Default Recruiting Email Settings"}),e.jsx(Qn,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(P8e,{brokerageId:s})]})})]});function Ce(qe,ve){const Je=OXe[qe.warmth_level]||OXe.cold,we=Je.icon,it=W[qe.id]||[],Ne=r===qe.id,He=!!(qe.sender_name||qe.sender_email||qe.reply_to_email),$e=S[qe.id];return e.jsxs(fe,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(Mt,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(Ne?null:qe.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl ${Je.bg} flex items-center justify-center`,children:e.jsx(we,{className:`h-5 w-5 ${Je.color}`})}),e.jsxs("div",{children:[e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[qe.name,e.jsx(ze,{variant:qe.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:qe.is_active?"Active":"Draft"}),ve&&e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),He&&e.jsxs(ze,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(Hs,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(Hn,{className:"text-xs mt-0.5",children:qe.theme||qe.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Ye=>{Ye.stopPropagation(),v({...qe})},children:e.jsx(Vo,{className:"h-4 w-4 text-muted-foreground"})}),ve&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:Ye=>{Ye.stopPropagation(),confirm("Delete this campaign and all its emails? This cannot be undone.")&&ie.mutate(qe.id)},children:e.jsx(bn,{className:"h-4 w-4"})}),$e&&$e.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(Hs,{className:"h-2.5 w-2.5"})," ",$e.sent.toLocaleString()]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${$e.openRate.toFixed(1)}% open rate`,children:[e.jsx(Ir,{className:"h-2.5 w-2.5"})," ",$e.opened.toLocaleString()," (",$e.openRate.toFixed(0),"%)"]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${$e.clickRate.toFixed(1)}% click rate`,children:[e.jsx(oc,{className:"h-2.5 w-2.5"})," ",$e.clicked.toLocaleString()," (",$e.clickRate.toFixed(1),"%)"]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Ye=>{Ye.stopPropagation(),_(qe)},title:"View detailed engagement stats",children:[e.jsx(yo,{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(Hs,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[it.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Ne?e.jsx(sx,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(io,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Ne&&e.jsxs(Ae,{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:qe.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:qe.primary_cta||"—"})]})]}),He&&e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-sm",children:[e.jsxs("p",{className:"text-xs font-semibold text-primary mb-1 flex items-center gap-1",children:[e.jsx(Hs,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[qe.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",qe.sender_name]}),qe.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",qe.sender_email]}),qe.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",qe.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:it.map((Ye,Ke)=>{var rt,tt;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[Keat.stopPropagation(),onBlur:at=>{const Ge=parseInt(at.target.value)||0;Ge!==Ye.delay_days&&_e.mutate({emailId:Ye.id,delay_days:Ge})},onKeyDown:at=>{at.key==="Enter"&&at.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),Ye.email_number===1?"Sent immediately":`Day ${Ye.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",F(((rt=Ye.subject_line_options)==null?void 0:rt.length)>0&&Ye.subject_line_options[ee[Ye.id]??0]||Ye.subject_line)]})]}),((tt=Ye.subject_line_options)==null?void 0:tt.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(us,{value:String(ee[Ye.id]??0),onValueChange:at=>ne.mutate({campaignEmailId:Ye.id,selectedIndex:parseInt(at)}),children:[e.jsx(cs,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(hs,{placeholder:"Choose subject line"})}),e.jsx(ds,{children:Ye.subject_line_options.map((at,Ge)=>e.jsxs(Ze,{value:String(Ge),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[Ge===0?"Primary":`Alt ${Ge}`,":"]}),F(at)]},Ge))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(Ye),children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ye}),g("editor")},children:e.jsx(ja,{className:"h-4 w-4"})}),ve&&it.length>1&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>{confirm("Delete this email from the sequence?")&&ye.mutate(Ye.id)},children:e.jsx(bn,{className:"h-4 w-4"})})]})]})})]},Ye.id)})}),ve&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>de.mutate(qe.id),disabled:de.isPending,children:[e.jsx(As,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},qe.id)}}const FXe={active:{icon:Al,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:_f,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:zi,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:Gc,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},zXe={sent:{icon:Hs,color:"text-blue-500"},opened:{icon:Ir,color:"text-amber-500"},clicked:{icon:oc,color:"text-green-500"},failed:{icon:Dl,color:"text-destructive"}};function TNt({brokerageId:s}){var Fe,qe,ve,Je,we;const{user:t}=gs(),n=Gt(),[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(new Set),[d,u]=N.useState("assignments"),[h,p]=N.useState(null),[f,g]=N.useState(""),[b,v]=N.useState("all"),[j,_]=N.useState("all"),[S,A]=N.useState(!1),{data:T}=M1e(),{data:D={}}=lt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:it,error:Ne}=await q.from("recruit_campaign_emails").select("*").order("email_number");if(Ne)throw Ne;const He={};return(it??[]).forEach($e=>{He[$e.campaign_id]||(He[$e.campaign_id]=[]),He[$e.campaign_id].push($e)}),He}}),{data:L}=lt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:it,error:Ne}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(Ne)throw Ne;return it}}),{data:M}=lt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:it,error:Ne}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Ne)throw Ne;return it}}),{data:F=[]}=lt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:it,error:Ne}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Ne)throw Ne;return it}}),z={};F.forEach(it=>{z[it.campaign_email_id]=it.selected_subject_index});const V={first_name:((Fe=h==null?void 0:h.prospect)==null?void 0:Fe.first_name)||"Sarah",brokerage_name:((qe=M==null?void 0:M.merge_fields)==null?void 0:qe.brokerage_name)||(L==null?void 0:L.name)||"Your Brokerage",city:((ve=M==null?void 0:M.merge_fields)==null?void 0:ve.city)||(L==null?void 0:L.city)||"Your City",sender_name:((Je=M==null?void 0:M.merge_fields)==null?void 0:Je.sender_name)||(M==null?void 0:M.sender_name)||"Your Name"},W=it=>{const Ne=D[it.campaign_id]||[],He=it.current_email_number+1;return Ne.find($e=>$e.email_number===He)||null},{data:K=[],isLoading:Y}=lt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Ne=[],He=0;for(;;){const{data:$e,error:Ye}=await q.from("recruit_campaign_assignments").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign:recruit_campaigns(name, warmth_level) `).eq("brokerage_id",s).order("created_at",{ascending:!1}).range(He,He+1e3-1);if(Ye)throw Ye;if(Ne=Ne.concat($e??[]),!$e||$e.length<1e3)break;He+=1e3}return Ne}}),{data:ee=[]}=lt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:it,error:Ne}=await q.from("recruit_campaign_sends").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign_email:recruit_campaign_emails(title, campaign_id) `).eq("brokerage_id",s).neq("status","failed").order("sent_at",{ascending:!1}).limit(500);if(Ne)throw Ne;return it}}),{data:ne=[]}=lt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:it,error:Ne}=await q.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(Ne)throw Ne;return it}}),{data:oe=[]}=lt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let Ne=[],He=0;for(;;){const{data:$e,error:Ye}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(He,He+1e3-1);if(Ye)throw Ye;if(Ne=Ne.concat($e??[]),!$e||$e.length<1e3)break;He+=1e3}return Ne}}),pe=new Set(K.map(it=>`${it.prospect_id}-${it.campaign_id}`)),ce=gt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const it=new Date,Ne=Array.from(o).filter($e=>!pe.has(`${$e}-${i}`)).map($e=>({prospect_id:$e,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:it.toISOString(),started_at:it.toISOString()}));if(Ne.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:He}=await q.from("recruit_campaign_assignments").insert(Ne);if(He)throw He},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ae.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:it=>ae.error(it.message)}),de=gt({mutationFn:async({id:it,newStatus:Ne})=>{const{error:He}=await q.from("recruit_campaign_assignments").update({status:Ne,updated_at:new Date().toISOString()}).eq("id",it);if(He)throw He},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ae.success("Assignment updated")}}),ie=gt({mutationFn:async()=>{const{data:it,error:Ne}=await q.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(Ne)throw Ne;return it},onSuccess:it=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),ae.success(`Wave sent! ${it.sent} emails delivered, ${it.skipped} skipped, ${it.failed} failed`)},onError:it=>ae.error(`Send failed: ${it.message}`)}),ye=K.filter(it=>it.status==="active").length;K.filter(it=>it.status==="completed").length;const _e=K.filter(it=>it.status==="active"&&it.next_send_at&&new Date(it.next_send_at)<=new Date).length,{data:Me={}}=SNt(s),Te=K.reduce((it,Ne)=>it+Math.max(0,Ne.current_email_number||0),0),Ce=Object.values(Me).reduce((it,Ne)=>it+Ne.opened,0),Ee=Object.values(Me).reduce((it,Ne)=>it+Ne.clicked,0);Object.values(Me).reduce((it,Ne)=>it+Ne.failed,0);const De=Te>0?Math.round(Ce/Te*100):0,Ie=Te>0?Ee/Te*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:[_e>0&&e.jsxs(B,{variant:"outline",onClick:()=>{ie.mutate()},disabled:ie.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(ph,{className:"h-4 w-4 mr-1"}),ie.isPending?"Sending...":`Send Next Wave (${_e})`]}),e.jsxs(B,{onClick:()=>a(!0),children:[e.jsx(cr,{className:"h-4 w-4 mr-1"})," Assign Campaign"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(_n,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:K.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Al,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ye}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Hs,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:Te.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Ir,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[De,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",Ce.toLocaleString(),")"]})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(oc,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ie.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",Ee.toLocaleString(),")"]})]})]})})]}),e.jsxs($r,{value:d,onValueChange:u,children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"assignments",children:["Active Drips (",ye,")"]}),e.jsxs(Zt,{value:"history",children:["Send History (",Te.toLocaleString(),")"]})]}),e.jsx(ls,{value:"assignments",className:"mt-4",children:Y?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"})}):K.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(cr,{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:K.map(it=>{var rt,tt,at,Ge;const Ne=FXe[it.status]||FXe.active,He=Ne.icon,Ye=(D[it.campaign_id]||[]).length||4,Ke=W(it);return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(ze,{className:`text-xs ${Ne.color} border-0`,children:[e.jsx(He,{className:"h-3 w-3 mr-1"}),Ne.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(rt=it.prospect)==null?void 0:rt.first_name," ",(tt=it.prospect)==null?void 0:tt.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(at=it.prospect)==null?void 0:at.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Ge=it.campaign)==null?void 0:Ge.name," · Email ",it.current_email_number,"/",Ye,it.next_send_at&&it.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(gr,{className:"h-3 w-3 inline"})," Next: ",ks(new Date(it.next_send_at),"MMM d, h:mm a"),new Date(it.next_send_at)<=new Date&&e.jsx(ze,{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:[Ke&&e.jsx(B,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>p(it),children:e.jsx(Ir,{className:"h-3.5 w-3.5"})}),it.status==="active"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>de.mutate({id:it.id,newStatus:"paused"}),children:e.jsx(_f,{className:"h-3.5 w-3.5"})}),it.status==="paused"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>de.mutate({id:it.id,newStatus:"active"}),children:e.jsx(Al,{className:"h-3.5 w-3.5"})}),(it.status==="active"||it.status==="paused")&&e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>de.mutate({id:it.id,newStatus:"cancelled"}),children:e.jsx(Gc,{className:"h-3.5 w-3.5"})})]})]},it.id)})})}),e.jsxs(ls,{value:"history",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Filter:"}),e.jsxs(us,{value:b,onValueChange:v,children:[e.jsx(cs,{className:"w-[220px] h-8 text-xs",children:e.jsx(hs,{placeholder:"All campaigns"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All campaigns"}),ne.map(it=>e.jsx(Ze,{value:it.id,children:it.name},it.id))]})]}),e.jsxs(us,{value:j,onValueChange:_,children:[e.jsx(cs,{className:"w-[160px] h-8 text-xs",children:e.jsx(hs,{placeholder:"All statuses"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All statuses"}),e.jsx(Ze,{value:"sent",children:"Sent (no engagement)"}),e.jsx(Ze,{value:"opened",children:"Opened"}),e.jsx(Ze,{value:"clicked",children:"Clicked"})]})]}),(b!=="all"||j!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{v("all"),_("all")},children:"Clear"})]}),(()=>{var Ne;const it=ee.filter(He=>{var $e;return!(b!=="all"&&(($e=He.campaign_email)==null?void 0:$e.campaign_id)!==b||j==="opened"&&!He.opened_at||j==="clicked"&&!He.clicked_at||j==="sent"&&(He.opened_at||He.clicked_at))});return it.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Hs,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:ee.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:ee.length===0?"Emails will appear here once campaigns start sending":"Try clearing the filters above"})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",it.length," of ",ee.length," recent sends",b!=="all"&&` · ${(Ne=ne.find(He=>He.id===b))==null?void 0:Ne.name}`]}),e.jsx("div",{className:"space-y-1",children:it.map(He=>{var rt,tt,at;const $e=zXe[He.status]||zXe.sent,Ye=$e.icon,Ke=(rt=ne.find(Ge=>{var dt;return Ge.id===((dt=He.campaign_email)==null?void 0:dt.campaign_id)}))==null?void 0:rt.name;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(Ye,{className:`h-4 w-4 flex-shrink-0 ${$e.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(tt=He.prospect)==null?void 0:tt.first_name," ",(at=He.prospect)==null?void 0:at.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",He.email_number]}),Ke&&e.jsx(ze,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:Ke})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:He.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[He.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(Ir,{className:"h-3 w-3"})," ",ks(new Date(He.opened_at),"MMM d")]}),He.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(oc,{className:"h-3 w-3"})," ",ks(new Date(He.clicked_at),"MMM d")]}),e.jsx("span",{children:ks(new Date(He.sent_at),"MMM d, h:mm a")})]})]},He.id)})})]})})()]})]}),e.jsx(bs,{open:r,onOpenChange:it=>{a(it),it||(g(""),c(new Set),l(""))},children:e.jsxs(vs,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(ws,{className:"px-6 pt-6 pb-4",children:[e.jsx(_s,{children:"Assign Campaign to Prospects"}),e.jsx(Qn,{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(se,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(us,{value:i,onValueChange:l,children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Choose a campaign..."})}),e.jsx(ds,{children:ne.map(it=>e.jsx(Ze,{value:it.id,children:it.name},it.id))})]})]}),i&&(()=>{const it=f.toLowerCase(),Ne=oe.filter(Ye=>`${Ye.first_name} ${Ye.last_name}`.toLowerCase().includes(it)||Ye.email.toLowerCase().includes(it)),He=Ne.filter(Ye=>!pe.has(`${Ye.id}-${i}`)),$e=He.length>0&&He.every(Ye=>o.has(Ye.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{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(_r,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name or email...",value:f,onChange:Ye=>g(Ye.target.value),className:"pl-9 h-9"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if($e){const Ye=new Set(o);He.forEach(Ke=>Ye.delete(Ke.id)),c(Ye)}else{const Ye=new Set(o);He.forEach(Ke=>Ye.add(Ke.id)),c(Ye)}},children:[e.jsx(J7,{className:"h-3.5 w-3.5 mr-1"}),$e?"Deselect All":`Select All (${He.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:Ne.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:f?"No prospects match your search":"No prospects found for this brokerage"}):Ne.map(Ye=>{const Ke=pe.has(`${Ye.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${Ke?"opacity-40":""}`,children:[e.jsx(hi,{checked:o.has(Ye.id),disabled:Ke,onCheckedChange:rt=>{const tt=new Set(o);rt?tt.add(Ye.id):tt.delete(Ye.id),c(tt)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ye.first_name," ",Ye.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ye.email})]}),Ke&&e.jsx(ze,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Ye.id)})}),Ne.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",Ne.length," of ",oe.length," prospects",He.length0&&e.jsx(fe,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Ae,{className:"pt-3 pb-2 text-sm space-y-1",children:[e.jsxs("p",{className:"font-medium text-primary",children:["✅ Ready to assign ",o.size," prospect",o.size>1?"s":""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["• Campaign: ",e.jsx("strong",{children:(we=ne.find(it=>it.id===i))==null?void 0:we.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"• First email sends immediately · follow-ups every 7 days"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"• You can pause or cancel any assignment at any time"})]})})]}),e.jsxs(Xn,{className:"px-6 py-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>{ce.mutate()},disabled:ce.isPending||!i||o.size===0,children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),ce.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const it=W(h);return it?e.jsx(kNt,{email:it,mergeValues:V,selectedSubjectIndex:z[it.id],onClose:()=>p(null)}):null})(),e.jsx(I1e,{open:S,onOpenChange:A,hasPending:T==null?void 0:T.hasPendingSes,pendingEmails:T==null?void 0:T.pendingEmails})]})}function ENt({brokerageId:s}){const t=Gt(),[n,r]=N.useState([]),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=N.useRef(!1),{data:d,isLoading:u}=lt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:v,error:j}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(j)throw j;return v},enabled:!!s});N.useEffect(()=>{if(d){if(c.current){c.current=!1;return}r(d.map(v=>({id:v.id,name:v.name,color:v.color,sort_order:v.sort_order}))),i([]),o(!1)}},[d]);const h=gt({mutationFn:async()=>{for(const _ of a){const{error:S}=await q.from("recruit_pipeline_stages").delete().eq("id",_);if(S)throw S}const v=n.filter(_=>_.id&&!_.isNew),j=n.filter(_=>!_.id||_.isNew);for(const _ of v){const{error:S}=await q.from("recruit_pipeline_stages").update({name:_.name,color:_.color,sort_order:_.sort_order}).eq("id",_.id);if(S)throw S}if(j.length>0){const{error:_}=await q.from("recruit_pipeline_stages").insert(j.map(S=>({brokerage_id:s,name:S.name,color:S.color,sort_order:S.sort_order})));if(_)throw _}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),ae.success("Pipeline stages saved!"),o(!1)},onError:v=>ae.error(v.message)}),p=(v,j,_)=>{r(S=>S.map((A,T)=>T===v?{...A,[j]:_}:A)),o(!0)},f=()=>{const v=n.length>0?Math.max(...n.map(j=>j.sort_order)):0;r(j=>[...j,{name:"",color:"#6366f1",sort_order:v+1,isNew:!0}]),o(!0)},g=v=>{const j=n[v];j.id&&!j.isNew&&i(_=>[..._,j.id]),r(_=>_.filter((S,A)=>A!==v)),o(!0)},b=(v,j)=>{const _=v+j;if(_<0||_>=n.length)return;const S=[...n];[S[v],S[_]]=[S[_],S[v]],S.forEach((A,T)=>A.sort_order=T+1),r(S),o(!0)};return u?e.jsx("div",{className:"text-sm text-muted-foreground py-8 text-center",children:"Loading stages…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Customize the recruiting pipeline stages for this brokerage. Changes will apply to the Kanban board and all prospect tracking."})]}),e.jsx("div",{className:"space-y-2",children:n.map((v,j)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("button",{type:"button",onClick:()=>b(j,-1),disabled:j===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>b(j,1),disabled:j===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Uu,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:v.color,onChange:_=>p(j,"color",_.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(ge,{value:v.name,onChange:_=>p(j,"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:j+1}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(j),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(bn,{className:"h-4 w-4"})})]},v.id||`new-${j}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:f,className:"gap-1",children:[e.jsx(As,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs(B,{size:"sm",onClick:()=>h.mutate(),disabled:h.isPending,className:"gap-1",children:[e.jsx(Ho,{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 isn({brokerageId:s}){const{data:t=[],isLoading:n}=lt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:r,error:a}=await q.from("recruit_prospects").select("id, first_name, last_name, email, unsubscribed_at, unsubscribe_reason, current_brokerage").eq("brokerage_id",s).not("unsubscribed_at","is",null).order("unsubscribed_at",{ascending:!1}).limit(500);if(a)throw a;return r||[]},enabled:!!s});return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx($A,{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(ze,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"py-12 text-center text-muted-foreground",children:[e.jsx($A,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"No prospects have unsubscribed. Nice work!"})]})}):e.jsx("div",{className:"grid gap-3",children:t.map(r=>e.jsxs(fe,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Pt,{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(Hs,{className:"h-3 w-3"}),r.email]}),r.current_brokerage&&e.jsxs("span",{children:["· ",r.current_brokerage]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(yr,{className:"h-3 w-3"}),r.unsubscribed_at&&ks(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(Ae,{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 osn(){var o;const[s,t]=N.useState(""),[n,r]=N.useState("board"),{data:a=[],isLoading:i}=lt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await q.from("brokerages").select("id, name").order("name");if(d)throw d;return c}}),l=s||((o=a[0])==null?void 0:o.id)||"";return i?e.jsx(Cs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsx(Cs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[a.length>1?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(us,{value:l,onValueChange:t,children:[e.jsxs(cs,{className:"w-[280px]",children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),e.jsx(hs,{placeholder:"Select brokerage"})]}),e.jsx(ds,{children:a.map(c=>e.jsx(Ze,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(wNt,{brokerageId:l,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(vr,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs($r,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Ur,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Zt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Zt,{value:"contacts",children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Zt,{value:"video-outreach",children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Zt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"interest",children:"Interest Form"}),e.jsx(Zt,{value:"landing-page",children:"Landing Page"}),e.jsx(Zt,{value:"goals",children:"Goals"}),e.jsx(Zt,{value:"metrics",children:"Metrics"}),e.jsx(Zt,{value:"templates",children:"Email Templates"}),e.jsxs(Zt,{value:"campaigns",children:[e.jsx(Hs,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Zt,{value:"drip-assignments",children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Zt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Zt,{value:"email-settings",children:[e.jsx(Vo,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Zt,{value:"pipeline-stages",children:[e.jsx(c4,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Zt,{value:"unsubscribed",children:[e.jsx($A,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(ls,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs(B,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("board"),children:[e.jsx(vf,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(B,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("table"),children:[e.jsx(wL,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(pNt,{brokerageId:l}):e.jsx(Xge,{brokerageId:l})]}),e.jsx(ls,{value:"contacts",children:e.jsx(Xge,{brokerageId:l})}),e.jsx(ls,{value:"video-outreach",children:e.jsx(jNt,{brokerageId:l})}),e.jsx(ls,{value:"follow-ups",children:e.jsx(bNt,{brokerageId:l})}),e.jsx(ls,{value:"referrals",children:e.jsx(yNt,{brokerageId:l})}),e.jsx(ls,{value:"interest",children:e.jsx(vNt,{brokerageId:l})}),e.jsx(ls,{value:"landing-page",children:e.jsx(_Nt,{brokerageId:l})}),e.jsx(ls,{value:"goals",children:e.jsx(NNt,{brokerageId:l})}),e.jsx(ls,{value:"metrics",children:e.jsx(fNt,{brokerageId:l})}),e.jsx(ls,{value:"templates",children:e.jsx(xNt,{brokerageId:l})}),e.jsx(ls,{value:"campaigns",children:e.jsx(CNt,{brokerageId:l})}),e.jsx(ls,{value:"drip-assignments",children:e.jsx(TNt,{brokerageId:l})}),e.jsx(ls,{value:"activity",children:e.jsx(gNt,{brokerageId:l})}),e.jsx(ls,{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(P8e,{brokerageId:l})]})}),e.jsx(ls,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(ENt,{brokerageId:l})})}),e.jsx(ls,{value:"unsubscribed",children:e.jsx(isn,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ga,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function lsn({brokerageId:s}){const[t,n]=N.useState(""),[r,a]=N.useState("all"),{data:i,isLoading:l}=lt({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var v;const{data:d,error:u}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(j=>[j.id,j]));if(Array.from(h.keys()).length===0)return[];const{data:f}=await q.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:g}=await q.from("recruit_campaign_sends").select("id, prospect_id, subject, status, sent_at, opened_at, clicked_at, error_message, email_number").eq("brokerage_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}),b=[];for(const j of f||[]){const _=h.get(j.prospect_id);_&&b.push({id:`v-${j.id}`,kind:"video",prospect_id:j.prospect_id,prospect_name:`${_.first_name||""} ${_.last_name||""}`.trim()||"—",prospect_email:_.email,subject:(v=j.video)!=null&&v.title?`Video: ${j.video.title}`:"Recruiting Video",status:j.cta_clicked_at?"clicked":j.first_viewed_at?"viewed":"sent",sent_at:j.sent_at,opened_at:j.first_viewed_at,clicked_at:j.cta_clicked_at,view_count:j.view_count,share_token:j.share_token})}for(const j of g||[]){if(!j.sent_at)continue;const _=h.get(j.prospect_id);_&&b.push({id:`c-${j.id}`,kind:"campaign",prospect_id:j.prospect_id,prospect_name:`${_.first_name||""} ${_.last_name||""}`.trim()||"—",prospect_email:_.email,subject:j.subject||`Email #${j.email_number}`,status:j.status||"sent",sent_at:j.sent_at,opened_at:j.opened_at,clicked_at:j.clicked_at,error:j.error_message})}return b.sort((j,_)=>new Date(_.sent_at).getTime()-new Date(j.sent_at).getTime()),b}}),o=N.useMemo(()=>{const d=i||[];return{total:d.length,videos:d.filter(u=>u.kind==="video").length,campaigns:d.filter(u=>u.kind==="campaign").length,opened:d.filter(u=>u.opened_at).length,clicked:d.filter(u=>u.clicked_at).length}},[i]),c=N.useMemo(()=>(i||[]).filter(u=>{if(r!=="all"&&u.kind!==r)return!1;if(!t)return!0;const h=t.toLowerCase();return u.prospect_name.toLowerCase().includes(h)||(u.prospect_email||"").toLowerCase().includes(h)||u.subject.toLowerCase().includes(h)}),[i,t,r]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Total Sent",value:o.total,icon:cr,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:vr,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:Hs,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:Ir,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:oc,color:"text-emerald-500"}].map(d=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-3 flex items-center gap-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg bg-muted flex items-center justify-center ${d.color}`,children:e.jsx(d.icon,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold leading-tight",children:d.value}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d.label})]})]})},d.label))}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Pt,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($r,{value:r,onValueChange:d=>a(d),children:e.jsxs(Ur,{className:"h-8",children:[e.jsx(Zt,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(Zt,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(Zt,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search recruit, subject...",value:t,onChange:d=>n(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Ae,{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(Hs,{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(ze,{variant:"outline",className:"gap-1",children:[e.jsx(vr,{className:"h-3 w-3"}),"Video"]}):e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Hs,{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(ze,{variant:"destructive",className:"gap-1",children:[e.jsx(Gi,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(ze,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(oc,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(ze,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Ir,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(cr,{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:[ks(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:ks(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(Ir,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>window.open(`/recruit-video/${d.share_token}`,"_blank"),title:"Open landing page",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}function csn(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=gs(),[r,a]=N.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(Cs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ga,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages assigned to you. Contact an admin for access."})]})}):e.jsx(Cs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[s.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(us,{value:i,onValueChange:n,children:[e.jsxs(cs,{className:"w-[280px]",children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),e.jsx(hs,{placeholder:"Select brokerage"})]}),e.jsx(ds,{children:s.map(o=>e.jsx(Ze,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs($r,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Ur,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Zt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Zt,{value:"contacts",children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Zt,{value:"video-outreach",children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Zt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"interest",children:"Interest Form"}),e.jsx(Zt,{value:"landing-page",children:"Landing Page"}),e.jsx(Zt,{value:"goals",children:"Goals"}),e.jsx(Zt,{value:"metrics",children:"Metrics"}),e.jsx(Zt,{value:"templates",children:"Email Templates"}),e.jsxs(Zt,{value:"campaigns",children:[e.jsx(Hs,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Zt,{value:"drip-assignments",children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(Zt,{value:"sent-emails",children:[e.jsx(Z2,{className:"h-3.5 w-3.5 mr-1"}),"Sent Emails"]}),e.jsx(Zt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Zt,{value:"email-settings",children:[e.jsx(Vo,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Zt,{value:"pipeline-stages",children:[e.jsx(c4,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(ls,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs(B,{variant:r==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("board"),children:[e.jsx(vf,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(B,{variant:r==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("table"),children:[e.jsx(wL,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(pNt,{brokerageId:i}):e.jsx(Xge,{brokerageId:i})]}),e.jsx(ls,{value:"contacts",children:e.jsx(Xge,{brokerageId:i})}),e.jsx(ls,{value:"video-outreach",children:e.jsx(jNt,{brokerageId:i})}),e.jsx(ls,{value:"follow-ups",children:e.jsx(bNt,{brokerageId:i})}),e.jsx(ls,{value:"referrals",children:e.jsx(yNt,{brokerageId:i})}),e.jsx(ls,{value:"interest",children:e.jsx(vNt,{brokerageId:i})}),e.jsx(ls,{value:"landing-page",children:e.jsx(_Nt,{brokerageId:i})}),e.jsx(ls,{value:"goals",children:e.jsx(NNt,{brokerageId:i})}),e.jsx(ls,{value:"metrics",children:e.jsx(fNt,{brokerageId:i})}),e.jsx(ls,{value:"templates",children:e.jsx(xNt,{brokerageId:i})}),e.jsx(ls,{value:"campaigns",children:e.jsx(CNt,{brokerageId:i})}),e.jsx(ls,{value:"drip-assignments",children:e.jsx(TNt,{brokerageId:i})}),e.jsx(ls,{value:"sent-emails",children:e.jsx(lsn,{brokerageId:i})}),e.jsx(ls,{value:"activity",children:e.jsx(gNt,{brokerageId:i})}),e.jsx(ls,{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(P8e,{brokerageId:i})]})}),e.jsx(ls,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(ENt,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ga,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function dsn(){const[s,t]=N.useState(""),{data:n,isLoading:r}=lt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await q.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await q.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await q.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],h=d||[],p=o.map(f=>{const g=u.filter(j=>j.brokerage_id===f.id),b=h.filter(j=>j.brokerage_id===f.id),v=g.length>0?g.reduce((j,_)=>_.created_at>j?_.created_at:j,g[0].created_at):null;return{brokerage_id:f.id,brokerage_name:f.name,total_items:g.length,videos:g.filter(j=>j.content_type==="video").length,pdfs:g.filter(j=>j.content_type==="pdf").length,links:g.filter(j=>j.content_type==="link"||j.content_type==="canva_link").length,events:g.filter(j=>j.content_type==="event").length,graphics:g.filter(j=>j.content_type==="graphic").length,latest_item_date:v,categories:b.length}});return p.sort((f,g)=>g.total_items-f.total_items),p}}),a=(n||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx(Cs,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vd,{title:"Brokerage Content Activity",description:"See which brokerages are creating custom content for their agents"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Ae,{children:[e.jsx("p",{className:"text-2xl font-bold",children:l}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with content uploaded"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Ae,{children:[e.jsx("p",{className:"text-2xl font-bold",children:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"across all brokerages"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Pt,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Ae,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(fe,{children:e.jsx(Ae,{className:"p-0",children:e.jsxs(ha,{children:[e.jsx(ma,{children:e.jsxs(Gs,{children:[e.jsx(Ct,{children:"Brokerage"}),e.jsx(Ct,{className:"text-center",children:"Total"}),e.jsx(Ct,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(vr,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Ct,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Nr,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Ct,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(El,{className:"h-3 w-3"})," Links"]})}),e.jsx(Ct,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Tl,{className:"h-3 w-3"})," Events"]})}),e.jsx(Ct,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(nl,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Ct,{className:"text-center",children:"Categories"}),e.jsx(Ct,{children:"Last Upload"})]})}),e.jsx(pa,{children:r?e.jsx(Gs,{children:e.jsx(ut,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(Gs,{children:e.jsx(ut,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(Gs,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(ut,{className:"text-center",children:o.total_items>0?e.jsx(ze,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ut,{className:"text-center",children:o.videos||"–"}),e.jsx(ut,{className:"text-center",children:o.pdfs||"–"}),e.jsx(ut,{className:"text-center",children:o.links||"–"}),e.jsx(ut,{className:"text-center",children:o.events||"–"}),e.jsx(ut,{className:"text-center",children:o.graphics||"–"}),e.jsx(ut,{className:"text-center",children:o.categories||"–"}),e.jsx(ut,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:ks(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const usn=[{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:"📉"}],BXe=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(mu,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(mu,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(Oh,{className:"h-4 w-4"})}],hsn=[{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:"📰"}],$Xe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),UXe={"luxury-dark":HIe,"modern-clean":GIe,"bold-colorful":WIe,editorial:KIe};function msn(){const[s,t]=N.useState(""),[n,r]=N.useState("address"),[a,i]=N.useState(!1),[l,o]=N.useState([]),[c,d]=N.useState(null),[u,h]=N.useState(0),[p,f]=N.useState("just-listed"),[g,b]=N.useState(["instagram-square"]),[v,j]=N.useState("luxury-dark"),[_,S]=N.useState(!1),[A,T]=N.useState(""),[D,L]=N.useState(""),[M,F]=N.useState(""),[z,V]=N.useState(!1),[W,K]=N.useState(!1),[Y,ee]=N.useState([]),[ne,oe]=N.useState("search"),pe=N.useRef({});N.useEffect(()=>{(async()=>{const{data:{user:De}}=await q.auth.getUser();if(!De)return;const{data:Ie}=await q.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",De.id).single();if(Ie){T(Ie.name||""),F(Ie.avatar_url||"");const Fe=Ie.brokerages;L((Fe==null?void 0:Fe.name)||"")}})()},[]);const ce=async()=>{var Ee;if(s.trim()){i(!0),o([]);try{const{data:De,error:Ie}=await q.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Ie)throw Ie;if(De.error)throw new Error(De.error);o(De.listings||[]),((Ee=De.listings)==null?void 0:Ee.length)===0&&ae.info("No listings found. Try a different search.")}catch(De){ae.error(De.message||"Search failed")}finally{i(!1)}}},de=Ee=>{var De;d(Ee),h(0),oe("customize"),Ee.soldDate||(De=Ee.status)!=null&&De.toLowerCase().includes("sold")?f("just-sold"):f("just-listed")},ie=Ee=>{b(De=>De.includes(Ee)?De.filter(Ie=>Ie!==Ee):[...De,Ee])},ye=N.useCallback(async()=>{if(!(!c||g.length===0)){V(!0),ee([]),oe("generate");try{await new Promise(De=>setTimeout(De,500));const Ee=[];for(const De of g){const Ie=`${v}-${De}`,Fe=pe.current[Ie];if(!Fe)continue;const qe=OS[De],ve=await VIe(Fe,{width:qe.width,height:qe.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ee.push({format:De,imageUrl:ve})}ee(Ee),ae.success(`Generated ${Ee.length} social post${Ee.length>1?"s":""}!`)}catch(Ee){ae.error(Ee.message||"Generation failed")}finally{V(!1)}}},[c,g,v,u,_,A,D,M,p]),_e=async()=>{if(!(!c||g.length===0)){V(!0),ee([]),oe("generate");try{const Ee={...c,photos:c.photos.length>0?[c.photos[u]]:[]},De=[];for(const Ie of g){const{data:Fe,error:qe}=await q.functions.invoke("generate-listing-social-post",{body:{listing:Ee,postType:p,format:Ie,branding:_?{enabled:!0,agentName:A,brokerage:D}:{enabled:!1}}});if(qe)throw qe;if(Fe.error)throw new Error(Fe.error);De.push({format:Ie,imageUrl:Fe.imageUrl})}ee(De),ae.success(`Generated ${De.length} AI post${De.length>1?"s":""}!`)}catch(Ee){ae.error(Ee.message||"AI generation failed")}finally{V(!1)}}},Me=()=>W?_e():ye(),Te=(Ee,De)=>{var Fe;const Ie=document.createElement("a");Ie.href=Ee,Ie.download=`${((Fe=c==null?void 0:c.address)==null?void 0:Fe.replace(/\s+/g,"-"))||"listing"}-${p}-${De}.png`,document.body.appendChild(Ie),Ie.click(),document.body.removeChild(Ie)},Ce=c?{listing:c,postType:p,format:"instagram-square",branding:_?{enabled:!0,agentName:A,brokerage:D,agentPhotoUrl:M||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Vd,{title:"Social Post Generator",description:"Search MLS listings and generate stunning social media posts"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsxs("button",{onClick:()=>oe("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${ne==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(_r,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&oe("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${ne==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(un,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full ${ne==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(nl,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),ne==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(_r,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(fpt,{})]}),e.jsx(Hn,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsx($r,{value:n,onValueChange:Ee=>r(Ee),children:e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"address",children:[e.jsx(Ca,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(mh,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:s,onChange:Ee=>t(Ee.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ee=>Ee.key==="Enter"&&ce()}),e.jsxs(B,{onClick:ce,disabled:a||!s.trim(),children:[a?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(_r,{className:"h-4 w-4"})," Search"]})]})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[l.length," listing",l.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:l.map((Ee,De)=>{var Ie;return e.jsx(fe,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>de(Ee),children:e.jsx(Ae,{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=Ee.photos)!=null&&Ie[0]?e.jsx("img",{src:Ee.photos[0],alt:Ee.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(zr,{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:$Xe(Ee.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ee.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ee.city,", ",Ee.state," ",Ee.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ee.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(G2,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Tp,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(OA,{className:"h-3 w-3"})," ",Ee.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Ee.mlsNumber}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Ee.status})]})]})]})})},Ee.mlsNumber||De)})})]})]}),ne==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"lg:col-span-1",children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(Pt,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Ae,{className:"space-y-3",children:[c.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.photos[u],alt:"Listing photo",className:"w-full h-full object-cover"})}),c.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(Ee=>Math.max(0,Ee-1)),disabled:u===0,children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u+1," of ",c.photos.length]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(Ee=>Math.min(c.photos.length-1,Ee+1)),disabled:u===c.photos.length-1,children:e.jsx(ga,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:$Xe(c.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.city,", ",c.state," ",c.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[c.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),c.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),c.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{oe("search"),d(null)},children:[e.jsx(Fh,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(fe,{className:"lg:col-span-2",children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Hn,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Ae,{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(xl,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:W?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:W?"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(vn,{checked:W,onCheckedChange:K}),W&&e.jsx(Rm,{className:"h-4 w-4 text-purple-500"})]})]}),!W&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(xl,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:hsn.map(Ee=>e.jsxs("button",{onClick:()=>j(Ee.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${v===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Ee.preview}),e.jsx("span",{className:"text-sm font-medium",children:Ee.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Ee.description})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:usn.map(Ee=>e.jsxs("button",{onClick:()=>f(Ee.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${p===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Ee.icon})," ",Ee.label]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:BXe.map(Ee=>e.jsxs("button",{onClick:()=>ie(Ee.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${g.includes(Ee.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ee.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:Ee.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ee.dimensions})]})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Xi,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(vn,{checked:_,onCheckedChange:S})]}),_&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[M&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:M,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(se,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(ge,{value:A,onChange:Ee=>T(Ee.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(ge,{value:D,onChange:Ee=>L(Ee.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!W&&Ce&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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*(OS[g[0]||"instagram-square"].height/OS[g[0]||"instagram-square"].width)},children:(()=>{const Ee=UXe[v],De=g[0]||"instagram-square";return e.jsx(Ee,{...Ce,format:De})})()})})]}),e.jsx(B,{onClick:Me,disabled:g.length===0||z,size:"lg",className:"w-full gap-2",children:z?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-5 w-5 animate-spin"})," Generating ",g.length," post",g.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[W?e.jsx(Rm,{className:"h-5 w-5"}):e.jsx(un,{className:"h-5 w-5"}),"Generate ",g.length," Social Post",g.length>1?"s":"",W&&e.jsx(ze,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),ne==="generate"&&e.jsxs("div",{className:"space-y-4",children:[z&&e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(ss,{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:W?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),Y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Generated Posts"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>oe("customize"),children:[e.jsx(Fh,{className:"h-3.5 w-3.5 mr-1.5"})," Regenerate"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Y.map((Ee,De)=>{const Ie=BXe.find(Fe=>Fe.value===Ee.format);return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Ee.imageUrl,alt:`${Ee.format} social post`,className:"w-full rounded"})}),e.jsxs(Ae,{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(ze,{variant:"outline",className:"text-[10px]",children:Ie==null?void 0:Ie.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>Te(Ee.imageUrl,Ee.format),children:[e.jsx(Da,{className:"h-3.5 w-3.5"})," Download"]})]})]},De)})})]})]}),ne==="generate"&&!W&&c&&Ce&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:g.map(Ee=>{const De=UXe[v],Ie=OS[Ee];return e.jsx("div",{style:{width:Ie.width,height:Ie.height},children:e.jsx(De,{ref:Fe=>{pe.current[`${v}-${Ee}`]=Fe},...Ce,format:Ee})},`${v}-${Ee}`)})})]})})}function psn(){return lt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await q.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function fsn(s){return lt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*)), access:lms_course_access(*)").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function xsn(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_courses").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function ANt(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("lms_courses").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-courses-admin"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function gsn(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("lms_courses").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function ysn(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_modules").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function vsn(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("lms_modules").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function bsn(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("lms_modules").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function _sn(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_module_resources").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function wsn(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("lms_module_resources").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function jsn(){const s=Gt();return gt({mutationFn:async({courseId:t,accessRules:n})=>{const{error:r}=await q.from("lms_course_access").delete().eq("course_id",t);if(r)throw r;if(n.length>0){const a=n.map(l=>({...l,course_id:t})),{error:i}=await q.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function Nsn(){return lt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await q.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function ksn(s){return lt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*))").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function MNt(s){return lt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("lms_progress").select("*").eq("course_id",s);if(n)throw n;return t},enabled:!!s})}function Ssn(){const s=Gt();return gt({mutationFn:async({courseId:t,moduleId:n,userId:r})=>{const{data:a,error:i}=await q.from("lms_progress").upsert({user_id:r,course_id:t,module_id:n,completed:!0,completed_at:new Date().toISOString()},{onConflict:"user_id,module_id"}).select().single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["lms-progress"]})})}function Csn(){const{user:s}=gs(),t=In(),{data:n,isLoading:r}=psn(),a=xsn(),i=ANt(),l=gsn(),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(!0),b=async()=>{if(!(!d.trim()||!s))try{const _=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:f,created_by:s.id});ae.success("Course created"),c(!1),u(""),p(""),g(!0),t(`/admin/lms/${_.id}`)}catch{ae.error("Failed to create course")}},v=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")}},j=async _=>{if(confirm("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(Cs,{title:"LevelUp U - Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(_d,{className:"h-7 w-7 text-primary"}),"LevelUp U — Course Manager"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create and manage training courses for your agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(yo,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(As,{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(fe,{className:"animate-pulse",children:e.jsxs(Mt,{children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-2"})]})},_))}):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 D,L;const S=((L=(D=_.modules)==null?void 0:D[0])==null?void 0:L.count)??0,A=_.access||[],T=A.length===0?"No access set":A.some(M=>M.access_type==="all")?"All agents":`${A.length} rule(s)`;return e.jsxs(fe,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${_.id}`),children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Pt,{className:"text-base truncate",children:_.title}),_.description&&e.jsx(Hn,{className:"mt-1 line-clamp-2",children:_.description})]}),e.jsx(ze,{variant:_.is_published?"default":"secondary",className:"ml-2 shrink-0",children:_.is_published?"Published":"Draft"})]})}),e.jsxs(Ae,{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($u,{className:"h-3.5 w-3.5"}),S," module",S!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[_.is_sequential?e.jsx(zv,{className:"h-3.5 w-3.5"}):e.jsx(UA,{className:"h-3.5 w-3.5"}),_.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_n,{className:"h-3.5 w-3.5"}),T]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs(B,{size:"sm",variant:"ghost",onClick:M=>{M.stopPropagation(),v(_)},children:[_.is_published?e.jsx(gf,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1"}),_.is_published?"Unpublish":"Publish"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:M=>{M.stopPropagation(),j(_.id)},children:e.jsx(bn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(za,{className:"h-4 w-4 text-muted-foreground"})]})]})]},_.id)})}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx($u,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-1",children:"No courses yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first training course to get started"}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create New Course"}),e.jsx(Qn,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Course Title"}),e.jsx(ge,{value:d,onChange:_=>u(_.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{value:h,onChange:_=>p(_.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(vn,{checked:f,onCheckedChange:g})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:b,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function Tsn(){const{courseId:s}=_i(),t=In(),{data:n,isLoading:r}=fsn(s),a=ANt(),i=ysn(),l=vsn(),o=bsn(),c=_sn(),d=wsn(),u=jsn(),{data:h}=lt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:tt}=await q.from("brokerages").select("id, name").order("name");return tt||[]}}),[p,f]=N.useState(null),[g,b]=N.useState(!1),[v,j]=N.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[_,S]=N.useState(null),[A,T]=N.useState({title:"",resource_type:"link",url:""}),[D,L]=N.useState(new Set),[M,F]=N.useState(null),[z,V]=N.useState(0),[W,K]=N.useState(!1),Y=N.useRef(null),ee=N.useRef(null),[ne,oe]=N.useState(!1),[pe,ce]=N.useState(""),[de,ie]=N.useState(""),[ye,_e]=N.useState(""),[Me,Te]=N.useState(!1);if(r)return e.jsx(Cs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!n)return e.jsx(Cs,{title:"Course Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const Ce=n.modules||[],Ee=n.access||[],De=Ee.some(tt=>tt.access_type==="all"),Ie=Ee.filter(tt=>tt.access_type==="brokerage").map(tt=>tt.brokerage_id),Fe=(h||[]).filter(tt=>tt.name.toLowerCase().includes(pe.toLowerCase())),qe=tt=>{const at=new Set(D);at.has(tt)?at.delete(tt):at.add(tt),L(at)},ve=async()=>{if(!M)return null;K(!0),V(0);try{const{data:tt,error:at}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:M.name}});if(at)throw new Error(at.message);const{videoId:Ge,libraryId:dt}=tt,{data:Bt,error:kt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ge,libraryId:dt}});if(kt)throw new Error(kt.message);const Qt=new XMLHttpRequest;return await new Promise((ns,$s)=>{Qt.upload.onprogress=Ds=>{Ds.lengthComputable&&V(Math.round(Ds.loaded/Ds.total*100))},Qt.onload=()=>Qt.status>=200&&Qt.status<300?ns():$s(new Error(`Upload failed: ${Qt.status}`)),Qt.onerror=()=>$s(new Error("Upload failed")),Qt.open("PUT",Bt.uploadUrl),Qt.setRequestHeader("AccessKey",Bt.apiKey),Qt.send(M)}),`https://iframe.mediadelivery.net/embed/${dt}/${Ge}`}catch(tt){return console.error("Bunny upload error:",tt),ae.error("Video upload failed"),null}finally{K(!1),V(0)}},Je=async()=>{if(v.title.trim())try{let tt=v.video_url.trim()||void 0;if(M){const at=await ve();if(!at)return;tt=at}await i.mutateAsync({course_id:n.id,title:v.title.trim(),description:v.description.trim()||void 0,video_url:tt,text_content:v.text_content.trim()||void 0,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):void 0,sort_order:Ce.length}),ae.success("Module added"),b(!1),j({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),F(null)}catch{ae.error("Failed to add module")}},we=async()=>{if(p)try{let tt=v.video_url.trim()||null;if(M){const at=await ve();if(!at)return;tt=at}await l.mutateAsync({id:p.id,title:v.title.trim(),description:v.description.trim()||null,video_url:tt,text_content:v.text_content.trim()||null,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):null}),ae.success("Module updated"),f(null),F(null)}catch{ae.error("Failed to update")}},it=async tt=>{if(confirm("Delete this module?"))try{await o.mutateAsync(tt),ae.success("Module deleted")}catch{ae.error("Failed to delete")}},Ne=async tt=>{if(A.title.trim())try{await c.mutateAsync({module_id:tt,title:A.title.trim(),resource_type:A.resource_type,url:A.url.trim()||void 0}),ae.success("Resource added"),S(null),T({title:"",resource_type:"link",url:""})}catch{ae.error("Failed to add resource")}},He=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),ae.success("Access updated: All brokerages / all agents")}catch{ae.error("Failed to update access")}},$e=async tt=>{const at=Ee.filter(kt=>kt.access_type==="brokerage").map(kt=>kt.brokerage_id),Ge=at.includes(tt);let dt;Ge?dt=at.filter(kt=>kt!==tt):dt=[...at,tt];const Bt=dt.map(kt=>({access_type:"brokerage",brokerage_id:kt}));try{await u.mutateAsync({courseId:n.id,accessRules:Bt}),ae.success(Ge?"Brokerage removed":"Brokerage added")}catch{ae.error("Failed to update access")}},Ye=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),ae.success("Access cleared")}catch{ae.error("Failed")}},Ke=async(tt,at)=>{const Ge=at==="up"?tt-1:tt+1;if(!(Ge<0||Ge>=Ce.length))try{await Promise.all([l.mutateAsync({id:Ce[tt].id,sort_order:Ge}),l.mutateAsync({id:Ce[Ge].id,sort_order:tt})])}catch{ae.error("Failed to reorder")}},rt=async()=>{try{await a.mutateAsync({id:n.id,title:de,description:ye||null}),ae.success("Course updated"),Te(!1)}catch{ae.error("Failed to update")}};return e.jsxs(Cs,{title:n.title,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(Wr,{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(ze,{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(zv,{className:"h-3.5 w-3.5"}):e.jsx(UA,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[Ce.length," module",Ce.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{ie(n.title),_e(n.description||""),Te(!0)},children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(B,{variant:n.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:n.id,is_published:!n.is_published}).then(()=>ae.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx(gf,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs($r,{defaultValue:"modules",className:"w-full",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"modules",children:"Modules"}),e.jsx(Zt,{value:"access",children:"Access & Permissions"}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(ls,{value:"modules",className:"mt-6 space-y-4",children:[Ce.map((tt,at)=>e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>qe(tt.id),children:[e.jsx("span",{className:"flex items-center gap-1 text-muted-foreground",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("button",{onClick:Ge=>{Ge.stopPropagation(),Ke(at,"up")},disabled:at===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(sx,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:Ge=>{Ge.stopPropagation(),Ke(at,"down")},disabled:at===Ce.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(io,{className:"h-3.5 w-3.5"})})]})}),e.jsx(ze,{variant:"outline",className:"shrink-0 font-mono text-xs",children:at+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:tt.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[tt.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(vr,{className:"h-3 w-3"})," Video"]}),tt.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Nr,{className:"h-3 w-3"})," Text"]}),tt.duration_minutes&&e.jsxs("span",{children:[tt.duration_minutes," min"]}),tt.resources&&tt.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(El,{className:"h-3 w-3"})," ",tt.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:Ge=>{var dt;Ge.stopPropagation(),f(tt),j({title:tt.title,description:tt.description||"",video_url:tt.video_url||"",text_content:tt.text_content||"",duration_minutes:((dt=tt.duration_minutes)==null?void 0:dt.toString())||""})},children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:Ge=>{Ge.stopPropagation(),it(tt.id)},children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]}),D.has(tt.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[tt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:tt.description}),tt.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:tt.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:tt.video_url})]}),tt.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:tt.text_content}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Resources"}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{S(tt.id),T({title:"",resource_type:"link",url:""})},children:[e.jsx(As,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),tt.resources&&tt.resources.length>0?e.jsx("div",{className:"space-y-1",children:tt.resources.map(Ge=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Ge.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:Ge.title}),Ge.url&&e.jsx("a",{href:Ge.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx(B,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(Ge.id),children:e.jsx(Fn,{className:"h-3 w-3"})})]},Ge.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},tt.id)),e.jsxs(B,{variant:"outline",className:"w-full border-dashed",onClick:()=>{b(!0),j({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(As,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(ls,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Ae,{className:"space-y-5",children:[e.jsxs("div",{className:Et("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",De?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:He,children:[e.jsx("div",{className:Et("h-10 w-10 rounded-full flex items-center justify-center shrink-0",De?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(lc,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:"All Brokerages / All Agents"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every agent on the platform can access this course"})]}),e.jsx(vn,{checked:De,onCheckedChange:He})]}),!De&&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(B,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ye,children:"Clear all"})]}),e.jsx(ge,{placeholder:"Search brokerages...",value:pe,onChange:tt=>ce(tt.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Fe.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Fe.map(tt=>{const at=Ie.includes(tt.id);return e.jsxs("div",{className:Et("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",at?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>$e(tt.id),children:[e.jsx("div",{className:Et("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",at?"bg-primary border-primary":"border-muted-foreground/30"),children:at&&e.jsx("svg",{className:"h-3 w-3 text-primary-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:tt.name}),at&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},tt.id)})})]})]})]})}),e.jsxs(ls,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Ae,{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(Fn,{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(ay,{className:"h-8 w-8 mb-1 opacity-50"}),e.jsx("span",{className:"text-xs",children:"No thumbnail"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a thumbnail image for this course. Recommended: 800×450px (16:9)."}),e.jsx("input",{ref:ee,type:"file",accept:"image/*",className:"hidden",onChange:async tt=>{var Ge;const at=(Ge=tt.target.files)==null?void 0:Ge[0];if(!(!at||!n)){oe(!0);try{const dt=at.name.split(".").pop(),Bt=`${n.id}/thumbnail.${dt}`,{error:kt}=await q.storage.from("lms-thumbnails").upload(Bt,at,{upsert:!0});if(kt)throw kt;const{data:Qt}=q.storage.from("lms-thumbnails").getPublicUrl(Bt),ns=`${Qt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:ns}),ae.success("Thumbnail uploaded")}catch{ae.error("Failed to upload thumbnail")}finally{oe(!1),ee.current&&(ee.current.value="")}}}}),e.jsxs(B,{variant:"outline",size:"sm",disabled:ne,onClick:()=>{var tt;return(tt=ee.current)==null?void 0:tt.click()},children:[ne?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-2"}),ne?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Course Settings"})}),e.jsxs(Ae,{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(vn,{checked:n.is_sequential,onCheckedChange:tt=>a.mutateAsync({id:n.id,is_sequential:tt}).then(()=>ae.success("Updated"))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this course visible to agents with access"})]}),e.jsx(vn,{checked:n.is_published,onCheckedChange:tt=>a.mutateAsync({id:n.id,is_published:tt}).then(()=>ae.success("Updated"))})]})]})]})]})]})]}),e.jsx(bs,{open:g||!!p,onOpenChange:tt=>{tt||(b(!1),f(null))},children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:p?"Edit Module":"Add Module"}),e.jsx(Qn,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ge,{value:v.title,onChange:tt=>j(at=>({...at,title:tt.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{value:v.description,onChange:tt=>j(at=>({...at,description:tt.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Et("border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors hover:border-primary/50",M?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var tt;return(tt=Y.current)==null?void 0:tt.click()},children:[e.jsx("input",{ref:Y,type:"file",accept:"video/*",className:"hidden",onChange:tt=>{var Ge;const at=(Ge=tt.target.files)==null?void 0:Ge[0];at&&(F(at),j(dt=>({...dt,video_url:""})))}}),M?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(vr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:M.name}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:tt=>{tt.stopPropagation(),F(null)},children:e.jsx(Fn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(Sa,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),W&&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(ss,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",z,"%"]})]}),e.jsx(xi,{value:z,className:"h-1.5"})]}),!M&&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(ge,{value:v.video_url,onChange:tt=>j(at=>({...at,video_url:tt.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Text Content"}),e.jsx(Ts,{value:v.text_content,onChange:tt=>j(at=>({...at,text_content:tt.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Duration (minutes)"}),e.jsx(ge,{type:"number",value:v.duration_minutes,onChange:tt=>j(at=>({...at,duration_minutes:tt.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>{b(!1),f(null),F(null)},children:"Cancel"}),e.jsxs(B,{onClick:p?we:Je,disabled:!v.title.trim()||W,children:[W?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),W?"Uploading...":p?"Save Changes":"Add Module"]})]})]})}),e.jsx(bs,{open:!!_,onOpenChange:tt=>{tt||S(null)},children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add Resource"}),e.jsx(Qn,{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(se,{children:"Title"}),e.jsx(ge,{value:A.title,onChange:tt=>T(at=>({...at,title:tt.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Type"}),e.jsxs(us,{value:A.resource_type,onValueChange:tt=>T(at=>({...at,resource_type:tt})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"link",children:"Link"}),e.jsx(Ze,{value:"pdf",children:"PDF"}),e.jsx(Ze,{value:"template",children:"Template"}),e.jsx(Ze,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"URL"}),e.jsx(ge,{value:A.url,onChange:tt=>T(at=>({...at,url:tt.target.value})),placeholder:"https://..."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{onClick:()=>_&&Ne(_),disabled:!A.title.trim(),children:"Add Resource"})]})]})}),e.jsx(bs,{open:Me,onOpenChange:Te,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Course"}),e.jsx(Qn,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ge,{value:de,onChange:tt=>ie(tt.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{value:ye,onChange:tt=>_e(tt.target.value),rows:3})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Te(!1),children:"Cancel"}),e.jsx(B,{onClick:rt,disabled:!de.trim(),children:"Save"})]})]})})]})}function Esn(){return lt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_stats");if(t)throw t;return s}})}function Asn(){return lt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function Msn(s){return lt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.rpc("get_lms_agent_progress",{p_course_id:s});if(n)throw n;return t||[]},enabled:!!s})}function Isn(){const s=In(),{data:t,isLoading:n}=Esn(),{data:r,isLoading:a}=Asn(),[i,l]=N.useState(null),{data:o,isLoading:c}=Msn(i),[d,u]=N.useState(""),h=r==null?void 0:r.find(g=>g.course_id===i),p=o==null?void 0:o.filter(g=>{var b,v;return!d||((b=g.agent_name)==null?void 0:b.toLowerCase().includes(d.toLowerCase()))||((v=g.email)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))}),f=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:$u,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:xr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:_n,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:vo,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:mo,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:yo,color:"text-rose-500"}];return e.jsx(Cs,{title:"LevelUp U - Stats",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(Wr,{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(_d,{className:"h-7 w-7 text-primary"}),"LevelUp U — Analytics"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Track enrollment, progress, and completion across all courses"})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3",children:f.map(g=>e.jsx(fe,{className:Et("transition-all",n&&"animate-pulse"),children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(g.icon,{className:Et("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(yo,{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(fe,{className:"animate-pulse",children:e.jsx(Ae,{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 b=i===g.course_id;return e.jsx(fe,{className:Et("cursor-pointer transition-all hover:shadow-md",b?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(b?null:g.course_id),children:e.jsxs(Ae,{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(ze,{variant:g.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:g.is_published?"Live":"Draft"})]})}),e.jsx(ga,{className:Et("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",b&&"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(xi,{value:g.avg_completion_pct,className:"h-2"})]})]})},g.course_id)})}):e.jsx(fe,{className:"border-dashed",children:e.jsx(Ae,{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(_b,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{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(fe,{className:"animate-pulse",children:e.jsx(Ae,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},g))}):p!=null&&p.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:p.map((g,b)=>{const v=g.completion_pct>=100;return e.jsx(fe,{className:Et("transition-all",v&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Et("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",b===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":b===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":b===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:b+1}),e.jsxs(aa,{className:"h-9 w-9 shrink-0",children:[e.jsx(ri,{src:g.avatar_url||void 0}),e.jsx(ia,{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}),v&&e.jsxs(ze,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(xr,{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(gr,{className:"h-3 w-3"}),ks(new Date(g.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Et("text-sm font-bold",v?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[g.completion_pct,"%"]}),e.jsx(xi,{value:g.completion_pct,className:"h-1.5 mt-1"})]})]})})},g.user_id)})}):e.jsx(fe,{className:"border-dashed",children:e.jsx(Ae,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:d?"No agents match your search":"No agents have started this course yet"})})})]}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"py-16 text-center",children:[e.jsx(_n,{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 Psn(){const{user:s}=gs(),t=In(),{data:n,isLoading:r}=Nsn();return e.jsx(Cs,{title:"LevelUp U",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/10 via-primary/5 to-background border p-8",children:[e.jsx("div",{className:"relative z-10",children:e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"h-12 w-12 rounded-xl bg-primary/15 flex items-center justify-center",children:e.jsx(_d,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"LevelUp U"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Your training & development hub"})]})]})}),e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-primary/5 rounded-full -translate-y-1/2 translate-x-1/2"})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(a=>e.jsx(fe,{className:"animate-pulse",children:e.jsxs(Ae,{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(Lsn,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx($u,{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 Lsn({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=MNt(s.id),i=(a==null?void 0:a.filter(c=>c.completed).length)??0,l=r>0?Math.round(i/r*100):0;return e.jsxs(fe,{className:"group cursor-pointer hover:shadow-lg transition-all hover:border-primary/50 overflow-hidden",onClick:n,children:[s.thumbnail_url?e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:s.thumbnail_url,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}):e.jsx("div",{className:"aspect-video bg-gradient-to-br from-primary/15 via-primary/5 to-muted flex items-center justify-center",children:e.jsx(_d,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Ae,{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($u,{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(zv,{className:"h-3.5 w-3.5"}):e.jsx(UA,{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(xi,{value:l,className:"h-1.5"})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs("span",{className:"text-xs text-primary font-medium flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[l===100?"Review":l>0?"Continue":"Start"," Course",e.jsx(ga,{className:"h-3.5 w-3.5"})]})})]})]})}function Dsn(){const{courseId:s}=_i(),t=In(),{user:n}=gs(),{data:r,isLoading:a}=ksn(s),{data:i}=MNt(s),l=Ssn(),[o,c]=N.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,p=d.length>0?Math.round(h/d.length*100):0;N.useEffect(()=>{if(d.length>0&&!o){const _=d.find(S=>!u.has(S.id));c((_==null?void 0:_.id)||d[0].id)}},[d,o,u]);const f=d.find(_=>_.id===o),g=d.findIndex(_=>_.id===o),b=(_,S)=>{if(!(r!=null&&r.is_sequential)||S===0)return!1;for(let A=0;A{if(!(!f||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:f.id,userId:n.id}),ae.success("Module completed! 🎉"),g{const S=_.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(S)return`https://www.youtube.com/embed/${S[1]}`;const A=_.match(/vimeo\.com\/(\d+)/);if(A)return`https://player.vimeo.com/video/${A[1]}`;const T=_.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return T?`https://iframe.mediadelivery.net/embed/${T[1]}/${T[2]}?responsive=true`:_};return a?e.jsx(Cs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):r?e.jsx(Cs,{title:r.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(Wr,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:r.title}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[h,"/",d.length," completed"]}),e.jsxs("span",{children:[p,"%"]})]})]}),e.jsx("div",{className:"w-32",children:e.jsx(xi,{value:p,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(fe,{className:"lg:sticky lg:top-4",children:e.jsxs(Ae,{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(mi,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((_,S)=>{const A=b(_,S),T=u.has(_.id),D=_.id===o;return e.jsxs("button",{disabled:A,onClick:()=>!A&&c(_.id),className:Et("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",D?"bg-primary/10 text-primary":"hover:bg-muted/50",A&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:A?e.jsx(Rc,{className:"h-4 w-4 text-muted-foreground"}):T?e.jsx(xr,{className:"h-4 w-4 text-green-500"}):e.jsx(dm,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Et("font-medium truncate",D&&"text-primary"),children:[S+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(gr,{className:"h-3 w-3"})," ",_.duration_minutes," min"]})]})]},_.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:f?e.jsxs(e.Fragment,{children:[f.video_url&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:j(f.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:f.title}),f.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:f.description})]}),u.has(f.id)?e.jsxs(ze,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(B,{size:"sm",onClick:v,disabled:l.isPending,children:[e.jsx(xr,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),f.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:f.text_content}),f.resources&&f.resources.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Resources"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:f.resources.map(_=>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(Nr,{className:"h-4 w-4 text-red-500 shrink-0"}):_.resource_type==="template"?e.jsx(_d,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(El,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:_.title}),e.jsx(tr,{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(B,{variant:"outline",size:"sm",disabled:g===0,onClick:()=>g>0&&c(d[g-1].id),children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),gc(d[g+1].id),children:["Next ",e.jsx(ga,{className:"h-3.5 w-3.5 ml-1"})]}):p===100&&e.jsx(ze,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(fe,{children:e.jsx(Ae,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(Cs,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function Rsn({headline:s,subtext:t,primaryColor:n,accentColor:r,heroImageUrl:a,logoUrl:i,brokerageName:l}){return e.jsxs("section",{className:"relative min-h-screen flex items-center justify-center overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(160deg, ${r} 0%, ${n} 50%, ${r}ee 100%)`}}),a&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${a})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px), radial-gradient(circle at 75% 75%, white 1px, transparent 1px)",backgroundSize:"60px 60px"}}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-white to-transparent"}),e.jsxs("div",{className:"relative z-10 text-center max-w-4xl mx-auto px-6 py-24",children:[i&&e.jsx(Zn.img,{src:i,alt:l,className:"h-14 md:h-20 w-auto mx-auto mb-10 drop-shadow-2xl",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.8,delay:.2}}),e.jsx(Zn.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.3},children:e.jsx("span",{className:"inline-block text-white/70 text-sm md:text-base font-medium tracking-[0.2em] uppercase mb-6",children:"Your Next Chapter Starts Here"})}),e.jsx(Zn.h1,{className:"text-4xl md:text-6xl lg:text-7xl font-bold text-white mb-8 leading-[1.1] tracking-tight",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.9,delay:.5},children:s}),e.jsx(Zn.p,{className:"text-lg md:text-xl text-white/80 mb-12 max-w-2xl mx-auto leading-relaxed font-light",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.7},children:t}),e.jsxs(Zn.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.7,delay:.9},className:"flex flex-col sm:flex-row items-center justify-center gap-4",children:[e.jsxs("a",{href:"#apply",className:"group inline-flex items-center gap-3 px-10 py-4 rounded-full text-lg font-semibold shadow-2xl transition-all duration-300 hover:scale-105 hover:shadow-3xl",style:{backgroundColor:"white",color:r},children:["Get In Touch",e.jsx(za,{className:"h-5 w-5 transition-transform group-hover:translate-x-1"})]}),e.jsx("a",{href:"#benefits",className:"inline-flex items-center gap-2 px-8 py-4 rounded-full text-base font-medium text-white/90 border border-white/30 backdrop-blur-sm transition-all duration-300 hover:bg-white/10 hover:border-white/50",children:"Learn More"})]})]}),e.jsx(Zn.div,{className:"absolute bottom-8 left-1/2 -translate-x-1/2 z-10",animate:{y:[0,8,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:e.jsx("div",{className:"w-6 h-10 border-2 border-white/40 rounded-full flex justify-center pt-2",children:e.jsx("div",{className:"w-1.5 h-3 bg-white/60 rounded-full"})})})]})}function Ny({children:s,className:t="",delay:n=0,direction:r="up"}){const a=N.useRef(null),i=NJt(a,{once:!0,margin:"-80px"}),l={hidden:{opacity:0,y:r==="up"?40:0,x:r==="left"?-40:r==="right"?40:0},visible:{opacity:1,y:0,x:0}};return e.jsx(Zn.div,{ref:a,initial:"hidden",animate:i?"visible":"hidden",variants:l,transition:{duration:.7,delay:n,ease:[.25,.46,.45,.94]},className:t,children:s})}function Osn({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(Ny,{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(Ny,{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 Fsn({images:s,primaryColor:t,accentColor:n}){const[r,a]=N.useState(null);return s.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"py-24 md:py-32 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(Ny,{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(_n,{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(Ny,{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(Fn,{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 zsn({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(Ny,{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(Ny,{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(yb,{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 Bsn({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(Ny,{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(Ny,{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(se,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(ge,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(ge,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(ge,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(ge,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(ge,{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(se,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(ge,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(ge,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(ge,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(Ts,{value:s.why_interested,onChange:l=>t(o=>({...o,why_interested:l.target.value})),rows:3,className:"rounded-lg border-gray-200 focus:border-gray-400 transition-colors resize-none",placeholder:"Tell us about your goals and what you're looking for..."})]}),e.jsx(B,{type:"submit",className:"w-full h-13 text-base font-semibold rounded-xl group transition-all duration-300 hover:shadow-lg",style:{background:`linear-gradient(135deg, ${a}, ${i})`},disabled:r,children:r?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Submitting..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:["Send My Info",e.jsx(za,{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(hh,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function $sn({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=N.useState(1),[d,u]=N.useState(""),h=3,p=!!s.first_name&&!!s.email,f=g=>{u(g),t(b=>({...b,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(Ny,{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(Rc,{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(Ny,{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(Pye,{mode:"wait",children:[o===1&&e.jsxs(Zn.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-3",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"What's most important to you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-5",children:"Pick the one that resonates most. We'll tailor the conversation."}),[{val:"Better commission split / cap",label:"Better Splits & Caps",icon:"💰"},{val:"Better technology and tools",label:"Better Tech & Tools",icon:"🛠️"},{val:"Better training and mentorship",label:"Better Training",icon:"📚"},{val:"Better culture and team",label:"Better Culture",icon:"🤝"},{val:"Just exploring options confidentially",label:"Just Exploring",icon:"🔍"}].map(g=>e.jsxs("button",{type:"button",onClick:()=>f(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(za,{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(Zn.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"How can we reach you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"We'll text first, on your schedule."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(ge,{required:!0,value:s.first_name,onChange:g=>t(b=>({...b,first_name:g.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(ge,{value:s.last_name,onChange:g=>t(b=>({...b,last_name:g.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(ge,{type:"email",required:!0,value:s.email,onChange:g=>t(b=>({...b,email:g.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(ge,{value:s.phone,onChange:g=>t(b=>({...b,phone:g.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs(B,{type:"button",disabled:!p,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(za,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Zn.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"A few quick details (optional)"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"Helps us prepare a more personalized comp comparison."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(ge,{value:s.current_brokerage,onChange:g=>t(b=>({...b,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(se,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(ge,{type:"number",min:"0",value:s.experience_years,onChange:g=>t(b=>({...b,experience_years:g.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(ge,{value:s.annual_production,onChange:g=>t(b=>({...b,annual_production:g.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Ts,{value:s.why_interested,onChange:g=>t(b=>({...b,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(B,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(B,{type:"button",onClick:n,disabled:r,className:"flex-1 h-12 text-white font-semibold rounded-xl",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:r?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Sending..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4"})," Start the Conversation"]})})]})]},"step3")]}),l&&e.jsxs("div",{className:"mt-6 pt-5 border-t border-gray-100 grid grid-cols-3 gap-2 text-[10px] text-gray-400",children:[e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(hh,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Ci,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Pr,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function Usn({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=Ua(),[l,o]=N.useState("250000"),[c,d]=N.useState("12"),[u,h]=N.useState("70"),[p,f]=N.useState("150"),[g,b]=N.useState(""),[v,j]=N.useState(!1),[_,S]=N.useState(!1),A=s.commission_split_pct??80,T=s.cap_amount??16e3,D=s.post_cap_split_pct??100,L=s.monthly_fee??99,M=s.transaction_fee??0,F=N.useMemo(()=>{const W=parseFloat(l)||0,K=Math.max(0,parseInt(c,10)||0),Y=parseFloat(u)||0,ee=parseFloat(p)||0,ne=W*(Y/100)-ee*12-M*K,oe=1-A/100,pe=oe>0?T/oe:W,ce=Math.min(W,pe),de=Math.max(0,W-pe),ie=ce*oe+de*(1-D/100),ye=W-ie-L*12-M*K,_e=ye-ne;return{currentNet:ne,newNet:ye,diff:_e}},[l,c,u,p,A,T,D,L,M]),z=W=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(W),V=async W=>{if(W.preventDefault(),!!g){S(!0);try{const{error:K}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:g,source:"calculator"});if(K)throw K;const{error:Y}=await q.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(p)||0},plan:{commission_split_pct:A,cap_amount:T,post_cap_split_pct:D,monthly_fee:L,transaction_fee:M},result:F,primary_color:t,accent_color:n}});Y&&console.error("Breakdown email failed:",Y),j(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(K){i({title:"Error",description:K.message,variant:"destructive"})}finally{S(!1)}}};return e.jsx("section",{className:"py-20 md:py-28 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsx(Ny,{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(Rc,{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(Ny,{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(xw,{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(se,{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(ge,{type:"number",value:l,onChange:W=>o(W.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(ge,{type:"number",min:"0",value:c,onChange:W=>d(W.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(ge,{type:"number",value:u,onChange:W=>h(W.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(se,{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(ge,{type:"number",value:p,onChange:W=>f(W.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(mo,{className:"h-5 w-5"}),e.jsxs("h3",{className:"font-semibold",children:["Your Earnings at ",a]})]}),e.jsxs("div",{className:"space-y-4 mb-6",children:[e.jsxs("div",{className:"flex items-baseline justify-between border-b border-white/20 pb-3",children:[e.jsx("span",{className:"text-white/70 text-sm",children:"Current take-home"}),e.jsx("span",{className:"text-xl font-semibold",children:z(F.currentNet)})]}),e.jsxs("div",{className:"flex items-baseline justify-between border-b border-white/20 pb-3",children:[e.jsx("span",{className:"text-white/70 text-sm",children:"With us"}),e.jsx("span",{className:"text-xl font-semibold",children:z(F.newNet)})]})]}),e.jsxs(Zn.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},className:"bg-white/10 backdrop-blur rounded-2xl p-5 text-center",children:[e.jsx("p",{className:"text-white/80 text-xs uppercase tracking-wide mb-1",children:F.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[F.diff>=0?"+":"",z(F.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:F.diff>=0?"more per year":"per year"})]},F.diff),s.show_email_capture&&!v&&e.jsxs("form",{onSubmit:V,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(ge,{type:"email",required:!0,value:g,onChange:W=>b(W.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx(B,{type:"submit",disabled:_,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),v&&e.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-white/90 bg-white/10 rounded-lg p-3",children:[e.jsx(Lr,{className:"h-4 w-4"})," Check your inbox shortly."]})]})]})}),e.jsx("p",{className:"text-center text-xs text-gray-400 mt-4",children:"Estimates only. Actual results vary by individual production and plan terms."})]})})}function qsn({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=Ua(),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,p]=N.useState(!1),f=async g=>{g.preventDefault(),p(!0);try{const{error:b}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:i,first_name:o||null,source:"lead_magnet",user_agent:navigator.userAgent,referrer:document.referrer||null});if(b)throw b;u(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(b){a({title:"Error",description:b.message,variant:"destructive"})}finally{p(!1)}};return e.jsx("section",{className:"py-20 md:py-24 px-6 bg-white",children:e.jsx("div",{className:"max-w-3xl mx-auto",children:e.jsx(Ny,{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(TA,{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(Rc,{className:"h-2.5 w-2.5"})," No call required — instant download"]}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold tracking-tight mb-2",style:{color:n},children:s.title||"Get the Full Comp Plan PDF"}),e.jsx("p",{className:"text-gray-500 leading-relaxed mb-5",children:s.description||"See exactly how splits, caps, and fees work — no call required."}),d?e.jsxs("div",{className:"flex items-center gap-2 p-4 rounded-xl bg-green-50 border border-green-200 text-green-800 text-sm",children:[e.jsx(Lr,{className:"h-5 w-5 shrink-0"}),e.jsxs("span",{children:["Sent! ",s.pdf_url?"Your download should open in a new tab.":"Check your email shortly."]})]}):e.jsxs("form",{onSubmit:f,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(ge,{value:o,onChange:g=>c(g.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(ge,{type:"email",required:!0,value:i,onChange:g=>l(g.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs(B,{type:"submit",disabled:h,className:"w-full sm:w-auto h-12 px-6 text-white font-semibold",style:{background:`linear-gradient(135deg, ${t}, ${n})`},children:[e.jsx(TA,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function Vsn(){const{slug:s}=_i(),{toast:t}=Ua(),[n,r]=N.useState(!1),[a,i]=N.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});N.useEffect(()=>{document.body.classList.add("recruit-landing-page");const F=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(K=>document.querySelectorAll(K).forEach(Y=>Y.style.display="none"))};F();const z=[setTimeout(F,500),setTimeout(F,1500),setTimeout(F,3e3)],V=new MutationObserver(F);return V.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),z.forEach(clearTimeout),V.disconnect()}},[]);const{data:l,isLoading:o,error:c}=lt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:F,error:z}=await q.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(z)throw z;return F},enabled:!!s}),{data:d}=lt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:F,error:z}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(z&&z.code!=="PGRST116")throw z;return F},enabled:!!(l!=null&&l.id)}),u=gt({mutationFn:async()=>{const F={brokerage_id:l.id,first_name:a.first_name,last_name:a.last_name||null,email:a.email,phone:a.phone||null,current_brokerage:a.current_brokerage||null,experience_years:a.experience_years?parseInt(a.experience_years):null,annual_production:a.annual_production||null,license_number:a.license_number||null,why_interested:a.why_interested||null},{error:z}=await q.from("recruit_interest_submissions").insert(F);if(z)throw z;q.functions.invoke("recruit-lead-notify",{body:{lead:F,brokerage_id:l.id}}).catch(V=>console.error("Lead notification error:",V))},onSuccess:()=>r(!0),onError:F=>t({title:"Error",description:F.message,variant:"destructive"})});if(o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-3 border-gray-200 border-t-gray-800"}),e.jsx("span",{className:"text-sm text-gray-400 tracking-wide",children:"Loading..."})]})});if(c||!l||!l.recruit_form_enabled)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"max-w-md w-full mx-4 text-center",children:[e.jsx(Ga,{className:"h-10 w-10 mx-auto text-gray-300 mb-4"}),e.jsx("p",{className:"text-gray-400 text-lg",children:"This page is not available."})]})});const h=d,p=(h==null?void 0:h.primary_color)||"#406E71",f=(h==null?void 0:h.accent_color)||"#2a4c64",g=(h==null?void 0:h.benefits)||[],b=(h==null?void 0:h.testimonials)||[],v=(h==null?void 0:h.gallery_images)||[],j=(h==null?void 0:h.hero_headline)||`Join ${l.name}`,_=(h==null?void 0:h.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",S=(h==null?void 0:h.calculator_enabled)===!0,A=(h==null?void 0:h.calculator_config)||{},T=(h==null?void 0:h.lead_magnet_enabled)===!0,D=(h==null?void 0:h.lead_magnet_config)||{},L=(h==null?void 0:h.form_style)||"classic",M=(h==null?void 0:h.confidential_messaging)!==!1;return n?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs(Zn.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{duration:.6},className:"max-w-md w-full mx-4 text-center",children:[e.jsx("div",{className:"h-20 w-20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg",style:{background:`linear-gradient(135deg, ${p}, ${f})`},children:e.jsx(Lr,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:f},children:"Thank You!"}),e.jsxs("p",{className:"text-gray-500 text-lg leading-relaxed mb-8",children:["Your interest in joining ",e.jsx("span",{className:"font-semibold",style:{color:f},children:l.name})," has been received. A member of our recruitment team will be in touch shortly."]}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full",style:{backgroundColor:p}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":p,"--recruit-accent":f},children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-40 bg-white/80 backdrop-blur-lg border-b border-gray-100/50",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-6 h-14 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[(h==null?void 0:h.logo_url)&&e.jsx("img",{src:h.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:f},children:l.name})]}),e.jsxs("a",{href:"#apply",className:"inline-flex items-center gap-2 px-5 py-2 rounded-full text-sm font-semibold text-white transition-all duration-300 hover:shadow-md hover:scale-105",style:{background:`linear-gradient(135deg, ${p}, ${f})`},children:["Apply Now ",e.jsx(za,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(Rsn,{headline:j,subtext:_,primaryColor:p,accentColor:f,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx(Osn,{benefits:g,accentColor:f,primaryColor:p}),e.jsx(Fsn,{images:v,primaryColor:p,accentColor:f}),e.jsx(zsn,{testimonials:b,primaryColor:p,accentColor:f}),S&&e.jsx(Usn,{config:A,primaryColor:p,accentColor:f,brokerageId:l.id,brokerageName:l.name}),T&&e.jsx(qsn,{config:D,primaryColor:p,accentColor:f,brokerageId:l.id}),L==="multi_step"?e.jsx($sn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:p,accentColor:f,showConfidentialBadges:M}):e.jsx(Bsn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:p,accentColor:f}),e.jsx("footer",{className:"py-10 text-center bg-white border-t border-gray-100",children:e.jsxs("p",{className:"text-sm text-gray-400",children:["© ",new Date().getFullYear()," ",l.name,". All rights reserved."]})})]})}function Hsn(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 Gsn(){var p,f,g,b;const{shareToken:s}=_i(),t=N.useRef(!1),{data:n,isLoading:r,error:a}=lt({queryKey:["public-recruit-video",s],queryFn:async()=>{var T;if(!s)throw new Error("No token");const{data:v,error:j}=await q.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(j)throw j;const{data:_}=await q.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(T=v.video)==null?void 0:T.owner_user_id).single(),{data:S}=await q.from("brokerages").select("name").eq("id",v.brokerage_id).single(),{data:A}=await q.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",v.brokerage_id).maybeSingle();return{rv:v,profile:_,brokerage:S,settings:A}},enabled:!!s});if(N.useEffect(()=>{var v;!((v=n==null?void 0:n.rv)!=null&&v.id)||t.current||(t.current=!0,q.rpc("log_recruit_video_view",{p_recruit_video_id:n.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(p=n==null?void 0:n.rv)==null?void 0:p.id]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=n,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((f=i.prospect)==null?void 0:f.first_name)||"there",h=(g=i.video)!=null&&g.playback_url?Hsn(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(Yo,{children:e.jsx("title",{children:o!=null&&o.name?`${o.name} — A Message For You`:"Personal Video Message"})}),e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:[e.jsx("header",{className:"border-b bg-white/80 backdrop-blur-sm",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-4 flex items-center gap-3",children:[(c==null?void 0:c.logo_url)&&e.jsx("img",{src:c.logo_url,alt:"",className:"h-8 object-contain"}),e.jsx("span",{className:"font-semibold text-sm",style:{color:d},children:(o==null?void 0:o.name)||"Recruiting"})]})}),e.jsxs("main",{className:"max-w-3xl mx-auto px-4 py-8 space-y-6",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground",children:["Hey ",u,", ",l==null?void 0:l.name," has a message for you"]}),i.message&&e.jsx("p",{className:"text-muted-foreground max-w-xl mx-auto",children:i.message})]}),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:((b=l==null?void 0:l.name)==null?void 0:b.charAt(0))||"?"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold",children:l==null?void 0:l.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(l==null?void 0:l.title)||"Recruiter"," · ",o==null?void 0:o.name]})]})]}),(l==null?void 0:l.recruit_cta_url)&&e.jsx("div",{className:"text-center",children:e.jsx(B,{size:"lg",asChild:!0,className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{q.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:e.jsxs("a",{href:l.recruit_cta_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(yr,{className:"h-5 w-5 mr-2"})," Schedule a Conversation"]})})})]}),e.jsx("footer",{className:"text-center py-6 text-xs text-muted-foreground",children:"Powered by LevelUp"})]})]})}const Wsn="relzejiswnotikjgvjhz",qXe=`https://${Wsn}.supabase.co/functions/v1/recruit-unsubscribe`;function Ksn(){const[s]=yl(),t=s.get("token")||"",[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState({});N.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const f=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(j=>document.querySelectorAll(j).forEach(_=>_.style.display="none"))};f();const g=[setTimeout(f,500),setTimeout(f,1500),setTimeout(f,3e3)],b=new MutationObserver(f);return b.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),g.forEach(clearTimeout),b.disconnect()}},[]),N.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${qXe}?token=${encodeURIComponent(t)}`).then(async f=>{const g=await f.json();if(!f.ok)throw new Error(g.error||"Lookup failed");h(g),g.already_unsubscribed&&o(!0)}).catch(f=>h({error:f.message||"Could not load status"})).finally(()=>r(!1))},[t]);const p=async()=>{i(!0);try{const f=await fetch(qXe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),g=await f.json();if(!f.ok)throw new Error(g.error||"Failed");o(!0)}catch(f){h({...u,error:f.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(ss,{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(Gi,{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(xr,{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(ng,{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(ng,{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(se,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(Ts,{id:"reason",value:c,onChange:f=>d(f.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(B,{onClick:p,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(ss,{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 Ysn="relzejiswnotikjgvjhz",VXe=`https://${Ysn}.supabase.co/functions/v1/event-invite-unsubscribe`;function Zsn(){const[s]=yl(),t=s.get("token")||"",[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState({});N.useEffect(()=>(document.body.classList.add("event-invite-unsubscribe-page"),()=>{document.body.classList.remove("event-invite-unsubscribe-page")}),[]),N.useEffect(()=>{if(!t){d({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${VXe}?token=${encodeURIComponent(t)}`).then(async h=>{const p=await h.json();if(!h.ok)throw new Error(p.error||"Lookup failed");d(p),p.already_unsubscribed&&o(!0)}).catch(h=>d({error:h.message||"Could not load status"})).finally(()=>r(!1))},[t]);const u=async()=>{i(!0);try{const h=await fetch(VXe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})}),p=await h.json();if(!h.ok)throw new Error(p.error||"Failed");o(!0)}catch(h){d({...c,error:h.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(ss,{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(Gi,{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(xr,{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(ng,{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(X7,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe from event invites",c.first_name?`, ${c.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll stop receiving event invite emails from LevelUp. Your ",e.jsx("span",{className:"font-medium text-slate-700",children:"Monday weekly digest"})," will keep coming."]}),c.email&&e.jsx("p",{className:"text-xs text-slate-400",children:c.email})]}),e.jsx(B,{onClick:u,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(ss,{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 Qsn(){const s=In(),t=Gt(),{isAdmin:n}=gs(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState(null),{data:d,isLoading:u}=lt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:T},error:D}=await q.auth.getUser();if(D)throw D;if(!T)return[];const{data:L,error:M}=await q.from("social_accounts").select("*").eq("user_id",T.id).order("created_at",{ascending:!1});if(M)throw M;return L}}),h=gt({mutationFn:async T=>{const{data:{user:D},error:L}=await q.auth.getUser();if(L)throw L;if(!D)throw new Error("Not authenticated");const{error:M}=await q.from("social_accounts").delete().eq("id",T).eq("user_id",D.id);if(M)throw M},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),ae.success("Account disconnected successfully")},onError:()=>{ae.error("Failed to disconnect account")}}),p=async T=>{a(!0);try{const{data:D,error:L}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:T}});if(L)throw L;if(D!=null&&D.authUrl)window.location.href=D.authUrl;else throw new Error("Failed to get authorization URL")}catch(D){console.error("Meta OAuth error:",D),ae.error("Failed to start connection. Please try again."),a(!1)}},f=async()=>{a(!0);try{const{data:T,error:D}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(D)throw D;if(T!=null&&T.authUrl)window.location.href=T.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(T){console.error("LinkedIn OAuth error:",T),ae.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},g=async()=>{a(!0);try{const{data:T,error:D}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(D)throw D;if(T!=null&&T.authUrl)window.location.href=T.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(T){console.error("Google OAuth error:",T),ae.error("Failed to start Google connection. Please try again."),a(!1)}},b=(d==null?void 0:d.filter(T=>T.platform==="facebook"))||[],v=(d==null?void 0:d.filter(T=>T.platform==="instagram"))||[],j=(d==null?void 0:d.filter(T=>T.platform==="linkedin"))||[],_=(d==null?void 0:d.filter(T=>T.platform==="google_business"))||[],S=((d==null?void 0:d.length)||0)>0,A=async(T,D)=>{l(T),c(null);try{const{data:L,error:M}=await q.functions.invoke("meta-api-test",{body:{testType:"all",accountId:T}});if(M)throw M;c(L.results||[]),ae.success(L.summary||"API tests completed")}catch(L){console.error("Meta API test error:",L),ae.error("Failed to run API tests")}finally{l(null)}};return e.jsx(Cs,{title:"Social Connections",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-pink-500 via-purple-500 to-blue-500 p-6 md:p-8 text-white",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs(ze,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Post directly from Social Swag"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold mb-2",children:"Connect Your Social Accounts"}),e.jsx("p",{className:"text-white/90 max-w-xl",children:"Link your Facebook Pages and Instagram Business accounts to post content directly from Social Swag with one click."})]})]}),e.jsxs(B,{variant:"ghost",onClick:()=>s("/social-swag-2"),className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Back to Social Swag"]}),S&&e.jsx(fe,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Ae,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(zi,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-green-800 dark:text-green-200",children:"You're all set!"}),e.jsx("p",{className:"text-sm text-green-600 dark:text-green-400",children:"You can now post directly to your connected accounts from Social Swag."})]})]})}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-blue-500/10 p-3",children:e.jsx(Oh,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-lg",children:"Facebook"}),e.jsx(Hn,{children:"Connect your Facebook Pages"})]})]})}),e.jsxs(Ae,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ai,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(T=>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(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:T.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(Oh,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.page_name||T.platform_username||"Facebook Page"}),e.jsx(ze,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Facebook?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs(B,{onClick:()=>p("facebook"),disabled:r,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[r?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(As,{className:"h-4 w-4"}),b.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-gradient-to-br from-purple-500/10 via-pink-500/10 to-orange-500/10 p-3",children:e.jsx(mu,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-lg",children:"Instagram"}),e.jsx(Hn,{children:"Connect Instagram Business accounts"})]})]})}),e.jsxs(Ae,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ai,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length>0?e.jsx("div",{className:"space-y-3",children:v.map(T=>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(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:T.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(mu,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",T.platform_username||"Instagram Account"]}),e.jsx(ze,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Instagram?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs(B,{onClick:()=>p("instagram"),disabled:r,className:"w-full gap-2",variant:v.length>0?"outline":"default",children:[r?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(As,{className:"h-4 w-4"}),v.length>0?"Connect Another Account":"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Use Instagram login for Business or Creator accounts; Facebook Page login is only needed if you want to connect Pages."})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-blue-600/10 p-3",children:e.jsx(bf,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-lg",children:"LinkedIn"}),e.jsx(Hn,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Ae,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ai,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length>0?e.jsx("div",{className:"space-y-3",children:j.map(T=>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(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:T.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(bf,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.platform_username||"LinkedIn Account"}),e.jsx(ze,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect LinkedIn?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs(B,{onClick:f,disabled:r,className:"w-full gap-2",variant:j.length>0?"outline":"default",children:[r?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(As,{className:"h-4 w-4"}),j.length>0?"Reconnect LinkedIn":"Connect LinkedIn"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Share content directly to your LinkedIn profile"})]})]}),e.jsxs(fe,{className:`relative overflow-hidden ${n?"":"opacity-75"}`,children:[!n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(ze,{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(ze,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-red-500/10 p-3",children:e.jsx(Ca,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-lg",children:"Google Business"}),e.jsx(Hn,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Ae,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ai,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):_.length>0?e.jsx("div",{className:"space-y-3",children:_.map(T=>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(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:T.profile_picture_url||""}),e.jsx(ia,{children:e.jsx(Ca,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.page_name||T.platform_username||"Google Business"}),e.jsx(ze,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Rh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Google Business?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:n?"No Google Business account connected yet":"Google Business Profile integration is coming soon!"}),e.jsxs(B,{onClick:n?g:void 0,disabled:!n||r,className:"w-full gap-2",variant:_.length>0?"outline":"default",children:[r?e.jsx(Ai,{className:"h-4 w-4 animate-spin"}):e.jsx(As,{className:"h-4 w-4"}),_.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&&(b.length>0||v.length>0)&&e.jsxs(fe,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-amber-500/10 p-3",children:e.jsx(XS,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(Hn,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Ae,{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:[b.map(T=>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(Oh,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:T.page_name||"Facebook Page"})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(T.id),disabled:i===T.id,children:i===T.id?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(XS,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${T.id}`)),v.map(T=>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(mu,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",T.platform_username||"Instagram"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(T.id),disabled:i===T.id,children:i===T.id?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(XS,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${T.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((T,D)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[T.status==="success"?e.jsx(xr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):T.status==="pending"?e.jsx(ss,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(Gc,{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:T.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:T.details})]})]},D))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Note: Facebook posts are auto-deleted. Instagram posts will remain and should be manually deleted. Allow up to 24 hours for Meta to register the API calls."})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-lg",children:"How it works"})}),e.jsx(Ae,{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 Xsn(){const[s]=yl(),t=In(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing your connection...");return N.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:f}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u,callbackPath:"/social-connections/callback"}});if(f)throw f;if(p!=null&&p.success)r("success"),i(`Successfully connected ${((h=p.accounts)==null?void 0:h.length)||0} account(s)!`),ae.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),r("error"),i(p instanceof Error?p.message:"Failed to connect accounts"),ae.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[n==="loading"&&e.jsx(ss,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(zi,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Gc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Pt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Hn,{children:a})]}),e.jsx(Ae,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function Jsn(){const[s]=yl(),t=In(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your Google Business Profile...");return N.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:h,error:p}=await q.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:u}});if(p)throw p;if(h!=null&&h.success)r("success"),i(h.message||"Successfully connected Google Business Profile!"),ae.success("Google Business Profile connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Google OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Google Business Profile"),ae.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[n==="loading"&&e.jsx(ss,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(zi,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Gc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Pt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Hn,{children:a})]}),e.jsx(Ae,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/social-connections"),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function enn(){const[s]=yl(),t=In(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your LinkedIn account...");return N.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("state"),d=s.get("error"),u=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,u),r("error"),i(u||"Failed to connect LinkedIn account"),ae.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:f}=await q.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(f)throw f;if(p!=null&&p.success)r("success"),i(`Successfully connected ${((h=p.accounts)==null?void 0:h.length)||1} LinkedIn account`),ae.success("LinkedIn connected successfully!");else throw new Error((p==null?void 0:p.error)||"Failed to connect LinkedIn account")}catch(p){console.error("LinkedIn callback error:",p),r("error"),i(p instanceof Error?p.message:"Failed to connect LinkedIn account"),ae.error("Failed to connect LinkedIn")}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-background",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{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(ss,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(zi,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(Gc,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(Pt,{className:"flex items-center justify-center gap-2",children:[e.jsx(bf,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Hn,{children:a})]}),e.jsx(Ae,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/mission-control/integrations"),disabled:n==="loading",children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function tnn(){const s=In(),[t,n]=N.useState(null),{data:r,isLoading:a}=rNt(t||void 0,!0),{data:i,isLoading:l}=M8e(!0),{cartItems:o}=Hye(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(Cs,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(u=>e.jsx(Ws,{className:"h-10 w-24 flex-shrink-0"},u))}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[1,2,3,4].map(u=>e.jsx(Ws,{className:"h-72 w-full"},u))})]})}):e.jsx(Cs,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),e.jsxs(B,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(zg,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(ze,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:c})]})]}),i&&i.length>0&&e.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[e.jsx(B,{variant:t===null?"default":"outline",size:"sm",onClick:()=>n(null),children:"All"}),i.map(u=>e.jsx(B,{variant:t===u.id?"default":"outline",size:"sm",onClick:()=>n(u.id),children:u.name},u.id))]}),r&&r.length>0?e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:r.map(u=>{var h;return e.jsxs(fe,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>d(u),children:[e.jsxs("div",{className:"aspect-square bg-muted relative",children:[u.images&&u.images.length>0?e.jsx("img",{src:((h=u.images.find(p=>p.is_primary))==null?void 0:h.image_url)||u.images[0].image_url,alt:u.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Oc,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx(ze,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(Ae,{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(Oc,{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 INt=N.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));INt.displayName="Breadcrumb";const PNt=N.forwardRef(({className:s,...t},n)=>e.jsx("ol",{ref:n,className:Et("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));PNt.displayName="BreadcrumbList";const cpe=N.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Et("inline-flex items-center gap-1.5",s),...t}));cpe.displayName="BreadcrumbItem";const PTe=N.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?uAe:"a";return e.jsx(a,{ref:r,className:Et("transition-colors hover:text-foreground",t),...n})});PTe.displayName="BreadcrumbLink";const LNt=N.forwardRef(({className:s,...t},n)=>e.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:Et("font-normal text-foreground",s),...t}));LNt.displayName="BreadcrumbPage";const LTe=({children:s,className:t,...n})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Et("[&>svg]:size-3.5",t),...n,children:s??e.jsx(ga,{})});LTe.displayName="BreadcrumbSeparator";function snn(){var K,Y;const{productId:s}=_i(),t=In(),{data:n,isLoading:r}=Ken(s||""),{addToCart:a,cartItems:i}=Hye(),[l,o]=N.useState(null),[c,d]=N.useState(1),[u,h]=N.useState(0),[p,f]=N.useState(null),[g,b]=N.useState(!1),[v,j]=N.useState(!1),_=(K=n==null?void 0:n.variants)==null?void 0:K.find(ee=>ee.id===l),S=((Y=n==null?void 0:n.variants)==null?void 0:Y.filter(ee=>ee.is_active))||[],A=Number((n==null?void 0:n.base_price)||0),T=_?Number(_.price_adjustment):0,D=A+T,L=Number((n==null?void 0:n.shipping_fee)||0),M=i.reduce((ee,ne)=>ee+ne.quantity,0),F=async ee=>{if(!ee.target.files||ee.target.files.length===0)return;b(!0);const ne=ee.target.files[0],oe=ne.name.split(".").pop(),pe=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${oe}`;try{const{error:ce}=await q.storage.from("marketplace").upload(pe,ne);if(ce)throw ce;const{data:{publicUrl:de}}=q.storage.from("marketplace").getPublicUrl(pe);f(de),ae.success("Artwork uploaded successfully")}catch(ce){ae.error("Failed to upload artwork: "+ce.message)}finally{b(!1)}},z=()=>{if(n){if(S.length>0&&!l){ae.error("Please select an option");return}a(n,_||void 0,c,p||void 0),j(!0),ae.success("Added to cart!"),setTimeout(()=>j(!1),2e3)}},V=()=>{n!=null&&n.images&&h(ee=>(ee+1)%n.images.length)},W=()=>{n!=null&&n.images&&h(ee=>(ee-1+n.images.length)%n.images.length)};return r?e.jsx(Cs,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(Ws,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-8 w-3/4"}),e.jsx(Ws,{className:"h-6 w-1/4"}),e.jsx(Ws,{className:"h-24 w-full"}),e.jsx(Ws,{className:"h-12 w-full"})]})]})}):n?e.jsxs(Cs,{title:n.name,children:[e.jsx(INt,{className:"mb-6",children:e.jsxs(PNt,{children:[e.jsx(cpe,{children:e.jsx(PTe,{asChild:!0,children:e.jsx(Ln,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(LTe,{}),e.jsx(cpe,{children:e.jsx(PTe,{asChild:!0,children:e.jsx(Ln,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(LTe,{}),e.jsx(cpe,{children:e.jsx(LNt,{children:n.name})})]})}),e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative aspect-square bg-muted rounded-lg overflow-hidden flex items-center justify-center",children:n.images&&n.images.length>0?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:n.images[u].image_url,alt:n.name,className:"max-w-full max-h-full object-contain"}),n.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:W,children:e.jsx(fl,{className:"h-6 w-6"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:V,children:e.jsx(ga,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Oc,{className:"h-24 w-24 text-muted-foreground"})})}),n.images&&n.images.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:n.images.map((ee,ne)=>e.jsx("button",{onClick:()=>h(ne),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${ne===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:ee.image_url,alt:"",className:"w-full h-full object-cover"})},ee.id))}),n.video&&e.jsx(fe,{children:e.jsxs(Ae,{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(ze,{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:["$",D.toFixed(2)]}),L>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",L.toFixed(2)," shipping"]})]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})}),S.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(ee=>e.jsxs(B,{variant:l===ee.id?"default":"outline",onClick:()=>o(ee.id),children:[ee.name,Number(ee.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(ee.price_adjustment)>0?"+":"","$",Number(ee.price_adjustment).toFixed(2),")"]})]},ee.id))})]}),n.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Upload Your Artwork (Optional)"}),p?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:p,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx(B,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>f(null),children:"×"})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6",children:[e.jsx("input",{type:"file",accept:"image/*,.pdf,.ai,.eps",onChange:F,className:"hidden",id:"artwork-upload",disabled:g}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(Sa,{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(se,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(ee=>Math.max(1,ee-1)),children:"-"}),e.jsx(ge,{type:"number",value:c,onChange:ee=>d(Math.max(1,parseInt(ee.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(ee=>ee+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(B,{size:"lg",className:"flex-1",onClick:z,disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(zg,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs(B,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(zg,{className:"h-5 w-5"}),M>0&&e.jsx(ze,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:M})]})]}),n.requires_proof_approval&&e.jsx("p",{className:"text-sm text-muted-foreground bg-muted p-3 rounded-lg",children:"📋 This product requires proof approval before production. You'll receive a proof to review after your order is placed."})]})]})]}):e.jsx(Cs,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Oc,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Product not found"}),e.jsx(B,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function nnn(){const s=In(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=Hye(),[d,u]=N.useState(!1),[h,p]=N.useState(""),f=async()=>{if(t.length===0){ae.error("Your cart is empty");return}u(!0);try{const{data:g,error:b}=await q.functions.invoke("marketplace-checkout",{body:{items:t.map(v=>{var j;return{product_id:v.product.id,variant_id:((j=v.variant)==null?void 0:j.id)||null,quantity:v.quantity,artwork_url:v.artworkUrl||null}}),notes:h.trim()||null}});if(b)throw b;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(Cs,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ww,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your cart is empty"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Add some products to get started!"}),e.jsx(B,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Cs,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(g=>{var b,v;return e.jsx(fe,{children:e.jsx(Ae,{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:((b=g.product.images.find(j=>j.is_primary))==null?void 0:b.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(ww,{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(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return n(g.product.id,(j=g.variant)==null?void 0:j.id)},children:e.jsx(bn,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return r(g.product.id,(j=g.variant)==null?void 0:j.id,g.quantity-1)},disabled:g.quantity<=1,children:e.jsx(xb,{className:"h-3 w-3"})}),e.jsx(ge,{type:"number",value:g.quantity,onChange:j=>{var _;return r(g.product.id,(_=g.variant)==null?void 0:_.id,parseInt(j.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return r(g.product.id,(j=g.variant)==null?void 0:j.id,g.quantity+1)},children:e.jsx(As,{className:"h-3 w-3"})})]})]})]})})},`${g.product.id}-${((v=g.variant)==null?void 0:v.id)||"base"}`)}),e.jsx(B,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(fe,{className:"sticky top-4",children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Order Summary"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((g,b)=>g+b.quantity,0)," items)"]}),e.jsxs("span",{children:["$",i().toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",l().toFixed(2)]})]}),e.jsx(cl,{}),e.jsxs("div",{className:"flex justify-between font-bold text-lg",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",o().toFixed(2)]})]}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Ts,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:g=>p(g.target.value),rows:3,className:"resize-none"})]}),e.jsx(B,{className:"w-full",size:"lg",onClick:f,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(za,{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 rnn(){const s=In(),{data:t,isLoading:n}=atn();return n?e.jsx(Cs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(Ws,{className:"h-32 w-full"},r))})}):!t||t.length===0?e.jsx(Cs,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Oc,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No orders yet"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Start shopping to see your orders here!"}),e.jsx(B,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Cs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(fe,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.id}`),children:e.jsxs(Ae,{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:ks(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx(ze,{className:A8e[r.status],children:KL[r.status]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex -space-x-2",children:[(a=r.items)==null?void 0:a.slice(0,3).map((o,c)=>e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",style:{zIndex:3-c},children:[o.quantity,"×"]},o.id)),r.items&&r.items.length>3&&e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",children:["+",r.items.length-3]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:((i=r.items)==null?void 0:i.length)===1?r.items[0].product_name:`${(l=r.items)==null?void 0:l.length} items`}),e.jsxs("p",{className:"font-semibold",children:["$",Number(r.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r.tracking_url&&e.jsxs(B,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(r.tracking_url,"_blank")},children:[e.jsx(tr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(ga,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const HXe=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function ann({currentStatus:s,statusHistory:t}){const n=HXe.indexOf(s);return e.jsx("div",{className:"space-y-3",children:HXe.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(xr,{className:"h-4 w-4"}):o?e.jsx(gr,{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:KL[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ks(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function inn(){var j;const{orderId:s}=_i(),t=In(),{data:n,isLoading:r,refetch:a}=itn(s||""),i=ctn(),l=dtn(),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(""),[f,g]=N.useState(null),b=async _=>{g(_);try{await i.mutateAsync({orderId:s,itemId:_}),ae.success("Proof approved!"),a()}catch{ae.error("Failed to approve proof")}finally{g(null)}},v=async()=>{if(d){g(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),ae.success("Revision requested"),c(!1),p(""),u(null),a()}catch{ae.error("Failed to request revision")}finally{g(null)}}};return r?e.jsx(Cs,{title:"Order Details",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-48 w-full"})]}),e.jsx(Ws,{className:"h-96 w-full"})]})}):n?e.jsxs(Cs,{title:`Order ${n.order_number}`,children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Pt,{children:"Order Status"}),e.jsx(ze,{className:A8e[n.status],children:KL[n.status]})]}),e.jsx(Ae,{children:e.jsx(ann,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Items"})}),e.jsx(Ae,{className:"space-y-4",children:(j=n.items)==null?void 0:j.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(K2,{className:"h-4 w-4"}),"View Artwork",e.jsx(tr,{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(K2,{className:"h-4 w-4"}),"View Proof",e.jsx(tr,{className:"h-3 w-3"})]}),_.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",onClick:()=>b(_.id),disabled:f===_.id,children:[f===_.id?e.jsx(ss,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Hm,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{u(_.id),c(!0)},disabled:f===_.id,children:[e.jsx(R9,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),_.proof_status==="approved"&&e.jsxs(ze,{className:"bg-green-100 text-green-800",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),_.proof_status==="rejected"&&_.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(ze,{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(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(F9,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Ae,{children:[e.jsx("p",{className:"font-medium",children:n.shipping_name}),e.jsxs("p",{className:"text-muted-foreground",children:[n.shipping_address,e.jsx("br",{}),n.shipping_city,", ",n.shipping_state," ",n.shipping_zip]}),n.tracking_number&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tracking Number:"}),e.jsx("p",{className:"font-mono font-medium",children:n.tracking_number}),n.tracking_url&&e.jsxs(B,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(n.tracking_url,"_blank"),children:["Track Package",e.jsx(tr,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(fe,{className:"sticky top-4",children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Order Summary"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",ks(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(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(cl,{}),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(cl,{}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Order Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.notes})]})]})]})]})})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Request Changes"}),e.jsx(Qn,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Ts,{placeholder:"Describe the changes needed...",value:h,onChange:_=>p(_.target.value),rows:4}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:v,disabled:!h.trim()||f!==null,children:[f?e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(Cs,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Oc,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Order not found"}),e.jsx(B,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function onn(){const s=In(),[t]=yl();return t.get("session_id"),N.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(Cs,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(fe,{children:e.jsxs(Ae,{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(xr,{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(Oc,{className:"h-4 w-4"}),"What happens next?"]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("li",{children:"• We'll review your order and prepare it for production"}),e.jsx("li",{children:"• If your order requires a proof, you'll receive it for approval"}),e.jsx("li",{children:"• Once approved, we'll begin production and ship when ready"}),e.jsx("li",{children:"• You'll receive tracking info when your order ships"})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(B,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(za,{className:"h-4 w-4 ml-2"})]}),e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function lnn(){const{user:s}=gs(),[t,n]=N.useState("store"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),[d,u]=N.useState(5),[h,p]=N.useState(""),[f,g]=N.useState(!1),[b,v]=N.useState(!1),[j,_]=N.useState(""),[S,A]=N.useState(null),[T,D]=N.useState(!1),{hasSubmittedReview:L,submitReview:M,markPostedToGoogle:F}=Umt(),{data:z}=iNt(),{data:V,isLoading:W}=aNt(),{data:K,isLoading:Y}=gtn(r),{data:ee,isLoading:ne}=ytn(s==null?void 0:s.id),{data:oe=0}=btn(s==null?void 0:s.id),pe=_tn(),ce=new Set((ee==null?void 0:ee.map(Ce=>Ce.item_id))||[]),de=async()=>{if(i)try{const Ce=await pe.mutateAsync(i.id);i.item_type==="reelflow_credits"?ae.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):ae.success(`Successfully purchased "${i.name}"!`),l(null)}catch(Ce){ae.error(Ce.message||"Failed to purchase item")}},ie=async()=>{if(!h.trim()){ae.error("Please write a review");return}g(!0);const Ce=await M(d,h);g(!1),Ce.success?(ae.success("Thank you for your review! You earned 25 points!"),_(h),v(!0),p(""),u(5)):ae.error(Ce.error||"Failed to submit review")},ye=()=>{navigator.clipboard.writeText(j),ae.success("Review copied to clipboard!")},_e=()=>{F(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},Me=()=>{v(!1),c(!1),_("")};return W||Y||ne?e.jsx(Cs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-24 w-full"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(Ce=>e.jsx(Ws,{className:"h-64"},Ce))})]})}):e.jsxs(Cs,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Reward Store"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Redeem your points for exclusive rewards"})]}),e.jsx(fe,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Ae,{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(ua,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Spendable Points"}),e.jsx("p",{className:"text-3xl font-bold text-primary",children:oe.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-6 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(vo,{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(_c,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(uy,{open:T,onOpenChange:D,children:e.jsxs(fe,{className:"border-primary/20",children:[e.jsx(hy,{asChild:!0,children:e.jsx(Mt,{className:"cursor-pointer hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(vo,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Pt,{className:"text-base",children:"How to Earn Points"}),e.jsx(Hn,{children:"See all the ways you can earn spendable points"})]})]}),T?e.jsx(sx,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(io,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(my,{children:e.jsx(Ae,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[z==null?void 0:z.filter(Ce=>Ce.is_active).map(Ce=>{const Ee=De=>{switch(De){case"event_attendance":return e.jsx(yr,{className:"h-5 w-5"});case"leave_review":return e.jsx(ua,{className:"h-5 w-5"});case"add_listing":return e.jsx(zr,{className:"h-5 w-5"});case"first_contact":return e.jsx(_n,{className:"h-5 w-5"});case"first_video":return e.jsx(vr,{className:"h-5 w-5"});case"first_community_post":return e.jsx(Ci,{className:"h-5 w-5"});default:return e.jsx(Bi,{className:"h-5 w-5"})}};return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50 border",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0",children:Ee(Ce.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:Ce.action_name}),Ce.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ce.description})]}),e.jsxs(ze,{variant:"secondary",className:"font-bold shrink-0",children:["+",Ce.points]})]},Ce.id)}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/20 flex items-center justify-center text-orange-500 shrink-0",children:e.jsx(_c,{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(ze,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!L&&e.jsx(fe,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Ae,{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(Ci,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Earn 25 Free Points!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Leave a quick review and earn 25 spendable points"})]})]}),e.jsxs(B,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(ua,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs($r,{value:t,onValueChange:n,children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(ww,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Zt,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(Oc,{className:"h-4 w-4"}),"My Rewards",ee&&ee.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1",children:ee.length})]})]}),e.jsxs(ls,{value:"store",className:"mt-6",children:[V&&V.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx(B,{variant:r===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),V.map(Ce=>e.jsxs(B,{variant:r===Ce.id?"default":"outline",size:"sm",onClick:()=>a(Ce.id),children:[Ce.icon&&`${Ce.icon} `,Ce.name]},Ce.id))]}),!K||K.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Bi,{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:K.map(Ce=>{const Ee=Ce.item_type==="reelflow_credits",De=!Ee&&ce.has(Ce.id),Ie=!Ee&&Ce.max_quantity!==null&&Ce.current_quantity===0,Fe=oe>=Ce.points_cost;return e.jsxs(fe,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${De?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>A(Ce),children:[Ce.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:Ce.preview_image_url,alt:Ce.name,className:"w-full h-full object-cover"}),De&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Ie&&!De&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(ze,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(Bi,{className:"h-12 w-12 text-muted-foreground/50"}),De&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(Mt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(Pt,{className:"text-lg",children:Ce.name}),e.jsxs(ze,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(ua,{className:"h-3 w-3 mr-1"}),Ce.points_cost]})]}),Ce.category&&e.jsxs(ze,{variant:"outline",className:"w-fit",children:[Ce.category.icon&&`${Ce.category.icon} `,Ce.category.name]})]}),e.jsxs(Ae,{children:[e.jsx(Hn,{className:"mb-4 line-clamp-2",children:Ce.description||"No description available"}),Ce.max_quantity!==null&&!De&&!Ee&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[Ce.current_quantity," of ",Ce.max_quantity," remaining"]}),Ee&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",Ce.max_quantity," ReelFlow credits per purchase"]}),De?e.jsx(B,{className:"w-full",onClick:qe=>{qe.stopPropagation(),Ce.file_url&&ZNe(Ce.file_url,Ce.name)},disabled:!Ce.file_url,children:Ce.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx(B,{className:"w-full",onClick:qe=>{qe.stopPropagation(),l(Ce)},disabled:Ie||!Fe,children:Ie?"Sold Out":Fe?e.jsxs(e.Fragment,{children:[e.jsx(ww,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${Ce.points_cost-oe} more pts`})]})]},Ce.id)})})]}),e.jsx(ls,{value:"my-rewards",className:"mt-6",children:!ee||ee.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Oc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No rewards yet"}),e.jsx("p",{className:"text-sm",children:"Purchase items from the store to see them here!"})]})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:ee.map(Ce=>{var Ee,De,Ie,Fe,qe,ve,Je;return e.jsxs(fe,{className:"overflow-hidden",children:[(Ee=Ce.item)!=null&&Ee.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:Ce.item.preview_image_url,alt:((De=Ce.item)==null?void 0:De.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(Bi,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Pt,{className:"text-lg",children:((Ie=Ce.item)==null?void 0:Ie.name)||"Unknown Item"}),e.jsxs(Hn,{className:"text-xs",children:["Purchased for ",Ce.points_spent," points • ",new Date(Ce.purchased_at).toLocaleDateString()]})]}),e.jsx(Ae,{children:((Fe=Ce.item)==null?void 0:Fe.item_type)==="reelflow_credits"?e.jsxs(B,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(xr,{className:"h-4 w-4 mr-2 text-green-500"}),(qe=Ce.item)==null?void 0:qe.max_quantity," Credits Applied"]}):e.jsx(B,{className:"w-full",onClick:()=>{var we,it;(we=Ce.item)!=null&&we.file_url&&ZNe(Ce.item.file_url,(it=Ce.item)==null?void 0:it.name)},disabled:!((ve=Ce.item)!=null&&ve.file_url),children:((Je=Ce.item)==null?void 0:Je.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},Ce.id)})})})]})]}),e.jsx(Oo,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Confirm Purchase"}),e.jsxs(Mo,{children:['Are you sure you want to purchase "',i==null?void 0:i.name,'" for ',i==null?void 0:i.points_cost," points?",(i==null?void 0:i.item_type)==="reelflow_credits"&&e.jsxs(e.Fragment,{children:[e.jsx("br",{}),e.jsx("br",{}),"🎬 ",e.jsxs("strong",{children:[i==null?void 0:i.max_quantity," ReelFlow credits"]})," will be added to your balance instantly."]}),e.jsx("br",{}),e.jsx("br",{}),"You currently have ",e.jsxs("strong",{children:[oe," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[oe-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:de,disabled:pe.isPending,children:pe.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(bs,{open:o,onOpenChange:Ce=>{!Ce&&b?Me():c(Ce)},children:e.jsx(vs,{children:b?e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Qn,{children:"Would you also share your review on Google? It helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-muted p-4 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your review:"}),e.jsxs("p",{className:"text-sm italic",children:['"',j,'"']})]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:ye,children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(Xn,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(B,{variant:"outline",onClick:Me,children:"Maybe Later"}),e.jsxs(B,{onClick:_e,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Leave a Review"}),e.jsx(Qn,{children:"Share your experience with LevelUp and earn 25 spendable points!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Rating"}),e.jsx("div",{className:"flex gap-1",children:[1,2,3,4,5].map(Ce=>e.jsx("button",{type:"button",onClick:()=>u(Ce),className:"focus:outline-none",children:e.jsx(ua,{className:`h-8 w-8 transition-colors ${d>=Ce?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},Ce))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Ts,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:Ce=>p(Ce.target.value),rows:4})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:ie,disabled:f,className:"bg-yellow-600 hover:bg-yellow-700",children:f?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(bs,{open:!!S,onOpenChange:()=>A(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[S==null?void 0:S.name,e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(ua,{className:"h-3 w-3 mr-1"}),S==null?void 0:S.points_cost]})]}),(S==null?void 0:S.category)&&e.jsxs(ze,{variant:"outline",className:"w-fit",children:[S.category.icon&&`${S.category.icon} `,S.category.name]})]}),(S==null?void 0:S.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:S.preview_image_url,alt:S.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(S==null?void 0:S.description)||"No description available"}),(S==null?void 0:S.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",S==null?void 0:S.max_quantity," ReelFlow credits per purchase"]}),(S==null?void 0:S.item_type)!=="reelflow_credits"&&(S==null?void 0:S.max_quantity)!==null&&!ce.has((S==null?void 0:S.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[S==null?void 0:S.current_quantity," of ",S==null?void 0:S.max_quantity," remaining"]})]}),e.jsx(Xn,{children:S&&S.item_type!=="reelflow_credits"&&ce.has(S.id)?e.jsx(B,{className:"w-full",onClick:()=>{S.file_url&&ZNe(S.file_url,S.name)},disabled:!S.file_url,children:S.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Access"]})}):S&&e.jsx(B,{className:"w-full",onClick:()=>{A(null),l(S)},disabled:S.item_type!=="reelflow_credits"&&S.max_quantity!==null&&S.current_quantity===0||oe{s&&ne()},[s==null?void 0:s.id]);const ne=async()=>{if(!s)return;o(!0),j(!1),b(!0);const{data:qe}=await q.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);qe==null||qe.forEach(it=>{it.action_key==="referral_signup"&&h(it.points),it.action_key==="referral_paid"&&f(it.points)});const{data:ve}=await q.from("profiles").select("name").eq("id",s.id).maybeSingle();ve!=null&&ve.name&&S(ve.name);let{data:Je}=await q.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Je){const{data:it}=await q.rpc("generate_agent_referral_code",{_user_id:s.id}),Ne=it||`agent${s.id.slice(0,6)}`,{data:He,error:$e}=await q.from("agent_referral_codes").insert({user_id:s.id,code:Ne}).select("code").maybeSingle();!$e&&He&&(Je=He)}i((Je==null?void 0:Je.code)??null);const{data:we}=await q.from("agent_referrals").select("id, referred_user_id, status, signed_up_at, qualified_at, signup_points_awarded, paid_points_awarded").eq("referrer_user_id",s.id).order("signed_up_at",{ascending:!1});if(we&&we.length>0){const it=we.map($e=>$e.referred_user_id),{data:Ne}=await q.from("profiles").select("id, name, email").in("id",it),He=new Map((Ne==null?void 0:Ne.map($e=>[$e.id,$e]))??[]);d(we.map($e=>({...$e,referred_profile:He.get($e.referred_user_id)??null})))}else d([]);o(!1)},oe=N.useMemo(()=>a?`${cnn}/trial?ref=${a}`:"",[a]),pe=c.length,ce=c.filter(qe=>qe.status==="qualified").length,de=c.filter(qe=>qe.signup_points_awarded).length*u+c.filter(qe=>qe.paid_points_awarded).length*p,ie=async()=>{oe&&(await navigator.clipboard.writeText(oe),ae.success("Referral link copied!"))},ye=()=>{const qe=encodeURIComponent("Join me on LevelUp"),ve=encodeURIComponent(`Hi — I've been using LevelUp to grow my real estate business and thought you'd love it too. Sign up using my link and we'll both get a head start: ${oe} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${qe}&body=${ve}`},_e=()=>{const qe=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${oe}`);window.location.href=`sms:?&body=${qe}`},Me=async()=>{if(navigator.share&&oe)try{await navigator.share({title:"Join me on LevelUp",text:"I use LevelUp to grow my real estate business — try it with my link:",url:oe})}catch{}else ie()},Te=qe=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(qe.trim()),Ce=qe=>{const ve=(qe??D).trim().replace(/,$/,"");if(!ve)return;const Je=ve.split(/[\s,;]+/).filter(Boolean),we=[...M];let it=0;for(const Ne of Je){if(!Te(Ne)){ae.error(`Invalid email: ${Ne}`);continue}we.includes(Ne)||(we.push(Ne),it++)}F(we),it>0&&L("")},Ee=qe=>F(M.filter(ve=>ve!==qe)),De=()=>{K(`${_?_.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),V("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."),T(!0)},Ie=qe=>{const ve=qe.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Je=_||"A fellow agent",we="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",it=oe;return`
LevelUp
You're Invited

${Je} thinks you'd love LevelUp 🎉

${ve}

What you get
  • AI tools built for real estate agents
  • Lead generation, marketing & CRM in one place
  • Branded lead sites, video tools & more
Start Your Free Trial →

Or copy & paste this link:
${it}

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

`.trim()},Fe=async()=>{if(M.length===0&&(D.trim()&&Ce(),M.length===0)){ae.error("Add at least one recipient");return}if(!W.trim()){ae.error("Subject is required");return}ee(!0);const qe=Ie(z);let ve=0,Je=0;for(const we of M)try{const{data:it,error:Ne}=await q.functions.invoke("gmail-send",{body:{to:we,subject:W,body:qe,source:"referral_invite"}});if(Ne||it!=null&&it.error)throw new Error((Ne==null?void 0:Ne.message)||(it==null?void 0:it.error));ve++}catch(it){console.error("Gmail send failed for",we,it),Je++}ee(!1),ve>0?(ae.success(`Invite sent to ${ve} ${ve===1?"person":"people"}`+(Je>0?` (${Je} failed)`:"")),F([]),L(""),T(!1)):ae.error("Failed to send invites")};return!v&&!g?e.jsx(Cs,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(Yo,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(fe,{className:"border-2 border-dashed",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-muted flex items-center justify-center mb-3",children:e.jsx(Rc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(Pt,{children:"Refer & Earn is for active members"}),e.jsx(Hn,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Ae,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(Cs,{title:"Refer & Earn",children:[e.jsxs("div",{className:"container max-w-5xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"Refer & Earn | LevelUp"}),e.jsx("meta",{name:"description",content:"Invite peers to LevelUp and earn points for every agent who joins."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bi,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Refer & Earn"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["Share LevelUp with peers, mentees, or fellow agents. Earn"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[u," points"]})," when they sign up and"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[p," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 flex items-center gap-3",children:[e.jsx(_n,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:pe}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 flex items-center gap-3",children:[e.jsx(xr,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ce}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4 flex items-center gap-3",children:[e.jsx(vo,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:de.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Hn,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(ge,{readOnly:!0,value:l?"Loading…":oe,className:"font-mono text-sm",onFocus:qe=>qe.currentTarget.select()}),e.jsxs(B,{onClick:ie,disabled:!oe,children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n&&e.jsxs(B,{size:"sm",onClick:De,disabled:!oe,className:"bg-primary hover:bg-primary/90",children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ye,disabled:!oe,children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:_e,disabled:!oe,children:[e.jsx(Ci,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Me,disabled:!oe,children:[e.jsx(Hl,{className:"h-4 w-4 mr-2"})," More…"]})]}),!n&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["💡 ",e.jsx("button",{onClick:()=>t("/integrations"),className:"underline hover:text-foreground",children:"Connect Gmail"})," to send branded invite emails directly from your inbox."]}),a&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Your code: ",e.jsx("span",{className:"font-mono font-semibold text-foreground",children:a})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Your Referrals"}),e.jsx(Hn,{children:"Track who joined and when they upgrade."})]}),e.jsx(Ae,{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(_n,{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(qe=>{var we,it;const ve=((we=qe.referred_profile)==null?void 0:we.name)||((it=qe.referred_profile)==null?void 0:it.email)||"New agent",Je=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(qe.signed_up_at));return e.jsxs("div",{className:"py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:ve}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Je]})]}),qe.status==="qualified"?e.jsxs(ze,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"})," Paid · +",u+p," pts"]}):e.jsxs(ze,{variant:"secondary",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},qe.id)})})})]}),e.jsx(fe,{className:"bg-muted/30",children:e.jsxs(Ae,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"})," How it works"]}),e.jsxs("ol",{className:"text-sm text-muted-foreground space-y-2 list-decimal list-inside",children:[e.jsx("li",{children:"Share your unique link with peers, mentees, or other agents."}),e.jsxs("li",{children:["They sign up — you instantly earn ",e.jsxs("strong",{className:"text-foreground",children:[u," points"]}),"."]}),e.jsxs("li",{children:["When they activate a paid plan, you earn another ",e.jsxs("strong",{className:"text-foreground",children:[p," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(cl,{className:"opacity-0"})]}),e.jsx(bs,{open:A,onOpenChange:T,children:e.jsxs(vs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Qn,{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(se,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[M.map(qe=>e.jsxs(ze,{variant:"secondary",className:"gap-1 pr-1",children:[qe,e.jsx("button",{type:"button",onClick:()=>Ee(qe),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${qe}`,children:e.jsx(Fn,{className:"h-3 w-3"})})]},qe)),e.jsx("input",{type:"email",value:D,onChange:qe=>L(qe.target.value),onKeyDown:qe=>{qe.key==="Enter"||qe.key===","||qe.key===" "?(qe.preventDefault(),Ce()):qe.key==="Backspace"&&!D&&M.length>0&&F(M.slice(0,-1))},onBlur:()=>D.trim()&&Ce(),onPaste:qe=>{const ve=qe.clipboardData.getData("text");/[\s,;]/.test(ve)&&(qe.preventDefault(),Ce(ve))},placeholder:M.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(se,{htmlFor:"email-subject",children:"Subject"}),e.jsx(ge,{id:"email-subject",value:W,onChange:qe=>K(qe.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Ts,{id:"personal-note",value:z,onChange:qe=>V(qe.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(se,{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: ",W||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Ie(z),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>T(!1),disabled:Y,children:"Cancel"}),e.jsxs(B,{onClick:Fe,disabled:Y,children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),Y?"Sending…":`Send${M.length>0?` to ${M.length}`:""}`]})]})]})})]})}const DNt=()=>{const{user:s}=gs(),t=Gt(),n=lt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await q.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(u)throw u;return d||[]},enabled:!!s}),r=lt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await q.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(u)throw u;return d||[]},enabled:!!s}),a=gt({mutationFn:async d=>{const{data:u,error:h}=await q.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=gt({mutationFn:async({id:d,...u})=>{const{data:h,error:p}=await q.from("smart_presentations").update(u).eq("id",d).select().single();if(p)throw p;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=gt({mutationFn:async d=>{const{data:u,error:h}=await q.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ae.success("Presentation published!")}}),o=gt({mutationFn:async d=>{const{error:u}=await q.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ae.success("Presentation archived")}}),c=gt({mutationFn:async d=>{const{error:u}=await q.from("smart_presentation_templates").insert({owner_user_id:s.id,name:d.title+" Template",description:"Created from "+d.title,template_type:"custom",icon:"📄",sections:d.sections,cta_config:{type:d.cta_type,label:d.cta_label},is_system:!1});if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),ae.success("Saved as template!")}});return{presentations:n.data||[],templates:r.data||[],isLoading:n.isLoading,templatesLoading:r.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},unn=()=>{const s=In(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=DNt(),i=o=>o.status==="draft"?e.jsx(ze,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(ze,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(ze,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),ae.success("Link copied!")};return e.jsx(Cs,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-serif font-bold text-foreground",children:"Smart Presentations"})}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create personalized, video-first presentations for your clients"})]}),e.jsxs(B,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(Ws,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(fe,{children:e.jsxs(Ae,{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(oy,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No presentations yet"}),e.jsx("p",{className:"text-muted-foreground mb-6 max-w-md",children:"Create your first Smart Presentation to impress clients with personalized, video-first content."}),e.jsxs(B,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(fe,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Ae,{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(Nr,{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 ",ks(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ir,{className:"h-3 w-3"})," ",o.view_count," view",o.view_count!==1?"s":""]}),o.cta_clicked_count>0&&e.jsx("span",{className:"text-emerald-600 font-medium",children:"CTA clicked"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap sm:flex-nowrap sm:shrink-0",children:[o.status==="published"&&o.share_token&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Lg,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(Xr,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(Xr,{onClick:()=>a.mutate(o),children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(Xr,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(im,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},GXe={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."}]},hnn=[{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 mnn(s){const t=GXe[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(GXe))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return hnn}function pnn({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=N.useState(!1),[i,l]=N.useState("script"),[o,c]=N.useState(0),[d,u]=N.useState(0),{canRecord:h}=V_t(),p=PN(),[f,g]=N.useState(""),[b,v]=N.useState(!1),[j,_]=N.useState(!0),[S,A]=N.useState(!1),[T,D]=N.useState(null),L=mnn(s),M=()=>{l("script"),c(0),u(0),g(""),v(!1),_(!0),A(!1),D(null)},F=Y=>{!Y&&(i==="uploading"||i==="processing")||(a(Y),Y||M())},z=Y=>{D(Y),g(L[Y].text),v(!1)},V=()=>{l("record"),_(f.trim().length>0)},W=()=>{g(""),_(!1),l("record")},K=N.useCallback(async(Y,ee)=>{l("uploading");try{const ne=s||"Presentation Video",{videoId:oe,uploadUrl:pe,libraryId:ce}=await l6(ne),{apiKey:de}=await c6(oe),ie=new XMLHttpRequest;ie.upload.onprogress=Ce=>{Ce.lengthComputable&&c(Ce.loaded/Ce.total*100)},await new Promise((Ce,Ee)=>{ie.onload=()=>ie.status>=200&&ie.status<300?Ce():Ee(new Error("Upload failed")),ie.onerror=()=>Ee(new Error("Upload failed")),ie.open("PUT",pe),ie.setRequestHeader("AccessKey",de),ie.send(Y)}),l("processing");let ye=0;const _e=Date.now(),Me=9e4;let Te=null;for(;ye<4;){if(await new Promise(Ee=>setTimeout(Ee,3e3)),Date.now()-_e>Me){const Ee=Y.size/1048576,De=`https://iframe.mediadelivery.net/embed/${ce}/${oe}?responsive=true`;await p.mutateAsync({bunny_video_id:oe,playback_url:De,file_size_mb:Ee,title:ne,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(De),ae.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const Ce=await Uw(oe);if(ye=Ce.status,u(Ce.encodeProgress||0),ye===4)Te={playbackUrl:Ce.directPlayUrl,thumbnailUrl:Ce.thumbnailUrl,previewUrl:Ce.previewUrl||null,duration:Ce.length||ee,fileSizeMb:(Ce.storageSize||Y.size)/(1024*1024)};else if(ye===5||ye===6)throw new Error("Video processing failed")}if(!Te)throw new Error("No video data");await p.mutateAsync({bunny_video_id:oe,contact_id:t||void 0,playback_url:Te.playbackUrl,thumbnail_url:Te.thumbnailUrl,preview_url:Te.previewUrl,duration_seconds:Te.duration,file_size_mb:Te.fileSizeMb,title:ne,status:"ready",touch_type:"presentation"}),n(Te.playbackUrl),ae.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(ne){console.error("Recording upload error:",ne),ae.error("Failed to process video. Please try again."),l("record")}},[s,t,n,p]);return e.jsxs(bs,{open:r,onOpenChange:F,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(vr,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(vs,{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(ws,{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:L.map((Y,ee)=>e.jsxs("button",{onClick:()=>z(ee),className:Et("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",T===ee?"border-primary bg-primary/5 ring-1 ring-primary":"border-border"),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Nr,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:Y.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:Y.text})]},ee))})]}),f&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Your Script"}),!b&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>v(!0),className:"h-7 text-xs gap-1",children:[e.jsx(ja,{className:"h-3 w-3"}),"Edit"]})]}),b?e.jsx(Ts,{value:f,onChange:Y=>g(Y.target.value),rows:5,placeholder:"Type your script here...",className:"text-sm"}):e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-sm text-foreground leading-relaxed",children:f})]}),!f&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Or Write Your Own"}),e.jsx(Ts,{value:f,onChange:Y=>{g(Y.target.value),D(null)},rows:4,placeholder:"Type your own script here...",className:"text-sm"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:W,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(B,{onClick:V,disabled:!1,children:f.trim()?"Continue with Script":"Continue Without Script"})]})]}),!h&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(Dl,{className:"h-10 w-10 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You've reached your video storage limit. Delete some videos to free up space."})]}):i==="record"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Record up to 5 minutes. Saved to your library & auto-attached."}),f.trim()&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>_(!j),className:"h-7 text-xs gap-1",children:[j?e.jsx(gf,{className:"h-3 w-3"}):e.jsx(Ir,{className:"h-3 w-3"}),j?"Hide Script":"Show Script"]})]}),e.jsx(m6,{maxDurationSeconds:600,onRecordingComplete:K,onRecordingStateChange:A,onError:Y=>ae.error(Y),teleprompterContent:f.trim()?e.jsx(N8e,{text:f,isVisible:j,onToggleVisibility:()=>_(!j),isRecording:S,startCountdown:!1}):void 0}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>l("script"),className:"text-xs text-muted-foreground",children:"← Back to script"})]}):i==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(ss,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(xi,{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(ss,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(xi,{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(zi,{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 fnn({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState("idle"),[d,u]=N.useState(0),h=N.useRef(null),p=PN(),{data:f}=z1e(),g=(f==null?void 0:f.total_storage_mb)||0,v=((f==null?void 0:f.max_storage_mb)||1024)-g,j=()=>{l(null),c("idle"),u(0)},_=L=>{!L&&o!=="idle"&&o!=="done"||(a(L),L||j())},S=L=>{var z;const M=(z=L.target.files)==null?void 0:z[0];if(!M)return;if(!M.type.startsWith("video/")){ae.error("Please select a video file");return}const F=M.size/(1024*1024);if(F>500){ae.error("Video file must be less than 500MB");return}if(F>v){ae.error(`Not enough storage. You have ${v.toFixed(1)} MB remaining.`);return}l(M)},A=N.useCallback(async()=>{if(i){c("creating"),u(0);try{const L=s||i.name,{data:M,error:F}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:L,isAgentVideo:!0}});if(F)throw new Error(F.message);const{videoId:z,libraryId:V}=M;c("uploading");const{data:W,error:K}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:z,isAgentVideo:!0}});if(K)throw new Error(K.message);await new Promise((ne,oe)=>{const pe=new XMLHttpRequest;pe.upload.addEventListener("progress",ce=>{ce.lengthComputable&&u(Math.round(ce.loaded/ce.total*100))}),pe.addEventListener("load",()=>pe.status>=200&&pe.status<300?ne():oe(new Error(`Upload failed (${pe.status})`))),pe.addEventListener("error",()=>oe(new Error("Upload failed"))),pe.open("PUT",W.uploadUrl),pe.setRequestHeader("AccessKey",W.apiKey),pe.send(i)}),c("processing");const Y=i.size/(1024*1024),ee=`https://iframe.mediadelivery.net/embed/${V}/${z}`;await p.mutateAsync({bunny_video_id:z,playback_url:ee,file_size_mb:Y,title:L,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(ee),c("done"),ae.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(L){console.error("Upload error:",L),ae.error(L instanceof Error?L.message:"Failed to upload video"),c("idle")}}},[i,s,t,n,p]),T=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},D=o!=="idle"&&o!=="done";return e.jsxs(bs,{open:r,onOpenChange:_,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(Sa,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{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(vr,{className:"h-8 w-8 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(i.size/(1024*1024)).toFixed(1)," MB"]})]}),!D&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(Fn,{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 L;return(L=h.current)==null?void 0:L.click()},children:[e.jsx(Sa,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select a video file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MP4, MOV, WebM (max 500MB)"})]}),e.jsx("input",{ref:h,type:"file",accept:"video/*",className:"hidden",onChange:S,disabled:D}),D&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ss,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:T()})]}),e.jsx(xi,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>_(!1),disabled:D,children:"Cancel"}),e.jsx(B,{onClick:A,disabled:!i||D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const WXe=[{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"}],KXe=()=>{const s=In(),{id:t}=_i(),{user:n}=gs(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=DNt(),{isGmailConnected:c,gmailEmail:d}=bh(),[u,h]=N.useState(!1),[p,f]=N.useState("client"),[g,b]=N.useState(!1),[v,j]=N.useState(""),[_,S]=N.useState([]),[A,T]=N.useState(!1),[D,L]=N.useState(null),[M,F]=N.useState(!1),[z,V]=N.useState(""),[W,K]=N.useState(""),[Y,ee]=N.useState(""),[ne,oe]=N.useState("buyer"),[pe,ce]=N.useState(""),[de,ie]=N.useState(null),[ye,_e]=N.useState(""),[Me,Te]=N.useState([]),[Ce,Ee]=N.useState("schedule_call"),[De,Ie]=N.useState("Schedule a Call"),[Fe,qe]=N.useState(""),[ve,Je]=N.useState(""),[we,it]=N.useState(null),[Ne,He]=N.useState(t||null),[$e,Ye]=N.useState(null),[Ke,rt]=N.useState(!1),tt=async(ht,Ut)=>{if(!n)return;const Es=5*1024*1024;if(ht.size>Es){ae.error("Image must be under 5MB");return}if(!ht.type.startsWith("image/")){ae.error("Please upload an image file");return}it(Ut);try{const Xt=ht.name.split(".").pop()||"jpg",Ys=`${n.id}/${Date.now()}.${Xt}`,{error:Ss}=await q.storage.from("listing-photos").upload(Ys,ht);if(Ss)throw Ss;const{data:{publicUrl:Bs}}=q.storage.from("listing-photos").getPublicUrl(Ys);Qt(Ut,{image_url:Bs}),ae.success("Image uploaded")}catch{ae.error("Failed to upload image")}finally{it(null)}};N.useEffect(()=>{t&&at(t)},[t]);const at=async ht=>{const{data:Ut,error:Es}=await q.from("smart_presentations").select("*").eq("id",ht).single();if(Es||!Ut)return;const Xt=Ut;if(b(!0),_e(Xt.title),V(Xt.client_name||""),ce(Xt.property_address||""),Te(Xt.sections||[]),Ee(Xt.cta_type||"schedule_call"),Ie(Xt.cta_label||"Schedule a Call"),qe(Xt.cta_url||""),Je(Xt.heading||""),Ye(Xt.share_token),rt(Xt.status==="published"),He(Xt.id),f("builder"),Xt.contact_id){const{data:Ys}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",Xt.contact_id).maybeSingle();Ys&&(L(Ys),K(Ys.email||""),ee(Ys.phone||""))}};N.useEffect(()=>{if(!n||v.length<1){S([]);return}const ht=setTimeout(async()=>{T(!0);const{data:Ut}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",n.id).or(`first_name.ilike.%${v}%,last_name.ilike.%${v}%,email.ilike.%${v}%`).limit(10);S(Ut||[]),T(!1)},300);return()=>clearTimeout(ht)},[v,n]);const Ge=ht=>{L(ht),V(`${ht.first_name} ${ht.last_name||""}`.trim()),K(ht.email||""),ee(ht.phone||""),F(!1)},dt=async()=>{if(!z.trim()){ae.error("Client name is required");return}const ht=z.trim().split(" "),Ut=ht[0],Es=ht.slice(1).join(" ")||null,{data:Xt,error:Ys}=await q.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:Ut,last_name:Es,email:W||null,phone:Y||null,lead_source:"Smart Presentation"}).select().single();if(Ys){ae.error("Failed to create client");return}L(Xt),ae.success("Client created & saved to Agent OS"),f("template")},Bt=ht=>{ie(ht);const Ut=(ht.sections||[]).map(Es=>({...Es,is_visible:!0,video_url:"",text:""}));if(Te(Ut),_e(ht.name+(z?` for ${z}`:"")),ht.cta_config){const Es=ht.cta_config;Ee(Es.type||"schedule_call"),Ie(Es.label||"Schedule a Call")}f("builder")},kt=()=>{Te([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),_e(z?`Presentation for ${z}`:"New Presentation"),f("builder")},Qt=(ht,Ut)=>{Te(Es=>Es.map((Xt,Ys)=>Ys===ht?{...Xt,...Ut}:Xt))},ns=ht=>{Qt(ht,{is_visible:!Me[ht].is_visible})},$s=()=>{Te(ht=>[...ht,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},Ds=ht=>{Te(Ut=>Ut.filter((Es,Xt)=>Xt!==ht))},Dt=async()=>{if(!ye.trim()){ae.error("Title is required");return}try{if(Ne){const ht=await l.mutateAsync({id:Ne,title:ye,sections:Me,client_name:z,property_address:pe||null,cta_type:Ce,cta_label:De,cta_url:Fe||null,heading:ve||null});ae.success("Saved")}else{const ht=await i.mutateAsync({title:ye,contact_id:(D==null?void 0:D.id)||void 0,client_name:z,property_address:pe||void 0,template_id:(de==null?void 0:de.id)||void 0,sections:Me,cta_type:Ce,cta_label:De,cta_url:Fe||void 0,heading:ve||void 0});He(ht.id),Ye(ht.share_token),ae.success("Presentation created!")}}catch(ht){console.error("Failed to save presentation:",ht);const Ut=(ht==null?void 0:ht.message)||(ht==null?void 0:ht.toString())||"Unknown error";ae.error(`Failed to save: ${Ut}`)}},St=async()=>{try{await Dt();const ht=Ne;if(ht){const Ut=await o.mutateAsync(ht);Ye(Ut.share_token),rt(!0),f("share")}}catch(ht){console.error("Failed to publish presentation:",ht),ae.error(`Failed to publish: ${(ht==null?void 0:ht.message)||"Unknown error"}`)}},$t=$e?`https://presentations.relevelup.com/${$e}`:"";return e.jsx(Cs,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(Wr,{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:[p==="client"&&"Who is this presentation for?",p==="template"&&"Choose a starting template",p==="builder"&&"Customize your presentation",p==="share"&&"Share with your client"]})]})]}),!g&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((ht,Ut)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Et("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",p===ht?"bg-primary text-primary-foreground":Ut<["client","template","builder","share"].indexOf(p)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:Ut<["client","template","builder","share"].indexOf(p)?e.jsx(Lr,{className:"h-4 w-4"}):Ut+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:ht}),Ut<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},ht))}),p==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{L(null),V(""),K(""),ee(""),F(!1),f("template")},className:"w-full group flex items-center justify-between gap-4 rounded-xl border border-dashed border-primary/30 bg-primary/5 hover:bg-primary/10 transition-all p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(cr,{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(za,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors shrink-0"})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(_r,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Ae,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search by name or email...",value:v,onChange:ht=>j(ht.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[A&&e.jsx(Ws,{className:"h-12 w-full"}),_.map(ht=>e.jsxs("button",{onClick:()=>Ge(ht),className:Et("w-full text-left p-3 rounded-lg border transition-colors",(D==null?void 0:D.id)===ht.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[ht.first_name," ",ht.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ht.email||ht.phone||"No contact info"})]},ht.id)),!v&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),v&&_.length===0&&!A&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),D&&e.jsxs(B,{onClick:()=>f("template"),className:"w-full gap-2",children:["Continue with ",D.first_name,e.jsx(za,{className:"h-4 w-4"})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Ae,{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(se,{className:"text-xs",children:"Name *"}),e.jsx(ge,{value:z,onChange:ht=>{V(ht.target.value),F(!0),L(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Email"}),e.jsx(ge,{value:W,onChange:ht=>K(ht.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(ge,{value:Y,onChange:ht=>ee(ht.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Client Type"}),e.jsxs(us,{value:ne,onValueChange:oe,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"}),e.jsx(Ze,{value:"recruit",children:"Recruit"}),e.jsx(Ze,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Property Address"}),e.jsx(ge,{value:pe,onChange:ht=>ce(ht.target.value),placeholder:"Optional"})]})]}),M&&z&&e.jsxs(B,{onClick:dt,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(za,{className:"h-4 w-4"})]})]})]})]})]}),p==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs($r,{defaultValue:"system",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"mine",children:"My Core Templates"}),e.jsx(Zt,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Zt,{value:"blank",children:"+ Start Blank"})]}),e.jsx(ls,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(ht=>e.jsx(Ws,{className:"h-32"},ht))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(ht=>!ht.is_system).length===0?e.jsx("p",{className:"text-muted-foreground col-span-2 text-center py-8",children:"You haven't saved any templates yet. Create a presentation and save it as a template!"}):r.filter(ht=>!ht.is_system).map(ht=>e.jsx(YXe,{template:ht,onSelect:Bt},ht.id))})}),e.jsx(ls,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(ht=>ht.is_system).map(ht=>e.jsx(YXe,{template:ht,onSelect:Bt},ht.id))})}),e.jsx(ls,{value:"blank",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start with a blank canvas and add your own sections."}),e.jsx(B,{onClick:kt,children:"Start from Scratch"})]})})})]}),e.jsxs(B,{variant:"outline",onClick:()=>f("client"),className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Back"]})]}),p==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Presentation Title"}),e.jsx(ge,{value:ye,onChange:ht=>_e(ht.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Page Heading"}),e.jsx(ge,{value:ve,onChange:ht=>Je(ht.target.value),placeholder:z?`Welcome, ${z}!`:"e.g. Welcome! or Your Custom Listing Plan"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:['The main heading visitors see. Leave blank for "Welcome, ',"",'!"']})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Client Name"}),e.jsx(ge,{value:z,onChange:ht=>V(ht.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Property Address"}),e.jsx(ge,{value:pe,onChange:ht=>ce(ht.target.value),placeholder:"Optional"})]})]})]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sections"}),e.jsx(B,{variant:"outline",size:"sm",onClick:$s,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:Me.map((ht,Ut)=>e.jsx(fe,{className:Et(!ht.is_visible&&"opacity-50"),children:e.jsx(Ae,{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(Uu,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:ht.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ge,{value:ht.title,onChange:Es=>Qt(Ut,{title:Es.target.value}),className:"font-semibold border-none p-0 h-auto text-base focus-visible:ring-0 bg-transparent"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ns(Ut),children:ht.is_visible?e.jsx(Ir,{className:"h-4 w-4"}):e.jsx(gf,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ds(Ut),className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})]})]}),e.jsx(ge,{value:ht.description||"",onChange:Es=>Qt(Ut,{description:Es.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(se,{className:"text-xs",children:"Video URL"}),e.jsx(ge,{value:ht.video_url||"",onChange:Es=>Qt(Ut,{video_url:Es.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(pnn,{sectionTitle:ht.title,contactId:D==null?void 0:D.id,onVideoReady:Es=>Qt(Ut,{video_url:Es})}),e.jsx(fnn,{sectionTitle:ht.title,contactId:D==null?void 0:D.id,onVideoReady:Es=>Qt(Ut,{video_url:Es})}),e.jsx(o6,{userId:n==null?void 0:n.id,onSelect:Es=>Qt(Ut,{video_url:Es})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),ht.image_url?e.jsxs("div",{className:"relative mt-1 rounded-lg overflow-hidden border border-border bg-muted/30 group",children:[e.jsx("img",{src:ht.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>Qt(Ut,{image_url:""}),children:e.jsx(Fn,{className:"h-3.5 w-3.5"})})]}):e.jsxs("label",{className:"mt-1 flex items-center gap-2 cursor-pointer rounded-lg border border-dashed border-border hover:border-primary/50 p-3 transition-colors",children:[we===Ut?e.jsx(ss,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(ay,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:we===Ut?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:we===Ut,onChange:Es=>{var Ys;const Xt=(Ys=Es.target.files)==null?void 0:Ys[0];Xt&&tt(Xt,Ut),Es.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Text (optional)"}),e.jsx(Db,{content:ht.text||"",onChange:Es=>Qt(Ut,{text:Es}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},Ut))})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Call to Action"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"CTA Type"}),e.jsxs(us,{value:Ce,onValueChange:ht=>{Ee(ht);const Ut=WXe.find(Es=>Es.value===ht);Ut&&Ie(Ut.label)},children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:WXe.map(ht=>e.jsx(Ze,{value:ht.value,children:ht.label},ht.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Button Label"}),e.jsx(ge,{value:De,onChange:ht=>Ie(ht.target.value)})]}),e.jsxs("div",{children:[e.jsxs(se,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(ge,{value:Fe,onChange:ht=>qe(ht.target.value),placeholder:"https://calendly.com/..."}),!Fe&&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(B,{variant:"outline",onClick:()=>f("template"),className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx(B,{variant:"outline",onClick:Dt,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(B,{onClick:St,disabled:o.isPending,className:"gap-2",children:[e.jsx(cr,{className:"h-4 w-4"}),Ke?"Update & Reshare":"Publish & Share"]})]})]})]}),p==="share"&&$e&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center py-12 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4",children:e.jsx(Lr,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your Presentation is Live!"}),e.jsxs("p",{className:"text-muted-foreground mb-6 max-w-md",children:["Share this link with ",z||"your client",". You'll be notified when they view it."]}),e.jsxs("div",{className:"flex items-center gap-2 w-full max-w-lg",children:[e.jsx(ge,{value:$t,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(B,{onClick:()=>{navigator.clipboard.writeText($t),ae.success("Link copied!")},children:e.jsx(ta,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs(B,{variant:"outline",className:"gap-2",onClick:()=>{const ht=`Hi ${z||""}! I put together something for you — check it out: ${$t}`;navigator.clipboard.writeText(ht),ae.success("Message copied!")},children:[e.jsx(Ci,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(B,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${W||""}?subject=${encodeURIComponent(ye)}&body=${encodeURIComponent(`Hi ${(D==null?void 0:D.first_name)||(z==null?void 0:z.split(" ")[0])||""}, I put together a personalized presentation for you: ${$t} Looking forward to connecting!`)}`)},children:[e.jsx(Hs,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(Ty,{open:u,onOpenChange:h,contact:D?{id:D.id,first_name:D.first_name,last_name:D.last_name,email:W||D.email||""}:W?{id:"",first_name:(z==null?void 0:z.split(" ")[0])||"",last_name:(z==null?void 0:z.split(" ").slice(1).join(" "))||"",email:W}:void 0,defaultSubject:ye,defaultBody:`Hi ${(D==null?void 0:D.first_name)||(z==null?void 0:z.split(" ")[0])||""}, I put together a personalized presentation for you: ${$t} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(B,{variant:"outline",onClick:()=>f("builder"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(B,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},YXe=({template:s,onSelect:t})=>e.jsx(fe,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Ae,{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(ze,{variant:"outline",className:"text-xs capitalize",children:s.template_type}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(s.sections||[]).length," sections"]})]})]})]}),e.jsx(B,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),xnn=()=>{var b;const{shareToken:s}=_i(),[t,n]=N.useState(null),[r,a]=N.useState(!0),[i,l]=N.useState(0),[o,c]=N.useState(!1);N.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),N.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:v,error:j}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(j||!v){c(!0),a(!1);return}const{data:_}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",v.owner_user_id).single();let S;if(_!=null&&_.brokerage_id){const{data:T}=await q.from("brokerages").select("name").eq("id",_.brokerage_id).single();S=(T==null?void 0:T.name)||void 0}let A=null;if(v.contact_id){const{data:T}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",v.contact_id).single();A=T}n({...v,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:S,contact_name:A?[A.first_name,A.last_name].filter(Boolean).join(" "):void 0,contact_email:(A==null?void 0:A.email)||void 0,contact_phone:(A==null?void 0:A.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:v.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(Ws,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const h=t.sections.filter(v=>v.is_visible!==!1),p=h[i],f=v=>{const j=v.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(j)return`https://www.youtube.com/embed/${j[1]}?rel=0`;if(v.includes("iframe.mediadelivery.net/play/")){const A=v.replace("/play/","/embed/"),T=A.includes("?")?"&":"?";return`${A}${T}responsive=true`}if(v.includes("iframe.mediadelivery.net")){if(v.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const T=v.includes("?")?"&":"?";return`${v}${T}responsive=true`}return""}const _=v.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(_)return`https://www.loom.com/embed/${_[1]}`;const S=v.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return S?`https://iframe.mediadelivery.net/embed/${S[1]}/${S[2]}?responsive=true`:v},g=!!((b=t.cta_url)!=null&&b.trim());return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})]})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[p!=null&&p.video_url&&f(p.video_url)?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:f(p.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):p!=null&&p.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:p.image_url,alt:p.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:p==null?void 0:p.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:p==null?void 0:p.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:p==null?void 0:p.description})]}),(p==null?void 0:p.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:h.map((v,j)=>e.jsx("button",{onClick:()=>l(j),className:Et("w-full text-left p-4 rounded-xl border transition-all",i===j?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(j+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:v.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:v.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:v.description})]})]})},j))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),g?e.jsxs(B,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(tr,{className:"h-5 w-5 ml-2"})]}):e.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:e.jsx(Cct,{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 gnn({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=mBt(s),i=gBt(),l=yBt(),o=vBt(),c=bBt(),[d,u]=N.useState(""),[h,p]=N.useState("rating"),f=async j=>{n(j),j&&(!r||r.length===0)&&await c.mutateAsync(s)},g=async()=>{if(!d.trim())return;const j=(r==null?void 0:r.reduce((_,S)=>Math.max(_,S.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:j+1}),u("")},b=async j=>{await l.mutateAsync({id:j.id,open_house_id:s,is_active:!j.is_active})},v=async j=>{await o.mutateAsync({id:j.id,open_house_id:s})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ov,{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(vn,{checked:t,onCheckedChange:f})]}),t&&e.jsx("div",{className:"space-y-3 pt-2 border-t border-border",children:a?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ss,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:r==null?void 0:r.map(j=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Uu,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm truncate",children:j.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:j.question_type.replace("_"," ")})]}),e.jsx(vn,{checked:j.is_active,onCheckedChange:()=>b(j),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>v(j),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]},j.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(ge,{value:d,onChange:j=>u(j.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:j=>j.key==="Enter"&&g()})]}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(cs,{className:"w-28 h-9 text-xs",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"rating",children:"Rating"}),e.jsx(Ze,{value:"open_text",children:"Text"})]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:g,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(As,{className:"h-3.5 w-3.5"})})]})]})})]})}function ynn({openHouseId:s}){const{user:t}=gs(),{data:n=[],isLoading:r}=NBt(s),a=SBt(),[i,l]=N.useState(""),[o,c]=N.useState(!1),d=async()=>{const u=i.trim();if(u){c(!0);try{await a.mutateAsync({open_house_id:s,name:u,sort_order:n.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{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(ss,{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(vnn,{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(ge,{value:i,onChange:u=>l(u.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())}}),e.jsx(B,{onClick:d,disabled:!i.trim()||o,size:"sm",children:o?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function vnn({room:s,index:t,total:n,userId:r,openHouseId:a}){const i=CBt(),l=TBt(),o=EBt(),c=ABt(),d=N.useRef(null),[u,h]=N.useState(!0),[p,f]=N.useState(s.name),[g,b]=N.useState(s.description||""),[v,j]=N.useState(!1),_=N.useMemo(()=>s.media.filter(F=>F.kind==="video"&&F.agent_video_id).map(F=>F.agent_video_id),[s.media]),{data:S={}}=lt({queryKey:["room-video-statuses",s.id,_.join(",")],enabled:_.length>0,queryFn:async()=>{const{data:F,error:z}=await q.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",_);if(z)throw z;const V=F||[],W=V.filter(Y=>Y.status==="processing"&&Y.bunny_video_id);await Promise.all(W.map(async Y=>{try{const{data:ee}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:Y.bunny_video_id,isAgentVideo:!0}});ee&&ee.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:ee.directPlayUrl,thumbnail_url:ee.thumbnailUrl,preview_url:ee.previewUrl,duration_seconds:ee.length||void 0,updated_at:new Date().toISOString()}).eq("id",Y.id),Y.status="ready",Y.thumbnail_url=ee.thumbnailUrl,Y.preview_url=ee.previewUrl)}catch{}}));const K={};return V.forEach(Y=>{K[Y.id]={status:Y.status,thumbnail_url:Y.thumbnail_url,preview_url:Y.preview_url}}),K},refetchInterval:F=>{const z=F.state.data;return z?Object.values(z).some(V=>V.status!=="ready"&&V.status!=="failed")?5e3:!1:5e3}}),A=()=>{p.trim()&&p!==s.name&&i.mutate({id:s.id,open_house_id:a,name:p.trim()})},T=()=>{g!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:g.trim()||null})},D=()=>{confirm(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},L=F=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+F})},M=async F=>{const z=Array.from(F.target.files||[]);if(!(!z.length||!r)){j(!0);try{for(const V of z){const W=V.type.startsWith("video/"),K=W?500*1024*1024:15*1024*1024;if(V.size>K){Dr({title:`${V.name} is too large`,description:W?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(W){try{const pe=`${s.name} – ${V.name.replace(/\.[^/.]+$/,"")}`,{data:ce,error:de}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:pe,isAgentVideo:!0}});if(de||!ce)throw new Error((de==null?void 0:de.message)||"Could not start upload");const{videoId:ie,libraryId:ye}=ce,{data:_e,error:Me}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ie,isAgentVideo:!0}});if(Me||!_e)throw new Error((Me==null?void 0:Me.message)||"Could not get upload URL");await new Promise((Ie,Fe)=>{const qe=new XMLHttpRequest;qe.addEventListener("load",()=>{qe.status>=200&&qe.status<300?Ie():Fe(new Error(`Upload failed (${qe.status})`))}),qe.addEventListener("error",()=>Fe(new Error("Upload failed"))),qe.open("PUT",_e.uploadUrl),qe.setRequestHeader("AccessKey",_e.apiKey),qe.send(V)});const Te=`https://iframe.mediadelivery.net/embed/${ye}/${ie}`,Ce=V.size/(1024*1024),{data:Ee,error:De}=await q.from("agent_videos").insert({owner_user_id:r,bunny_video_id:ie,playback_url:Te,file_size_mb:Ce,title:pe,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(De)throw De;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Te,sort_order:s.media.length,agent_video_id:Ee.id}),Dr({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(pe){Dr({title:"Video upload failed",description:(pe==null?void 0:pe.message)||"Try again",variant:"destructive"})}continue}const Y=V.name.split(".").pop()||"jpg",ee=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${Y}`,{error:ne}=await q.storage.from("open-house-tour-media").upload(ee,V,{upsert:!1,contentType:V.type});if(ne){Dr({title:"Upload failed",description:ne.message,variant:"destructive"});continue}const{data:oe}=q.storage.from("open-house-tour-media").getPublicUrl(ee);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:oe.publicUrl,sort_order:s.media.length})}}finally{j(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:"rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx(Uu,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>h(F=>!F),className:"flex-1 text-left text-sm font-medium truncate",children:[s.name," ",e.jsxs("span",{className:"text-muted-foreground font-normal text-xs",children:["· ",s.media.length," ",s.media.length===1?"item":"items"]})]}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>L(-1),disabled:t===0,children:e.jsx(sx,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>L(1),disabled:t===n-1,children:e.jsx(io,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:D,children:e.jsx(bn,{className:"h-4 w-4"})})]}),u&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(ge,{value:p,onChange:F=>f(F.target.value),onBlur:A,placeholder:"Room name",className:"h-9"}),e.jsx(Ts,{value:g,onChange:F=>b(F.target.value),onBlur:T,placeholder:"Optional description — what makes this room special?",rows:2,className:"text-sm"}),s.media.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:s.media.map(F=>{const z=F.agent_video_id?S[F.agent_video_id]:void 0,V=z==null?void 0:z.status,W=F.kind==="video"&&V&&V!=="ready"&&V!=="failed",K=F.kind==="video"&&V==="failed",Y=(z==null?void 0:z.thumbnail_url)||(z==null?void 0:z.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[F.kind==="video"?e.jsxs(e.Fragment,{children:[Y?e.jsx("img",{src:Y,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(F.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:F.url,className:"w-full h-full object-cover"}),!W&&!K&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(vr,{className:"h-6 w-6 text-white"})}),W&&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(ss,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),K&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-destructive/80 text-white text-[10px] font-medium uppercase tracking-wide pointer-events-none px-2 text-center",children:"Failed"})]}):e.jsx("img",{src:F.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>c.mutate({id:F.id,open_house_id:a}),className:"absolute top-1 right-1 w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition",children:e.jsx(Fn,{className:"h-3.5 w-3.5"})})]},F.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:M,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{var F;return(F=d.current)==null?void 0:F.click()},disabled:v,className:"flex-1",children:v?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(o6,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async F=>{try{await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:F.playback_url||"",sort_order:s.media.length,agent_video_id:F.id}),Dr({title:"Video added to room"})}catch(z){Dr({title:"Failed to add video",description:z==null?void 0:z.message,variant:"destructive"})}}})]})]})]})}function bnn({open:s,onOpenChange:t,openHouse:n}){const r=Ect(),{user:a}=gs(),i=N.useRef(null),l=N.useRef(null),o=N.useRef(null),c=n.kind==="virtual",[d,u]=N.useState(n.auto_forward_to_card??!1),[h,p]=N.useState(n.disclosure_pdf_url??""),[f,g]=N.useState(n.enable_survey??!1),[b,v]=N.useState(n.ask_visitor_intent??!0),[j,_]=N.useState(n.ask_visitor_address??!1),[S,A]=N.useState(n.photo_url??""),[T,D]=N.useState(!1),[L,M]=N.useState(!1),[F,z]=N.useState(!1),[V,W]=N.useState(n.hero_video_url??""),[K,Y]=N.useState(!1),[ee,ne]=N.useState(n.price!=null?String(n.price):""),[oe,pe]=N.useState(n.beds!=null?String(n.beds):""),[ce,de]=N.useState(n.baths!=null?String(n.baths):""),[ie,ye]=N.useState(n.sqft!=null?String(n.sqft):""),[_e,Me]=N.useState(n.enable_question??!0),[Te,Ce]=N.useState(n.enable_showing??!0),[Ee,De]=N.useState(n.enable_disclosures??!0),[Ie,Fe]=N.useState(n.enable_offer??!0),[qe,ve]=N.useState(n.brand_color_override??""),[Je,we]=N.useState(n.property_description??""),it=async rt=>{var kt;const tt=(kt=rt.target.files)==null?void 0:kt[0];if(!tt||!a)return;if(tt.size>200*1024*1024){Dr({title:"Video must be under 200MB",variant:"destructive"});return}if(!tt.type.startsWith("video/")){Dr({title:"Please upload a video file",variant:"destructive"});return}Y(!0);const at=tt.name.split(".").pop()||"mp4",Ge=`${a.id}/${n.id}/hero-${Date.now()}.${at}`,{error:dt}=await q.storage.from("open-house-tour-media").upload(Ge,tt,{upsert:!0,contentType:tt.type});if(dt){Dr({title:"Upload failed",description:dt.message,variant:"destructive"}),Y(!1);return}const{data:Bt}=q.storage.from("open-house-tour-media").getPublicUrl(Ge);W(Bt.publicUrl),Y(!1),Dr({title:"Video uploaded!"})},Ne=async rt=>{var kt;const tt=(kt=rt.target.files)==null?void 0:kt[0];if(!tt||!a)return;if(tt.size>10*1024*1024){Dr({title:"Image must be under 10MB",variant:"destructive"});return}if(!tt.type.startsWith("image/")){Dr({title:"Please upload an image file",variant:"destructive"});return}M(!0);const at=tt.name.split(".").pop()||"jpg",Ge=`${a.id}/${n.id}-${Date.now()}.${at}`,{error:dt}=await q.storage.from("open-house-photos").upload(Ge,tt,{upsert:!0});if(dt){Dr({title:"Upload failed",description:dt.message,variant:"destructive"}),M(!1);return}const{data:Bt}=q.storage.from("open-house-photos").getPublicUrl(Ge);A(Bt.publicUrl),M(!1),Dr({title:"Photo updated!"})},He=()=>{A(""),l.current&&(l.current.value="")},$e=async rt=>{var Bt;const tt=(Bt=rt.target.files)==null?void 0:Bt[0];if(!tt||!a)return;if(tt.size>20*1024*1024){Dr({title:"File must be under 20MB",variant:"destructive"});return}if(tt.type!=="application/pdf"){Dr({title:"Only PDF files are accepted",variant:"destructive"});return}D(!0);const at=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:Ge}=await q.storage.from("open-house-photos").upload(at,tt,{upsert:!0});if(Ge){Dr({title:"Upload failed",description:Ge.message,variant:"destructive"}),D(!1);return}const{data:dt}=q.storage.from("open-house-photos").getPublicUrl(at);p(dt.publicUrl),D(!1),Dr({title:"PDF uploaded!"})},Ye=()=>{p(""),i.current&&(i.current.value="")},Ke=async()=>{z(!0);try{const rt={id:n.id,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:f,ask_visitor_intent:b,ask_visitor_address:j,photo_url:S||null};c&&(rt.hero_video_url=V||null,rt.price=ee.trim()?Number(ee):null,rt.beds=oe.trim()?parseInt(oe,10):null,rt.baths=ce.trim()?Number(ce):null,rt.sqft=ie.trim()?parseInt(ie,10):null,rt.enable_question=_e,rt.enable_showing=Te,rt.enable_disclosures=Ee,rt.enable_offer=Ie,rt.brand_color_override=qe.trim()||null,rt.property_description=Je.trim()||null),await r.mutateAsync(rt),Dr({title:"Settings saved!"}),t(!1)}catch{Dr({title:"Failed to save",variant:"destructive"})}finally{z(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Qn,{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(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(vr,{className:"h-4 w-4"})," Hero Tour Video"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The video visitors watch right after they sign in. MP4 recommended (max 200MB)."}),e.jsx("input",{ref:o,type:"file",accept:"video/*",onChange:it,className:"hidden"}),V?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:V,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx(B,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var rt;return(rt=o.current)==null?void 0:rt.click()},disabled:K,children:K?e.jsx(ss,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>W(""),children:e.jsx(Fn,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=o.current)==null?void 0:rt.click()},disabled:K,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:K?e.jsx(ss,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(vr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(ynn,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(se,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(ge,{type:"number",value:ee,onChange:rt=>ne(rt.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(ge,{type:"number",value:ie,onChange:rt=>ye(rt.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(ge,{type:"number",value:oe,onChange:rt=>pe(rt.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(ge,{type:"number",step:"0.5",value:ce,onChange:rt=>de(rt.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(Ts,{value:Je,onChange:rt=>we(rt.target.value),placeholder:"Stunning 4-bedroom in the heart of River Oaks. Chef's kitchen, oversized primary suite, and a backyard oasis perfect for entertaining…",rows:5,className:"w-full resize-y"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{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(vn,{checked:_e,onCheckedChange:Me})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(vn,{checked:Te,onCheckedChange:Ce})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(vn,{checked:Ee,onCheckedChange:De})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(vn,{checked:Ie,onCheckedChange:Fe})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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:qe||"#0f172a",onChange:rt=>ve(rt.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(ge,{value:qe,onChange:rt=>ve(rt.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),qe&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ve(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(rt=>e.jsx("button",{type:"button",onClick:()=>ve(rt),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:rt},"aria-label":rt},rt))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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:Ne,className:"hidden"}),S?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:S,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs(B,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var rt;return(rt=l.current)==null?void 0:rt.click()},disabled:L,children:[L?e.jsx(ss,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),L?"":"Replace"]}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:He,children:e.jsx(Fn,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=l.current)==null?void 0:rt.click()},disabled:L,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:L?e.jsx(ss,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(nl,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(se,{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(vn,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Seller's Disclosures (PDF)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visitors can view or download this on the thank you screen after check-in"}),e.jsx("input",{ref:i,type:"file",accept:"application/pdf",onChange:$e,className:"hidden"}),h?e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:[e.jsx(Nr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:Ye,children:e.jsx(Fn,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=i.current)==null?void 0:rt.click()},disabled:T,className:"w-full h-24 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:T?e.jsx(ss,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{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(se,{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(vn,{checked:b,onCheckedChange:v})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(se,{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(vn,{checked:j,onCheckedChange:_})]})}),e.jsx(gnn,{openHouseId:n.id,enableSurvey:f,onToggleSurvey:g}),e.jsx(B,{onClick:Ke,disabled:F,className:"w-full",children:F?"Saving...":"Save Settings"})]})]})})}const RNt={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function _nn({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:RNt[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 wnn({openHouseId:s}){const{data:t,isLoading:n}=xBt(s),{data:r}=Tct(s),a=N.useMemo(()=>{const h={};return r==null||r.forEach(p=>{h[p.id]=p}),h},[r]);if(n||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(h=>h.question_type==="rating"),c=i.filter(h=>h.question_type!=="rating"),d=[...new Set(l.map(h=>h.visitor_id))],u=d.length;return u===0?e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ov,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Ae,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ov,{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(Ae,{children:e.jsxs($r,{defaultValue:"summary",children:[e.jsxs(Ur,{className:"mb-4",children:[e.jsxs(Zt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(yo,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Zt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(Xi,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(ls,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(_nn,{question:h,responses:l},h.id)),c.map(h=>{const p=l.filter(f=>f.question_id===h.id&&f.text_value);return p.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:h.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:p.map(f=>{const g=a[f.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[g?`${g.first_name} ${g.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:f.text_value})]},f.id)})})]},h.id)})]}),e.jsx(ls,{value:"individual",className:"space-y-4",children:d.map(h=>{const p=a[h],f=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:[p?`${p.first_name} ${p.last_name||""}`.trim():"Unknown Visitor",(p==null?void 0:p.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:p.email})]}),e.jsx("div",{className:"space-y-1",children:f.map(g=>{const b=i.find(v=>v.id===g.question_id);return b?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:b.question_text}),e.jsx("span",{className:"font-medium",children:g.rating_value!=null?RNt[g.rating_value]||g.rating_value:g.text_value})]},g.id):null})})]},h)})})]})})]})}const jnn={question:{label:"Question",icon:Ci,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:yr,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:Nr,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:Zl,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},ZXe={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 Nnn({openHouseId:s}){const{data:t=[],isLoading:n}=MBt(s),r=IBt(),[a,i]=N.useState(null),[l,o]=N.useState("all"),c=t.filter(h=>l==="all"?!0:l==="new"?h.status==="new":h.action_type===l),d={all:t.length,new:t.filter(h=>h.status==="new").length,question:t.filter(h=>h.action_type==="question").length,showing:t.filter(h=>h.action_type==="showing").length,disclosure:t.filter(h=>h.action_type==="disclosure").length,offer:t.filter(h=>h.action_type==="offer").length},u=(h,p)=>{r.mutate({id:h,status:p,open_house_id:s})};return n?e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"Loading leads…"}):e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 bg-muted/40 border-b flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(Z2,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(ze,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(ze,{className:"bg-emerald-600 hover:bg-emerald-600",children:[d.new," new"]})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:[["all","All",d.all],["new","New",d.new],["offer","Hot",d.offer],["showing","Showings",d.showing],["question","Questions",d.question],["disclosure","Docs",d.disclosure]].map(([h,p,f])=>e.jsxs("button",{onClick:()=>o(h),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===h?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[p," ",e.jsx("span",{className:"opacity-60",children:f})]},h))})]}),c.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:t.length===0?"No leads yet. Share your virtual open house link to start capturing leads.":"No leads match this filter."}):e.jsx("ul",{className:"divide-y",children:c.map(h=>{const p=jnn[h.action_type],f=p.icon,g=h.payload||{},b=a===h.id,v=h.status==="contacted",j=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${j?"opacity-60":""} ${h.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(b?null:h.id),className:"w-full text-left px-4 py-3 flex items-start gap-3 hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${p.bg}`,children:e.jsx(f,{className:`h-4 w-4 ${p.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:g.visitor_name||"Visitor"}),e.jsx(ze,{variant:"outline",className:`text-[10px] ${p.color}`,children:p.label}),h.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),v&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(xr,{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(gr,{className:"h-3 w-3"}),ks(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(Hs,{className:"h-3 w-3"}),g.email]}),g.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pr,{className:"h-3 w-3"}),g.phone]})]})]}),b?e.jsx(io,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(ga,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),b&&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(ZXe).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(ZXe).map(([_,S])=>{const A=g[_];return A==null||A===""||Array.isArray(A)&&A.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:S}),e.jsx("div",{className:"font-medium",children:Array.isArray(A)?A.join(", "):String(A)})]},_)})}),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(B,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(Hs,{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(B,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(Pr,{className:"h-3.5 w-3.5"}),"Call"]})}),!v&&e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(xr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),j?e.jsx(B,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"new"),children:"Restore"}):e.jsxs(B,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"archived"),children:[e.jsx(im,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}function knn({open:s,onOpenChange:t,openHouse:n}){const{isGmailConnected:r,gmailEmail:a}=bh(),i=fa(),[l,o]=N.useState([]),[c,d]=N.useState([]),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,b]=N.useState(""),[v,j]=N.useState(""),[_,S]=N.useState(""),[A,T]=N.useState(!1),[D,L]=N.useState(!1),[M,F]=N.useState(!1),z=`https://guestbook.relevelup.com/${n.slug}`;N.useEffect(()=>{s&&(j(`Take a virtual tour of ${n.property_address}`),S(`I wanted to share an immersive virtual tour of ${n.property_address} with you. Step inside from anywhere — explore every room at your own pace.`),d([]),b(""),T(r),l.length===0&&V())},[s,n.id,r]);const V=async()=>{if(i){f(!0);try{const{data:ce,error:de}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i).not("email","is",null).neq("email","").order("first_name",{ascending:!0}).limit(1e3);if(de)throw de;o(ce||[])}catch{ae.error("Failed to load contacts")}finally{f(!1)}}},W=ce=>`${ce.first_name} ${ce.last_name||""}`.trim(),K=ce=>{d(de=>de.find(ie=>ie.id===ce.id)?de.filter(ie=>ie.id!==ce.id):[...de,ce])},Y=()=>{const ce=g.trim();if(!ce)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ce)){ae.error("Invalid email");return}d(ie=>[...ie,{id:`manual-${ce}`,first_name:ce.split("@")[0],last_name:null,email:ce}]),b("")},ee=N.useMemo(()=>c.filter(ce=>!!ce.email).map(ce=>({email:ce.email,name:W(ce)})),[c]),ne=ce=>{const de=ce?`Hi ${ce},`:"Hi there,",ie=_.split(/\n\n+/).map(ye=>`

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

`).join("");return`

${de}

${ie}

▶ Start Virtual Tour

Or copy this link: ${z}

`},oe=async()=>{var ce;if(ee.length===0){ae.error("Add at least one recipient");return}L(!0);try{if(A&&r){let de=0;for(const ie of ee){const{data:ye,error:_e}=await q.functions.invoke("gmail-send",{body:{to:ie.email,subject:v,body:ne((ce=ie.name)==null?void 0:ce.split(" ")[0])}});!_e&&(ye!=null&&ye.success)?de+=1:console.warn("gmail-send error",_e,ye)}if(de===0)throw new Error("Gmail send failed");ae.success(`Sent to ${de} of ${ee.length} via Gmail`)}else{const{data:de,error:ie}=await q.functions.invoke("send-virtual-tour-invite",{body:{openHouseId:n.id,recipients:ee,subject:v,personalMessage:_}});if(ie)throw ie;if(!(de!=null&&de.success))throw new Error((de==null?void 0:de.error)||"Send failed");ae.success(`Sent to ${de.sent} of ${de.total} recipient${de.total===1?"":"s"}`)}t(!1)}catch(de){ae.error((de==null?void 0:de.message)||"Failed to send")}finally{L(!1)}},pe=async()=>{await navigator.clipboard.writeText(z),F(!0),setTimeout(()=>F(!1),1500)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[560px] w-[calc(100vw-2rem)] max-h-[90vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(ws,{className:"min-w-0",children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5 text-primary"}),"Share Virtual Tour"]}),e.jsx(Qn,{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(tl,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:z}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:pe,className:"shrink-0 h-7 gap-1",children:[M?e.jsx(Lr,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(ta,{className:"h-3.5 w-3.5"}),M?"Copied":"Copy"]})]}),r&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{type:"button",variant:A?"default":"outline",size:"sm",onClick:()=>T(!0),className:"gap-1.5",children:[e.jsx(Hs,{className:"h-3.5 w-3.5"}),"Send from Gmail"]}),e.jsx(B,{type:"button",variant:A?"outline":"default",size:"sm",onClick:()=>T(!1),className:"gap-1.5",children:"Send from LevelUp"})]}),A&&a&&e.jsxs("p",{className:"text-xs text-muted-foreground -mt-2",children:["Sending as ",e.jsx("span",{className:"font-medium",children:a})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{className:"flex items-center gap-1.5",children:[e.jsx(_n,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsxs(Wo,{open:u,onOpenChange:h,modal:!0,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:c.length?`${c.length} selected`:"Select contacts..."}),e.jsx(Hg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(zo,{className:"w-[440px] max-w-[calc(100vw-2rem)] p-0",align:"start",children:e.jsxs(Xg,{children:[e.jsx(Jg,{placeholder:"Search contacts..."}),e.jsxs(e0,{className:"max-h-[300px] overflow-y-auto",children:[e.jsx(t0,{children:p?"Loading...":"No contacts found."}),e.jsx(s0,{children:l.map(ce=>{const de=!!c.find(_e=>_e.id===ce.id),ie=W(ce).slice(0,80),ye=(ce.email||"").slice(0,80);return e.jsxs(ex,{value:`${ie} ${ye}`,onSelect:()=>K(ce),className:"py-2",children:[e.jsx(Lr,{className:Et("mr-2 h-4 w-4 shrink-0",de?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:ie||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ye})]})]},ce.id)})})]})]})})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:c.map(ce=>e.jsxs(ze,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:W(ce)}),e.jsx("button",{onClick:()=>K(ce),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(Fn,{className:"h-3 w-3"})})]},ce.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(ge,{value:g,onChange:ce=>b(ce.target.value),placeholder:"Or type an email...",type:"email",onKeyDown:ce=>{ce.key==="Enter"&&(ce.preventDefault(),Y())}}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:Y,children:"Add"})]})]}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(ge,{id:"vt-subject",value:v,onChange:ce=>j(ce.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vt-message",children:"Personal Message"}),e.jsx(Ts,{id:"vt-message",value:_,onChange:ce=>S(ce.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:D,children:"Cancel"}),e.jsxs(B,{onClick:oe,disabled:D||ee.length===0||!v.trim(),className:"gap-2",children:[D?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),D?"Sending...":`Send${ee.length?` to ${ee.length}`:""}`]})]})]})]})})}const DTe="guestbook.relevelup.com";function Snn(){const{data:s,isLoading:t}=cBt(),n=dBt(),r=Ect(),a=uBt(),[i,l]=N.useState(!1),[o,c]=N.useState(null),{user:d}=gs(),u=fa(),[h,p]=N.useState(null),[f,g]=N.useState(null),[b,v]=N.useState(!1),j=N.useRef(null),[_,S]=N.useState({property_address:"",city:"",state:"",zip:"",event_date:ks(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),A=M=>{var z;const F=(z=M.target.files)==null?void 0:z[0];if(F){if(F.size>5*1024*1024){Dr({title:"Photo must be under 5MB",variant:"destructive"});return}p(F),g(URL.createObjectURL(F))}},T=()=>{p(null),g(null),j.current&&(j.current.value="")},D=async()=>{if(!_.property_address){Dr({title:_.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let M;if(h&&d){v(!0);const z=h.name.split(".").pop(),V=`${u}/${Date.now()}.${z}`,{error:W}=await q.storage.from("open-house-photos").upload(V,h,{upsert:!0});if(W){Dr({title:"Photo upload failed",description:W.message,variant:"destructive"}),v(!1);return}const{data:K}=q.storage.from("open-house-photos").getPublicUrl(V);M=K.publicUrl,v(!1)}const F=_.kind==="virtual"?{..._,start_time:void 0,end_time:void 0,photo_url:M}:{..._,photo_url:M};await n.mutateAsync(F),l(!1),S({property_address:"",city:"",state:"",zip:"",event_date:ks(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"}),T()},L=M=>{navigator.clipboard.writeText(`https://${DTe}/${M}`),Dr({title:"Link copied!"})};return e.jsxs(Cs,{title:"Guest Book",children:[e.jsx(Yo,{children:e.jsx("title",{children:"Guest Book | LevelUp"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold font-serif text-foreground",children:"Guest Book"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"The modern open house sign-in experience"})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"New Open House"]})}),e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create Open House"}),e.jsx(Qn,{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(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Open House Type"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>S(M=>({...M,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${_.kind==="physical"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Physical Open House"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"In-person sign-in at the property"})]}),e.jsxs("button",{type:"button",onClick:()=>S(M=>({...M,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${_.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"})]})]})]}),_.kind==="physical"&&e.jsx("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:e.jsxs("div",{className:"flex gap-1 flex-1",children:[e.jsx("button",{type:"button",onClick:()=>S(M=>({...M,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${_.event_type==="property"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Single Property"}),e.jsx("button",{type:"button",onClick:()=>S(M=>({...M,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${_.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),_.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tour Format"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>S(M=>({...M,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${_.tour_mode==="rooms"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Room-by-room"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Photos & videos per room"})]}),e.jsxs("button",{type:"button",onClick:()=>S(M=>({...M,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${_.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(se,{children:_.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(ge,{value:_.property_address,onChange:M=>S(F=>({...F,property_address:M.target.value})),placeholder:_.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(se,{children:"City"}),e.jsx(ge,{value:_.city,onChange:M=>S(F=>({...F,city:M.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(ge,{value:_.state,onChange:M=>S(F=>({...F,state:M.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"ZIP"}),e.jsx(ge,{value:_.zip,onChange:M=>S(F=>({...F,zip:M.target.value})),placeholder:"78701"})]})]}),_.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(se,{children:"Date"}),e.jsx(ge,{type:"date",value:_.event_date,onChange:M=>S(F=>({...F,event_date:M.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Start Time"}),e.jsx(ge,{type:"time",value:_.start_time,onChange:M=>S(F=>({...F,start_time:M.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"End Time"}),e.jsx(ge,{type:"time",value:_.end_time,onChange:M=>S(F=>({...F,end_time:M.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Welcome Message"}),e.jsx(Ts,{value:_.agent_greeting,onChange:M=>S(F=>({...F,agent_greeting:M.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(se,{children:_.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:j,type:"file",accept:"image/*",onChange:A,className:"hidden"}),f?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:f,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:T,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(Fn,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var M;return(M=j.current)==null?void 0:M.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(ay,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",_.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(B,{onClick:D,disabled:n.isPending||b,className:"w-full",children:b?"Uploading photo...":n.isPending?"Creating...":_.kind==="virtual"?"Create Virtual Open House":_.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})]}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(M=>e.jsx(fe,{className:"animate-pulse",children:e.jsxs(Mt,{children:[e.jsx("div",{className:"h-5 bg-muted rounded w-48"}),e.jsx("div",{className:"h-4 bg-muted rounded w-32 mt-2"})]})},M))}):s!=null&&s.length?e.jsx("div",{className:"space-y-4",children:s.map(M=>e.jsx(Cnn,{openHouse:M,isExpanded:o===M.id,onToggle:()=>c(o===M.id?null:M.id),onCopyLink:()=>L(M.slug||""),onToggleActive:()=>r.mutate({id:M.id,is_active:!M.is_active}),onDelete:()=>a.mutate(M.id)},M.id))}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{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(ly,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No Open Houses Yet"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm mb-6",children:"Create your first open house to get a beautiful, mobile-friendly sign-in page with a shareable link and QR code."}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function Cnn({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i}){const{data:l}=Tct(t?s.id:void 0),{data:o}=lt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:L,error:M}=await q.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(M)throw M;const F=L.brokerages;return{...L,brokerage_name:(F==null?void 0:F.name)||null}},enabled:!!s.agent_id}),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,b]=N.useState(!1),v=N.useRef(null),j=`https://${DTe}/${s.slug}`,_=L=>{if(!L)return"";const[M,F]=L.split(":"),z=parseInt(M),V=z>=12?"PM":"AM";return`${z>12?z-12:z||12}:${F} ${V}`},S=()=>{if(!(l!=null&&l.length))return;const L=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],M=l.map(K=>[K.first_name,K.last_name||"",K.email||"",K.phone||"",K.visitor_address||"",K.visitor_intent||"",K.wants_market_updates?"Yes":"No",(K.message||"").replace(/"/g,'""'),ks(new Date(K.created_at),"MM/dd/yyyy h:mm a")]),F=[L,...M].map(K=>K.map(Y=>`"${Y}"`).join(",")).join(` `),z=new Blob([F],{type:"text/csv"}),V=URL.createObjectURL(z),W=document.createElement("a");W.href=V,W.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,W.click(),URL.revokeObjectURL(V)},A=N.useCallback(()=>{if(!v.current)return;const L=v.current.querySelector("svg");if(!L)return;const M=new XMLSerializer().serializeToString(L),F=document.createElement("canvas");F.width=1024,F.height=1024;const z=F.getContext("2d"),V=new Image;V.onload=()=>{z==null||z.drawImage(V,0,0,1024,1024);const W=document.createElement("a");W.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,W.href=F.toDataURL("image/png"),W.click()},V.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(M)))},[s.property_address]),T=N.useCallback(()=>{var we;if(!v.current)return;const L=v.current.querySelector("svg");if(!L)return;const M=new XMLSerializer().serializeToString(L),F="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(M))),z=ks(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),V=s.start_time?`${_(s.start_time)}${s.end_time?" – "+_(s.end_time):""}`:"",W=[s.city,s.state].filter(Boolean).join(", "),K=s.agent_greeting||"Welcome! Please sign in below.",Y=!!s.photo_url,ee=!!o,ne=Y||ee,oe=Y&&ee,pe=oe?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ce=oe?"28px":"34px",de=oe?"0.2in 0.75in":ne?"0.3in 0.75in":"0.4in 0.75in",ie=ne?"0.15in":"0.3in",ye=ne?"0.15in":"0.3in",_e=oe?"14px 36px":"22px 44px",Me=oe?"20px":"24px",Te=ne?"0.2in":"0.35in",Ce=oe?"1.8in":"2.4in",Ee=ne?"0.15in":"0.3in",De=oe?"140px":ne?"160px":"200px",Ie=oe?"16px":"24px",Fe=oe?"10px 20px":"16px 28px",qe=oe?"44px":"56px",ve="0.15in",Je=window.open("","_blank");Je&&(Je.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${W?`
${W}${s.zip?" "+s.zip:""}
`:""}
Date
${z}
${V?`
Time
${V}
`:""}
${K}
${o?`
${o.avatar_url?`${o.name}`:`
${((we=o.name)==null?void 0:we.charAt(0))||"A"}
`}
Hosted By
${o.name}
${o.title?`
${o.title}
`:""} ${o.brokerage_name?`
${o.brokerage_name}
`:""} ${o.phone?`
${o.phone}
`:""}
`:""} ${s.photo_url?`Property`:""}
QR Code
Scan to Sign In
Point your phone camera at the QR code
`),Je.document.close(),setTimeout(()=>{Je.focus(),Je.print()},500))},[s,j,o]),D=async()=>{b(!0);try{const{error:L}=await q.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(L)throw L;Dr({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(L){Dr({title:"Failed to send",description:L.message,variant:"destructive"})}finally{b(!1)}};return e.jsxs(fe,{className:`transition-all ${s.is_active?"border-primary/30":"opacity-75"}`,children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Pt,{className:"text-base leading-snug break-words",children:s.property_address}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[e.jsx(ze,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(ze,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-purple-50 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300 border-purple-200 dark:border-purple-800",children:[e.jsx(Ir,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(ze,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800",children:[e.jsx(Ca,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(ze,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300 border-blue-200 dark:border-blue-800",children:[e.jsx(Xi,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(ze,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Ga,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(sx,{className:"h-4 w-4"}):e.jsx(io,{className:"h-4 w-4"})})]}),e.jsxs(Hn,{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-xs",children:[s.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),s.city,s.state?`, ${s.state}`:""]}),s.kind==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),ks(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(gr,{className:"h-3 w-3"}),_(s.start_time),s.end_time?` – ${_(s.end_time)}`:""]})]}),e.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[e.jsx(_n,{className:"h-3 w-3"}),s.visitor_count," signed in"]}),s.qr_scan_count>0&&e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(ly,{className:"h-3 w-3"}),s.qr_scan_count," scan",s.qr_scan_count===1?"":"s"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:items-center",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.location.href=`/mission-control/guest-book/live/${s.id}`,title:"Go Live",className:"h-9 w-full justify-center gap-1.5 text-xs text-emerald-600 border-emerald-200 hover:bg-emerald-50 dark:text-emerald-400 dark:border-emerald-800 dark:hover:bg-emerald-900/20 sm:h-8 sm:w-auto",children:[e.jsx(wf,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:r,title:"Copy link",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(ta,{className:"h-3.5 w-3.5"}),"Copy"]}),s.kind==="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>f(!0),title:"Share tour via email",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(Hl,{className:"h-3.5 w-3.5"}),"Share"]}),s.kind==="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),title:"Preview tour as visitor",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(Ir,{className:"h-3.5 w-3.5"}),"Preview Tour"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>d(!0),title:"QR Code",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(ly,{className:"h-3.5 w-3.5"}),"QR"]}),s.kind!=="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(`${j}?kiosk=1`,"_blank"),title:"Launch tablet/kiosk sign-in mode",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(jL,{className:"h-3.5 w-3.5"}),"Tablet"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>h(!0),title:"Settings",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(Vo,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>window.open(j,"_blank"),title:"Preview",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(tr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:a,title:s.is_active?"Deactivate":"Activate",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:s.is_active?e.jsx(gf,{className:"h-3.5 w-3.5"}):e.jsx(Ir,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:i,title:"Delete",className:"h-9 w-full justify-center text-xs text-destructive border-destructive/30 hover:bg-destructive/10 sm:h-8 sm:w-auto",children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})}),t&&e.jsxs(Ae,{className:"pt-0",children:[e.jsx(cl,{className:"mb-4"}),e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Share Link"}),e.jsxs("code",{className:"text-xs bg-muted/50 px-2 py-1 rounded block truncate",children:["https://",DTe,"/",s.slug]})]}),l!=null&&l.length?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:[l.length," Visitor",l.length!==1?"s":""]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:S,className:"h-7 text-xs gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),"Export CSV"]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/30 text-xs text-muted-foreground",children:[e.jsx("th",{className:"text-left p-2 font-medium",children:"Name"}),e.jsx("th",{className:"text-left p-2 font-medium hidden sm:table-cell",children:"Contact"}),e.jsx("th",{className:"text-left p-2 font-medium hidden md:table-cell",children:"Intent"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Time"})]})}),e.jsx("tbody",{children:l.map(L=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"p-2 font-medium",children:[L.first_name,L.last_name?` ${L.last_name}`:""]}),e.jsxs("td",{className:"p-2 text-muted-foreground hidden sm:table-cell",children:[L.email&&e.jsx("div",{className:"truncate max-w-[180px]",children:L.email}),L.phone&&e.jsx("div",{className:"text-xs",children:L.phone}),L.visitor_address&&e.jsx("div",{className:"text-xs truncate max-w-[180px]",children:L.visitor_address})]}),e.jsx("td",{className:"p-2 hidden md:table-cell",children:L.visitor_intent?e.jsx(ze,{variant:"outline",className:"text-xs capitalize",children:L.visitor_intent}):L.partial_signin?e.jsx(ze,{variant:"outline",className:"text-xs text-amber-600 border-amber-300 dark:text-amber-400 dark:border-amber-700",children:"Didn't finish"}):null}),e.jsx("td",{className:"p-2 text-xs text-muted-foreground",children:ks(new Date(L.created_at),"h:mm a")})]},L.id))})]})})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No visitors yet. Share the link to start collecting sign-ins!"}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(Nnn,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(wnn,{openHouseId:s.id})})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"sm:max-w-sm",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"QR Code"}),e.jsx(Qn,{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(QU,{value:j,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:j}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:T,children:[e.jsx(j9,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(B,{variant:"default",className:"w-full",onClick:D,disabled:g,children:[e.jsx(Hs,{className:"h-4 w-4 mr-2"}),g?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(bnn,{open:u,onOpenChange:h,openHouse:s}),s.kind==="virtual"&&e.jsx(knn,{open:p,onOpenChange:f,openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state}})]})}function Tnn(){const{slug:s}=_i();return s?e.jsx(Wht,{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 ONt({photoUrl:s,videoUrl:t,onPhotoChange:n,onVideoChange:r,contactId:a}){const{user:i}=gs(),l=PN(),o=N.useRef(null),c=N.useRef(null),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,g]=N.useState(0),b=async j=>{if(i){u(!0);try{const _=j.name.split(".").pop()||"jpg",S=`${i.id}/card-${Date.now()}.${_}`,{error:A}=await q.storage.from("listing-photos").upload(S,j);if(A)throw A;const{data:{publicUrl:T}}=q.storage.from("listing-photos").getPublicUrl(S);n(T),ae.success("Photo uploaded")}catch(_){ae.error(_.message||"Failed to upload photo")}finally{u(!1)}}},v=async j=>{if(i){if(j.size>500*1024*1024){ae.error("Video must be under 500MB");return}p(!0),g(0);try{const{videoId:_,libraryId:S}=await l6(`Card Video - ${Date.now()}`),{uploadUrl:A,apiKey:T}=await c6(_);await new Promise((M,F)=>{const z=new XMLHttpRequest;z.upload.addEventListener("progress",V=>{V.lengthComputable&&g(Math.round(V.loaded/V.total*100))}),z.addEventListener("load",()=>{z.status>=200&&z.status<300?M():F(new Error("Upload failed"))}),z.addEventListener("error",()=>F(new Error("Upload failed"))),z.open("PUT",A),z.setRequestHeader("AccessKey",T),z.send(j)});const D=`https://iframe.mediadelivery.net/embed/${S}/${_}`;r(D);const L=parseFloat((j.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:_,playback_url:`https://iframe.mediadelivery.net/play/${S}/${_}`,file_size_mb:L,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{p(!1),g(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Media (optional)"}),e.jsxs($r,{defaultValue:"photo",className:"w-full",children:[e.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(nl,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(Zt,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(vr,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(ls,{value:"photo",className:"mt-3",children:[s?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:s,alt:"Card photo",className:"w-full h-40 object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>n(null),children:e.jsx(Fn,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var j;return(j=o.current)==null?void 0:j.click()},disabled:d,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:d?e.jsx(ss,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(pf,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a photo"})]})}),e.jsx("input",{ref:o,type:"file",accept:"image/*",className:"hidden",onChange:j=>{var S;const _=(S=j.target.files)==null?void 0:S[0];_&&b(_),j.target.value=""}})]}),e.jsxs(ls,{value:"video",className:"mt-3",children:[t?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("iframe",{src:`${t}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>r(null),children:e.jsx(Fn,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var j;return(j=c.current)==null?void 0:j.click()},disabled:h,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:h?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(ss,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",f,"%"]}),e.jsx("div",{className:"w-32 h-1.5 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${f}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{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(k8e,{contactId:a,onVideoReady:j=>r(j)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:j=>{var S;const _=(S=j.target.files)==null?void 0:S[0];_&&v(_),j.target.value=""}}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1.5 text-center",children:"Videos are also saved to your Video Library"})]})]})]})}const Enn=[{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 Ann({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:Enn.map((t,n)=>e.jsxs(Zn.button,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:n*.04,duration:.25},onClick:()=>s(t.type),className:`group relative flex flex-col items-start gap-1 p-3.5 rounded-xl border bg-gradient-to-br ${t.gradient} hover:shadow-md hover:scale-[1.02] active:scale-[0.98] transition-all text-left`,children:[e.jsx("span",{className:"text-2xl",children:t.emoji}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:t.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground leading-tight",children:t.description})]},t.type))})}const zR={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 QXe({initialOpen:s,initialCardType:t,initialContactId:n,initialRecipientName:r,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=gs(),c=Gt(),[d,u]=N.useState(!1),[h,p]=N.useState("type"),[f,g]=N.useState(""),[b,v]=N.useState(null),[j,_]=N.useState(!1),[S,A]=N.useState("home_anniversary"),[T,D]=N.useState(""),[L,M]=N.useState(""),[F,z]=N.useState(""),[V,W]=N.useState(""),[K,Y]=N.useState("elegant"),[ee,ne]=N.useState(null),[oe,pe]=N.useState(null),ce=N.useState(!1);!ce[0]&&s&&t&&(ce[1](!0),u(!0),A(t),n&&v(n),r&&D(r),a&&M(a),i&&z(i),p(r?"details":"contact"));const{data:de}=lt({queryKey:["contacts-for-card",o==null?void 0:o.id,f],queryFn:async()=>{let qe=q.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, wedding_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);f&&(qe=qe.or(`first_name.ilike.%${f}%,last_name.ilike.%${f}%`));const{data:ve,error:Je}=await qe;if(Je)throw Je;return ve},enabled:!!(o!=null&&o.id)&&d}),{data:ie}=lt({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:qe,error:ve}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(ve)throw ve;return qe},enabled:!!(o!=null&&o.id)}),ye=qe=>{v(qe.id),D(`${qe.first_name}${qe.last_name?" "+qe.last_name:""}`),M([qe.address,qe.city,qe.state].filter(Boolean).join(", "));const ve=S==="wedding_anniversary"?qe.wedding_anniversary:S==="home_anniversary"?qe.home_anniversary:"";z(ve||""),p("details")},_e=qe=>{A(qe),p("contact")},Me=async()=>{var qe;if(!(!o||!ie)){_(!0);try{const ve={owner_user_id:o.id,contact_id:b,card_type:S,template:K,recipient_name:T,property_address:L||null,home_anniversary_date:F||null,custom_message:V||null,property_photo_url:ee||null,video_url:oe||null,agent_name:ie.name||"Agent",agent_photo_url:ie.avatar_url,agent_phone:ie.phone,agent_email:ie.email,agent_brokerage:((qe=ie.brokerage)==null?void 0:qe.name)||null},{error:Je}=await q.from("sendable_cards").insert(ve);if(Je)throw Je;ae.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),Te()}catch(ve){ae.error(ve.message||"Failed to create card")}finally{_(!1)}}},Te=()=>{u(!1),p("type"),A("home_anniversary"),g(""),v(null),D(""),M(""),z(""),W(""),Y("elegant"),ne(null),pe(null)},Ce={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"},Ee=zR[S],De=S==="home_anniversary"||S==="wedding_anniversary",Ie=S==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date",Fe=["home_anniversary","just_listed","just_sold"].includes(S);return e.jsxs(bs,{open:d,onOpenChange:qe=>{qe?u(!0):(Te(),l==null||l(!1))},children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:h==="type"?"What type of card?":h==="contact"?`${Ce[S]} — Choose a Contact`:`${Ce[S]} — Customize`})}),h==="type"&&e.jsx(Ann,{onSelect:_e}),h==="contact"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>p("type"),children:[e.jsx(Wr,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search contacts...",value:f,onChange:qe=>g(qe.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[de==null?void 0:de.map(qe=>e.jsxs("button",{onClick:()=>ye(qe),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(Xi,{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:[qe.first_name," ",qe.last_name]}),qe.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(zr,{className:"h-3 w-3"}),qe.address]})]}),(S==="home_anniversary"&&qe.home_anniversary||S==="wedding_anniversary"&&qe.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"})]},qe.id)),(de==null?void 0:de.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No contacts found"})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{p("details")},children:"Skip — enter details manually"})})]}),h==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>p("contact"),children:[e.jsx(Wr,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipient Name"}),e.jsx(ge,{value:T,onChange:qe=>D(qe.target.value),placeholder:"John & Jane Smith"})]}),Fe&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Address"}),e.jsx(ge,{value:L,onChange:qe=>M(qe.target.value),placeholder:"123 Main St, Austin, TX"})]}),De&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:Ie}),e.jsx(ge,{type:"date",value:F,onChange:qe=>z(qe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Message (optional)"}),e.jsx(Ts,{value:V,onChange:qe=>W(qe.target.value),placeholder:Ee.defaultMessage,rows:3})]}),e.jsx(ONt,{photoUrl:ee,videoUrl:oe,onPhotoChange:ne,onVideoChange:pe,contactId:b}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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:qe,label:ve,gradient:Je})=>e.jsxs("button",{onClick:()=>Y(qe),className:`p-2 rounded-lg border-2 transition-all text-center ${K===qe?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${Je}`}),e.jsx("span",{className:"text-[10px] font-medium",children:ve})]},qe))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>p("contact"),className:"flex-1",children:"Back"}),e.jsx(B,{onClick:Me,disabled:!T||j,className:"flex-1 gap-2",children:j?"Creating...":"Create Card"})]})]})]})]})}function Mnn({open:s,onOpenChange:t}){const n=In(),r=a=>{t(!1),n(a)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Set up an email sender"}),e.jsx(Qn,{children:"To send emails from the platform, connect Gmail or verify a Mass Email (Amazon SES) sender address. Either option lets you send from your own email."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>r("/integrations"),className:"w-full flex items-start gap-3 rounded-lg border p-4 text-left hover:bg-muted/50 transition",children:[e.jsx(Hs,{className:"h-5 w-5 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Connect Gmail"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Send from your Google account with your full inbox history."})]})]}),e.jsxs("button",{onClick:()=>r("/integrations"),className:"w-full flex items-start gap-3 rounded-lg border p-4 text-left hover:bg-muted/50 transition",children:[e.jsx(Z2,{className:"h-5 w-5 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Verify a Mass Email sender"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Send via Amazon SES from any verified email address you own."})]})]}),e.jsx("div",{className:"flex justify-end pt-2",children:e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Not now"})})]})]})})}const Inn={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 Pnn({card:s}){const{user:t}=gs(),{isGmailConnected:n,hasVerifiedSes:r,canSendEmail:a,sendMethod:i}=bh(),l=Gt(),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState("");N.useEffect(()=>{o&&s.contact_id&&!h&&q.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:T})=>{T!=null&&T.email&&p(T.email)})},[o,s.contact_id]);const f={home_anniversary:`🏡 Happy Home Anniversary, ${s.recipient_name}!`,wedding_anniversary:`💍 Happy Anniversary, ${s.recipient_name}!`,just_listed:`🏠 Just Listed — Check This Out, ${s.recipient_name}!`,just_sold:`🎉 Just Sold! Congrats, ${s.recipient_name}!`,congratulations:`🏆 Congratulations, ${s.recipient_name}!`,birthday:`🎂 Happy Birthday, ${s.recipient_name}!`,holiday:`🎄 Happy Holidays, ${s.recipient_name}!`,thank_you:`💐 Thank You, ${s.recipient_name}!`,thinking_of_you:`💭 Thinking of You, ${s.recipient_name}!`},[g,b]=N.useState(f[s.card_type]||`A Special Card for ${s.recipient_name}!`),[v,j]=N.useState(""),_=`https://cardstudio.relevelup.com/c/${s.share_token}`,S=gt({mutationFn:async()=>{var F;if(!h)throw new Error("Recipient email is required");const T=`
${v?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,{data:D}=await q.auth.getSession(),L=(F=D==null?void 0:D.session)==null?void 0:F.access_token,M=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/gmail-send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L}`},body:JSON.stringify({to:h,subject:g,body:T,contactId:s.contact_id||void 0})});if(!M.ok){const z=await M.json();throw new Error(z.error||"Failed to send")}return M.json()},onSuccess:async()=>{await q.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:"gmail"}).eq("id",s.id),l.invalidateQueries({queryKey:["sendable-cards"]}),ae.success(`Card sent to ${h}!`),c(!1)},onError:T=>{ae.error(T.message||"Failed to send email")}}),A=i==="mass_email"?"Mass Email":"Gmail";return a?e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Di,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(cr,{className:"h-3 w-3"})})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Send Card via ",A]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"gmail-to",children:"To"}),e.jsx(P_t,{value:h,onChange:p,userId:t==null?void 0:t.id,placeholder:"Search contacts or type an email..."}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Pick from your Agent OS contacts, or type any email address."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subject"}),e.jsx(ge,{value:g,onChange:T=>b(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Note (optional)"}),e.jsx(Ts,{value:v,onChange:T=>j(T.target.value),placeholder:"Add a warm personal note before the card link...",rows:3})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:[i==="mass_email"?e.jsx(e.Fragment,{children:"Sending via your verified Mass Email sender (Gmail isn't connected)."}):e.jsx(e.Fragment,{children:"The email will include a beautiful button linking to your card at:"}),e.jsx("br",{}),e.jsx("span",{className:"font-mono text-foreground",children:_})]}),e.jsx(B,{onClick:()=>S.mutate(),disabled:!h||S.isPending,className:"w-full gap-2",children:S.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4"})," Send Card"]})})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",title:"Set up an email sender to send cards",onClick:()=>u(!0),children:e.jsx(cr,{className:"h-3 w-3"})}),e.jsx(Mnn,{open:d,onOpenChange:u})]})}function Lnn({card:s}){const t=Gt(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(s.recipient_name),[c,d]=N.useState(s.property_address||""),[u,h]=N.useState(s.home_anniversary_date||""),[p,f]=N.useState(s.custom_message||""),[g,b]=N.useState(s.template),[v,j]=N.useState(s.property_photo_url),[_,S]=N.useState(s.video_url||null),A=D=>{D&&(o(s.recipient_name),d(s.property_address||""),h(s.home_anniversary_date||""),f(s.custom_message||""),b(s.template),j(s.property_photo_url),S(s.video_url||null)),r(D)},T=async()=>{if(!l.trim()){ae.error("Recipient name is required");return}i(!0);try{const{error:D}=await q.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:u||null,custom_message:p.trim()||null,template:g,property_photo_url:v||null,video_url:_||null}).eq("id",s.id);if(D)throw D;t.invalidateQueries({queryKey:["sendable-cards"]}),ae.success("Card updated"),r(!1)}catch(D){ae.error(D.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(bs,{open:n,onOpenChange:A,children:[e.jsx(Di,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(ja,{className:"h-3 w-3"})})}),e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{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(se,{children:"Recipient Name"}),e.jsx(ge,{value:l,onChange:D=>o(D.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Address"}),e.jsx(ge,{value:c,onChange:D=>d(D.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Home Anniversary Date"}),e.jsx(ge,{type:"date",value:u,onChange:D=>h(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Message (optional)"}),e.jsx(Ts,{value:p,onChange:D=>f(D.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(ONt,{photoUrl:v,videoUrl:_,onPhotoChange:j,onVideoChange:S,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(D=>e.jsxs("button",{onClick:()=>b(D),className:`p-3 rounded-lg border-2 transition-all text-center ${g===D?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${D==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":D==="bold"?"bg-gradient-to-br from-violet-500 to-fuchsia-500":"bg-gradient-to-br from-amber-200 to-orange-300"}`}),e.jsx("span",{className:"text-xs font-medium capitalize",children:D})]},D))})]}),e.jsx(B,{onClick:T,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function Dnn(){const{user:s}=gs(),t=Gt(),[n,r]=N.useState(""),[a,i]=yl(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),u=a.get("date"),h=!!l,{data:p,isLoading:f}=lt({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:S,error:A}=await q.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(A)throw A;return S},enabled:!!(s!=null&&s.id)}),g=gt({mutationFn:async S=>{const{error:A}=await q.from("sendable_cards").delete().eq("id",S);if(A)throw A},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),ae.success("Card deleted")}}),b=S=>{const A=`https://cardstudio.relevelup.com/c/${S}`;navigator.clipboard.writeText(A),ae.success("Share link copied!")},v=p==null?void 0:p.filter(S=>{var A;return!n||S.recipient_name.toLowerCase().includes(n.toLowerCase())||((A=S.property_address)==null?void 0:A.toLowerCase().includes(n.toLowerCase()))}),j={elegant:"Elegant",bold:"Bold",warm:"Warm"},_={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};return e.jsx(Cs,{title:"Card Studio",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Card Studio"})}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create & send beautiful branded cards to your clients"})]}),e.jsx(QXe,{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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Search cards...",value:n,onChange:S=>r(S.target.value),className:"pl-9"})]}),f?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(S=>e.jsx(fe,{className:"animate-pulse",children:e.jsxs(Ae,{className:"p-4",children:[e.jsx("div",{className:"h-40 bg-muted rounded-lg mb-3"}),e.jsx("div",{className:"h-4 bg-muted rounded w-2/3 mb-2"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2"})]})},S))}):v!=null&&v.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(S=>e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`aspect-[16/10] flex items-center justify-center relative overflow-hidden ${S.template==="elegant"?"bg-gradient-to-br from-slate-50 via-slate-100 to-slate-200 dark:from-slate-900 dark:via-slate-800 dark:to-slate-700":S.template==="bold"?"bg-gradient-to-br from-violet-600 via-fuchsia-500 to-pink-500":"bg-gradient-to-br from-amber-100 via-orange-200 to-rose-200 dark:from-amber-900 dark:via-orange-800 dark:to-rose-800"}`,children:[S.template==="elegant"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"absolute top-0 left-0 w-full h-full opacity-10",children:[e.jsx("div",{className:"absolute top-3 left-3 w-16 h-16 border-t-2 border-l-2 border-primary/40 rounded-tl-lg"}),e.jsx("div",{className:"absolute bottom-3 right-3 w-16 h-16 border-b-2 border-r-2 border-primary/40 rounded-br-lg"})]}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 rounded-full border border-primary/10"})]}),S.template==="bold"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-8 -right-8 w-32 h-32 rounded-full bg-white/10 blur-sm"}),e.jsx("div",{className:"absolute -bottom-6 -left-6 w-24 h-24 rounded-full bg-white/10 blur-sm"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.15)_0%,transparent_70%)]"})]}),S.template==="warm"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-4 -left-4 w-28 h-28 rounded-full bg-orange-400/15 blur-md"}),e.jsx("div",{className:"absolute -bottom-6 -right-6 w-32 h-32 rounded-full bg-rose-400/15 blur-md"})]}),e.jsxs("div",{className:"text-center px-4 relative z-10",children:[e.jsx("div",{className:"text-3xl mb-1.5 opacity-80",children:S.card_type==="home_anniversary"?"🏡":S.card_type==="wedding_anniversary"?"💍":S.card_type==="birthday"?"🎂":S.card_type==="just_sold"?"🎉":S.card_type==="just_listed"?"🏠":S.card_type==="thank_you"?"💐":S.card_type==="congratulations"?"🏆":S.card_type==="holiday"?"🎄":S.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${S.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:_[S.card_type]||S.card_type}),e.jsx("p",{className:`font-semibold text-base ${S.template==="bold"?"text-white":"text-foreground"}`,children:S.recipient_name}),S.property_address&&e.jsx("p",{className:`text-xs mt-1 ${S.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:S.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(ze,{variant:S.template==="bold"?"outline":"secondary",className:`text-[10px] ${S.template==="bold"?"border-white/30 text-white/80":""}`,children:j[S.template]||S.template})})]}),e.jsxs(Ae,{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(Ir,{className:"h-3 w-3"}),S.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Go(new Date(S.created_at),{addSuffix:!0})})]}),S.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",ks(new Date(S.sent_at),"MMM d, yyyy")," via ",S.sent_via]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1 gap-1 text-xs",onClick:()=>b(S.share_token),children:[e.jsx(ta,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(Lnn,{card:S}),e.jsx(Pnn,{card:S}),e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${S.share_token}`,"_blank"),children:e.jsx(tr,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>g.mutate(S.id),children:e.jsx(bn,{className:"h-3 w-3"})})]})]})]},S.id))}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ae,{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(Hs,{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(QXe,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]})})]})})}const RG=[{id:"mls",label:"MLS Description",tag:"Standard",icon:zr,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:xf,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:ph,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:gw,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:o9,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:mo,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:Oh,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:mu,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:bf,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:qd,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:gr,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:bb,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:Tl,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:n9,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:uh,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:vr,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:Ph,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:Bv,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:xf,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:_9,accent:"from-sky-500 to-blue-500",desc:"Voiceover for aerial b-roll",category:"video",extras:["signoff"]},{id:"neighborhoodTour",label:"Neighborhood Tour",tag:"Local",icon:Ca,accent:"from-emerald-500 to-teal-500",desc:"Area lifestyle script",category:"video",extras:["neighborhood","signoff"]},{id:"justListedEmail",label:"Just Listed Email",tag:"Announce",icon:Hs,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:dL,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:_n,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:bb,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:KS,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:Ca,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function Rnn(){var kr,dr,Jr,jr,qn,wi,Oi,ea,ya,Mi,da;const{user:s}=gs(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState([]),[o,c]=N.useState(""),[d,u]=N.useState([]),[h,p]=N.useState(""),[f,g]=N.useState(""),[b,v]=N.useState(""),[j,_]=N.useState(""),[S,A]=N.useState(""),[T,D]=N.useState(""),[L,M]=N.useState(""),[F,z]=N.useState(null),[V,W]=N.useState(""),[K,Y]=N.useState(""),[ee,ne]=N.useState(""),[oe,pe]=N.useState(""),[ce,de]=N.useState(""),[ie,ye]=N.useState(""),[_e,Me]=N.useState(""),[Te,Ce]=N.useState(""),[Ee,De]=N.useState(""),[Ie,Fe]=N.useState(""),[qe,ve]=N.useState(""),[Je,we]=N.useState(""),[it,Ne]=N.useState(""),[He,$e]=N.useState(""),[Ye,Ke]=N.useState(""),[rt,tt]=N.useState(""),[at,Ge]=N.useState(""),[dt,Bt]=N.useState(""),[kt,Qt]=N.useState(""),[ns,$s]=N.useState(""),[Ds,Dt]=N.useState(""),[St,$t]=N.useState(""),[ht,Ut]=N.useState(""),[Es,Xt]=N.useState(""),[Ys,Ss]=N.useState(""),[Bs,Us]=N.useState("listing"),[sn,Jn]=N.useState("mls"),[fn,Sn]=N.useState({}),[Gn,Hr]=N.useState({}),[pi,Ms]=N.useState(!1),[bi,Rr]=N.useState(!1),er=jn=>{Us(jn);const Aa=RG.find(Yi=>Yi.category===jn);Aa&&Jn(Aa.id)},{data:lr}=lt({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&pi,queryFn:async()=>{const{data:jn,error:Aa}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, property_type, description").eq("agent_id",s.id).order("created_at",{ascending:!1}).limit(50);if(Aa)throw Aa;return jn||[]}}),Fs=()=>{const jn=o.trim();jn&&(l(Aa=>[...Aa,jn]),c(""))},$n=jn=>l(Aa=>Aa.filter((Yi,Bo)=>Bo!==jn)),Cr=jn=>{var Aa,Yi,Bo,rl;z(jn.id),n(jn.property_address||""),D(jn.city||""),M(jn.state||""),_(((Aa=jn.price)==null?void 0:Aa.toString())||""),p(((Yi=jn.bedrooms)==null?void 0:Yi.toString())||""),g(((Bo=jn.bathrooms)==null?void 0:Bo.toString())||""),v(((rl=jn.square_footage)==null?void 0:rl.toString())||""),A(jn.property_type||""),a(jn.description||""),Ms(!1),ae.success("Listing imported")},ts=async jn=>{if(!(!jn.target.files||!(s!=null&&s.id))){Rr(!0);try{const Aa=[];for(const Yi of Array.from(jn.target.files).slice(0,10)){const Bo=`${s.id}/${Date.now()}-${Yi.name.replace(/[^\w.-]/g,"_")}`,{error:rl}=await q.storage.from("listing-photos").upload(Bo,Yi,{upsert:!1});if(rl){console.error(rl);continue}const{data:po}=q.storage.from("listing-photos").getPublicUrl(Bo);Aa.push(po.publicUrl)}u(Yi=>[...Yi,...Aa]),Aa.length&&ae.success(`${Aa.length} photo(s) uploaded`)}catch(Aa){ae.error(Aa.message||"Photo upload failed")}finally{Rr(!1)}}},Oe=RG.find(jn=>jn.id===sn),Qe=async jn=>{var Yi,Bo,rl;const Aa=RG.find(po=>po.id===jn);if(!t.trim()&&!r.trim()&&i.length===0){ae.error("Add a property address, MLS remarks, or features first");return}if((Yi=Aa.extras)!=null&&Yi.includes("openHouse")&&(!V||!K||!ee)){ae.error("Add the open house date, start and end time");return}if((Bo=Aa.extras)!=null&&Bo.includes("priceImprovement")&&(!oe||!ce)){ae.error("Add previous and new price");return}if((rl=Aa.extras)!=null&&rl.includes("sold")&&!ie){ae.error("Add the sold price");return}Jn(jn),Hr(po=>({...po,[jn]:!0}));try{const{data:po,error:zc}=await q.functions.invoke("listing-studio-generate",{body:{copyType:jn,propertyAddress:t,mlsRemarks:r,features:i,photoUrls:d,listingId:F,bedrooms:h?Number(h):null,bathrooms:f?Number(f):null,squareFootage:b?Number(b):null,price:j?Number(j):null,propertyType:S||null,city:T||null,state:L||null,openHouseDate:V||null,openHouseStart:K||null,openHouseEnd:ee||null,previousPrice:oe?Number(oe):null,newPrice:ce?Number(ce):null,soldPrice:ie?Number(ie):null,soldDate:_e||null,comingSoonDate:Te||null,builderName:Ee||null,yearBuilt:Ie?Number(Ie):null,warrantyInfo:qe||null,monthlyRent:Je?Number(Je):null,capRate:it||null,occupancy:He||null,daysOnMarket:Ye?Number(Ye):null,offerCount:rt?Number(rt):null,originalListPrice:at?Number(at):null,soldDaysOnMarket:dt?Number(dt):null,commissionOffered:kt||null,refreshments:ns||null,vibe:Ds||null,neighborhoodHighlights:St||null,agentName:ht||null,agentBrokerage:Es||null,agentContact:Ys||null}});if(zc)throw zc;if(po!=null&&po.error)throw new Error(po.error);Sn(Sd=>({...Sd,[jn]:po.content}))}catch(po){ae.error(po.message||"Generation failed")}finally{Hr(po=>({...po,[jn]:!1}))}},ct=jn=>{navigator.clipboard.writeText(jn),ae.success("Copied to clipboard")},vt=Oe.icon,It=fn[sn]?fn[sn].trim().split(/\s+/).length:0,qt=jn=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:RG.filter(Aa=>Aa.category===jn).map(Aa=>{const Yi=Aa.icon,Bo=sn===Aa.id,rl=!!fn[Aa.id];return e.jsxs("button",{onClick:()=>Jn(Aa.id),className:Et("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",Bo?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[Bo&&e.jsx("div",{className:Et("absolute inset-0 opacity-[0.07] bg-gradient-to-br",Aa.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:Et("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",Aa.accent),children:e.jsx(Yi,{className:"h-4 w-4"})}),rl&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(Lr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:Aa.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:Aa.desc})]})]})]},Aa.id)})}),xs=(kr=Oe.extras)==null?void 0:kr.includes("openHouse"),as=(dr=Oe.extras)==null?void 0:dr.includes("priceImprovement"),Ns=(Jr=Oe.extras)==null?void 0:Jr.includes("sold"),ln=(jr=Oe.extras)==null?void 0:jr.includes("comingSoon"),Ks=(qn=Oe.extras)==null?void 0:qn.includes("newConstruction"),Un=(wi=Oe.extras)==null?void 0:wi.includes("investment"),br=(Oi=Oe.extras)==null?void 0:Oi.includes("underContract"),Ar=(ea=Oe.extras)==null?void 0:ea.includes("brokerOpen"),sr=(ya=Oe.extras)==null?void 0:ya.includes("vibe"),Tr=(Mi=Oe.extras)==null?void 0:Mi.includes("neighborhood"),Ot=(da=Oe.extras)==null?void 0:da.includes("signoff"),wn=xs||as||Ns||ln||Ks||Un||br||Ar||sr||Tr||Ot;return e.jsx(Cs,{title:"Listing Studio",children:e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl border bg-gradient-to-br from-fuchsia-500/10 via-violet-500/5 to-sky-500/10 dark:from-fuchsia-500/20 dark:via-violet-500/10 dark:to-sky-500/20",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_top_right,_hsl(var(--primary)/0.15),_transparent_60%)]"}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-fuchsia-500/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-24 h-72 w-72 rounded-full bg-sky-500/20 blur-3xl"}),e.jsxs("div",{className:"relative px-6 py-8 sm:px-10 sm:py-12 flex flex-col md:flex-row md:items-center gap-6",children:[e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-background/60 backdrop-blur-sm border text-xs font-medium",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-fuchsia-500"}),"AI-powered listing & social copy"]}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold tracking-tight bg-gradient-to-br from-foreground to-foreground/60 bg-clip-text",children:"Listing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-xl",children:"Drop in a property, generate magnetic MLS copy, luxury narratives, open-house promos, and ready-to-post social content — all in seconds."})]}),e.jsxs(bs,{open:pi,onOpenChange:Ms,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(lr!=null&&lr.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),lr==null?void 0:lr.map(jn=>e.jsxs("button",{onClick:()=>Cr(jn),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:jn.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[jn.city,jn.state].filter(Boolean).join(", "),jn.price?` · $${Number(jn.price).toLocaleString()}`:"",jn.bedrooms?` · ${jn.bedrooms}bd`:"",jn.bathrooms?` · ${jn.bathrooms}ba`:""]})]},jn.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(fe,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(Ae,{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(zr,{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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(ge,{value:t,onChange:jn=>n(jn.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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(ge,{value:T,onChange:jn=>D(jn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(ge,{value:L,onChange:jn=>M(jn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(ge,{type:"number",value:j,onChange:jn=>_(jn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(ge,{value:S,onChange:jn=>A(jn.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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(ge,{type:"number",value:h,onChange:jn=>p(jn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(ge,{type:"number",step:"0.5",value:f,onChange:jn=>g(jn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(ge,{type:"number",value:b,onChange:jn=>v(jn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(Ts,{value:r,onChange:jn=>a(jn.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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:o,onChange:jn=>c(jn.target.value),onKeyDown:jn=>jn.key==="Enter"&&(jn.preventDefault(),Fs()),placeholder:"e.g. Quartz countertops"}),e.jsx(B,{type:"button",size:"icon",variant:"secondary",onClick:Fs,children:e.jsx(As,{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((jn,Aa)=>e.jsxs(ze,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[jn,e.jsx("button",{onClick:()=>$n(Aa),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(Fn,{className:"h-3 w-3"})})]},Aa))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(ay,{className:"h-4 w-4"}),bi?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:ts,disabled:bi,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((jn,Aa)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:jn,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>u(Yi=>Yi.filter((Bo,rl)=>rl!==Aa)),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(Fn,{className:"h-3 w-3"})})]},Aa))})]}),wn&&e.jsxs("div",{className:"space-y-4 p-4 rounded-xl border border-dashed border-primary/40 bg-primary/5 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",Oe.label]})]}),xs&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(ge,{type:"date",value:V,onChange:jn=>W(jn.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(ge,{type:"time",value:K,onChange:jn=>Y(jn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(ge,{type:"time",value:ee,onChange:jn=>ne(jn.target.value)})]})]})]}),as&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(ge,{type:"number",value:oe,onChange:jn=>pe(jn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(ge,{type:"number",value:ce,onChange:jn=>de(jn.target.value),placeholder:"$"})]})]}),Ns&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(ge,{type:"number",value:ie,onChange:jn=>ye(jn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(ge,{type:"date",value:_e,onChange:jn=>Me(jn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(ge,{type:"number",value:at,onChange:jn=>Ge(jn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(ge,{type:"number",value:dt,onChange:jn=>Bt(jn.target.value)})]})]})]}),ln&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(ge,{type:"date",value:Te,onChange:jn=>Ce(jn.target.value)})]}),Ks&&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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(ge,{value:Ee,onChange:jn=>De(jn.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(ge,{type:"number",value:Ie,onChange:jn=>Fe(jn.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(ge,{value:qe,onChange:jn=>ve(jn.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),Un&&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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(ge,{type:"number",value:Je,onChange:jn=>we(jn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(ge,{value:it,onChange:jn=>Ne(jn.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:He,onChange:jn=>$e(jn.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"})]})]})]}),br&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(ge,{type:"number",value:Ye,onChange:jn=>Ke(jn.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(ge,{type:"number",value:rt,onChange:jn=>tt(jn.target.value),placeholder:"e.g. 5"})]})]}),Ar&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(ge,{value:kt,onChange:jn=>Qt(jn.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(ge,{value:ns,onChange:jn=>$s(jn.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),sr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:Ds,onChange:jn=>Dt(jn.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"})]})]}),Tr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(Ts,{value:St,onChange:jn=>$t(jn.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),Ot&&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(se,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(ge,{value:ht,onChange:jn=>Ut(jn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(ge,{value:Es,onChange:jn=>Xt(jn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(ge,{value:Ys,onChange:jn=>Ss(jn.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:Nr},{key:"social",label:"Social Media",icon:mu},{key:"video",label:"Video Scripts",icon:vr},{key:"email",label:"Email Marketing",icon:Hs}].map(jn=>{const Aa=jn.icon,Yi=Bs===jn.key;return e.jsxs("button",{onClick:()=>er(jn.key),className:Et("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",Yi?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(Aa,{className:"h-4 w-4"}),jn.label]},jn.key)})}),qt(Bs),e.jsxs(fe,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:Et("h-1 bg-gradient-to-r",Oe.accent)}),e.jsxs(Ae,{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:Et("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",Oe.accent),children:e.jsx(vt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[Oe.label,e.jsx(ze,{variant:"outline",className:"text-[10px] font-normal",children:Oe.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:fn[sn]?`${It} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[fn[sn]&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>ct(fn[sn]),children:[e.jsx(ta,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(B,{onClick:()=>Qe(sn),disabled:Gn[sn],className:Et("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",Oe.accent),size:"sm",children:Gn[sn]?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):fn[sn]?e.jsxs(e.Fragment,{children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(Rm,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),fn[sn]?e.jsx(Ts,{value:fn[sn],onChange:jn=>Sn(Aa=>({...Aa,[sn]:jn.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:Et("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",Oe.accent),children:e.jsx(Rm,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",Oe.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 qF({delay:s,x:t,y:n,size:r}){return e.jsx(Zn.div,{className:"absolute rounded-full bg-slate-300/30 dark:bg-slate-500/20",style:{left:t,top:n,width:r,height:r},animate:{y:[0,-20,0],opacity:[.3,.7,.3],scale:[1,1.2,1]},transition:{duration:4,delay:s,repeat:1/0,ease:"easeInOut"}})}function Onn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:p}=s,f=zR[t];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-blue-50/30 to-white dark:from-slate-950 dark:to-slate-900 flex items-center justify-center p-4 overflow-hidden relative",children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx(Zn.div,{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-gradient-to-br from-blue-100/40 to-slate-100/20 blur-3xl",animate:{scale:[1,1.1,1],rotate:[0,5,0]},transition:{duration:8,repeat:1/0,ease:"easeInOut"}}),e.jsx(Zn.div,{className:"absolute -bottom-20 -left-20 w-64 h-64 rounded-full bg-gradient-to-tr from-slate-200/30 to-blue-100/20 blur-3xl",animate:{scale:[1,1.15,1],rotate:[0,-5,0]},transition:{duration:10,repeat:1/0,ease:"easeInOut"}}),e.jsx(qF,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(qF,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(qF,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(qF,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(qF,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(Zn.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,ease:"easeOut"},children:[e.jsxs(Zn.div,{className:"bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl rounded-3xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.1)] overflow-hidden border border-slate-200/60 dark:border-slate-700/50",initial:{scale:.95},animate:{scale:1},transition:{duration:.6,delay:.2},children:[e.jsx("div",{className:"relative h-2 bg-gradient-to-r from-slate-200 via-blue-300 to-slate-200 dark:from-slate-700 dark:via-blue-500 dark:to-slate-700 overflow-hidden",children:e.jsx(Zn.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}})}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs(Zn.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-slate-100 to-blue-50 dark:from-slate-800 dark:to-slate-700 flex items-center justify-center shadow-lg relative",initial:{scale:0,rotate:-10},animate:{scale:1,rotate:0},transition:{duration:.5,delay:.4,type:"spring",stiffness:200},children:[e.jsx(Zn.div,{className:"absolute inset-0 rounded-2xl border-2 border-slate-200/50 dark:border-slate-600/50",animate:{scale:[1,1.15,1],opacity:[.5,0,.5]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl",children:f.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Zn.div,{className:"inline-block mb-4",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:e.jsxs("span",{className:"text-sm font-semibold tracking-[0.25em] uppercase text-blue-400 dark:text-blue-300",children:[a," ",a===1?"Year":"Years"]})}),e.jsx(Zn.h1,{className:"text-4xl font-light text-slate-800 dark:text-slate-100 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:f.title[0]}),f.title[1]&&e.jsx(Zn.h2,{className:"text-4xl font-bold text-slate-800 dark:text-slate-100 mb-8 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:f.title[1]}),e.jsxs(Zn.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:n}),r&&e.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:r})]}),e.jsx(Zn.div,{className:"h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"80%"},transition:{duration:.8,delay:1.1},style:{margin:"0 auto 1.5rem"}}),h&&e.jsx(Zn.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Zn.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zn.p,{className:"text-sm text-slate-500 dark:text-slate-400 leading-relaxed max-w-xs mx-auto mb-8 italic",initial:{opacity:0},animate:{opacity:1},transition:{duration:.6,delay:1.3},children:i||f.defaultMessage}),e.jsxs(Zn.div,{className:"border-t border-slate-100 dark:border-slate-800 pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.5,delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(Zn.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-700 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-gradient-to-br from-slate-200 to-blue-100 dark:from-slate-700 dark:to-slate-600 flex items-center justify-center shadow-md",children:e.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:l}),u&&e.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[c&&e.jsxs(Zn.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Pr,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zn.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Hs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zn.p,{className:"text-center text-[10px] text-slate-400 dark:text-slate-600 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function QNe({delay:s,x:t,y:n,color:r,size:a}){return e.jsx(Zn.div,{className:`absolute rounded-full blur-2xl ${r}`,style:{left:t,top:n,width:a,height:a},animate:{scale:[1,1.4,1],opacity:[.2,.5,.2]},transition:{duration:5,delay:s,repeat:1/0,ease:"easeInOut"}})}function VF({delay:s,x:t,y:n}){return e.jsx(Zn.div,{className:"absolute text-white/30 text-lg",style:{left:t,top:n},animate:{opacity:[0,1,0],scale:[.5,1,.5],rotate:[0,180,360]},transition:{duration:3,delay:s,repeat:1/0,ease:"easeInOut"},children:"✦"})}const XXe={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 Fnn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:p}=s,f=zR[t],g=XXe[t]||XXe.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(QNe,{delay:0,x:"10%",y:"10%",color:g.orbs[0],size:200}),e.jsx(QNe,{delay:1,x:"70%",y:"60%",color:g.orbs[1],size:180}),e.jsx(QNe,{delay:2,x:"50%",y:"20%",color:g.orbs[2],size:150}),e.jsx(VF,{delay:0,x:"20%",y:"25%"}),e.jsx(VF,{delay:.8,x:"75%",y:"15%"}),e.jsx(VF,{delay:1.6,x:"85%",y:"65%"}),e.jsx(VF,{delay:2.4,x:"10%",y:"75%"}),e.jsx(VF,{delay:.4,x:"45%",y:"85%"}),e.jsxs(Zn.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.7,ease:"easeOut"},children:[e.jsxs(Zn.div,{className:"relative rounded-3xl overflow-hidden",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[e.jsx(Zn.div,{className:"absolute -inset-[1px] rounded-3xl bg-gradient-to-r from-violet-500 via-fuchsia-500 to-violet-500 opacity-50",animate:{backgroundPosition:["0% 50%","100% 50%","0% 50%"]},transition:{duration:4,repeat:1/0,ease:"linear"},style:{backgroundSize:"200% 200%"}}),e.jsxs("div",{className:"relative bg-white/5 backdrop-blur-xl border border-white/10 rounded-3xl px-8 py-10 text-center m-[1px]",children:[e.jsxs(Zn.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-2xl shadow-violet-500/40 relative",initial:{scale:0,rotate:-20},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:200},children:[e.jsx(Zn.div,{className:"absolute inset-0 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500",animate:{scale:[1,1.3,1],opacity:[.6,0,.6]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl relative z-10",children:f.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Zn.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/10 border border-white/15 backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[e.jsx(Zn.span,{className:"text-3xl font-black text-white",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.8},children:a}),e.jsx("span",{className:"text-xs font-semibold text-violet-200 uppercase tracking-widest",children:a===1?"Year":"Years"})]}),e.jsx(Zn.h1,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-violet-200 via-white to-fuchsia-200 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:f.title[0]}),f.title[1]&&e.jsx(Zn.h2,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-fuchsia-300 via-violet-200 to-purple-300 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:f.title[1]}),e.jsx(Zn.div,{className:"text-3xl mb-4",initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},transition:{duration:.4,delay:1,type:"spring",stiffness:300},children:f.emojis.slice(0,3).join("")}),e.jsxs(Zn.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:n}),r&&e.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(zr,{className:"h-3.5 w-3.5"}),r]})]}),h&&e.jsx(Zn.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Zn.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zn.div,{className:"bg-white/5 rounded-2xl p-5 border border-white/10 mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:i||f.defaultMessage})}),e.jsxs(Zn.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(Zn.img,{src:o,alt:l,className:"h-12 w-12 rounded-xl object-cover ring-2 ring-violet-500/40 shadow-lg",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-lg",children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-bold text-white",children:l}),u&&e.jsx("p",{className:"text-xs text-violet-300/60",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[c&&e.jsxs(Zn.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Pr,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(Zn.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Hs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zn.p,{className:"text-center text-[10px] text-violet-400/40 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function znn({emoji:s,delay:t,x:n,duration:r}){return e.jsx(Zn.div,{className:"absolute text-2xl pointer-events-none",style:{left:n,bottom:-20},animate:{y:[0,-600],opacity:[0,1,1,0],x:[0,15,-10,5],rotate:[0,20,-15,10]},transition:{duration:r,delay:t,repeat:1/0,ease:"easeOut"},children:s})}const JXe={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 Bnn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:p}=s,f=zR[t],g=JXe[t]||JXe.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:[f.emojis.map((b,v)=>e.jsx(znn,{emoji:b,delay:v*1.2,x:`${15+v*14}%`,duration:5+v%3},v)),e.jsx(Zn.div,{className:"absolute top-1/4 left-1/2 -translate-x-1/2 w-96 h-96 bg-gradient-to-r from-amber-200/30 to-rose-200/30 rounded-full blur-[100px]",animate:{scale:[1,1.2,1],opacity:[.3,.5,.3]},transition:{duration:6,repeat:1/0,ease:"easeInOut"}}),e.jsxs(Zn.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.7},children:[e.jsxs(Zn.div,{className:"bg-white rounded-3xl shadow-[0_20px_60px_-15px_rgba(251,146,60,0.2)] overflow-hidden border border-amber-100",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[e.jsxs(Zn.div,{className:`h-28 bg-gradient-to-r ${g.header} relative overflow-hidden`,children:[e.jsx(Zn.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}}),e.jsx(Zn.div,{className:"absolute top-3 left-10 text-5xl",animate:{rotate:[0,10,-5,0],y:[0,-3,0]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:f.emojis[0]}),e.jsx(Zn.div,{className:"absolute top-2 right-14 text-3xl",animate:{scale:[1,1.3,1],rotate:[0,15,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut",delay:.5},children:f.emojis[1]}),e.jsx(Zn.div,{className:"absolute bottom-2 left-1/2 -translate-x-1/2 text-3xl",animate:{y:[0,-5,0],scale:[1,1.1,1]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut",delay:1},children:f.emojis[2]})]}),e.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[e.jsx(Zn.div,{className:"mx-auto mb-4 h-20 w-20 rounded-full bg-white shadow-xl flex items-center justify-center border-4 border-white relative",initial:{scale:0},animate:{scale:1},transition:{delay:.4,type:"spring",stiffness:300},children:e.jsx(Zn.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-3xl",children:f.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Zn.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:e.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${g.accent}`,children:[e.jsx(Zn.span,{className:"text-5xl font-black",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.8},children:a}),e.jsx("span",{className:"text-sm font-semibold",children:a===1?"year":"wonderful years"})]})}),e.jsxs(Zn.h1,{className:`text-3xl font-bold ${g.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[f.title.join(" ")," ",f.emojis[4]]}),e.jsxs(Zn.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${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(Ca,{className:"h-3 w-3"}),r]})]}),h&&e.jsx(Zn.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Zn.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zn.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:`text-sm ${g.text} leading-relaxed italic`,children:['"',i||f.defaultMessage,'"']})}),e.jsxs(Zn.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center gap-3 justify-center",children:[o?e.jsx(Zn.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${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(Zn.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(Pr,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zn.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${g.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Hs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zn.p,{className:"text-center text-[10px] text-amber-400 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function OG({delay:s,x:t,y:n,size:r,color:a}){return e.jsx(Zn.div,{className:`absolute rounded-full ${a} blur-3xl`,style:{left:t,top:n,width:r,height:r},animate:{scale:[1,1.3,1],opacity:[.4,.7,.4],x:[0,20,-10,0],y:[0,-15,10,0]},transition:{duration:8,delay:s,repeat:1/0,ease:"easeInOut"}})}function XNe({delay:s,x:t,y:n,size:r}){return e.jsx(Zn.div,{className:"absolute rounded-full border border-white/10",style:{left:t,top:n,width:r,height:r},animate:{scale:[1,1.2,1],opacity:[.1,.3,.1],rotate:[0,180,360]},transition:{duration:12,delay:s,repeat:1/0,ease:"linear"}})}const eJe={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 $nn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:p}=s,f=zR[t],g=eJe[t]||eJe.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(OG,{delay:0,x:"5%",y:"10%",size:300,color:g.mesh[0]}),e.jsx(OG,{delay:2,x:"60%",y:"50%",size:250,color:g.mesh[1]}),e.jsx(OG,{delay:4,x:"30%",y:"70%",size:200,color:g.mesh[2]}),e.jsx(OG,{delay:1,x:"80%",y:"15%",size:180,color:g.mesh[0]}),e.jsx(XNe,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(XNe,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(XNe,{delay:6,x:"40%",y:"10%",size:80}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`}}),e.jsxs(Zn.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.8,ease:[.16,1,.3,1]},children:[e.jsxs(Zn.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${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(Zn.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:4,repeat:1/0,repeatDelay:3,ease:"easeInOut"}})}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs(Zn.div,{className:"mx-auto mb-6 h-24 w-24 rounded-3xl bg-white/[0.08] backdrop-blur-xl border border-white/[0.15] flex items-center justify-center relative",initial:{scale:0,rotate:-15},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:180},children:[e.jsx(Zn.div,{className:"absolute -inset-1 rounded-3xl border border-white/[0.08]",animate:{scale:[1,1.1,1],opacity:[.3,0,.3]},transition:{duration:3,repeat:1/0,ease:"easeInOut"}}),e.jsx(Zn.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:f.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Zn.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/[0.06] border border-white/[0.1] backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[e.jsx(Zn.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:a}),e.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${g.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(Zn.h1,{className:"text-4xl font-extralight text-white/90 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.7},children:f.title[0]}),f.title[1]&&e.jsx(Zn.h2,{className:"text-4xl font-bold text-white mb-6 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.85},children:f.title[1]}),e.jsxs(Zn.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:n}),r&&e.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",r]})]}),e.jsx(Zn.div,{className:"h-px bg-gradient-to-r from-transparent via-white/15 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"70%"},transition:{duration:1,delay:1.1},style:{margin:"0 auto 1.5rem"}}),h&&e.jsx(Zn.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Zn.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zn.div,{className:"bg-white/[0.04] rounded-2xl p-5 border border-white/[0.08] mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',i||f.defaultMessage,'"']})}),e.jsxs(Zn.div,{className:"border-t border-white/[0.06] pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(Zn.img,{src:o,alt:l,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-semibold text-white/60",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-white/80",children:l}),u&&e.jsx("p",{className:"text-xs text-white/30",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Zn.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Pr,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zn.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Hs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zn.p,{className:"text-center text-[10px] text-white/20 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function JNe({delay:s,x:t,angle:n,color:r}){return e.jsx(Zn.div,{className:`absolute h-[400px] w-[1px] ${r} origin-top`,style:{left:t,top:"-10%",transform:`rotate(${n}deg)`},animate:{opacity:[0,.4,0],scaleY:[.5,1,.5]},transition:{duration:6,delay:s,repeat:1/0,ease:"easeInOut"}})}function FG({delay:s,x:t}){return e.jsx(Zn.div,{className:"absolute w-1 h-1 rounded-full bg-amber-400/60",style:{left:t,bottom:"20%"},animate:{y:[0,-200,-400],x:[0,15,-10],opacity:[0,.8,0],scale:[0,1.5,0]},transition:{duration:4,delay:s,repeat:1/0,ease:"easeOut"}})}const tJe={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 Unn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:p}=s,f=zR[t],g=tJe[t]||tJe.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(JNe,{delay:0,x:"20%",angle:15,color:g.stripe}),e.jsx(JNe,{delay:2,x:"75%",angle:-12,color:g.stripe}),e.jsx(JNe,{delay:4,x:"50%",angle:5,color:g.stripe}),e.jsx(FG,{delay:0,x:"30%"}),e.jsx(FG,{delay:1.5,x:"60%"}),e.jsx(FG,{delay:3,x:"45%"}),e.jsx(FG,{delay:.7,x:"75%"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.015] mix-blend-overlay",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 512 512' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.7' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`}}),e.jsxs(Zn.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(Zn.div,{className:"relative overflow-hidden",initial:{y:50},animate:{y:0},transition:{duration:.8,delay:.3,ease:[.16,1,.3,1]},children:e.jsxs("div",{className:"px-8 py-12 text-center",children:[e.jsx(Zn.div,{className:"mx-auto mb-8 relative",initial:{scale:0},animate:{scale:1},transition:{duration:.8,delay:.5,type:"spring",stiffness:100},children:e.jsx(Zn.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${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:f.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Zn.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(Zn.span,{className:`text-6xl font-black bg-gradient-to-r ${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(Zn.h1,{className:"text-5xl font-thin text-white/90 tracking-wide",initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.8,ease:[.16,1,.3,1]},children:f.title[0]})}),f.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(Zn.h2,{className:`text-5xl font-black bg-gradient-to-r ${g.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:f.title[1]})}),e.jsxs(Zn.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[e.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:n}),r&&e.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",r]})]}),e.jsxs(Zn.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(Zn.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-r from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"right"}}),e.jsx(Zn.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(Zn.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-l from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"left"}})]}),h&&e.jsxs(Zn.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.3,duration:.6},children:[e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),p&&e.jsx(Zn.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.35,duration:.6},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zn.p,{className:"text-sm text-white/40 leading-relaxed max-w-xs mx-auto mb-10 font-light",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.4,duration:.8},children:i||f.defaultMessage}),e.jsxs(Zn.div,{className:"pt-6 border-t border-white/[0.04]",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{delay:1.6,duration:.6},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[o?e.jsx(Zn.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${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(Zn.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(Pr,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zn.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/60 hover:bg-white/[0.12] transition-colors",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Hs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(Zn.p,{className:"text-center text-[10px] text-white/10 mt-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:2.2},children:"Powered by LevelUp"})]})]})}function FNt(){const{shareToken:s}=_i(),{data:t,isLoading:n,error:r}=lt({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await q.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(N.useEffect(()=>{s&&q.rpc("log_sendable_card_view",{p_share_token:s}).then(({error:l})=>{l&&console.error("Error tracking view:",l)})},[s]),n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[e.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),e.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const a=t.home_anniversary_date?Math.floor((Date.now()-ll(t.home_anniversary_date).getTime())/(365.25*24*60*60*1e3)):null,i={cardType:t.card_type||"home_anniversary",recipientName:t.recipient_name,propertyAddress:t.property_address,anniversaryYears:a,customMessage:t.custom_message,agentName:t.agent_name,agentPhotoUrl:t.agent_photo_url,agentPhone:t.agent_phone,agentEmail:t.agent_email,agentBrokerage:t.agent_brokerage,propertyPhotoUrl:t.property_photo_url,videoUrl:t.video_url||null};switch(t.template){case"bold":return e.jsx(Fnn,{...i});case"warm":return e.jsx(Bnn,{...i});case"glass":return e.jsx($nn,{...i});case"cinematic":return e.jsx(Unn,{...i});case"elegant":default:return e.jsx(Onn,{...i})}}function qnn(){const s=fa();return lt({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function Vnn(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r}=await q.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(r){const{data:a,error:i}=await q.from("drip_settings").update(n).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await q.from("drip_settings").insert({user_id:s,is_globally_enabled:n.is_globally_enabled??!1,append_signature:n.append_signature??!0}).select().single();if(i)throw i;return a}},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-settings"]})}})}function Hnn(){const s=In(),{isGmailConnected:t,gmailEmail:n}=bh(),{data:r,isLoading:a}=qnn(),i=Vnn(),[l,o]=N.useState(!1),[c,d]=N.useState(!0),[u,h]=N.useState(!1);N.useEffect(()=>{r&&(o(r.is_globally_enabled),d(r.append_signature))},[r]);const p=async 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")}},f=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(bs,{open:u,onOpenChange:h,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Vo,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vo,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(Qn,{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(Hs,{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(ze,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(xr,{className:"h-3 w-3"}),"Active"]}):e.jsxs(B,{variant:"outline",size:"sm",className:"text-xs gap-1",onClick:()=>{h(!1),s("/mission-control/integrations")},children:[e.jsx(tr,{className:"h-3 w-3"}),"Connect"]})]}),!t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Smart Drips sends emails from your Gmail account. Connect Gmail to get started."})]}),e.jsx(cl,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-full ${l?"bg-emerald-500/10":"bg-muted"}`,children:e.jsx(w9,{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(vn,{checked:l,onCheckedChange:p,disabled:a||i.isPending})]}),e.jsx(cl,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-full ${c?"bg-primary/10":"bg-muted"}`,children:e.jsx(Nv,{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(vn,{checked:c,onCheckedChange:f,disabled:a||i.isPending})]}),c&&e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{h(!1),s("/profile")},children:[e.jsx(Nv,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function Gnn(){const s=fa();return lt({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_templates").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Wnn(){const s=fa();return lt({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Knn(){const s=fa(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("drip_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title||"",subject:n.subject||"",body:n.body||"",video_url:n.video_url||null,channel:n.channel||"email",delay_type:n.delay_type||"instant",delay_minutes:n.delay_minutes||0,is_enabled:!1,deal_type:n.deal_type||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}function Ynn(){const s=Gt();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("drip_templates").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function Znn(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("drip_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function Qnn(){const s=fa(),t=Gt();return gt({mutationFn:async({templateId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("drip_templates").select("*").eq("id",n).single();if(i)throw i;const{data:l,error:o}=await q.from("drip_templates").insert({owner_user_id:s,stage_id:r,title:a.title,subject:a.subject,body:a.body,video_url:a.video_url,channel:a.channel,delay_type:a.delay_type,delay_minutes:a.delay_minutes,is_enabled:!1,is_starter:!1,deal_type:a.deal_type}).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}const Xnn=[{key:"{{client_first_name}}",label:"Client First Name"},{key:"{{client_last_name}}",label:"Client Last Name"},{key:"{{property_address}}",label:"Property Address"},{key:"{{agent_name}}",label:"Your Name"},{key:"{{agent_phone}}",label:"Your Phone"},{key:"{{close_date}}",label:"Target Close Date"},{key:"{{stage_name}}",label:"Current Stage"},{key:"{{portal_link}}",label:"Portal Link"},{key:"{{review_link}}",label:"Review Link"}];function Jnn({open:s,onOpenChange:t,campaignId:n,campaignName:r}){const{data:a,isLoading:i}=PGs(n||void 0),l=DGs(),o=q_t(),c=async(h,p)=>{try{await l.mutateAsync({id:h,status:p}),ae.success(`Enrollment ${p}`)}catch{ae.error("Failed to update")}},d=async h=>{if(n)try{const p=await o.mutateAsync({campaignId:n,contactIds:[h]});p.enrolled>0?ae.success("Contact re-enrolled — first email queued"):p.skipped>0?ae.message("Already active in this campaign"):ae.error("Could not re-enroll")}catch{ae.error("Failed to re-enroll")}},u=h=>{const p={active:"bg-emerald-500/10 text-emerald-600 border-emerald-200",paused:"bg-amber-500/10 text-amber-600 border-amber-200",completed:"bg-blue-500/10 text-blue-600 border-blue-200",exited:"bg-muted text-muted-foreground"};return e.jsx(ze,{variant:"outline",className:`text-[10px] capitalize ${p[h]||""}`,children:h})};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{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(_n,{className:"h-4 w-4 text-primary"}),"Enrollments — ",r||"Campaign"]}),e.jsx(Qn,{className:"text-xs mt-1",children:"Manage every contact currently in this campaign. Pause to take over, or exit to remove."})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-5",children:i?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(h=>e.jsx(Ws,{className:"h-14"},h))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(_n,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No contacts enrolled yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Head to your contacts page and bulk-enroll to start nurturing."})]}):e.jsx("div",{className:"space-y-2",children:a.map(h=>{var p,f,g,b;return e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(p=h.contact)==null?void 0:p.first_name," ",(f=h.contact)==null?void 0:f.last_name]}),u(h.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((g=h.contact)==null?void 0:g.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hs,{className:"h-2.5 w-2.5"})," ",h.contact.email]}),e.jsxs("span",{children:["Step ",h.current_step]}),h.next_send_at&&h.status==="active"&&e.jsxs("span",{children:["Next: ",ks(new Date(h.next_send_at),"MMM d, h:mma")]}),h.exit_reason&&e.jsxs("span",{children:["Exit: ",h.exit_reason]})]})]}),h.status==="active"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>c(h.id,"paused"),title:"Pause",children:e.jsx(_f,{className:"h-3.5 w-3.5"})}),h.status==="paused"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>c(h.id,"active"),title:"Resume",children:e.jsx(Al,{className:"h-3.5 w-3.5"})}),(h.status==="active"||h.status==="paused")&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>c(h.id,"exited"),title:"Exit",children:e.jsx(Fn,{className:"h-3.5 w-3.5 text-destructive"})}),(h.status==="exited"||h.status==="completed")&&((b=h.contact)==null?void 0:b.id)&&e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>d(h.contact.id),disabled:o.isPending,children:[e.jsx(Fh,{className:"h-3 w-3"}),"Re-enroll"]})]},h.id)})})})})]})})}function ern(){var S;const{data:s,isLoading:t}=O1e(),{hasLeadSite:n}=Pp(),r=$_t(),a=EGs(),i=B_t(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(null),g=(s||[]).filter(A=>!A.is_starter),b=(s||[]).filter(A=>A.is_starter).filter(A=>!A.requires_lead_site||n),v=async A=>{try{await r.mutateAsync(A),ae.success("Campaign added to your library — customize and activate it!"),o(null)}catch(T){ae.error(T.message||"Failed to copy campaign")}},j=async A=>{try{await i.mutateAsync({id:A.id,is_active:!A.is_active}),ae.success(A.is_active?"Campaign paused":"Campaign activated")}catch{ae.error("Failed to update")}},_=async A=>{if(confirm("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(A),ae.success("Campaign deleted")}catch{ae.error("Failed to delete")}};return t?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(A=>e.jsx(Ws,{className:"h-44 rounded-xl"},A))}):e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/5 via-background to-background p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(vw,{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(wc,{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(cr,{className:"h-3.5 w-3.5 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Campaigns (manual / bulk)"}),e.jsx("p",{className:"text-muted-foreground",children:"You enroll contacts yourself — from this page or the Contacts list."})]})]})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-2.5 italic",children:["Tip: A campaign must be ",e.jsx("strong",{children:"Active"})," before its emails will send to enrolled contacts."]})]})]})}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(_n,{className:"h-4 w-4 text-primary"}),"My Campaigns"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Custom drip campaigns you've created or copied"})]}),e.jsxs(B,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),g.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(un,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold mb-1",children:"No custom campaigns yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Build one from scratch or clone a starter from the library below."}),e.jsxs(B,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(As,{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:g.map(A=>e.jsx(trn,{campaign:A,onPreview:()=>o(A.id),onToggleActive:()=>j(A),onDelete:()=>_(A.id),onEdit:()=>{h(A.id),d(!0)},onViewEnrollments:()=>f(A.id)},A.id))})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-amber-500"}),"Starter Library"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Premium, ready-to-go campaigns crafted for real estate. One-click copy."})]}),e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:[b.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(A=>e.jsx(srn,{campaign:A,onPreview:()=>o(A.id)},A.id))})]}),e.jsx(nrn,{campaignId:l,open:!!l,onOpenChange:A=>!A&&o(null),onClone:v,isCloning:r.isPending,onEdit:A=>{o(null),h(A),d(!0)}}),e.jsx(G_t,{open:c,onOpenChange:d,campaignId:u}),e.jsx(Jnn,{open:!!p,onOpenChange:A=>!A&&f(null),campaignId:p,campaignName:(S=g.find(A=>A.id===p))==null?void 0:S.name})]})}function trn({campaign:s,onPreview:t,onToggleActive:n,onDelete:r,onEdit:a,onViewEnrollments:i}){const o=LGs(s.id).data??0,c=!s.is_active&&o>0;return e.jsxs("div",{className:"group rounded-xl border bg-card overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`h-20 bg-gradient-to-br ${s.cover_color} relative flex items-center justify-center`,children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:s.icon}),s.is_active&&e.jsx(ze,{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(ze,{variant:"outline",className:"text-[9px] mt-2",children:F1e[s.category]}),c&&e.jsxs("button",{onClick:n,className:"mt-2 w-full flex items-start gap-1.5 p-2 rounded-md bg-amber-500/10 border border-amber-500/30 text-left hover:bg-amber-500/15 transition-colors",children:[e.jsx(Dl,{className:"h-3 w-3 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5"}),e.jsxs("span",{className:"text-[10px] leading-tight text-amber-700 dark:text-amber-300",children:[e.jsxs("strong",{children:[o," contact",o===1?"":"s"," enrolled"]})," but not sending — tap to activate"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 mt-3",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:a,children:[e.jsx(ja,{className:"h-3 w-3 mr-1"})," Edit"]}),e.jsx(B,{size:"sm",variant:s.is_active?"secondary":"default",className:"h-7 text-xs",onClick:n,children:s.is_active?"Pause":"Activate"})]}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-[10px]",children:[e.jsx("button",{onClick:i,className:"text-primary hover:underline",children:"View enrollments"}),e.jsx("button",{onClick:t,className:"text-muted-foreground hover:underline",children:"Preview"}),e.jsx("button",{onClick:r,className:"text-muted-foreground hover:text-destructive",children:"Delete"})]})]})]})}function srn({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(ze,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(un,{className:"h-2.5 w-2.5 mr-0.5"})," Starter"]})]}),e.jsxs("div",{className:"p-3.5",children:[e.jsx("h3",{className:"font-semibold text-sm",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 min-h-[2rem]",children:s.description}),e.jsx(ze,{variant:"outline",className:"text-[9px] mt-2",children:F1e[s.category]})]})]})}function nrn({campaignId:s,open:t,onOpenChange:n,onClone:r,isCloning:a,onEdit:i}){const{data:l}=O1e(),{data:o}=U_t(s||void 0),[c,d]=N.useState(new Set),u=l==null?void 0:l.find(f=>f.id===s);if(!u)return null;const h=f=>{d(g=>{const b=new Set(g);return b.has(f)?b.delete(f):b.add(f),b})},p=(f,g)=>{if(f.delay_type==="calendar_anchor"){const v=f.anchor_field==="birthday"?"birthday":"home anniversary",j=f.anchor_offset_days||0;return j===0?`On their ${v}`:j<0?`${Math.abs(j)} days before ${v}`:`${j} days after ${v}`}if(g===0&&f.delay_days===0&&f.delay_hours===0)return"Sends immediately";const b=[];return f.delay_days&&b.push(`${f.delay_days}d`),f.delay_hours&&b.push(`${f.delay_hours}h`),g===0?`After ${b.join(" ")}`:`+${b.join(" ")}`};return e.jsx(bs,{open:t,onOpenChange:n,children:e.jsxs(vs,{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(Qn,{className:"text-white/90 mt-1",children:u.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(ze,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:F1e[u.category]}),e.jsxs(ze,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:[(o==null?void 0:o.length)||0," step",(o==null?void 0:o.length)!==1?"s":""]})]})]})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"The sequence"}),u.is_starter?e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Copy to your library to edit"}):e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Tap a step to expand · Edit to customize"})]}),o==null?void 0:o.map((f,g)=>{const b=c.has(f.id);return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"shrink-0 flex flex-col items-center",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:g+1}),gh(f.id),className:"flex-1 pb-4 text-left",children:e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/20 hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 text-xs text-muted-foreground",children:[f.delay_type==="calendar_anchor"?e.jsx(yr,{className:"h-3 w-3"}):e.jsx(gr,{className:"h-3 w-3"}),e.jsx("span",{children:p(f,g)}),e.jsx("span",{children:"·"}),e.jsx(Hs,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:f.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:f.subject}),(()=>{const v=f.body||"",j=/<\/?[a-z][\s\S]*>/i.test(v),_=j?v.replace(//gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim():v;return b?j?e.jsx("div",{className:"text-xs text-foreground mt-2 prose prose-sm max-w-none [&_a]:text-primary",dangerouslySetInnerHTML:{__html:v}}):e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:v}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:_})})(),f.body&&f.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:b?"Show less":"Show full email"})]})})]},f.id)})]})}),e.jsxs(Xn,{className:"border-t p-4 shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!u.is_starter&&i&&e.jsxs(B,{variant:"secondary",onClick:()=>i(u.id),children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-1.5"})," Edit Campaign"]}),u.is_starter&&e.jsxs(B,{onClick:()=>r(u.id),disabled:a,children:[a?e.jsx(ss,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(ta,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}const dpe=[{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 rrn(){const s=fa();return lt({queryKey:["drip-auto-rules",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.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 arn(){const s=fa(),t=Gt();return gt({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 q.from("drip_auto_enroll_rules").upsert(r).select().single();if(i)throw i;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-auto-rules"]})}})}function irn(){const s=Gt();return gt({mutationFn:async({id:t,is_active:n})=>{const{error:r}=await q.from("drip_auto_enroll_rules").update({is_active:n}).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function orn(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("drip_auto_enroll_rules").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function lrn(s=25){const t=fa();return lt({queryKey:["drip-auto-log",t,s],queryFn:async()=>{if(!t)return[];const{data:n,error:r}=await q.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 crn(){const s=fa();return lt({queryKey:["life-event-coverage",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.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 drn(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.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 urn={birthday:hu,home_anniversary:mb,spouse_birthday:Bi,wedding_anniversary:yi};function hrn(){var A;const{data:s,isLoading:t}=rrn(),{data:n}=O1e(),{data:r}=crn(),{data:a}=lrn(10),i=arn(),l=irn(),o=orn(),c=drn(),d=$_t(),[u,h]=N.useState(null),p=N.useMemo(()=>(n||[]).filter(T=>!T.is_starter),[n]),f={birthday:"Birthday",home_anniversary:"Home Anniversary",spouse_birthday:"Spouse Birthday",wedding_anniversary:"Wedding Anniversary"},g=N.useMemo(()=>{if(!(u!=null&&u.trigger_type))return null;const T=f[u.trigger_type];return!T||p.some(L=>String(L.name||"").toLowerCase().includes(T.toLowerCase()))?null:(n||[]).find(L=>L.is_starter&&String(L.name||"").toLowerCase()===T.toLowerCase())??null},[n,p,u==null?void 0:u.trigger_type]),b=async()=>{if(g)try{const T=await d.mutateAsync(g.id);h(D=>({...D,campaign_id:T.id})),ae.success(`“${g.name}” template added to your campaigns`)}catch(T){ae.error((T==null?void 0:T.message)||"Could not copy the template")}},v=T=>(s||[]).find(D=>D.trigger_type===T),j=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(T){ae.error((T==null?void 0:T.message)||"Could not save rule")}},_=async()=>{try{const T=await c.mutateAsync(void 0);ae.success(T!=null&&T.enrolled?`Enrolled ${T.enrolled} contact${T.enrolled===1?"":"s"} with upcoming life events`:"All caught up — nobody new to enroll right now")}catch(T){ae.error((T==null?void 0:T.message)||"Autopilot run failed")}},S=(s||[]).filter(T=>T.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(un,{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(B,{variant:"outline",onClick:_,disabled:c.isPending||S===0,className:"gap-2 shrink-0",children:[c.isPending?e.jsx(ss,{className:"h-4 w-4 animate-spin"}):e.jsx(Ai,{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:dpe.map(T=>{const D=r.counts[T.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:[T.emoji," ",T.label]}),e.jsx("p",{className:"text-lg font-bold leading-tight",children:(D==null?void 0:D.total)??0}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[(D==null?void 0:D.upcoming30)??0," in next 30 days"]})]},T.value)})})]}),t?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(ss,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:dpe.map(T=>{var F;const D=v(T.value),L=urn[T.value]||hu,M=r==null?void 0:r.counts[T.value];return e.jsxs("div",{className:Et("rounded-xl border bg-card p-4 transition-colors",(D==null?void 0:D.is_active)&&"border-primary/40 bg-primary/[0.03]"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Et("h-10 w-10 rounded-lg flex items-center justify-center shrink-0",D!=null&&D.is_active?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(L,{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:T.label}),(D==null?void 0:D.is_active)&&e.jsx(ze,{className:"text-[10px] bg-primary/10 text-primary hover:bg-primary/10",children:"On"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D?`${((F=D.campaign)==null?void 0:F.name)??"Campaign"} · starts ${D.lead_days} days before`:T.description}),D&&D.total_enrolled>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:[D.total_enrolled," contact",D.total_enrolled===1?"":"s"," enrolled so far"]}),!D&&((M==null?void 0:M.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."})]}),D?e.jsx(vn,{checked:D.is_active,onCheckedChange:z=>l.mutate({id:D.id,is_active:z})}):null]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",variant:D?"outline":"default",className:"flex-1 gap-1.5",onClick:()=>h(D??{trigger_type:T.value,lead_days:T.value==="birthday"?7:14,require_email:!0,is_active:!0,filter_tags:[],filter_relationship_types:[]}),children:[D?e.jsx(ph,{className:"h-3.5 w-3.5"}):e.jsx(As,{className:"h-3.5 w-3.5"}),D?"Edit rule":"Turn on autopilot"]}),D&&e.jsx(B,{size:"sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive",onClick:()=>o.mutate(D.id),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]},T.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(T=>{var D,L;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[e.jsx(Lr,{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:[(D=T.contact)==null?void 0:D.first_name," ",(L=T.contact)==null?void 0:L.last_name]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[String(T.trigger_type).replace(/_/g," ")," · ",T.note]})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground shrink-0",children:new Date(T.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})})]},T.id)})})]}),e.jsx(bs,{open:!!u,onOpenChange:T=>!T&&h(null),children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[(A=dpe.find(T=>T.value===(u==null?void 0:u.trigger_type)))==null?void 0:A.label," autopilot"]}),e.jsx(Qn,{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(se,{children:"Campaign to enroll into"}),e.jsxs(us,{value:(u==null?void 0:u.campaign_id)??"",onValueChange:T=>h(D=>({...D,campaign_id:T})),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select one of your campaigns"})}),e.jsx(ds,{children:p.map(T=>e.jsx(Ze,{value:T.id,children:T.name},T.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(un,{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(B,{size:"sm",variant:"outline",className:"mt-2 gap-1.5",disabled:d.isPending,onClick:b,children:[d.isPending?e.jsx(ss,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(As,{className:"h-3.5 w-3.5"}),"Use this template"]})]})]})}),p.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(se,{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($m,{min:0,max:45,step:1,value:[(u==null?void 0:u.lead_days)??14],onValueChange:([T])=>h(D=>({...D,lead_days:T}))}),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(se,{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(vn,{checked:(u==null?void 0:u.require_email)??!0,onCheckedChange:T=>h(D=>({...D,require_email:T}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm",children:"Autopilot active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Runs every morning automatically."})]}),e.jsx(vn,{checked:(u==null?void 0:u.is_active)??!0,onCheckedChange:T=>h(D=>({...D,is_active:T}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>h(null),children:"Cancel"}),e.jsxs(B,{onClick:j,disabled:i.isPending||!(u!=null&&u.campaign_id),children:[i.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save rule"]})]})]})})]})}function mrn(){const s=fa(),t=In(),{isGmailConnected:n,gmailEmail:r,isLoading:a}=bh(),{data:i,isLoading:l}=Gnn(),{data:o,isLoading:c}=Wnn(),d=Knn(),u=Ynn(),h=Znn(),p=Qnn(),[f,g]=N.useState(null),[b,v]=N.useState(null),j=(i==null?void 0:i.filter(F=>!F.is_starter&&F.owner_user_id===s))||[],_=(i==null?void 0:i.filter(F=>F.is_starter))||[],S=F=>j.filter(z=>z.stage_id===F),A=async F=>{try{await u.mutateAsync({id:F.id,is_enabled:!F.is_enabled}),ae.success(F.is_enabled?"Drip disabled":"Drip enabled")}catch{ae.error("Failed to update")}},T=async F=>{try{const z=o==null?void 0:o.find(V=>V.id===F);await d.mutateAsync({stage_id:F,title:`${(z==null?void 0:z.name)||"Stage"} follow-up`,subject:"",body:"",channel:"email",delay_type:"instant",delay_minutes:0}),g(F),ae.success("Drip template created")}catch{ae.error("Failed to create template")}},D=async F=>{try{await h.mutateAsync(F),ae.success("Template deleted")}catch{ae.error("Failed to delete")}},L=async F=>{if(!o||o.length===0){ae.error("No pipeline stages found");return}const z=o[0].id;try{await p.mutateAsync({templateId:F,stageId:z}),ae.success("Template copied to your drips!")}catch{ae.error("Failed to copy template")}},M=l||c;return e.jsx(Cs,{children:e.jsxs("div",{className:"container max-w-4xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ph,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(ze,{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(Hnn,{})]}),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(vw,{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(Hs,{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(vw,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsx("p",{className:"font-medium text-foreground mb-0.5",children:"Drips will send from our shared sender"}),e.jsxs("p",{className:"text-muted-foreground mb-2",children:["You haven't connected Gmail, so drips will send from ",e.jsx("strong",{children:"send.relevelup.com"})," with your name on the From line and your email as Reply-To. Connect Gmail to send directly from your own inbox for better deliverability and a more personal touch."]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>t("/mission-control/integrations"),children:[e.jsx(Hs,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs($r,{defaultValue:"my-drips",children:[e.jsxs(Ur,{className:"grid grid-cols-4 w-full max-w-2xl mb-6",children:[e.jsx(Zt,{value:"my-drips",children:"Stage Drips"}),e.jsxs(Zt,{value:"campaigns",children:["Campaigns",e.jsx(ze,{variant:"outline",className:"ml-1.5 text-[9px] bg-amber-500/10 text-amber-600 border-amber-200 px-1 py-0",children:"New"})]}),e.jsxs(Zt,{value:"autopilot",children:["Life Events",e.jsx(ze,{variant:"outline",className:"ml-1.5 text-[9px] bg-primary/10 text-primary border-primary/20 px-1 py-0",children:"Auto"})]}),e.jsxs(Zt,{value:"starters",children:["Stage Starters",_.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:_.length})]})]}),e.jsx(ls,{value:"campaigns",children:e.jsx(ern,{})}),e.jsx(ls,{value:"autopilot",children:e.jsx(hrn,{})}),e.jsx(ls,{value:"my-drips",children:M?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(F=>e.jsx(Ws,{className:"h-16 w-full rounded-xl"},F))}):!o||o.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(ph,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create pipeline stages first to set up drip automations."})]}):e.jsxs("div",{className:"space-y-2",children:[o.filter(F=>!F.is_won_stage&&!F.is_lost_stage).map(F=>{const z=S(F.id),V=f===F.id,W=z.some(K=>K.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>g(V?null:F.id),className:"w-full flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors text-left",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:F.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:F.name}),z.length>0&&e.jsxs(ze,{variant:"outline",className:`text-[10px] ${W?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[z.length," drip",z.length!==1?"s":"",W&&" · Active"]}),V?e.jsx(io,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"})]}),V&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:z.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>T(F.id),disabled:d.isPending,children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[z.map(K=>e.jsx(sJe,{template:K,isEditing:b===K.id,onToggleEdit:()=>v(b===K.id?null:K.id),onToggleEnabled:()=>A(K),onUpdate:Y=>u.mutateAsync({id:K.id,...Y}),onDelete:()=>D(K.id),userId:s||""},K.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>T(F.id),children:[e.jsx(As,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},F.id)}),o.filter(F=>F.is_won_stage||F.is_lost_stage).length>0&&e.jsxs("div",{className:"pt-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground font-medium mb-2 px-1",children:"Closing Stages"}),o.filter(F=>F.is_won_stage||F.is_lost_stage).map(F=>{const z=S(F.id),V=f===F.id,W=z.some(K=>K.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>g(V?null:F.id),className:"w-full flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors text-left",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:F.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:F.name}),z.length>0&&e.jsxs(ze,{variant:"outline",className:`text-[10px] ${W?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[z.length," drip",z.length!==1?"s":"",W&&" · Active"]}),V?e.jsx(io,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"})]}),V&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:z.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>T(F.id),disabled:d.isPending,children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[z.map(K=>e.jsx(sJe,{template:K,isEditing:b===K.id,onToggleEdit:()=>v(b===K.id?null:K.id),onToggleEnabled:()=>A(K),onUpdate:Y=>u.mutateAsync({id:K.id,...Y}),onDelete:()=>D(K.id),userId:s||""},K.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>T(F.id),children:[e.jsx(As,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},F.id)})]})]})}),e.jsx(ls,{value:"starters",children:_.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(un,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Starter Templates Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"Admin-created starter templates will appear here. You'll be able to copy them into your own drips."})]}):e.jsx("div",{className:"space-y-3",children:_.map(F=>e.jsx(prn,{template:F,onCopy:()=>L(F.id),isCopying:p.isPending},F.id))})})]})]})})}function sJe({template:s,isEditing:t,onToggleEdit:n,onToggleEnabled:r,onUpdate:a,onDelete:i,userId:l}){const[o,c]=N.useState(s.title),[d,u]=N.useState(s.subject),[h,p]=N.useState(s.body),[f,g]=N.useState(s.video_url||""),[b,v]=N.useState(s.channel),[j,_]=N.useState(s.delay_type),[S,A]=N.useState(s.delay_minutes),[T,D]=N.useState(!1),L=async()=>{D(!0);try{await a({title:o,subject:d,body:h,video_url:f||null,channel:b,delay_type:j,delay_minutes:S}),ae.success("Drip saved"),n()}catch{ae.error("Failed to save")}finally{D(!1)}},M=F=>{p(z=>z+F)};return e.jsxs("div",{className:"border rounded-lg bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",role:"button",onClick:n,children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.title||"Untitled drip"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.channel==="sms"?e.jsx(Ci,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Hs,{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(vr,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(vn,{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(se,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(ge,{value:o,onChange:F=>c(F.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Buyer intro video"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs font-medium",children:"Channel"}),e.jsx("div",{className:"flex gap-1 mt-1",children:["email","sms"].map(F=>e.jsxs("button",{onClick:()=>v(F),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${b===F?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[F==="sms"?e.jsx(Ci,{className:"h-3 w-3"}):e.jsx(Hs,{className:"h-3 w-3"}),F==="sms"?"SMS":"Email"]},F))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{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 ${j==="instant"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:"Instant"}),e.jsxs("button",{onClick:()=>_("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${j==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(gr,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),j==="scheduled"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ge,{type:"number",min:1,value:S>=60?Math.round(S/60):S,onChange:F=>{const z=parseInt(F.target.value)||0;A(S>=60?z*60:z)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:S<60?S:30},{label:"Hours",mins:S>=60?S:60},{label:"Days",mins:S>=1440?S:1440}].map(F=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${F.label==="Minutes"&&S<60||F.label==="Hours"&&S>=60&&S<1440||F.label==="Days"&&S>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{F.label==="Minutes"?A(30):F.label==="Hours"?A(60):A(1440)},children:F.label},F.label))})]})]}),b==="email"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(ge,{value:d,onChange:F=>u(F.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Next steps for your home purchase"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(se,{className:"text-xs font-medium",children:b==="sms"?"Message":"Email Body"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Insert:"}),e.jsxs("select",{className:"text-[10px] border rounded px-1 py-0.5 bg-background text-muted-foreground",value:"",onChange:F=>{F.target.value&&M(F.target.value),F.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),Xnn.map(F=>e.jsx("option",{value:F.key,children:F.label},F.key))]})]})]}),e.jsx("textarea",{value:h,onChange:F=>p(F.target.value),placeholder:b==="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(se,{className:"text-xs font-medium",children:"Attached Video"}),f?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:[e.jsx(vr,{className:"h-3 w-3 inline mr-1 text-primary"}),f.length>50?f.slice(0,50)+"...":f]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>g(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(k8e,{onVideoReady:F=>g(F)}),e.jsx(o6,{userId:l,onSelect:F=>g(F),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const F=prompt("Paste a YouTube or Loom URL:");F&&g(F)},children:[e.jsx(tl,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(bn,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",className:"text-xs",onClick:n,children:"Cancel"}),e.jsx(B,{size:"sm",className:"text-xs",onClick:L,disabled:T,children:T?"Saving...":"Save Drip"})]})]})]})]})}function prn({template:s,onCopy:t,isCopying:n}){const[r,a]=N.useState(!1),i=s.body.replace(/<[^>]+>/g,""),l=s.deal_type==="buyer"?"Buyer":s.deal_type==="seller"?"Seller":null,o=s.delay_type==="instant"?"Sends instantly":s.delay_minutes>=1440?`Sends after ${Math.round(s.delay_minutes/1440)} day${Math.round(s.delay_minutes/1440)!==1?"s":""}`:s.delay_minutes>=60?`Sends after ${Math.round(s.delay_minutes/60)} hour${Math.round(s.delay_minutes/60)!==1?"s":""}`:`Sends after ${s.delay_minutes} min`;return e.jsxs("div",{className:"border rounded-xl overflow-hidden transition-all hover:shadow-sm",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-start gap-3 p-4 text-left hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:s.subject}),!r&&e.jsx("p",{className:"text-xs text-muted-foreground/70 line-clamp-1 mt-1",children:i})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",children:[l&&e.jsx(ze,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(Ci,{className:"h-3 w-3"}):e.jsx(Hs,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),r?e.jsx(io,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(ga,{className:"h-4 w-4 text-muted-foreground ml-1"})]})]}),r&&e.jsxs("div",{className:"border-t bg-muted/10 p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Subject Line"}),e.jsx("p",{className:"text-sm font-medium",children:s.subject})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Email Body"}),e.jsx("div",{className:"text-sm text-foreground/80 bg-background rounded-lg border p-4 prose prose-sm max-w-none [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_li]:my-0.5 [&_p]:my-2 [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:s.body}})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs(B,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:n,children:[e.jsx(ta,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const zNt=()=>{const s=Jl();return N.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",s.pathname)},[s.pathname]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),e.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),e.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function frn(){return N.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(sfe,{children:[e.jsx(is,{path:"/c/:shareToken",element:e.jsx(FNt,{})}),e.jsx(is,{path:"*",element:e.jsx(zNt,{})})]})}const eke={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function BNt({slugOverride:s}){const t=_i(),n=s||t.slug,[r,a]=N.useState("types"),[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(new Date),[f,g]=N.useState({name:"",email:"",phone:"",message:""}),[b,v]=N.useState(!1),{data:j,isLoading:_}=lt({queryKey:["public-booking-settings",n],queryFn:async()=>{const{data:Y,error:ee}=await q.from("agent_booking_settings").select("*").eq("slug",n).eq("is_active",!0).single();if(ee)throw ee;return Y},enabled:!!n}),{data:S}=lt({queryKey:["public-booking-profile",j==null?void 0:j.user_id],queryFn:async()=>{const{data:Y,error:ee}=await q.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",j.user_id).single();if(ee)throw ee;return Y},enabled:!!(j!=null&&j.user_id)}),{data:A=[]}=lt({queryKey:["public-booking-types",j==null?void 0:j.user_id],queryFn:async()=>{const{data:Y,error:ee}=await q.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",j.user_id).eq("is_active",!0).order("sort_order");if(ee)throw ee;return Y},enabled:!!(j!=null&&j.user_id)}),{data:T=[]}=lt({queryKey:["public-availability",j==null?void 0:j.user_id],queryFn:async()=>{const{data:Y,error:ee}=await q.from("agent_availability_slots").select("day_of_week, start_time, end_time").eq("user_id",j.user_id).eq("is_active",!0);if(ee)throw ee;return Y},enabled:!!(j!=null&&j.user_id)}),{data:D=[]}=lt({queryKey:["public-blocked-dates",j==null?void 0:j.user_id],queryFn:async()=>{const{data:Y,error:ee}=await q.from("agent_blocked_dates").select("blocked_date").eq("user_id",j.user_id);if(ee)throw ee;return Y.map(ne=>ne.blocked_date)},enabled:!!(j!=null&&j.user_id)}),{data:L=[]}=lt({queryKey:["public-existing-bookings",j==null?void 0:j.user_id,o],queryFn:async()=>{if(!o)return[];const Y=ks(o,"yyyy-MM-dd"),{data:ee,error:ne}=await q.from("bookings").select("start_time, end_time").eq("agent_user_id",j.user_id).eq("booking_date",Y).eq("status","confirmed");if(ne)throw ne;return ee},enabled:!!(j!=null&&j.user_id)&&!!o}),M=N.useMemo(()=>[...new Set(T.map(Y=>Y.day_of_week))],[T]),F=Y=>{const ee=Sf(new Date),ne=Ul(ee,(j==null?void 0:j.max_advance_days)||30),oe=Ul(ee,0);return jb(Y,oe)||Uv(Y,ne)||D.includes(ks(Y,"yyyy-MM-dd"))?!1:M.includes(Y.getDay())},z=N.useMemo(()=>{if(!o||!i||!j)return[];const Y=T.filter(de=>de.day_of_week===o.getDay()),ee=i.duration_minutes,ne=j.buffer_minutes||0,oe=[],pe=new Date,ce=(j.min_notice_hours||2)*60*60*1e3;for(const de of Y){const[ie,ye]=de.start_time.split(":").map(Number),[_e,Me]=de.end_time.split(":").map(Number);let Te=Q9(Z9(o,ie),ye);const Ce=Q9(Z9(o,_e),Me);for(;CP(Te,ee)<=Ce;){const Ee=ks(Te,"HH:mm"),De=ks(CP(Te,ee),"HH:mm");Te.getTime()-pe.getTime()>=ce&&(L.some(Fe=>{const qe=Fe.start_time.slice(0,5),ve=Fe.end_time.slice(0,5);return Eeqe})||oe.push(Ee)),Te=CP(Te,ee+ne)}}return oe},[o,i,T,j,L]),V=N.useMemo(()=>{const Y=h.getFullYear(),ee=h.getMonth(),ne=new Date(Y,ee,1),oe=new Date(Y,ee+1,0),pe=ne.getDay(),ce=[];for(let de=0;de{if(!(!i||!o||!d||!f.name||!j)){v(!0);try{const Y=ks(CP(Q9(Z9(new Date,parseInt(d.split(":")[0])),parseInt(d.split(":")[1])),i.duration_minutes),"HH:mm"),{error:ee}=await q.from("bookings").insert({agent_user_id:j.user_id,booking_type_id:i.id,booking_date:ks(o,"yyyy-MM-dd"),start_time:d,end_time:Y,guest_name:f.name,guest_email:f.email||null,guest_phone:f.phone||null,guest_message:f.message||null});if(ee)throw ee;q.functions.invoke("booking-notify",{body:{agentUserId:j.user_id,guestName:f.name,guestEmail:f.email||null,guestPhone:f.phone||null,guestMessage:f.message||null,bookingTypeName:i.name,bookingDate:ks(o,"yyyy-MM-dd"),startTime:d,endTime:Y,durationMinutes:i.duration_minutes,meetingLink:j.meeting_link||null}}).catch(ne=>console.error("Booking notify error:",ne)),a("confirmed")}catch(Y){ae.error("Failed to book: "+Y.message)}finally{v(!1)}}},K=Y=>{const[ee,ne]=Y.split(":").map(Number),oe=ee>=12?"PM":"AM";return`${ee%12||12}:${ne.toString().padStart(2,"0")} ${oe}`};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("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[#406E71] border-t-transparent"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading booking page..."})]})}):j?e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8]",children:[e.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#406E71] via-[#5a9a9d] to-[#2a4c64]"}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 sm:py-10",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden mb-6",children:[e.jsx("div",{className:"relative bg-gradient-to-r from-[#406E71] to-[#2a4c64] px-6 pt-6 pb-12",children:e.jsxs("div",{className:"absolute inset-0 opacity-10",children:[e.jsx("div",{className:"absolute top-2 right-8 w-20 h-20 rounded-full border-2 border-white/30"}),e.jsx("div",{className:"absolute bottom-4 left-12 w-10 h-10 rounded-full border border-white/20"})]})}),e.jsx("div",{className:"relative -mt-10 px-6",children:e.jsxs("div",{className:"flex items-end gap-4",children:[S!=null&&S.avatar_url?e.jsx("img",{src:S.avatar_url,alt:(S==null?void 0:S.name)||"Agent",className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl object-cover border-4 border-white shadow-md"}):e.jsx("div",{className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] border-4 border-white shadow-md flex items-center justify-center",children:e.jsx(Xi,{className:"h-10 w-10 text-white"})}),e.jsxs("div",{className:"pb-1.5",children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-800 leading-tight",children:(S==null?void 0:S.name)||"Agent"}),(S==null?void 0:S.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:S.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(S==null?void 0:S.phone)&&e.jsxs("a",{href:`tel:${S.phone}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#406E71]/8 hover:bg-[#406E71]/15 text-[#406E71] text-xs font-medium transition-colors",children:[e.jsx(Pr,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:S.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(S==null?void 0:S.email)&&e.jsxs("a",{href:`mailto:${S.email}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#2a4c64]/8 hover:bg-[#2a4c64]/15 text-[#2a4c64] text-xs font-medium transition-colors",children:[e.jsx(Hs,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:S.email}),e.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),e.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[r==="types"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),e.jsx("div",{className:"space-y-2.5",children:A.map(Y=>e.jsx("button",{onClick:()=>{l(Y),a("date")},className:"w-full text-left group",children:e.jsx("div",{className:"relative rounded-xl border border-slate-150 p-4 transition-all duration-200 hover:shadow-md hover:border-[#406E71]/30 hover:-translate-y-0.5 active:translate-y-0",style:{borderLeftWidth:"3px",borderLeftColor:Y.color},children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("span",{className:"text-2xl shrink-0 mt-0.5",children:eke[Y.icon]||"📅"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-semibold text-sm text-slate-800 group-hover:text-[#406E71] transition-colors",children:Y.name}),Y.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:Y.description})]})]}),e.jsxs("div",{className:"shrink-0 flex items-center gap-1 px-2.5 py-1 rounded-full bg-slate-100 text-slate-600 text-xs font-medium",children:[e.jsx(gr,{className:"h-3 w-3"}),Y.duration_minutes,"m"]})]})})},Y.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(Wr,{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:eke[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(gr,{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:ks(h,"MMMM yyyy")}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>p(new Date(h.getFullYear(),h.getMonth()-1)),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>p(new Date(h.getFullYear(),h.getMonth()+1)),children:e.jsx(ga,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-7 gap-0.5 text-center",children:[["Su","Mo","Tu","We","Th","Fr","Sa"].map(Y=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:Y},Y)),V.map((Y,ee)=>{if(!Y)return e.jsx("div",{},`pad-${ee}`);const ne=F(Y),oe=o&&Rl(Y,o),pe=Rl(Y,new Date);return e.jsx("button",{disabled:!ne,onClick:()=>{c(Y),u(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${oe?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":ne?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${pe&&!oe?"ring-1 ring-[#406E71]/40":""}`,children:Y.getDate()},Y.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tl,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:ks(o,"EEEE, MMMM d")})]}),z.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(gr,{className:"h-8 w-8 text-slate-300 mx-auto"}),e.jsx("p",{className:"text-sm text-slate-400",children:"No available times on this day"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Try selecting a different date"})]}):e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-52 overflow-y-auto pr-1 custom-scrollbar",children:z.map(Y=>{const ee=d===Y;return e.jsx("button",{onClick:()=>u(Y),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${ee?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-[1.02]":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10 hover:text-[#406E71] border border-slate-150"}`,children:K(Y)},Y)})}),d&&e.jsx(B,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg",onClick:()=>a("form"),children:"Continue to Details"})]})]}),r==="form"&&i&&o&&d&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>a("date"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(Wr,{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:eke[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(Tl,{className:"h-3.5 w-3.5 text-[#406E71]"}),ks(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3.5 w-3.5 text-[#406E71]"}),K(d)," · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(ge,{value:f.name,onChange:Y=>g({...f,name:Y.target.value}),placeholder:"Jane Smith",className:"h-11 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(Hs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ge,{type:"email",value:f.email,onChange:Y=>g({...f,email:Y.target.value}),placeholder:"jane@email.com",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ge,{type:"tel",value:f.phone,onChange:Y=>g({...f,phone:Y.target.value}),placeholder:"(555) 123-4567",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(Ts,{value:f.message,onChange:Y=>g({...f,message:Y.target.value}),placeholder:"Anything you'd like the agent to know ahead of time?",rows:3,className:"rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20 resize-none"})]})]}),e.jsx(B,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg disabled:opacity-60",onClick:W,disabled:!f.name||b,children:b?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(xr,{className:"h-10 w-10 text-white"})})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-slate-800",children:"You're booked!"}),e.jsxs("p",{className:"text-slate-500 mt-1.5",children:[i==null?void 0:i.name," with ",(S==null?void 0:S.name)||"your agent"]})]}),e.jsx("div",{className:"inline-flex items-center gap-3 px-5 py-3 rounded-xl bg-slate-50 border border-slate-100",children:e.jsxs("div",{className:"text-left text-sm",children:[e.jsx("p",{className:"font-semibold text-slate-800",children:o&&ks(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[d&&K(d)," · ",i==null?void 0:i.duration_minutes," min"]})]})}),e.jsx("p",{className:"text-sm text-slate-400 max-w-xs mx-auto",children:"A confirmation with meeting details will be sent to you shortly."}),((S==null?void 0:S.phone)||(S==null?void 0:S.email))&&e.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wider font-semibold",children:"Contact"}),e.jsxs("div",{className:"flex gap-3",children:[(S==null?void 0:S.phone)&&e.jsxs("a",{href:`tel:${S.phone}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#406E71]/10 text-[#406E71] text-xs font-medium hover:bg-[#406E71]/20 transition-colors",children:[e.jsx(Pr,{className:"h-3.5 w-3.5"})," Call"]}),(S==null?void 0:S.email)&&e.jsxs("a",{href:`mailto:${S.email}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#2a4c64]/10 text-[#2a4c64] text-xs font-medium hover:bg-[#2a4c64]/20 transition-colors",children:[e.jsx(Hs,{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(Tl,{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 xrn(){const t=Jl().pathname.slice(1).split("/")[0];return N.useEffect(()=>{document.body.classList.add("booking-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("booking-page"),r.forEach(clearTimeout)}},[]),t?e.jsx(BNt,{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 grn(){const t=Jl().pathname.slice(1);return N.useEffect(()=>{document.body.classList.add("connect-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("connect-page"),r.forEach(clearTimeout)}},[]),!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),e.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):e.jsx(spt,{slugOverride:t})}function yrn(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 vrn={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function brn({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=vrn[s.heading_font||"playfair"],u=s.eyebrow||null,h=s.headline_accent||null,p=Array.isArray(s.trust_pills)?s.trust_pills:[],f=t.slice(0,5);return e.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:c},children:[s.hero_image_url?e.jsx("img",{src:s.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${c}, #000)`}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),e.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[e.jsxs("div",{className:"lg:col-span-3 text-white",children:[s.logo_url&&e.jsx(_rn,{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(Pr,{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(Hs,{className:"h-3 w-3"})," ",s.agent_email]})]})]})]})]}),e.jsx("div",{className:"lg:col-span-2",children:e.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[e.jsxs("form",{className:"space-y-3",onSubmit:a,children:[f.map(g=>e.jsxs("div",{children:[e.jsxs(se,{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"})]}),p.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:p.map((g,b)=>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]},b))})]})})]})})]})}function _rn({src:s}){const[t,n]=N.useState(null),r=e.jsx("img",{src:s,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:a=>n(yrn(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 wrn(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 jrn(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 Nrn(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 krn({startsAt:s,locationName:t,address:n,title:r,accent:a}){const[i,l]=N.useState(Date.now());N.useEffect(()=>{const f=setInterval(()=>l(Date.now()),1e3);return()=>clearInterval(f)},[]);const o=new Date(s).getTime();if(!Number.isFinite(o))return null;const c=wrn(o-i),d=o-i<=0,u=new Date(s).toLocaleString("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"}),h=[t,n].filter(Boolean).join(" · "),p=n?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(n)}`:null;return e.jsx("section",{className:"max-w-5xl mx-auto px-4 py-10",children:e.jsx("div",{className:"rounded-2xl border bg-white/80 backdrop-blur p-6 md:p-8 shadow-sm",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider font-medium",style:{color:a},children:d?"Just happened":"Event starts in"}),d?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Missed this one? Submit the form and we'll let you know about the next one."}):e.jsx("div",{className:"flex items-baseline gap-3",children:[{v:c.d,l:"days"},{v:c.h,l:"hrs"},{v:c.m,l:"min"},{v:c.s,l:"sec"}].map(f=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl md:text-4xl font-bold tabular-nums",style:{color:a},children:String(f.v).padStart(2,"0")}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:f.l})]},f.l))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 pt-2 text-sm text-neutral-700",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(gr,{className:"h-3.5 w-3.5"})," ",u]}),h&&e.jsxs("a",{href:p||"#",target:p?"_blank":void 0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 hover:underline",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"})," ",h]})]})]}),!d&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:jrn(r,s,h||null),target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[e.jsx(yr,{className:"h-4 w-4"})," Add to Google"]}),e.jsxs("a",{href:Nrn(r,s,h||null),download:`${r.replace(/\W+/g,"-").toLowerCase()}.ics`,className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[e.jsx(yr,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function Srn(){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 $Nt({slugOverride:s}){var V;const{slug:t}=_i(),n=s||t,[r,a]=N.useState(!1),[i,l]=N.useState({}),[o,c]=N.useState(0),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f]=N.useState(()=>Date.now()),g=N.useState(()=>Srn())[0],{data:b,isLoading:v}=lt({queryKey:["public-landing-page",n],queryFn:async()=>{const{data:W,error:K}=await q.from("landing_pages").select("*").eq("slug",n).eq("is_published",!0).single();if(K)throw K;return W},enabled:!!n}),{data:j=[]}=lt({queryKey:["public-landing-page-fields",b==null?void 0:b.id],queryFn:async()=>{const{data:W,error:K}=await q.from("landing_page_fields").select("*").eq("page_id",b.id).order("sort_order");if(K)throw K;return W},enabled:!!(b!=null&&b.id)});N.useEffect(()=>{b!=null&&b.id&&q.from("landing_pages").update({view_count:(b.view_count||0)+1}).eq("id",b.id).then(()=>{})},[b==null?void 0:b.id]),N.useEffect(()=>{if(!(b!=null&&b.id))return;const W=new URLSearchParams(window.location.search);q.functions.invoke("landing-page-track",{body:{page_id:b.id,event_type:"view",session_id:g,utm_source:W.get("utm_source"),utm_medium:W.get("utm_medium"),utm_campaign:W.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[b==null?void 0:b.id,g]);const _=gt({mutationFn:async()=>{const W=j.find(ie=>ie.field_type==="text"&&ie.label.toLowerCase().includes("name")),K=j.find(ie=>ie.field_type==="email"),Y=j.find(ie=>ie.field_type==="phone"),ee=W?String(i[W.label]||""):null,ne=K?String(i[K.label]||""):null,oe=Y?String(i[Y.label]||""):null,pe=new URLSearchParams(window.location.search),{data:ce,error:de}=await q.functions.invoke("landing-page-submit",{body:{page_id:b.id,answers:JSON.parse(JSON.stringify(i)),contact_name:ee,contact_email:ne,contact_phone:oe,session_id:g,honeypot:h,rendered_at:f,utm_source:pe.get("utm_source"),utm_medium:pe.get("utm_medium"),utm_campaign:pe.get("utm_campaign"),referrer:document.referrer||null}});if(de)throw de;return ce},onSuccess:W=>{a(!0),W!=null&&W.redirect_url&&setTimeout(()=>{window.location.href=W.redirect_url},1500)}}),S=W=>{W.preventDefault(),!(j.filter(Y=>Y.is_required&&!i[Y.label]).length>0)&&_.mutate()};if(v)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gray-400 border-t-transparent"})});if(!b)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-700",children:"Page Not Found"}),e.jsx("p",{className:"text-gray-500 mt-2",children:"This page doesn't exist or is no longer available."})]})});const A=b.primary_color||"#406E71",T=b.accent_color||"#2a4c64",D=b,L=b.page_type==="lead_magnet",M=b.page_type==="just_listed"||b.page_type==="just_sold",F=Array.isArray(D.property_photos)?D.property_photos:[],z=D.lead_magnet_file_url||D.lead_magnet_external_url;if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${A}, ${T})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(xr,{className:"h-16 w-16 mx-auto mb-4",style:{color:A}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:L?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:b.success_message}),L&&z&&e.jsxs("a",{href:z,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:A},children:[e.jsx(Da,{className:"h-5 w-5"}),"Download ",D.lead_magnet_file_name||"Your File"]}),b.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:b.agent_name}),b.agent_phone&&e.jsxs("a",{href:`tel:${b.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:A},children:[e.jsx(Pr,{className:"h-3 w-3"})," ",b.agent_phone]}),b.agent_email&&e.jsxs("a",{href:`mailto:${b.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:A},children:[e.jsx(Hs,{className:"h-3 w-3"})," ",b.agent_email]})]})]})});if(M){const W=K=>{const Y=parseFloat(K.replace(/[^0-9.]/g,""));return isNaN(Y)?K:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Y)};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[d&&F.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>u(!1),children:[e.jsx("button",{onClick:()=>u(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:e.jsx(Fn,{className:"h-8 w-8"})}),e.jsx("button",{onClick:K=>{K.stopPropagation(),c(Y=>Y===0?F.length-1:Y-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(fl,{className:"h-6 w-6"})}),e.jsx("img",{src:F[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:K=>K.stopPropagation()}),e.jsx("button",{onClick:K=>{K.stopPropagation(),c(Y=>Y===F.length-1?0:Y+1)},className:"absolute right-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:e.jsx(ga,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white/70 text-sm",children:[o+1," / ",F.length]})]}),F.length>0&&e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[e.jsx("div",{className:"absolute top-10 left-8 z-10 px-4 py-1.5 rounded-full text-white font-bold text-sm uppercase tracking-wider shadow-lg",style:{backgroundColor:D.property_status==="just_sold"?"#e74c3c":A},children:D.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),F.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),u(!0)},children:[e.jsx("img",{src:F[0],alt:"Property",className:"w-full h-[50vh] object-cover group-hover:scale-105 transition-transform duration-500"}),e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white px-3 py-1.5 rounded-lg text-sm flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(h4,{className:"h-4 w-4"})," View"]})]}):F.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:F.slice(0,2).map((K,Y)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(Y),u(!0)},children:e.jsx("img",{src:K,alt:`Property ${Y+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},Y))}):e.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[e.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{c(0),u(!0)},children:e.jsx("img",{src:F[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),F.slice(1,5).map((K,Y)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(Y+1),u(!0)},children:[e.jsx("img",{src:K,alt:`Property ${Y+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),Y===3&&F.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",F.length-5," more"]})]},Y))]}),F.length>2&&e.jsxs("button",{onClick:()=>{c(0),u(!0)},className:"absolute bottom-4 right-8 bg-white shadow-lg hover:shadow-xl text-gray-800 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-shadow",children:[e.jsx(h4,{className:"h-4 w-4"})," View all ",F.length," photos"]})]}),F.length===0&&e.jsx("div",{className:"relative py-16 px-4",style:{background:b.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${b.hero_image_url}) center/cover`:`linear-gradient(135deg, ${A}, ${T})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[b.logo_url&&e.jsx("img",{src:b.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:b.hero_headline}),b.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:b.hero_subtext})]})}),e.jsx("div",{className:"max-w-4xl mx-auto px-4 py-8",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-6",children:[e.jsx("div",{className:"md:col-span-3 space-y-6",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[D.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:A},children:W(D.property_price)}),D.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(Ca,{className:"h-5 w-5 shrink-0"})," ",D.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[D.property_beds&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(ny,{className:"h-5 w-5",style:{color:A}})," ",D.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),D.property_baths&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(Tp,{className:"h-5 w-5",style:{color:A}})," ",D.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),D.property_sqft&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(eN,{className:"h-5 w-5",style:{color:A}})," ",Number(D.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),D.property_description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-800 mb-2",children:"About This Property"}),e.jsx("p",{className:"text-gray-600 leading-relaxed whitespace-pre-line",children:D.property_description})]})]})}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[e.jsx("h2",{className:"text-lg font-bold mb-1",style:{color:A},children:D.property_status==="just_sold"?"Want results like this?":"Interested in this property?"}),e.jsx("p",{className:"text-gray-500 text-sm mb-4",children:"Fill out the form and I'll be in touch!"}),b.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[b.agent_photo_url&&e.jsx("img",{src:b.agent_photo_url,alt:b.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:b.agent_name}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[b.agent_phone&&e.jsxs("a",{href:`tel:${b.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Pr,{className:"h-3 w-3"})," ",b.agent_phone]}),b.agent_email&&e.jsxs("a",{href:`mailto:${b.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Hs,{className:"h-3 w-3"})," ",b.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:S,className:"space-y-3",children:[j.map(K=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs font-medium",children:[K.label,K.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),tke(K,i,l)]},K.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:A},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 b.theme_style!=="classic"&&!L?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:W=>p(W.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(brn,{page:b,fields:j,answers:i,setAnswers:l,onSubmit:S,isSubmitting:_.isPending,renderField:tke}),b.page_type==="event_registration"&&((V=b.settings)==null?void 0:V.event_starts_at)&&e.jsx(krn,{startsAt:b.settings.event_starts_at,locationName:b.settings.event_location_name,address:b.settings.event_address,title:b.hero_headline||b.title,accent:b.accent_color||b.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:b.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${b.hero_image_url}) center/cover`:`linear-gradient(135deg, ${A}, ${T})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[b.logo_url&&e.jsx("img",{src:b.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:b.hero_headline}),b.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:b.hero_subtext}),L&&D.lead_magnet_file_name&&e.jsxs("div",{className:"mt-6 inline-flex items-center gap-2 bg-white/20 backdrop-blur px-4 py-2 rounded-full text-sm",children:[e.jsx(Da,{className:"h-4 w-4"}),"Free Download: ",D.lead_magnet_file_name]})]})}),e.jsx("div",{className:"max-w-2xl mx-auto px-4 -mt-8",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[L&&e.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),b.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[b.agent_photo_url&&e.jsx("img",{src:b.agent_photo_url,alt:b.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:b.agent_name}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[b.agent_phone&&e.jsxs("a",{href:`tel:${b.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Pr,{className:"h-3 w-3"})," ",b.agent_phone]}),b.agent_email&&e.jsxs("a",{href:`mailto:${b.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Hs,{className:"h-3 w-3"})," ",b.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:S,className:"space-y-4",children:[j.map(W=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-sm font-medium",children:[W.label,W.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),tke(W,i,l)]},W.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:A},disabled:_.isPending,children:_.isPending?"Submitting...":L?"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 tke(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(ge,{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(Ts,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",rows:3,className:"mt-1"});case"select":return e.jsxs(us,{value:String(a),onValueChange:l=>n(o=>({...o,[s.label]:l})),children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{placeholder:"Select..."})}),e.jsx(ds,{children:i.map(l=>e.jsx(Ze,{value:l,children:l},l))})]});case"multiselect":return e.jsx("div",{className:"mt-1 space-y-2",children:i.map(l=>{const o=Array.isArray(a)?a:[];return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(hi,{checked:o.includes(l),onCheckedChange:c=>{const d=c?[...o,l]:o.filter(u=>u!==l);n(u=>({...u,[s.label]:d}))}}),e.jsx("span",{className:"text-sm",children:l})]},l)})});case"toggle":return e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx(vn,{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(ge,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function Crn(){const t=Jl().pathname.slice(1).split("/")[0];return N.useEffect(()=>{document.body.classList.add("landing-page-public");const n=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("landing-page-public"),r.forEach(clearTimeout)}},[]),t?e.jsx($Nt,{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 Trn=[{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}],Dgn={hero:"Hero Section",featured_listings:"Featured Listings",featured_areas:"Featured Areas",about:"About Me",testimonials:"Testimonials",cta_banner:"Call To Action",new_listings:"New Listings Carousel",open_houses:"Open Houses Carousel",my_listings:"My Listings Carousel",city_pages:"City Pages Grid",property_types:"Property Types Gallery",advantages:"Advantages / Why Choose Us",rate_my_agent:"RateMyAgent Reviews",lifestyle_gallery:"Lifestyle Gallery",market_pulse:"Market Pulse",concierge_services:"Concierge Services",land_use_guide:"Land Use Guide",land_valuation_cta:"Land Valuation CTA",acreage_showcase:"Acreage Showcase",featured_video:"Featured Video",schedule_cta:"Schedule a Consultation"},Rgn={hero:"Full-screen background image with headline, subtitle, and search bar",featured_listings:"Grid of highlighted properties from the MLS",featured_areas:"Spotlight regions or neighborhoods that link to property search",about:"Agent photo, bio, and credentials section",testimonials:"Client reviews carousel with quotes",cta_banner:"Call-to-action block to drive contact and search engagement",new_listings:"Horizontal carousel of newest listings, filterable by city",open_houses:"Horizontal carousel of open house listings, filterable by city",my_listings:"Showcase the agent's own active listings in a carousel",city_pages:"Grid of your city landing pages with photos and links",property_types:"Visual gallery of property categories (Ranch, Farm, Land, etc.)",advantages:"Feature cards highlighting your expertise and unique value",rate_my_agent:"Verified client reviews carousel powered by RateMyAgent",lifestyle_gallery:"Cinematic photo grid showcasing luxury living — pools, views, interiors",market_pulse:"Sleek market stats dashboard with avg price, days on market, inventory",concierge_services:"White-glove services showcase — staging, design, moving coordination",land_use_guide:"Interactive land use cards — Agriculture, Hunting, Equestrian, Recreational",land_valuation_cta:`"What's Your Land Worth?" — bold call-to-action for landowners`,acreage_showcase:"Large visual cards emphasizing lot size with aerial imagery",featured_video:"Embedded YouTube or Bunny video section for cinematic storytelling",schedule_cta:"Prominent booking section that sends visitors to your online scheduling calendar"},nJe={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","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 Ogn(s){return nJe[s]||nJe.basic}function Ern(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}):Trn,testimonials:Array.isArray(s.testimonials)?s.testimonials:[],featuredListingIds:s.featured_listing_ids||[],searchCities:Array.isArray(t.searchCities)?t.searchCities:[],searchZipCodes:Array.isArray(t.searchZipCodes)?t.searchZipCodes:[],searchCounties:Array.isArray(t.searchCounties)?t.searchCounties:[],searchSubdivisions:Array.isArray(t.searchSubdivisions)?t.searchSubdivisions:[],referralMode:t.referralMode===!0,referralPrimaryLabel:t.referralPrimaryLabel||void 0,referralPrimaryUrl:t.referralPrimaryUrl||void 0,referralSecondaryLabel:t.referralSecondaryLabel||void 0,referralSecondaryUrl:t.referralSecondaryUrl||void 0}}function Arn(){const t=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return t?t[1]:null}function Mrn(){const s=Arn(),{data:t,isLoading:n,error:r}=lt({queryKey:["lead-site",s],queryFn:async()=>{var u;if(!s)return null;const{data:a,error:i}=await q.from("lead_sites").select("*").eq("subdomain_slug",s).eq("is_active",!0).maybeSingle();if(i)throw i;if(!a)return null;const{data:l}=await q.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("id",a.agent_id).single();let o=null;if(a.show_team_logo)if(a.team_logo_url)o=a.team_logo_url;else{const{data:h}=await q.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",a.agent_id).limit(1).maybeSingle();h&&((u=h.teams)!=null&&u.avatar_url)&&(o=h.teams.avatar_url)}const c={id:a.id,agentId:a.agent_id,subdomainSlug:a.subdomain_slug,mlsProviderId:a.mls_provider_id,siteTitle:a.site_title,siteTagline:a.site_tagline,leadRegistrationMode:a.lead_registration_mode||"disabled",registrationTriggerCount:a.registration_trigger_count??1,themeConfig:a.theme_config||{},isActive:a.is_active,brokerageLegalName:a.brokerage_legal_name||null,brokerageLicenseNumber:a.brokerage_license_number||null,agentLicenseNumber:a.agent_license_number||null,licenseState:a.license_state||null,mlsDisclaimerText:a.mls_disclaimer_text||null,mlsLogoUrl:a.mls_logo_url||null,equalHousingEnabled:a.equal_housing_enabled??!0,faviconUrl:a.favicon_url||null,ogImageUrl:a.og_image_url||null,showTeamLogo:a.show_team_logo??!1,teamLogoUrl:o,noMlsMode:a.no_mls_mode===!0,bookingUrl:a.booking_url||null,pageSubtitles:a.page_subtitles||{},agent:l?{id:l.id,full_name:l.name||"",avatar_url:l.avatar_url,email:l.email,phone:l.phone,title:l.title,bio:l.bio,areas_served:l.areas_served||null,years_experience:l.years_experience??null,instagram_url:l.instagram_url||null,facebook_url:l.facebook_url||null,linkedin_url:l.linkedin_url||null}:void 0,testimonials:Array.isArray(a.testimonials)?a.testimonials.filter(h=>h&&typeof h=="object"&&h.text).map(h=>({name:String(h.name||"Client"),text:String(h.text),rating:typeof h.rating=="number"?h.rating:5,location:h.location?String(h.location):void 0})):[],seoMetaTitle:a.seo_meta_title||null,seoMetaDescription:a.seo_meta_description||null},d=Ern(a);return{siteConfig:c,themeConfig:d}},enabled:!!s,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1});return{siteConfig:(t==null?void 0:t.siteConfig)??null,themeConfig:(t==null?void 0:t.themeConfig)??null,isLoading:n,error:r,slug:s}}async function Irn(s,t){try{await q.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(n){console.warn("Lead notification failed:",n)}}const UNt=N.createContext(null);function hbe(){const s=N.useContext(UNt);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function Prn({siteConfig:s,children:t}){const[n,r]=N.useState(null),[a,i]=N.useState(null),[l,o]=N.useState(!0);N.useEffect(()=>{const{data:{subscription:h}}=q.auth.onAuthStateChange(async(p,f)=>{const g=(f==null?void 0:f.user)??null;if(r(g),g){const{data:b}=await q.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",g.id).eq("lead_site_id",s.id).maybeSingle();b&&i({...b,email:g.email||""})}else i(null);o(!1)});return q.auth.getSession().then(({data:{session:p}})=>{r((p==null?void 0:p.user)??null),p!=null&&p.user?q.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",p.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:f})=>{f&&i({...f,email:p.user.email||""}),o(!1)}):o(!1)}),()=>h.unsubscribe()},[s.id]);const c=N.useCallback(async h=>{const p=h.email.toLowerCase().trim(),f=h.phone.replace(/\D/g,""),{data:g,error:b}=await q.auth.signUp({email:p,password:f,options:{data:{full_name:h.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(b){if(b.message.includes("already registered")){await d(p,f);return}throw b}if(g.user){const{error:v}=await q.from("lead_site_consumer_profiles").insert({user_id:g.user.id,lead_site_id:s.id,name:h.name.trim(),phone:h.phone.trim()});v&&console.warn("Consumer profile insert error:",v);const{error:j}=await q.from("lead_site_leads").insert({lead_site_id:s.id,name:h.name.trim(),email:p,phone:h.phone.trim(),message:"Created account on website",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,has_account:!0}});j&&console.error("Lead insert error (CRM sync may not trigger):",j),Irn(s.id,{name:h.name.trim(),email:p,phone:h.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}},[s.id]),d=N.useCallback(async(h,p)=>{const f=p.replace(/\D/g,""),{error:g}=await q.auth.signInWithPassword({email:h.toLowerCase().trim(),password:f});if(g)throw g},[]),u=N.useCallback(async()=>{await q.auth.signOut(),r(null),i(null)},[]);return e.jsx(UNt.Provider,{value:{user:n,profile:a,isLoading:l,signUp:c,signIn:d,signOut:u},children:t})}const Lrn=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),Drn=new Set(["tomlois"]);function qNt(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||Lrn.has(s.id||"")||Drn.has((s.subdomainSlug||"").toLowerCase())||!s.mlsProviderId:!1}function Fgn(s){return`Contact ${s.split(" ")[0]||"Me"}`}const BR="#c9a96e",Rrn="Schedule a Free Consultation",Orn={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function iN({bookingUrl:s,label:t=Rrn,className:n="",variant:r="solid",color:a=BR,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 ${Orn[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(QS,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:t})]})}function zgn({bookingUrl:s,agentName:t,accentColor:n=BR,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:gr,title:r.point1Title||"30 Minutes",text:r.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:v9,title:r.point2Title||"A Personal Call",text:r.point2Text||`${t.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:xr,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(Zn.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((p,f)=>e.jsxs("div",{className:"border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(p.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:p.title}),e.jsx("p",{className:"text-white/45 text-sm leading-relaxed",children:p.text})]},f))}),e.jsxs("div",{className:"mt-12 flex flex-col items-center gap-4",children:[e.jsx(iN,{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 Bgn({bookingUrl:s,accentColor:t=BR,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(iN,{bookingUrl:s,label:"Schedule Now",color:t,size:"sm",className:"flex-shrink-0",source:l})]}):null}function Frn({bookingUrl:s,accentColor:t=BR}){const[n,r]=N.useState(!1),[a,i]=N.useState(!1);if(N.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(QS,{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(Fn,{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(iN,{bookingUrl:s,label:"Schedule a Free Consultation",size:"sm",color:t,source:"sticky"})})]})}function zrn({bookingUrl:s,agentName:t}){return N.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(QS,{className:"h-8 w-8 mx-auto mb-6",style:{color:BR}}),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(iN,{bookingUrl:s,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}function L8e({open:s,mode:t,siteConfig:n,onComplete:r,onSkip:a,theme:i="default",accentColor:l}){var K;const{signUp:o,signIn:c}=hbe(),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f,g]=N.useState(""),[b,v]=N.useState(""),[j,_]=N.useState(!1),[S,A]=N.useState(""),T=t==="required",D=i==="luxury",L=l||(D?"#c9a96e":"#2563eb"),M=((K=n.agent)==null?void 0:K.full_name)||"the agent",F={borderColor:`${L}66`,"--tw-ring-color":`${L}66`},z=async Y=>{var ne;if(Y.preventDefault(),A(""),!f.trim()||!b.trim()){A("Email and phone number are required.");return}if(!d&&!h.trim()){A("Name is required.");return}if(b.replace(/\D/g,"").length<7){A("Please enter a valid phone number.");return}_(!0);try{d?await c(f,b):await o({name:h,email:f,phone:b}),r()}catch(oe){(ne=oe==null?void 0:oe.message)!=null&&ne.includes("Invalid login")?A("Invalid email or phone number. Please try again."):A((oe==null?void 0:oe.message)||"Something went wrong. Please try again.")}finally{_(!1)}},V=D?"w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2":"w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",W=D?F:void 0;return e.jsx(bs,{open:s,onOpenChange:T?void 0:Y=>{Y||a()},children:e.jsxs(vs,{className:`sm:max-w-md ${D?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:T?Y=>Y.preventDefault():void 0,onEscapeKeyDown:T?Y=>Y.preventDefault():void 0,children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-xl",style:D?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:d?"Welcome Back":T?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),e.jsx(Qn,{className:D?"text-[#5f5145]":void 0,children:d?"Sign in with your email and phone number.":`Create a free account to save favorites, get alerts, and connect with ${M}.`})]}),e.jsxs("form",{onSubmit:z,className:"space-y-3 mt-2",children:[!d&&e.jsx("input",{type:"text",required:!0,placeholder:"Your name",value:h,onChange:Y=>p(Y.target.value),className:V,style:W}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:f,onChange:Y=>g(Y.target.value),className:V,style:W}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:b,onChange:Y=>v(Y.target.value),className:V,style:W}),e.jsx("p",{className:`text-xs mt-1 ${D?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),S&&e.jsx("p",{className:"text-red-600 text-sm",children:S}),e.jsx("button",{type:"submit",disabled:j,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${D?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:D?{backgroundColor:L}:void 0,children:j?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{u(!d),A("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:L},children:d?"Don't have an account? Sign up":"Already have an account? Sign in"}),!T&&!d&&e.jsx("button",{type:"button",onClick:a,className:`w-full py-2 text-sm transition-colors ${D?"text-[#7a6758] hover:text-[#201915]":"text-gray-500 hover:text-gray-700"}`,children:"Skip for now"})]}),e.jsx("p",{className:`text-xs text-center mt-1 ${D?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function D8e({siteConfig:s,pagePath:t}){const n=s.agent;if(!n)return null;const r=`https://${s.subdomainSlug}.thelocalmove.com`,i=(n.areas_served||"").split(/,|;|\|/).map(S=>S.trim()).filter(Boolean),l=i[0]||"",[o,c]=l.split(/,\s*/),d=(n.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],u=[...new Set(d.map(S=>S.toUpperCase()))],h=s.testimonials||[],p=h.length?{"@type":"AggregateRating",ratingValue:(h.reduce((S,A)=>S+(A.rating||5),0)/h.length).toFixed(1),reviewCount:h.length,bestRating:5,worstRating:1}:void 0,f=[n.facebook_url,n.instagram_url,n.linkedin_url].filter(Boolean),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:"$$",...f.length&&{sameAs:f},...s.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:s.brokerageLegalName,...s.brokerageLicenseNumber&&{identifier:s.brokerageLicenseNumber}}},...s.agentLicenseNumber&&{identifier:s.agentLicenseNumber},...o&&{address:{"@type":"PostalAddress",addressLocality:o,...c&&{addressRegion:c},addressCountry:"US"}},...i.length&&{areaServed:i.map(S=>{const[A,T]=S.split(/,\s*/);return{"@type":"City",name:A,...T&&{containedInPlace:{"@type":"State",name:T}}}})},...p&&{aggregateRating:p},...h.length&&{review:h.slice(0,10).map(S=>({"@type":"Review",author:{"@type":"Person",name:S.name},reviewBody:S.text,reviewRating:{"@type":"Rating",ratingValue:S.rating||5,bestRating:5,worstRating:1},...S.location&&{locationCreated:{"@type":"Place",name:S.location}}}))}},b={"@context":"https://schema.org","@type":"Person","@id":`${r}/#person`,name:n.full_name,jobTitle:n.title||"Real Estate Agent",description:n.bio||void 0,image:n.avatar_url||void 0,url:r,email:n.email,telephone:n.phone||void 0,...f.length&&{sameAs:f},...n.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...u.length&&{hasCredential:u.map(S=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:S}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},v={"@context":"https://schema.org","@type":"WebSite","@id":`${r}/#website`,name:s.siteTitle||`${n.full_name} Real Estate`,url:r,publisher:{"@id":`${r}/#agent`},potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${r}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}},j=[{name:"Search Homes",description:`Browse all current MLS listings${l?` in ${l}`:""}.`,path:"/search"},{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"},{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${n.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${n.full_name} for buying, selling, or relocation help.`,path:"/contact"}],_={"@context":"https://schema.org","@type":"ItemList","@id":`${r}/#nav`,name:"Main Navigation",itemListElement:j.map((S,A)=>({"@type":"SiteNavigationElement",position:A+1,name:S.name,description:S.description,url:`${r}${S.path}`}))};return e.jsxs(Yo,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(g)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(b)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(v)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(_)})]})}function $gn({items:s,siteConfig:t}){const n=`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:s.map((a,i)=>({"@type":"ListItem",position:i+1,name:a.name,item:`${n}${a.path}`}))};return e.jsx(Yo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function Ugn({listing:s,siteConfig:t}){var a;const n=`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${s.address}, ${s.city}, ${s.state} ${s.zip}`,url:`${n}/listing/${s.mlsNumber}`,image:((a=s.photos)==null?void 0:a[0])||void 0,numberOfRooms:s.bedrooms,numberOfBathroomsTotal:s.bathrooms,floorSize:s.sqft?{"@type":"QuantitativeValue",value:s.sqft,unitCode:"FTK"}:void 0,address:{"@type":"PostalAddress",streetAddress:s.address,addressLocality:s.city,addressRegion:s.state,postalCode:s.zip},...s.latitude&&s.longitude&&{geo:{"@type":"GeoCoordinates",latitude:s.latitude,longitude:s.longitude}},offers:{"@type":"Offer",price:s.price,priceCurrency:"USD",availability:s.status==="Active"?"https://schema.org/InStock":"https://schema.org/SoldOut"},...s.yearBuilt&&{yearBuilt:s.yearBuilt}};return e.jsx(Yo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function Brn({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(Yo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function qgn({title:s,description:t,publishedAt:n,imageUrl:r,slug:a,siteConfig:i}){const l=`https://${i.subdomainSlug}.thelocalmove.com`,o=i.agent,c={"@context":"https://schema.org","@type":"Article",headline:s,description:t,url:`${l}/blog/${a}`,datePublished:n,...r&&{image:r},author:o?{"@type":"Person",name:o.full_name,url:l}:void 0,publisher:{"@type":"Organization",name:i.siteTitle||(o==null?void 0:o.full_name)||"Agent",url:l}};return e.jsx(Yo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function R8e({siteConfig:s}){var f;const t=s.agent;if(!t)return null;const n=t.full_name,r=s.brokerageLegalName||"their brokerage",a=t.areas_served||"the local market",i=((f=a.split(/,|;|\|/)[0])==null?void 0:f.trim())||"the local area",l=t.years_experience,o=t.phone||"",c=t.email,d=s.agentLicenseNumber,u=(t.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],h=[...new Set(u.map(g=>g.toUpperCase()))],p=[{question:`Who is ${n}?`,answer:`${n} is a ${t.title||"REALTOR®"} with ${r}${l?`, with ${l}+ years of local real estate experience`:""} serving ${a}. ${t.bio?t.bio.slice(0,280):""}`.trim()},{question:`What areas does ${n} serve?`,answer:`${n} serves ${a} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${n.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${n}?`,answer:`You can reach ${n} by ${o?`phone at ${o}, `:""}email at ${c}, or by booking a consultation directly through this website.`},...h.length?[{question:`What real estate designations does ${n} hold?`,answer:`${n} holds the following professional designations: ${h.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...d?[{question:`Is ${n} a licensed real estate agent?`,answer:`Yes, ${n} is a fully licensed real estate professional (License #${d}) with ${r}.`}]:[],{question:`How do I search for homes for sale in ${i}?`,answer:`Use the property search on this site to view all current MLS listings in ${i}. You can filter by price, bedrooms, neighborhood, school district, and more. Save searches to receive instant email alerts when new homes match your criteria.`},{question:`What is the home buying process like in ${i}?`,answer:`${n} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${n.split(" ")[0]} for a free buyer consultation.`},{question:`How do I find out what my home is worth in ${i}?`,answer:`Request a free, no-obligation home valuation from ${n}. ${n.split(" ")[0]} provides a comparative market analysis (CMA) using recent sold comps and current market conditions in ${i}.`}];return e.jsx(Brn,{faqs:p})}const rJe="ls_visitor_geo",$rn=1e3*60*60,ske="lu_lc_attrib_v1",Urn=1e3*60*60*24*90;function qrn(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 Vrn(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 Hrn(){try{const s=localStorage.getItem(rJe);if(s){const t=JSON.parse(s);if(Date.now()-t.ts<$rn)return t}}catch{}try{const s=await fetch("https://ipapi.co/json/",{signal:AbortSignal.timeout(5e3)});if(!s.ok)return null;const t=await s.json();if(!t.city||!t.latitude)return null;const n={city:t.city,region:t.region,country:t.country_name||t.country,lat:t.latitude,lng:t.longitude,ts:Date.now()};return localStorage.setItem(rJe,JSON.stringify(n)),n}catch{return null}}function O8e(s,t){const n=Jl(),r=N.useRef(""),a=N.useRef(null),i=N.useRef(!1);N.useEffect(()=>{i.current||(i.current=!0,Hrn().then(l=>{a.current=l}))},[]),N.useEffect(()=>{if(!(s!=null&&s.id))return;const l=n.pathname;if(l===r.current)return;r.current=l;const o=qrn(l),c=Vrn(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,u=a.current;(async()=>{const p=new URLSearchParams(n.search),f=p.get("luc");if(f&&/^[0-9a-f-]{36}$/i.test(f)){try{localStorage.setItem(ske,JSON.stringify({contact_id:f,ts:Date.now()}))}catch{}return f}const g=p.get("lc");if(g&&/^[0-9a-f-]{36}$/i.test(g)){const{data:b}=await q.from("listing_email_recipients").select("contact_id").eq("id",g).maybeSingle(),v=b==null?void 0:b.contact_id;if(v){try{localStorage.setItem(ske,JSON.stringify({contact_id:v,ts:Date.now()}))}catch{}return v}}try{const b=localStorage.getItem(ske);if(b){const v=JSON.parse(b);if(v!=null&&v.contact_id&&Date.now()-(v.ts||0){q.from("lead_site_page_views").insert({lead_site_id:s.id,page_type:o,page_path:l,page_title:c,visitor_fingerprint:d,auth_user_id:t||null,contact_id:p,visitor_city:(u==null?void 0:u.city)||null,visitor_region:(u==null?void 0:u.region)||null,visitor_country:(u==null?void 0:u.country)||null,visitor_lat:(u==null?void 0:u.lat)||null,visitor_lng:(u==null?void 0:u.lng)||null}).then(({error:f})=>{f&&console.error("[PageTracking] insert failed:",f.message)})})},[n.pathname,n.search,s==null?void 0:s.id,t])}const Grn=3e4;function F8e(s,t){const n=Jl(),r=N.useRef(null),a=N.useRef(null),i=N.useRef(0),l=n.pathname,o=Wrn(l),c=Krn(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;N.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const u=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,h=async()=>{const{data:p,error:f}=await q.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:u,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,coalesce(auth_user_id::text,visitor_fingerprint,'')"}).select("id, notified_agent").single();!f&&p&&(r.current=p.id,i.current>=2&&!p.notified_agent&&q.functions.invoke("lead-site-presence-notify",{body:{visitor_id:p.id,lead_site_id:s.id}}).catch(()=>{}))};return h(),a.current&&clearInterval(a.current),a.current=setInterval(h,Grn),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),N.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const u=()=>{r.current&&q.from("lead_site_active_visitors").delete().eq("id",r.current).then(()=>{})};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[s==null?void 0:s.id,t])}function Wrn(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 Krn(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 Fa=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},Yrn=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=Zrn},Zrn=Number.MAX_SAFE_INTEGER||9007199254740991;let fi=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}({}),Pn=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s}({}),_t=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s}({});var ol={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Qa={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class HI{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 Qrn{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 HI(t),this.fast_=new HI(n),this.defaultTTFB_=a,this.ttfb_=new HI(t)}update(t,n){const{slow_:r,fast_:a,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new HI(t,r.getEstimate(),r.getTotalWeight())),a.halfLife!==n&&(this.fast_=new HI(n,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new HI(t,i.getEstimate(),i.getTotalWeight()))}sample(t,n){t=Math.max(t,this.minDelayMs_);const r=8*n,a=t/1e3,i=r/a;this.fast_.sample(a,i),this.slow_.sample(a,i)}sampleTTFB(t){const n=t/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(n,2)/2);this.ttfb_.sample(r,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function Xrn(s,t,n){return(t=ean(t))in s?Object.defineProperty(s,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[t]=n,s}function Yc(){return Yc=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):oS}function iJe(s,t,n){return t[s]?t[s].bind(t):san(s,n)}const OTe=RTe();function nan(s,t,n){const r=RTe();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{r[i]=iJe(i,s,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return RTe()}a.forEach(i=>{OTe[i]=iJe(i,s)})}else Yc(OTe,r);return r}const Lc=OTe;function $4(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ran(s){return typeof self<"u"&&s===self.ManagedMediaSource}function VNt(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 vy(s,t=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(s);if(t){const u=d.indexOf("\0");return u!==-1?d.substring(0,u):d}return d.replace(/\0/g,"")}const n=s.length;let r,a,i,l="",o=0;for(;o>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(r);break;case 12:case 13:a=s[o++],l+=String.fromCharCode((r&31)<<6|a&63);break;case 14:a=s[o++],i=s[o++],l+=String.fromCharCode((r&15)<<12|(a&63)<<6|(i&63)<<0);break}}return l}function rf(s){let t="";for(let n=0;n1||a===1&&(n=this.levelkeys[r[0]])!=null&&n.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!Fa(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return Mh(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 oan extends GNt{constructor(t,n,r,a,i){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=n,this.index=a;const l=t.enumeratedString("BYTERANGE");l&&this.setByteRange(l,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function WNt(s,t){const n=Object.getPrototypeOf(s);if(n){const r=Object.getOwnPropertyDescriptor(n,t);return r||WNt(n,t)}}function lan(s,t){const n=WNt(s,t);n&&(n.enumerable=!0,Object.defineProperty(s,t,n))}const lJe=Math.pow(2,32)-1,can=[].push,KNt={video:1,audio:2,id3:3,text:4};function Im(s){return String.fromCharCode.apply(null,s)}function YNt(s,t){const n=s[t]<<8|s[t+1];return n<0?65536+n:n}function uo(s,t){const n=ZNt(s,t);return n<0?4294967296+n:n}function cJe(s,t){let n=uo(s,t);return n*=Math.pow(2,32),n+=uo(s,t+4),n}function ZNt(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function dan(s){const t=s.byteLength;for(let n=0;n8&&s[n+4]===109&&s[n+5]===111&&s[n+6]===111&&s[n+7]===102)return!0;n=r>1?n+r:t}return!1}function sl(s,t){const n=[];if(!t.length)return n;const r=s.byteLength;for(let a=0;a1?a+i:r;if(l===t[0])if(t.length===1)n.push(s.subarray(a+8,o));else{const c=sl(s.subarray(a+8,o),t.slice(1));c.length&&can.apply(n,c)}a=o}return n}function uan(s){const t=[],n=s[0];let r=8;const a=uo(s,r);r+=4;let i=0,l=0;n===0?(i=uo(s,r),l=uo(s,r+4),r+=8):(i=cJe(s,r),l=cJe(s,r+8),r+=16),r+=2;let o=s.length+l;const c=YNt(s,r);r+=2;for(let d=0;d>>31===1)return Lc.warn("SIDX has hierarchical references (not supported)"),null;const g=uo(s,u);u+=4,t.push({referenceSize:p,subsegmentDuration:g,info:{duration:g/a,start:o,end:o+p-1}}),o+=p,u+=4,r=u}return{earliestPresentationTime:i,timescale:a,version:n,referencesCount:c,references:t}}function QNt(s){const t=[],n=sl(s,["moov","trak"]);for(let a=0;a{const i=uo(a,4),l=t[i];l&&(l.default={duration:uo(a,12),flags:uo(a,20)})}),t}function han(s){const t=s.subarray(8),n=t.subarray(86),r=Im(t.subarray(4,8));let a=r,i;const l=r==="enca"||r==="encv";if(l){const d=sl(t,[r])[0].subarray(r==="enca"?28:78);sl(d,["sinf"]).forEach(h=>{const p=sl(h,["schm"])[0];if(p){const f=Im(p.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=sl(h,["frma"])[0];g&&(a=Im(g))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=sl(n,["avcC"])[0];c&&c.length>3&&(a+="."+BG(c[1])+BG(c[2])+BG(c[3]),i=zG(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const c=sl(t,[r])[0],d=sl(c.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=ake(d,u),u+=2;const h=d[u++];if(h&128&&(u+=2),h&64&&(u+=d[u++]),d[u++]!==4)break;u=ake(d,u);const p=d[u++];if(p===64)a+="."+BG(p);else break;if(u+=12,d[u++]!==5)break;u=ake(d,u);const f=d[u++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((d[u]&224)>>5)),a+="."+g}break}case"hvc1":case"hev1":{const c=sl(n,["hvcC"])[0];if(c&&c.length>12){const d=c[1],u=["","A","B","C"][d>>6],h=d&31,p=uo(c,2),f=(d&32)>>5?"H":"L",g=c[12],b=c.subarray(6,12);a+="."+u+h,a+="."+man(p).toString(16).toUpperCase(),a+="."+f+g;let v="";for(let j=b.length;j--;){const _=b[j];(_||v)&&(v="."+_.toString(16).toUpperCase()+v)}a+=v}i=zG(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=zG(a,n)||a;break}case"vp09":{const c=sl(n,["vpcC"])[0];if(c&&c.length>6){const d=c[4],u=c[5],h=c[6]>>4&15;a+="."+H_(d)+"."+H_(u)+"."+H_(h)}break}case"av01":{const c=sl(n,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,u=c[1]&31,h=c[2]>>>7?"H":"M",p=(c[2]&64)>>6,f=(c[2]&32)>>5,g=d===2&&p?f?12:10:p?10:8,b=(c[2]&16)>>4,v=(c[2]&8)>>3,j=(c[2]&4)>>2,_=c[2]&3;a+="."+d+"."+H_(u)+h+"."+H_(g)+"."+b+"."+v+j+_+"."+H_(1)+"."+H_(1)+"."+H_(1)+"."+0,i=zG("dav1",n)}break}}return{codec:a,encrypted:l,supplemental:i}}function zG(s,t){const n=sl(t,["dvvC"]),r=n.length?n[0]:sl(t,["dvcC"])[0];if(r){const a=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return s+"."+H_(a)+"."+H_(i)}}function man(s){let t=0;for(let n=0;n<32;n++)t|=(s>>n&1)<<31-n;return t>>>0}function ake(s,t){const n=t+5;for(;s[t++]&128&&t{const i=r.subarray(8,24);i.some(l=>l!==0)||(Lc.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${rf(i)} -> ${rf(n)}`),r.set(n,8))})}function fan(s){const t=[];return XNt(s,n=>t.push(n.subarray(8,24))),t}function XNt(s,t){sl(s,["moov","trak"]).forEach(r=>{const a=sl(r,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=sl(i,["enca"]);const o=l.length>0;o||(l=sl(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);sl(d,["sinf"]).forEach(h=>{const p=JNt(h);p&&t(p,o)})})})}function JNt(s){const t=sl(s,["schm"])[0];if(t){const n=Im(t.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=sl(s,["schi","tenc"])[0];if(r)return r}}}function xan(s,t,n){const r={},a=sl(s,["moof","traf"]);for(let i=0;ir[i].duration)){let i=1/0,l=0;const o=sl(s,["sidx"]);for(let c=0;ch+p.info.duration||0,0);l=Math.max(l,u+d.earliestPresentationTime/d.timescale)}}l&&Fa(l)&&Object.keys(r).forEach(c=>{r[c].duration||(r[c].duration=l*r[c].timescale-r[c].start)})}return r}function gan(s){const t={valid:null,remainder:null},n=sl(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 Qv(s,t){const n=new Uint8Array(s.length+t.length);return n.set(s),n.set(t,s.length),n}function dJe(s,t){const n=[],r=t.samples,a=t.timescale,i=t.id;let l=!1;return sl(r,["moof"]).map(c=>{const d=c.byteOffset-8;sl(c,["traf"]).map(h=>{const p=sl(h,["tfdt"]).map(f=>{const g=f[0];let b=uo(f,4);return g===1&&(b*=Math.pow(2,32),b+=uo(f,8)),b/a})[0];return p!==void 0&&(s=p),sl(h,["tfhd"]).map(f=>{const g=uo(f,4),b=uo(f,0)&16777215,v=(b&1)!==0,j=(b&2)!==0,_=(b&8)!==0;let S=0;const A=(b&16)!==0;let T=0;const D=(b&32)!==0;let L=8;g===i&&(v&&(L+=8),j&&(L+=4),_&&(S=uo(f,L),L+=4),A&&(T=uo(f,L),L+=4),D&&(L+=4),t.type==="video"&&(l=mbe(t.codec)),sl(h,["trun"]).map(M=>{const F=M[0],z=uo(M,0)&16777215,V=(z&1)!==0;let W=0;const K=(z&4)!==0,Y=(z&256)!==0;let ee=0;const ne=(z&512)!==0;let oe=0;const pe=(z&1024)!==0,ce=(z&2048)!==0;let de=0;const ie=uo(M,4);let ye=8;V&&(W=uo(M,ye),ye+=4),K&&(ye+=4);let _e=W+d;for(let Me=0;Me>1&63;return n===39||n===40}else return(t&31)===6}function $8e(s,t,n,r){const a=ekt(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){Lc.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[u++]===181){const p=YNt(a,u);if(u+=2,p===49){const f=uo(a,u);if(u+=4,f===1195456820){const g=a[u++];if(g===3){const b=a[u++],v=31&b,j=64&b,_=j?2+v*3:0,S=new Uint8Array(_);if(j){S[0]=b;for(let A=1;A<_;A++)S[A]=a[u++]}r.push({type:g,payloadType:l,pts:n,bytes:S})}}}}}else if(l===5&&o>16){const h=[];for(let g=0;g<16;g++){const b=a[u++].toString(16);h.push(b.length==1?"0"+b:b),(g===3||g===5||g===7||g===9)&&h.push("-")}const p=o-16,f=new Uint8Array(p);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),ban([112,115,115,104],new Uint8Array([r,0,0,0]),s,i,a,l,n)}function wan(s){const t=[];if(s instanceof ArrayBuffer){const n=s.byteLength;let r=0;for(;r+32>>24;if(i!==0&&i!==1)return{offset:n,size:t};const l=s.buffer,o=rf(new Uint8Array(l,n+12,16));let c=null,d=null,u=0;if(i===0)u=28;else{const p=s.getUint32(28);if(!p||r<32+p*16)return{offset:n,size:t};c=[];for(let f=0;f/\(Windows.+Firefox\//i.test(navigator.userAgent),wD={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function U8e(s,t){const n=wD[t];return!!n&&!!n[s.slice(0,4)]}function N$(s,t,n=!0){return!s.split(",").some(r=>!q8e(r,t,n))}function q8e(s,t,n=!0){var r;const a=$4(n);return(r=a==null?void 0:a.isTypeSupported(k$(s,t)))!=null?r:!1}function k$(s,t){return`${t}/mp4;codecs=${s}`}function uJe(s){if(s){const t=s.substring(0,4);return wD.video[t]}return 2}function Jge(s){const t=tkt();return s.split(",").reduce((n,r)=>{const i=t&&mbe(r)?9:wD.video[r];return i?(i*2+n)/(n?3:2):(wD.audio[r]+n)/(n?2:1)},0)}const ike={};function Nan(s,t=!0){if(ike[s])return ike[s];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;aNan(n.toLowerCase(),t))}function San(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)&&(hJe(s,"audio")||hJe(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 hJe(s,t){return U8e(s,t)&&q8e(s,t)}function Can(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 Tan(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 mJe(s){const t=$4(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 FTe(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Ean={supported:!0,powerEfficient:!0,smooth:!0},Aan={supported:!1,smooth:!1,powerEfficient:!1},skt={supported:!0,configurations:[],decodingInfoResults:[Ean]};function nkt(s,t){return{supported:!1,configurations:t,decodingInfoResults:[Aan],error:s}}function Man(s,t,n,r,a,i){const l=s.videoCodec,o=s.audioCodec?s.audioGroups:null,c=i==null?void 0:i.audioCodec,d=i==null?void 0:i.channels,u=d?parseInt(d):c?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=t.groups[o[0]].channels:h=o.reduce((p,f)=>{if(f){const g=t.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(b=>{p[b]=(p[b]||0)+g.channels[b]})}return p},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(p=>mbe(p))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(r,30)||s.videoRange!=="SDR"&&s.videoRange!==n||s.bitrate>Math.max(a,8e6))||!!h&&Fa(u)&&Object.keys(h).some(p=>parseInt(p)>u)}function rkt(s,t,n,r={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!n)return Promise.resolve(skt);const i=[],l=Ian(s),o=l.length,c=Pan(s,t,o>0),d=c.length;for(let u=o||1*d||1;u--;){const h={type:"media-source"};if(o&&(h.video=l[u%o]),d){h.audio=c[u%d];const p=h.audio.bitrate;h.video&&p&&(h.video.bitrate-=p)}i.push(h)}if(a){const u=navigator.userAgent;if(a.split(",").some(h=>mbe(h))&&tkt())return Promise.resolve(nkt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const h=Dan(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 Ian(s){var t;const n=(t=s.videoCodec)==null?void 0:t.split(","),r=akt(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:k$(Tan(c),"video"),width:a,height:i,bitrate:r,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function Pan(s,t,n){var r;const a=(r=s.audioCodec)==null?void 0:r.split(","),i=akt(s);return a&&s.audioGroups?s.audioGroups.reduce((l,o)=>{var c;const d=o?(c=t.groups[o])==null?void 0:c.tracks:null;return d?d.reduce((u,h)=>{if(h.groupId===o){const p=parseFloat(h.channels||"");a.forEach(f=>{const g={contentType:k$(f,"audio"),bitrate:n?Lan(f,i):i};p&&(g.channels=""+p),u.push(g)})}return u},l):l},[]):[]}function Lan(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 akt(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function Dan(s){let t="";const{audio:n,video:r}=s;if(r){const a=FTe(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=FTe(n.contentType);t+=`${r?"_":""}${a}_c${n.channels}`}return t}const zTe=["NONE","TYPE-0","TYPE-1",null];function Ran(s){return zTe.indexOf(s)>-1}const t0e=["SDR","PQ","HLG"];function Oan(s){return!!s&&t0e.indexOf(s)>-1}var hpe={No:"",Yes:"YES",v2:"v2"};function pJe(s){const{canSkipUntil:t,canSkipDateRanges:n,age:r}=s,a=r!!r).map(r=>r.substring(0,4)).join(","),"supplemental"in t){var n;this.supplemental=t.supplemental;const r=(n=t.supplemental)==null?void 0:n.videoCodec;r&&r!==t.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return xJe(this._audioGroups,t)}hasSubtitleGroup(t){return xJe(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 xJe(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function Fan(){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 zan(s,t){let n=!1,r=[];if(s&&(n=s!=="SDR",r=[s]),t){r=t.allowedVideoRanges||t0e.slice(0);const a=r.join("")!=="SDR"&&!t.videoCodec;n=t.preferHDR!==void 0?t.preferHDR:a&&Fan(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const Ban=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}},id=(s,t)=>JSON.stringify(s,Ban(t));function $an(s,t,n,r,a){const i=Object.keys(s),l=r==null?void 0:r.channels,o=r==null?void 0:r.audioCodec,c=a==null?void 0:a.videoCodec,d=l&&parseInt(l)===2;let u=!1,h=!1,p=1/0,f=1/0,g=1/0,b=1/0,v=0,j=[];const{preferHDR:_,allowedVideoRanges:S}=zan(t,a);for(let M=i.length;M--;){const F=s[i[M]];u||(u=F.channels[2]>0),p=Math.min(p,F.minHeight),f=Math.min(f,F.minFramerate),g=Math.min(g,F.minBitrate),S.filter(V=>F.videoRanges[V]>0).length>0&&(h=!0)}p=Fa(p)?p:0,f=Fa(f)?f:0;const A=Math.max(1080,p),T=Math.max(30,f);g=Fa(g)?g:n,n=Math.max(g,n),h||(t=void 0);const D=i.length>1;return{codecSet:i.reduce((M,F)=>{const z=s[F];if(F===M)return M;if(j=h?S.filter(V=>z.videoRanges[V]>0):[],D){if(z.minBitrate>n)return I_(F,`min bitrate of ${z.minBitrate} > current estimate of ${n}`),M;if(!z.hasDefaultAudio)return I_(F,"no renditions with default or auto-select sound found"),M;if(o&&F.indexOf(o.substring(0,4))%5!==0)return I_(F,`audio codec preference "${o}" not found`),M;if(l&&!d){if(!z.channels[l])return I_(F,`no renditions with ${l} channel sound found (channels options: ${Object.keys(z.channels)})`),M}else if((!o||d)&&u&&z.channels[2]===0)return I_(F,"no renditions with stereo sound found"),M;if(z.minHeight>A)return I_(F,`min resolution of ${z.minHeight} > maximum of ${A}`),M;if(z.minFramerate>T)return I_(F,`min framerate of ${z.minFramerate} > maximum of ${T}`),M;if(!j.some(V=>z.videoRanges[V]>0))return I_(F,`no variants with VIDEO-RANGE of ${id(j)} found`),M;if(c&&F.indexOf(c.substring(0,4))%5!==0)return I_(F,`video codec preference "${c}" not found`),M;if(z.maxScore=Jge(M)||z.fragmentError>s[M].fragmentError)?M:(b=z.minIndex,v=z.maxScore,F)},void 0),videoRanges:j,preferHDR:_,minFramerate:f,minBitrate:g,minIndex:b}}function I_(s,t){Lc.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function ikt(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 Uan(s,t,n,r){return s.slice(n,r+1).reduce((a,i,l)=>{if(!i.codecSet)return a;const o=i.audioGroups;let c=a[i.codecSet];c||(a[i.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:l,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,i.bitrate);const d=Math.min(i.height,i.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,i.frameRate),c.minIndex=Math.min(c.minIndex,l),c.maxScore=Math.max(c.maxScore,i.score),c.fragmentError+=i.fragmentError,c.videoRanges[i.videoRange]=(c.videoRanges[i.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const h=t.groups[u];h&&(c.hasDefaultAudio=c.hasDefaultAudio||t.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(h.channels).forEach(p=>{c.channels[p]=(c.channels[p]||0)+h.channels[p]}))}),a},{})}function gJe(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 dw(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 OE(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 Han(s,t,n,r,a){const i=t[r],o=t.reduce((p,f,g)=>{const b=f.uri;return(p[b]||(p[b]=[])).push(g),p},{})[i.uri];o.length>1&&(r=Math.max.apply(Math,o));const c=i.videoRange,d=i.frameRate,u=i.codecSet.substring(0,4),h=yJe(t,r,p=>{if(p.videoRange!==c||p.frameRate!==d||p.codecSet.substring(0,4)!==u)return!1;const f=p.audioGroups,g=n.filter(b=>!f||f.indexOf(b.groupId)!==-1);return dw(s,g,a)>-1});return h>-1?h:yJe(t,r,p=>{const f=p.audioGroups,g=n.filter(b=>!f||f.indexOf(b.groupId)!==-1);return dw(s,g,a)>-1})}function yJe(s,t,n){for(let r=t;r>-1;r--)if(n(s[r]))return r;for(let r=t+1;r{var r;const{fragCurrent:a,partCurrent:i,hls:l}=this,{autoLevelEnabled:o,media:c}=l;if(!a||!c)return;const d=performance.now(),u=i?i.stats:a.stats,h=i?i.duration:a.duration,p=d-u.loading.start,f=l.minAutoLevel,g=a.level,b=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const v=b>-1&&b!==g,j=!!n||v;if(!j&&(c.paused||!c.playbackRate||!c.readyState))return;const _=l.mainForwardBufferInfo;if(!j&&_===null)return;const S=this.bwEstimator.getEstimateTTFB(),A=Math.abs(c.playbackRate);if(p<=Math.max(S,1e3*(h/(A*2))))return;const T=_?_.len/A:0,D=u.loading.first?u.loading.first-u.loading.start:-1,L=u.loaded&&D>-1,M=this.getBwEstimate(),F=l.levels,z=F[g],V=Math.max(u.loaded,Math.round(h*(a.bitrate||z.averageBitrate)/8));let W=L?p-D:p;W<1&&L&&(W=Math.min(p,u.loaded*8/M));const K=L?u.loaded*1e3/W:0,Y=S/1e3,ee=K?(V-u.loaded)/K:V*8/M+Y;if(ee<=T)return;const ne=K?K*8:M,oe=((r=(n==null?void 0:n.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,pe=this.hls.config.abrBandWidthUpFactor;let ce=Number.POSITIVE_INFINITY,de;for(de=g-1;de>f;de--){const Me=F[de].maxBitrate,Te=!F[de].details||oe;if(ce=this.getTimeToLoadFrag(Y,ne,h*Me,Te),ce=ee||ce>h*10)return;L?this.bwEstimator.sample(p-Math.min(S,D),u.loaded):this.bwEstimator.sampleTTFB(p);const ie=F[de].maxBitrate;this.getBwEstimate()*pe>ie&&this.resetEstimator(ie);const ye=this.findBestLevel(ie,f,de,0,T,1,1);ye>-1&&(de=ye),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: ${T.toFixed(3)} s Estimated load time for current fragment: ${ee.toFixed(3)} s Estimated load time for down switch fragment: ${ce.toFixed(3)} s TTFB estimate: ${D|0} ms Current BW estimate: ${Fa(M)?M|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${de} @ ${ie|0} bps`),l.nextLoadLevel=l.nextAutoLevel=de,this.clearTimer();const _e=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===de&&de>0){const Me=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${de>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${Me.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,de>f){let Te=this.findBestLevel(this.hls.levels[f].bitrate,f,de,0,Me,1,1);Te===-1&&(Te=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Te,this.resetEstimator(this.hls.levels[Te].bitrate)}}};v||ee>ce*2?_e():this.timer=self.setInterval(_e,ce*1e3),l.trigger(_t.FRAG_LOAD_EMERGENCY_ABORTED,{frag:a,part:i,stats:u})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new Qrn(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.FRAG_LOADING,this.onFragLoading,this),t.on(_t.FRAG_LOADED,this.onFragLoaded,this),t.on(_t.FRAG_BUFFERED,this.onFragBuffered,this),t.on(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_t.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.FRAG_LOADING,this.onFragLoading,this),t.off(_t.FRAG_LOADED,this.onFragLoaded,this),t.off(_t.FRAG_BUFFERED,this.onFragBuffered,this),t.off(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_t.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(_t.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,n){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,n){const r=n.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var a;this.fragCurrent=r,this.partCurrent=(a=n.part)!=null?a:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,n){this.clearTimer()}onError(t,n){if(!n.fatal)switch(n.details){case Pn.BUFFER_ADD_CODEC_ERROR:case Pn.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Pn.FRAG_LOAD_TIMEOUT:{const r=n.frag,{fragCurrent:a,partCurrent:i}=this;if(r&&a&&r.sn===a.sn&&r.level===a.level){const l=performance.now(),o=i?i.stats:r.stats,c=l-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(h,d),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(t,n,r,a){const i=t+r/n,l=a?t+this.lastLevelLoadSec:0;return i+l}onLevelLoaded(t,n){const r=this.hls.config,{loading:a}=n.stats,i=a.end-a.first;Fa(i)&&(this.lastLevelLoadSec=i/1e3),n.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(n.levelInfo)}onFragLoaded(t,{frag:n,part:r}){const a=r?r.stats:n.stats;if(n.type===Qa.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(n)){if(this.clearTimer(),n.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const i=r?r.duration:n.duration,l=this.hls.levels[n.level],o=(l.loaded?l.loaded.bytes:0)+a.loaded,c=(l.loaded?l.loaded.duration:0)+i;l.loaded={bytes:o,duration:c},l.realBitrate=Math.round(8*o/c)}if(n.bitrateTest){const i={stats:a,frag:n,part:r,id:n.type};this.onFragBuffered(_t.FRAG_BUFFERED,i),n.bitrateTest=!1}else this.lastLoadedFragLevel=n.level}}onFragBuffered(t,n){const{frag:r,part:a}=n,i=a!=null&&a.stats.loaded?a.stats:r.stats;if(i.aborted||this.ignoreFragment(r))return;const l=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(l,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=l/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Qa.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:n}=this.hls,r=this.getBwEstimate(),a=this.hls.config.maxStarvationDelay,i=this.findBestLevel(r,n,t,0,a,1,1);if(i>-1)return i;const l=this.hls.firstLevel,o=Math.min(Math.max(l,n),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,r=this.bwEstimator.canEstimate(),a=this.lastLoadedFragLevel>-1;if(t!==-1&&(!r||!a||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const i=r&&a?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const l=this.hls.levels;if(l.length>Math.max(t,i)&&l[t].loadError<=l[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:n,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:a,config:i,minAutoLevel:l}=r,o=n?n.duration:t?t.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let u=i.abrBandWidthFactor,h=i.abrBandWidthUpFactor;if(d){const v=this.findBestLevel(c,l,a,d,0,u,h);if(v>=0)return this.rebufferNotice=-1,v}let p=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const v=this.bitrateTestDelay;v&&(p=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-v,this.info(`bitrate test took ${Math.round(1e3*v)}ms, set first fragment max fetchDuration to ${Math.round(1e3*p)} ms`),u=h=1)}const f=this.findBestLevel(c,l,a,d,p,u,h);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=r.levels[l],b=r.loadLevelObj;return b&&(g==null?void 0:g.bitrate)=n;ne--){var ee;const oe=g[ne],pe=ne>h;if(!oe)continue;if(j.useMediaCapabilities&&!oe.supportedResult&&!oe.supportedPromise){const Te=navigator.mediaCapabilities;typeof(Te==null?void 0:Te.decodingInfo)=="function"&&Man(oe,z,D,L,t,M)?(oe.supportedPromise=rkt(oe,z,Te,this.supportedCache),oe.supportedPromise.then(Ce=>{if(!this.hls)return;oe.supportedResult=Ce;const Ee=this.hls.levels,De=Ee.indexOf(oe);Ce.error?this.warn(`MediaCapabilities decodingInfo error: "${Ce.error}" for level ${De} ${id(Ce)}`):Ce.supported?Ce.decodingInfoResults.some(Ie=>Ie.smooth===!1||Ie.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${De} not smooth or powerEfficient: ${id(Ce)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${De} ${id(Ce)}`),De>-1&&Ee.length>1&&(this.log(`Removing unsupported level ${De}`),this.hls.removeLevel(De),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ce=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ce}`)})):oe.supportedResult=skt}if((T&&oe.codecSet!==T||D&&oe.videoRange!==D||pe&&L>oe.frameRate||!pe&&L>0&&LTe.smooth===!1))&&(!A||ne!==V)){Y.push(ne);continue}const ce=oe.details,de=(f?ce==null?void 0:ce.partTarget:ce==null?void 0:ce.averagetargetduration)||W;let ie;pe?ie=o*t:ie=l*t;const ye=W&&a>=W*2&&i===0?oe.averageBitrate:oe.maxBitrate,_e=this.getTimeToLoadFrag(K,ie,ye*de,ce===void 0);if(ie>=ye&&(ne===u||oe.loadError===0&&oe.fragmentError===0)&&(_e<=K||!Fa(_e)||S&&!this.bitrateTestDelay||_e${ne} adjustedbw(${Math.round(ie)})-bitrate=${Math.round(ie-ye)} ttfb:${K.toFixed(1)} avgDuration:${de.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${_e.toFixed(1)} firstSelection:${A} codecSet:${oe.codecSet} videoRange:${oe.videoRange} hls.loadLevel:${v}`)),A&&(this.firstSelection=ne),ne}}return-1}set nextAutoLevel(t){const n=this.deriveNextAutoLevel(t);this._nextAutoLevel!==n&&(this.nextAutoLevelKey="",this._nextAutoLevel=n)}deriveNextAutoLevel(t){const{maxAutoLevel:n,minAutoLevel:r}=this.hls;return Math.min(Math.max(t,r),n)}}const okt={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 Wan(s,t,n){if(t===null||!Array.isArray(s)||!s.length||!Fa(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)&&vJe(n,r,i)===0||Kan(i,s,Math.min(a,r))))return i;const l=okt.search(t,vJe.bind(null,n,r));return l&&(l!==s||!i)?l:i}function Kan(s,t,n){if(t&&t.start===0&&t.level0){const r=t.tagList.reduce((a,i)=>(i[0]==="INF"&&(a+=parseFloat(i[1])),a),n);return s.start<=r}return!1}function vJe(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 Yan(s,t,n){const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>s}function lkt(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 okt.search(r,l=>l.cct?-1:(i=l,l.end<=n?1:l.start>n?-1:0)),i||null}return null}function n0e(s){switch(s.details){case Pn.FRAG_LOAD_TIMEOUT:case Pn.KEY_LOAD_TIMEOUT:case Pn.LEVEL_LOAD_TIMEOUT:case Pn.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ckt(s){return s.details.startsWith("key")}function dkt(s){return ckt(s)&&!!s.frag&&!s.frag.decryptdata}function bJe(s,t){const n=n0e(t);return s.default[`${n?"timeout":"error"}Retry`]}function V8e(s,t){const n=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(n*s.retryDelayMs,s.maxRetryDelayMs)}function _Je(s){return Ec(Ec({},s),{errorRetry:null,timeoutRetry:null})}function r0e(s,t,n,r){if(!s)return!1;const a=r==null?void 0:r.code,i=t499)}function BTe(s){return s===0&&navigator.onLine===!1}var nf={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},$0={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class Qan extends a1{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(_t.ERROR,this.onError,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(_t.ERROR,this.onError,this),t.off(_t.ERROR,this.onErrorOut,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(t==null?void 0:t.type)===Qa.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 Pn.FRAG_LOAD_ERROR:case Pn.FRAG_LOAD_TIMEOUT:case Pn.KEY_LOAD_ERROR:case Pn.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case Pn.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=YL();return}case Pn.FRAG_GAP:case Pn.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=nf.SendAlternateToPenaltyBox;return}case Pn.LEVEL_EMPTY_ERROR:case Pn.LEVEL_PARSING_ERROR:{var l;const c=n.parent===Qa.MAIN?n.level:a.loadLevel;n.details===Pn.LEVEL_EMPTY_ERROR&&((l=n.context)!=null&&(l=l.levelDetails)!=null&&l.live)?n.errorAction=this.getPlaylistRetryOrSwitchAction(n,c):(n.levelRetry=!1,n.errorAction=this.getLevelSwitchAction(n,c))}return;case Pn.LEVEL_LOAD_ERROR:case Pn.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.level));return;case Pn.AUDIO_TRACK_LOAD_ERROR:case Pn.AUDIO_TRACK_LOAD_TIMEOUT:case Pn.SUBTITLE_LOAD_ERROR:case Pn.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===ol.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===ol.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,a.loadLevel),n.errorAction.action=nf.SendAlternateToPenaltyBox,n.errorAction.flags=$0.MoveAllAlternatesMatchingHost;return}}return;case Pn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:nf.SendAlternateToPenaltyBox,flags:$0.MoveAllAlternatesMatchingHDCP};return;case Pn.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Pn.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Pn.KEY_SYSTEM_NO_SESSION:n.errorAction={action:nf.SendAlternateToPenaltyBox,flags:$0.MoveAllAlternatesMatchingKey};return;case Pn.BUFFER_ADD_CODEC_ERROR:case Pn.REMUX_ALLOC_ERROR:case Pn.BUFFER_APPEND_ERROR:if(!n.errorAction){var o;n.errorAction=this.getLevelSwitchAction(n,(o=n.level)!=null?o:a.loadLevel)}return;case Pn.INTERNAL_EXCEPTION:case Pn.BUFFER_APPENDING_ERROR:case Pn.BUFFER_FULL_ERROR:case Pn.LEVEL_SWITCH_ERROR:case Pn.BUFFER_STALLED_ERROR:case Pn.BUFFER_SEEK_OVER_HOLE:case Pn.BUFFER_NUDGE_ON_STALL:n.errorAction=YL();return}n.type===fi.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=YL())}getPlaylistRetryOrSwitchAction(t,n){const r=this.hls,a=bJe(r.config.playlistLoadPolicy,t),i=this.playlistError++;if(r0e(a,i,n0e(t),t.response))return{action:nf.RetryRequest,flags:$0.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=bJe(ckt(t)?l:i,t),c=n.levels.reduce((u,h)=>u+h.fragmentError,0);if(a&&(t.details!==Pn.FRAG_GAP&&a.fragmentError++,!dkt(t)&&r0e(o,c,n0e(t),t.response)))return{action:nf.RetryRequest,flags:$0.None,retryConfig:o,retryCount:c};const d=this.getLevelSwitchAction(t,r);return o&&(d.retryConfig=o,d.retryCount=c),d}getLevelSwitchAction(t,n){const r=this.hls;n==null&&(n=r.loadLevel);const a=this.hls.levels[n];if(a){var i,l;const d=t.details;a.loadError++,d===Pn.BUFFER_APPEND_ERROR&&a.fragmentError++;let u=-1;const{levels:h,loadLevel:p,minAutoLevel:f,maxAutoLevel:g}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const b=(i=t.frag)==null?void 0:i.type,j=(b===Qa.AUDIO&&d===Pn.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===Pn.BUFFER_ADD_CODEC_ERROR||d===Pn.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:D})=>a.audioCodec!==D),S=t.sourceBufferName==="video"&&(d===Pn.BUFFER_ADD_CODEC_ERROR||d===Pn.BUFFER_APPEND_ERROR)&&h.some(({codecSet:D,audioCodec:L})=>a.codecSet!==D&&a.audioCodec===L),{type:A,groupId:T}=(l=t.context)!=null?l:{};for(let D=h.length;D--;){const L=(D+p)%h.length;if(L!==p&&L>=f&&L<=g&&h[L].loadError===0){var o,c;const M=h[L];if(d===Pn.FRAG_GAP&&b===Qa.MAIN&&t.frag){const F=h[L].details;if(F){const z=BM(t.frag,F.fragments,t.frag.start);if(z!=null&&z.gap)continue}}else{if(A===ol.AUDIO_TRACK&&M.hasAudioGroup(T)||A===ol.SUBTITLE_TRACK&&M.hasSubtitleGroup(T))continue;if(b===Qa.AUDIO&&(o=a.audioGroups)!=null&&o.some(F=>M.hasAudioGroup(F))||b===Qa.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(F=>M.hasSubtitleGroup(F))||j&&a.audioCodec===M.audioCodec||S&&a.codecSet===M.codecSet||!j&&a.codecSet!==M.codecSet)continue}u=L;break}}if(u>-1&&r.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:nf.SendAlternateToPenaltyBox,flags:$0.None,nextAutoLevel:u}}return{action:nf.SendAlternateToPenaltyBox,flags:$0.MoveAllAlternatesMatchingHost}}onErrorOut(t,n){var r;switch((r=n.errorAction)==null?void 0:r.action){case nf.DoNothing:break;case nf.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==Pn.FRAG_GAP?n.fatal=!0:/MediaSource readyState: ended/.test(n.error.message)&&(this.warn(`MediaSource ended after "${n.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(n.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const n=this.hls,r=t.errorAction;if(!r)return;const{flags:a}=r,i=r.nextAutoLevel;switch(a){case $0.None:this.switchLevel(t,i);break;case $0.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(t.frag),d=n.levels[c],u=d==null?void 0:d.attrs["HDCP-LEVEL"];if(r.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){n.maxHdcpLevel=zTe[zTe.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`);break}}case $0.MoveAllAlternatesMatchingKey:{const c=t.decryptdata;if(c){const d=this.hls.levels,u=d.length;for(let p=u;p--;)if(this.variantHasKey(d[p],c)){var l,o;this.log(`Banned key found in level ${p} (${d[p].bitrate}bps) or audio group "${(l=d[p].audioGroups)==null?void 0:l.join(",")}" (${(o=t.frag)==null?void 0:o.type} fragment) ${rf(c.keyId||[])}`),d[p].fragmentError++,d[p].loadError++,this.log(`Removing level ${p} with key error (${t.error})`),this.hls.removeLevel(p)}const h=t.frag;if(this.hls.levels.length{const c=this.fragments[o];if(!c||l>=c.body.sn)return;if(!c.buffered&&(!c.loaded||i)){c.body.type===r&&this.removeFragment(c.body);return}const d=c.range[t];if(d){if(d.time.length===0){this.removeFragment(c.body);return}d.time.some(u=>{const h=!this.isTimeBuffered(u.startPTS,u.endPTS,n);return h&&this.removeFragment(c.body),h})}})}detectPartialFragments(t){const n=this.timeRanges;if(!n||t.frag.sn==="initSegment")return;const r=t.frag,a=GI(r),i=this.fragments[a];if(!i||i.buffered&&r.gap)return;const l=!r.relurl;Object.keys(n).forEach(o=>{const c=r.elementaryStreams[o];if(!c)return;const d=n[o],u=l||c.partial===!0;i.range[o]=this.getBufferedTimes(r,t.part,u,d)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,r),$G(i)||this.removeParts(r.sn-1,r.type)):this.removeFragment(i.body)}bufferedEnd(t,n){t.buffered=!0,(t.body.endList=n.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,n){const r=this.activePartLists[n];r&&(this.activePartLists[n]=wJe(r,a=>a.fragment.sn>=t))}fragBuffered(t,n){const r=GI(t);let a=this.fragments[r];!a&&n&&(a=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),a&&(a.loaded=null,this.bufferedEnd(a,t))}getBufferedTimes(t,n,r,a){const i={time:[],partial:r},l=t.start,o=t.end,c=t.minEndPTS||o,d=t.maxStartPTS||l;for(let u=0;u=h&&c<=p){i.time.push({startPTS:Math.max(l,a.start(u)),endPTS:Math.min(o,a.end(u))});break}else if(lh){const f=Math.max(l,a.start(u)),g=Math.min(o,a.end(u));g>f&&(i.partial=!0,i.time.push({startPTS:f,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&&$G(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||$G(n))}getState(t){const n=GI(t),r=this.fragments[n];return r?r.buffered?$G(r)?Dm.PARTIAL:Dm.OK:Dm.APPENDING:Dm.NOT_LOADED}isTimeBuffered(t,n,r){let a,i;for(let l=0;l=a&&n<=i)return!0;if(n<=a)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,n){if(n.frag.sn==="initSegment"||n.frag.bitrateTest)return;const r=n.frag,a=n.part?null:n,i=GI(r);this.fragments[i]={body:r,appendedPTS:null,loaded:a,buffered:!1,range:Object.create(null)}}onBufferAppended(t,n){const{frag:r,part:a,timeRanges:i,type:l}=n;if(r.sn==="initSegment")return;const o=r.type;if(a){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(a)}this.timeRanges=i;const c=i[l];this.detectEvictedFragments(l,c,o,a)}onFragBuffered(t,n){this.detectPartialFragments(n)}hasFragment(t){const n=GI(t);return!!this.fragments[n]}hasFragments(t){const{fragments:n}=this,r=Object.keys(n);if(!t)return r.length>0;for(let a=r.length;a--;){const i=n[r[a]];if((i==null?void 0:i.body.type)===t)return!0}return!1}hasParts(t){var n;return!!((n=this.activePartLists[t])!=null&&n.length)}removeFragmentsInRange(t,n,r,a,i){a&&!this.hasGaps||Object.keys(this.fragments).forEach(l=>{const o=this.fragments[l];if(!o)return;const c=o.body;c.type!==r||a&&!c.gap||c.startt&&(o.buffered||i)&&this.removeFragment(c)})}removeFragment(t){const n=GI(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const a=t.sn;this.activePartLists[t.type]=wJe(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 $G(s){var t,n,r;return s.buffered&&!!(s.body.gap||(t=s.range.video)!=null&&t.partial||(n=s.range.audio)!=null&&n.partial||(r=s.range.audiovideo)!=null&&r.partial)}function GI(s){return`${s.type}_${s.level}_${s.sn}`}function wJe(s,t){return s.filter(n=>{const r=t(n);return r||n.clearElementaryStreamInfo(),r})}var U4={cbc:0,ctr:1};class Jan{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 U4.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,t);case U4.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 ein(s){const t=s.byteLength,n=t&&new DataView(s.buffer).getUint8(t-1);return n?s.slice(0,t-n):s}class tin{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const n=new DataView(t),r=new Uint32Array(4);for(let a=0;a<4;a++)r[a]=n.getUint32(a*4);return r}initTable(){const t=this.sBox,n=this.invSBox,r=this.subMix,a=r[0],i=r[1],l=r[2],o=r[3],c=this.invSubMix,d=c[0],u=c[1],h=c[2],p=c[3],f=new Uint32Array(256);let g=0,b=0,v=0;for(v=0;v<256;v++)v<128?f[v]=v<<1:f[v]=v<<1^283;for(v=0;v<256;v++){let j=b^b<<1^b<<2^b<<3^b<<4;j=j>>>8^j&255^99,t[g]=j,n[j]=g;const _=f[g],S=f[_],A=f[S];let T=f[j]*257^j*16843008;a[g]=T<<24|T>>>8,i[g]=T<<16|T>>>16,l[g]=T<<8|T>>>24,o[g]=T,T=A*16843009^S*65537^_*257^g*16843008,d[j]=T<<24|T>>>8,u[j]=T<<16|T>>>16,h[j]=T<<8|T>>>24,p[j]=T,g?(g=_^f[f[f[A^_]]],b^=f[f[b]]):g=b=1}}expandKey(t){const n=this.uint8ArrayToUint32Array_(t);let r=!0,a=0;for(;a{const o=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(o,n,r,a);const c=this.flush();c?i(c.buffer):l(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),n,r,a)}softwareDecrypt(t,n,r,a){const{currentIV:i,currentResult:l,remainderData:o}=this;if(a!==U4.cbc||n.byteLength!==16)return Lc.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=Qv(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 tin),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 sin(this.subtle,n,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Jan(this.subtle,new Uint8Array(r),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(Lc.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%rin;return r!==t.length&&(n=t.slice(0,r),this.remainderData=t.slice(r)),n}logOnce(t){this.logEnabled&&(Lc.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const jJe=Math.pow(2,17);class ain{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,n){const r=t.url;if(!r)return Promise.reject(new k2({type:fi.NETWORK_ERROR,details:Pn.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(g=>g[0]==="GAP")){c(kJe(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),u=NJe(t);t.loader=d;const h=_Je(a.fragLoadPolicy.default),p={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:jJe};t.stats=d.stats;const f={onSuccess:(g,b,v,j)=>{this.resetLoader(t,d);let _=g.data;v.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(_.slice(0,16)),_=_.slice(16)),o({frag:t,part:null,payload:_,networkDetails:j})},onError:(g,b,v,j)=>{this.resetLoader(t,d),c(new k2({type:fi.NETWORK_ERROR,details:Pn.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Ec({url:r,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:v,stats:j}))},onAbort:(g,b,v)=>{this.resetLoader(t,d),c(new k2({type:fi.NETWORK_ERROR,details:Pn.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:v,stats:g}))},onTimeout:(g,b,v)=>{this.resetLoader(t,d),c(new k2({type:fi.NETWORK_ERROR,details:Pn.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${p.timeout}ms`),networkDetails:v,stats:g}))}};n&&(f.onProgress=(g,b,v,j)=>n({frag:t,part:null,payload:v,networkDetails:j})),d.load(u,p,f)})}loadPart(t,n,r){this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap||n.gap){c(kJe(t,n));return}const d=this.loader=i?new i(a):new l(a),u=NJe(t,n);t.loader=d;const h=_Je(a.fragLoadPolicy.default),p={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:jJe};n.stats=d.stats,d.load(u,p,{onSuccess:(f,g,b,v)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,n);const j={frag:t,part:n,payload:f.data,networkDetails:v};r(j),o(j)},onError:(f,g,b,v)=>{this.resetLoader(t,d),c(new k2({type:fi.NETWORK_ERROR,details:Pn.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:n,response:Ec({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:b,stats:v}))},onAbort:(f,g,b)=>{t.stats.aborted=n.stats.aborted,this.resetLoader(t,d),c(new k2({type:fi.NETWORK_ERROR,details:Pn.INTERNAL_ABORTED,fatal:!1,frag:t,part:n,error:new Error("Aborted"),networkDetails:b,stats:f}))},onTimeout:(f,g,b)=>{this.resetLoader(t,d),c(new k2({type:fi.NETWORK_ERROR,details:Pn.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:n,error:new Error(`Timeout after ${p.timeout}ms`),networkDetails:b,stats:f}))}})})}updateStatsFromPart(t,n){const r=t.stats,a=n.stats,i=a.total;if(r.loaded+=a.loaded,i){const c=Math.round(t.duration/n.duration),d=Math.min(Math.round(r.loaded/i),c),h=(c-d)*Math.round(r.loaded/d);r.total=r.loaded+h}else r.total=Math.max(r.loaded,r.total);const l=r.loading,o=a.loading;l.start?l.first+=o.first-o.start:(l.start=o.start,l.first=o.first),l.end=o.end}resetLoader(t,n){t.loader=null,this.loader===n&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),n.destroy()}}function NJe(s,t=null){const n=t||s,r={frag:s,part:t,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},a=n.byteRangeStartOffset,i=n.byteRangeEndOffset;if(Fa(a)&&Fa(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&iin((l=s.decryptdata)==null?void 0:l.method)){const d=i-a;d%16&&(c=i+(16-d%16)),a!==0&&(r.resetIV=!0,o=a-16)}r.rangeStart=o,r.rangeEnd=c}return r}function kJe(s,t){const n=new Error(`GAP ${s.gap?"tag":"attribute"} found`),r={type:fi.MEDIA_ERROR,details:Pn.FRAG_GAP,fatal:!1,frag:s,error:n,networkDetails:null};return t&&(r.part=t),(t||s).stats.aborted=!0,new k2(r)}function iin(s){return s==="AES-128"||s==="AES-256"}class k2 extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class ukt extends a1{constructor(t,n){super(t,n),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class G8e{constructor(t,n,r,a=0,i=-1,l=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=UG(),this.buffering={audio:UG(),video:UG(),audiovideo:UG()},this.level=t,this.sn=n,this.id=r,this.size=a,this.part=i,this.partial=l}}function UG(){return{start:0,executeStart:0,executeEnd:0,end:0}}const SJe={length:0,start:()=>0,end:()=>0};class wo{static isBuffered(t,n){if(t){const r=wo.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=wo.getBuffered(t);return wo.timeRangesToArray(n)}return[]}static timeRangesToArray(t){const n=[];for(let r=0;r1&&t.sort((u,h)=>u.start-h.start||h.end-u.end);let a=-1,i=[];if(r)for(let u=0;u=t[u].start&&n<=t[u].end&&(a=u);const h=i.length;if(h){const p=i[h-1].end;t[u].start-pp&&(i[h-1].end=t[u].end):i.push(t[u])}else i.push(t[u])}else i=t;let l=0,o,c=n,d=n;for(let u=0;u=h&&n<=p&&(a=u),n+r>=h&&n{const a=r.substring(2,r.length-1),i=n==null?void 0:n[a];return i===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${a}"`)),r):i})}return t}function TJe(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 oin(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 lin=/^(\d+)x(\d+)$/,EJe=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Su{constructor(t,n){typeof t=="string"&&(t=Su.parseAttrList(t,n)),Yc(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=lin.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(EJe.lastIndex=0;(r=EJe.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=$Te(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":Lc.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const cin="com.apple.hls.interstitial";function din(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function uin(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class mkt{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]){Lc.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=Yc(new Su({}),i,t)}if(this.attr=t,n?(this._startDate=n._startDate,this._cue=n._cue,this._endDate=n._endDate,this._dateAtEnd=n._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const i=(n==null?void 0:n.endDate)||new Date(this.attr["END-DATE"]);Fa(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?(Lc.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(Fa(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===cin}get isValid(){return!!this.id&&!this._badValueForSameId&&Fa(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const hin=10;class min{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const n=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!n||!this.live,this.advanced=this.endSN>t.endSN||n>0||n===0&&r>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(n=>{let r=n.decryptdata;return r||(n.setKeyFormat(t.keyFormat),r=n.decryptdata),!!r&&t.matches(r)})}get hasProgramDateTime(){return this.fragments.length?Fa(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||hin}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 a0e(s,t){return s.length===t.length?!s.some((n,r)=>n!==t[r]):!1}function AJe(s,t){return!s&&!t?!0:!s||!t?!1:a0e(s,t)}function ZL(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function W8e(s){switch(s){case"AES-128":case"AES-256":return U4.cbc;case"AES-256-CTR":return U4.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function K8e(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function UTe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function pin(s){const t=UTe(s).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function pkt(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 fkt(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=K8e(l)):n=pin(l)}}return n}const i0e=typeof self<"u"?self:void 0;var Du={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},lf={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function mpe(s){switch(s){case lf.FAIRPLAY:return Du.FAIRPLAY;case lf.PLAYREADY:return Du.PLAYREADY;case lf.WIDEVINE:return Du.WIDEVINE;case lf.CLEARKEY:return Du.CLEARKEY}}function oke(s){switch(s){case Du.FAIRPLAY:return lf.FAIRPLAY;case Du.PLAYREADY:return lf.PLAYREADY;case Du.WIDEVINE:return lf.WIDEVINE;case Du.CLEARKEY:return lf.CLEARKEY}}function L7(s){const{drmSystems:t,widevineLicenseUrl:n}=s,r=t?[Du.FAIRPLAY,Du.WIDEVINE,Du.PLAYREADY,Du.CLEARKEY].filter(a=>!!t[a]):[];return!r[Du.WIDEVINE]&&n&&r.push(Du.WIDEVINE),r}const xkt=function(s){return i0e!=null&&(s=i0e.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function fin(s,t,n,r){let a;switch(s){case Du.FAIRPLAY:a=["cenc","sinf"];break;case Du.WIDEVINE:case Du.PLAYREADY:a=["cenc"];break;case Du.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return xin(a,t,n,r)}function xin(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 gin(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(n=>n==="persistent-license")))}function gkt(s){const t=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),n=String.fromCharCode.apply(null,Array.from(t)),r=n.substring(n.indexOf("<"),n.length),l=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(l){const o=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(o){const c=K8e(o).subarray(0,16);return pkt(c),c}}return null}let WI={};class N4{static clearKeyUriToKeyIdMap(){WI={}}static setKeyIdForUri(t,n){WI[t]=n}static addKeyIdForUri(t){const n=Object.keys(WI).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),WI[t]=r,r}constructor(t,n,r,a=[1],i=null,l){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=n,this.keyFormat=r,this.keyFormatVersions=a,this.iv=i,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!ZL(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(HNt(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&a0e(t.keyFormatVersions,this.keyFormatVersions)&&AJe(t.iv,this.iv)&&AJe(t.keyId,this.keyId)}isSupported(){if(this.method){if(ZL(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case lf.FAIRPLAY:case lf.WIDEVINE:case lf.PLAYREADY:case lf.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,n){if(!this.encrypted||!this.uri)return null;if(ZL(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Lc.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=vin(t)),new N4(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=WI[this.uri];if(i&&!a0e(this.keyId,i)&&N4.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=fkt(this.uri);if(r)switch(this.keyFormat){case lf.WIDEVINE:if(this.pssh=r,!this.keyId){const i=wan(r.buffer);if(i.length){var a;const l=i[0];this.keyId=(a=l.kids)!=null&&a.length?l.kids[0]:null}}this.keyId||(this.keyId=MJe(n));break;case lf.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=_an(i,null,r),this.keyId=gkt(r);break}default:{let i=r.subarray(0,16);if(i.length!==16){const l=new Uint8Array(16);l.set(i,16-i.length),i=l}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i;i=yin(n),i||(i=MJe(n),i||(i=WI[this.uri])),i&&(this.keyId=i,N4.setKeyIdForUri(this.uri,i))}return this}}function yin(s){const t=s==null?void 0:s[lf.WIDEVINE];return t?t.keyId:null}function MJe(s){const t=s==null?void 0:s[lf.PLAYREADY];if(t){const n=fkt(t.uri);if(n)return gkt(n)}return null}function vin(s){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=s>>8*(15-n)&255;return t}const IJe=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,PJe=/#EXT-X-MEDIA:(.*)/g,bin=/^#EXT(?:INF|-X-TARGETDURATION):/m,lke=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),_in=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class uw{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(PJe.lastIndex=0;(a=PJe.exec(t))!==null;){const d=new Su(a[1],r),u=d.TYPE;if(u){const h=o[u],p=i[u]||[];i[u]=p;const f=d.LANGUAGE,g=d["ASSOC-LANGUAGE"],b=d.CHANNELS,v=d.CHARACTERISTICS,j=d["INSTREAM-ID"],_={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?uw.resolve(d.URI,n):""};if(g&&(_.assocLang=g),b&&(_.channels=b),v&&(_.characteristics=v),j&&(_.instreamId=j),h!=null&&h.length){const S=uw.findGroup(h,_.groupId)||h[0];OJe(_,S,"audioCodec"),OJe(_,S,"textCodec")}p.push(_)}}return i}static parseLevelPlaylist(t,n,r,a,i,l){var o;const c={url:n},d=new min(n),u=d.fragments,h=[];let p=null,f=0,g=0,b=0,v=0,j=0,_=null,S=new rke(a,c),A,T,D,L=-1,M=!1,F=null,z;if(lke.lastIndex=0,d.m3u8=t,d.hasVariableRefs=CJe(t),((o=lke.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(A=lke.exec(t))!==null;){M&&(M=!1,S=new rke(a,c),S.playlistOffset=b,S.setStart(b),S.sn=f,S.cc=v,j&&(S.bitrate=j),S.level=r,p&&(S.initSegment=p,p.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),F&&(S.setByteRange(F),F=null)));const Y=A[1];if(Y){S.duration=parseFloat(Y);const ee=(" "+A[2]).slice(1);S.title=ee||null,S.tagList.push(ee?["INF",Y,ee]:["INF",Y])}else if(A[3]){if(Fa(S.duration)){S.playlistOffset=b,S.setStart(b),D&&zJe(S,D,d),S.sn=f,S.level=r,S.cc=v,u.push(S);const ee=(" "+A[3]).slice(1);S.relurl=$Te(d,ee),qTe(S,_,h),_=S,b+=S.duration,f++,g=0,M=!0}}else{if(A=A[0].match(_in),!A){Lc.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T0&&BJe(d,ee,A),f=d.startSN=parseInt(ne);break;case"SKIP":{d.skippedSegments&&m2(d,ee,A);const pe=new Su(ne,d),ce=pe.decimalInteger("SKIPPED-SEGMENTS");if(Fa(ce)){d.skippedSegments+=ce;for(let ie=ce;ie--;)u.push(null);f+=ce}const de=pe.enumeratedString("RECENTLY-REMOVED-DATERANGES");de&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(de.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&m2(d,ee,A),d.targetduration=Math.max(parseInt(ne),1);break;case"VERSION":d.version!==null&&m2(d,ee,A),d.version=parseInt(ne);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||m2(d,ee,A),d.live=!1;break;case"#":(ne||oe)&&S.tagList.push(oe?[ne,oe]:[ne]);break;case"DISCONTINUITY":v++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([ee]);break;case"BITRATE":S.tagList.push([ee,ne]),j=parseInt(ne)*1e3,Fa(j)?S.bitrate=j:j=0;break;case"DATERANGE":{const pe=new Su(ne,d),ce=new mkt(pe,d.dateRanges[pe.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ce.isValid||d.skippedSegments?d.dateRanges[ce.id]=ce:Lc.warn(`Ignoring invalid DATERANGE tag: "${ne}"`),S.tagList.push(["EXT-X-DATERANGE",ne]);break}case"DEFINE":{{const pe=new Su(ne,d);"IMPORT"in pe?oin(d,pe,l):TJe(d,pe,n)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?m2(d,ee,A):u.length>0&&BJe(d,ee,A),d.startCC=v=parseInt(ne);break;case"KEY":{const pe=LJe(ne,n,d);if(pe.isSupported()){if(pe.method==="NONE"){D=void 0;break}D||(D={});const ce=D[pe.keyFormat];ce!=null&&ce.matches(pe)||(ce&&(D=Yc({},D)),D[pe.keyFormat]=pe)}else Lc.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${ne}"`);break}case"START":d.startTimeOffset=DJe(ne);break;case"MAP":{const pe=new Su(ne,d);if(S.duration){const ce=new rke(a,c);FJe(ce,pe,r,D),p=ce,S.initSegment=p,p.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime)}else{const ce=S.byteRangeEndOffset;if(ce){const de=S.byteRangeStartOffset;F=`${ce-de}@${de}`}else F=null;FJe(S,pe,r,D),p=S,M=!0}p.cc=v;break}case"SERVER-CONTROL":{z&&m2(d,ee,A),z=new Su(ne),d.canBlockReload=z.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=z.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&z.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=z.optionalFloat("PART-HOLD-BACK",0),d.holdBack=z.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&m2(d,ee,A);const pe=new Su(ne);d.partTarget=pe.decimalFloatingPoint("PART-TARGET");break}case"PART":{let pe=d.partList;pe||(pe=d.partList=[]);const ce=g>0?pe[pe.length-1]:void 0,de=g++,ie=new Su(ne,d),ye=new oan(ie,S,c,de,ce);pe.push(ye),S.duration+=ye.duration;break}case"PRELOAD-HINT":{const pe=new Su(ne,d);d.preloadHint=pe;break}case"RENDITION-REPORT":{const pe=new Su(ne,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(pe);break}default:Lc.warn(`line parsed but not handled: ${A}`);break}}}_&&!_.relurl?(u.pop(),b-=_.duration,d.partList&&(d.fragmentHint=_)):d.partList&&(qTe(S,_,h),S.cc=v,d.fragmentHint=S,D&&zJe(S,D,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const V=u.length,W=u[0],K=u[V-1];if(b+=d.skippedSegments*d.targetduration,b>0&&V&&K){d.averagetargetduration=b/V;const Y=K.sn;d.endSN=Y!=="initSegment"?Y:0,d.live||(K.endList=!0),L>0&&(jin(u,L),W&&h.unshift(W))}return d.fragmentHint&&(b+=d.fragmentHint.duration),d.totalduration=b,h.length&&d.dateRangeTagCount&&W&&ykt(h,d),d.endCC=v,d}}function ykt(s,t){let n=s.length;if(!n)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];s.push(o),n++}else return;const r=s[n-1],a=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let o=i.length;o--;){const c=t.dateRanges[i[o]],d=c.startDate.getTime();c.tagAnchor=r.ref;for(let u=n;u--;){var l;if(((l=s[u])==null?void 0:l.sn)=o||r===0){var l;const c=(((l=n[r+1])==null?void 0:l.start)||a)-i.start;if(t<=o+c*1e3){const d=n[r].sn-s.startSN;if(d<0)return-1;const u=s.fragments;if(u.length>n.length){const p=(n[r+1]||u[u.length-1]).sn-s.startSN;for(let f=p;f>d;f--){const g=u[f].programDateTime;if(t>=g&&tr);["video","audio","text"].forEach(r=>{const a=n.filter(i=>U8e(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 OJe(s,t,n){const r=t[n];r&&(s[n]=r)}function jin(s,t){let n=s[t];for(let r=t;r--;){const a=s[r];if(!a)return;a.programDateTime=n.programDateTime-a.duration*1e3,n=a}}function qTe(s,t,n){s.rawProgramDateTime?n.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function FJe(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 zJe(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 m2(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function BJe(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function cke(s,t){const n=t.startPTS;if(Fa(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 vkt(s,t,n,r,a,i,l){r-n<=0&&(l.warn("Fragment should have a positive duration",t),r=n+t.duration,i=a+t.duration);let c=n,d=r;const u=t.startPTS,h=t.endPTS;if(Fa(u)){const j=Math.abs(u-n);s&&j>s.totalduration?l.warn(`media timestamps and playlist times differ by ${j}s for level ${t.level} ${s.url}`):Fa(t.deltaPTS)?t.deltaPTS=Math.max(j,t.deltaPTS):t.deltaPTS=j,c=Math.max(n,u),n=Math.min(n,u),a=t.startDTS!==void 0?Math.min(a,t.startDTS):a,d=Math.min(r,h),r=Math.max(r,h),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const p=n-t.start;t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=c,t.startDTS=a,t.endPTS=r,t.minEndPTS=d,t.endDTS=i;const f=t.sn;if(!s||fs.endSN)return 0;let g;const b=f-s.startSN,v=s.fragments;for(v[b]=t,g=b;g>0;g--)cke(v[g],v[g-1]);for(g=b;g=0;u--){const h=a[u].initSegment;if(h){r=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;Cin(s,t,(u,h,p,f)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==u.cc){const g=u.cc-h.cc;for(let b=p;b{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=kin(s.dateRanges,t,n));const u=s.fragments.filter(h=>h.rawProgramDateTime);if(s.hasProgramDateTime&&!t.hasProgramDateTime)for(let h=1;h{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats}),i?vkt(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,n):bkt(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 kin(s,t,n){const{dateRanges:r,recentlyRemovedDateranges:a}=t,i=Yc({},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 mkt(r[c].attr,d);u.isValid?(i[c]=u,d||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${id(r[c].attr)}"`)}),i):r}function Sin(s,t,n){if(s&&t){let r=0;for(let a=0,i=s.length;a<=i;a++){const l=s[a],o=t[a+r];l&&o&&l.index===o.index&&l.fragment.sn===o.fragment.sn?n(l,o):r--}}}function Cin(s,t,n){const r=t.skippedSegments,a=Math.max(s.startSN,t.startSN)-t.startSN,i=(s.fragmentHint?1:0)+(r?t.endSN:Math.min(s.endSN,t.endSN))-t.startSN,l=t.startSN-s.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=a;d<=i;d++){const u=c[l+d];let h=o[d];if(r&&!h&&u&&(h=t.fragments[d]=u),u&&h){n(u,h,d,o);const p=u.relurl,f=h.relurl;if(p&&Tin(p,f)){t.playlistParsingError=$Je(`media sequence mismatch ${h.sn}:`,s,t,u,h);return}else if(u.cc!==h.cc){t.playlistParsingError=$Je(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,s,t,u,h);return}}}}function $Je(s,t,n,r,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${n.startSN} ${n.m3u8}`)}function bkt(s,t,n=!0){const r=t.startSN+t.skippedSegments-s.startSN,a=s.fragments,i=r>=0;let l=0;if(i&&rt){const i=r[r.length-1].duration*1e3;i{var r;(r=t.details)==null||r.fragments.forEach(a=>{a.level=n,a.initSegment&&(a.initSegment.level=n)})})}function Tin(s,t){return s!==t&&t?qJe(s)!==qJe(t):!1}function qJe(s){return s.replace(/\?[^?]*$/,"")}function Lz(s,t){for(let r=0,a=s.length;rs.startCC)}function VJe(s,t){const n=s.start+t;s.startPTS=n,s.setStart(n),s.endPTS=n+s.duration}function kkt(s,t){const n=t.fragments;for(let r=0,a=n.length;r{const{config:l,fragCurrent:o,media:c,mediaBuffer:d,state:u}=this,h=c?c.currentTime:0,p=wo.bufferInfo(d||c,h,l.maxBufferHole),f=!p.len;if(this.log(`Media seeking to ${Fa(h)?h.toFixed(3):h}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===ur.ENDED)this.resetLoadingState();else if(o){const g=l.maxFragLookUpTolerance,b=o.start-g,v=o.start+o.duration+g;if(f||vp.end){const j=h>v;(hg&&(this.lastCurrentTime=h),!this.loadingParts){const b=Math.max(p.end,h),v=this.shouldLoadParts(this.getLevelDetails(),b);v&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${b.toFixed(2)}`),this.loadingParts=v)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,f&&(this.startPosition=h)),f&&this.state===ur.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 ain(t.config),this.keyLoader=r,this.fragmentTracker=n,this.config=t.config,this.decrypter=new H8e(t.config)}registerListeners(){const{hls:t}=this;t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_t.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===ur.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ur.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:n}=this;return n===-1&&t?t:n}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,n){if(n.live||!this.media)return!1;const r=t.end||0,a=this.config.timelineOffset||0;if(r<=a)return!1;const i=t.buffered;this.config.maxBufferHole&&i&&i.length>1&&(t=wo.bufferedInfo(i,t.start,0));const l=t.nextStart;if(l&&l>a&&l{const l=i.frag;if(this.fragContextChanged(l)){this.warn(`${l.type} sn: ${l.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(l,!1,i.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(l);return}l.stats.chunkCount++,this._handleFragmentLoadProgress(i)};this._doFragLoad(t,n,r,a).then(i=>{if(!i)return;const l=this.state,o=i.frag;if(this.fragContextChanged(o)){(l===ur.FRAG_LOADING||!this.fragCurrent&&l===ur.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=ur.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(_t.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===ur.STOPPED||this.state===ur.ERROR||(this.warn(`Frag error: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var n;const{fragmentTracker:r}=this;if(r.getState(t)===Dm.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)===Dm.PARTIAL&&r.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const n=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:n,part:null,stats:n.stats,id:n.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const n=t.details;return(n==null?void 0:n.live)&&n.type!=="EVENT"&&(this.levelLastLoaded!==t||n.expired)}flushMainBuffer(t,n,r=null){if(!(t-n))return;const a={startOffset:t,endOffset:n,type:r};this.hls.trigger(_t.BUFFER_FLUSHING,a)}_loadInitSegment(t,n){this._doFragLoad(t,n).then(r=>{const a=r==null?void 0:r.frag;if(!a||this.fragContextChanged(a)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:a}=this,{frag:i,payload:l}=r,o=i.decryptdata;if(l&&l.byteLength>0&&o!=null&&o.key&&o.iv&&ZL(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,W8e(o.method)).catch(d=>{throw a.trigger(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const u=self.performance.now();return a.trigger(_t.FRAG_DECRYPTED,{frag:i,payload:d,stats:{tstart:c,tdecrypt:u}}),r.payload=d,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===ur.STOPPED||this.state===ur.ERROR||(this.warn(r),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:n}=this;if(!n)throw new Error("init load aborted, missing levels");const r=t.frag.stats;this.state!==ur.STOPPED&&(this.state=ur.IDLE),t.frag.data=new Uint8Array(t.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,n){var r,a;const i=t.tracks;if(i&&!n.encrypted&&((r=i.audio)!=null&&r.encrypted||(a=i.video)!=null&&a.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const l=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(n)} (media ${l?"attached mediaKeys: "+l.mediaKeys:"detached"})`);return this.warn(o.message),!l||l.mediaKeys?!1:(this.hls.trigger(_t.ERROR,{type:fi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:n}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:n}=this;return!t||!n||t.sn!==n.sn||t.level!==n.level}fragBufferedComplete(t,n){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)} > buffer:${r?Min.toString(wo.getBuffered(r)):"(detached)"})`),Mh(t)){var a;if(t.type!==Qa.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=ur.IDLE;return}}const i=(a=this.levels)==null?void 0:a[t.level];i!=null&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=ur.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:n}=this;if(!n)return;const{frag:r,part:a,partsLoaded:i}=t,l=!i||i.length===0||i.some(c=>!c),o=new G8e(r.level,r.sn,r.stats.chunkCount+1,0,a?a.index:-1,!l);n.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,n,r=null,a){var i;this.fragCurrent=t;const l=n.details;if(!this.levels||!l)throw new Error(`frag load aborted, missing level${l?"":" detail"}s`);let o=null;if(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${t.sn} of [${l.startSN}-${l.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=ur.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(p=>{if(!this.fragContextChanged(p.frag))return this.hls.trigger(_t.KEY_LOADED,p),this.state===ur.KEY_LOADING&&(this.state=ur.IDLE),p}),this.hls.trigger(_t.KEY_LOADING,{frag:t}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else t.encrypted||(o=this.keyLoader.loadClear(t,l.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(Mh(t)&&(!c||t.sn!==c.sn)){const p=this.shouldLoadParts(n.details,t.end);p!==this.loadingParts&&(this.log(`LL-Part loading ${p?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${t.sn}`),this.loadingParts=p)}if(r=Math.max(t.start,r||0),this.loadingParts&&Mh(t)){const p=l.partList;if(p&&a){r>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const f=this.getNextPart(p,t,r);if(f>-1){const g=p[f];t=this.fragCurrent=g.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${g.index} (${f}/${p.length-1}) of ${this.fragInfo(t,!1,g)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=ur.FRAG_LOADING;let b;return o?b=o.then(v=>!v||this.fragContextChanged(v.frag)?null:this.doFragPartsLoad(t,g,n,a)).catch(v=>this.handleFragLoadError(v)):b=this.doFragPartsLoad(t,g,n,a).catch(v=>this.handleFragLoadError(v)),this.hls.trigger(_t.FRAG_LOADING,{frag:t,part:g,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):b}else if(!t.url||this.loadedEndOfParts(p,r))return Promise.resolve(null)}}if(Mh(t)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${(d=l.partList)==null?void 0:d.filter(p=>p.loaded).map(p=>`[${p.start}-${p.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+l.startSN+"-"+l.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),Fa(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ur.FRAG_LOADING;const u=this.config.progressive&&t.type!==Qa.SUBTITLE;let h;return u&&o?h=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.fragmentLoader.load(t,a)).catch(p=>this.handleFragLoadError(p)):h=Promise.all([this.fragmentLoader.load(t,u?a:void 0),o]).then(([p])=>(!u&&a&&a(p),p)).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(_t.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,n,r,a){return new Promise((i,l)=>{var o;const c=[],d=(o=r.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(t,h,a).then(p=>{c[h.index]=p;const f=p.part;this.hls.trigger(_t.FRAG_LOADED,p);const g=UJe(r.details,t.sn,h.index+1)||jkt(d,t.sn,h.index+1);if(g)u(g);else return i({frag:t,part:f,partsLoaded:c})}).catch(l)};u(n)})}handleFragLoadError(t){if("data"in t){const n=t.data;n.frag&&n.details===Pn.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===fi.KEY_SYSTEM_ERROR?(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)):this.hls.trigger(_t.ERROR,n)}else this.hls.trigger(_t.ERROR,{type:fi.OTHER_ERROR,details:Pn.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const n=this.getCurrentContext(t);if(!n||this.state!==ur.PARSING){!this.fragCurrent&&this.state!==ur.STOPPED&&this.state!==ur.ERROR&&(this.state=ur.IDLE);return}const{frag:r,part:a,level:i}=n,l=self.performance.now();r.stats.parsing.end=l,a&&(a.stats.parsing.end=l);const o=this.getLevelDetails(),d=o&&r.sn>o.endSN||this.shouldLoadParts(o,r.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(r,a,i,t.partial)}shouldLoadParts(t,n){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var r;const i=t.partList[0];if(i.fragment.type===Qa.SUBTITLE)return!1;const l=i.end+(((r=t.fragmentHint)==null?void 0:r.duration)||0);if(n>=l){var a;if((this.hls.hasEnoughToStart?((a=this.media)==null?void 0:a.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:n,fragCurrent:r}=this,{level:a,sn:i,part:l}=t;if(!(n!=null&&n[a]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${a}. The current chunk will not be buffered.`),null;const o=n[a],c=o.details,d=l>-1?UJe(c,i,l):null,u=d?d.fragment:wkt(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!==ur.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=Qv(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(_t.BUFFER_APPENDING,h),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(n)}}flushBufferGap(t){const n=this.media;if(!n)return;if(!wo.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,t.start);return}const r=n.currentTime,a=wo.bufferInfo(n,r,0),i=t.duration,l=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(t.start-l,a.end-l),r+l);t.start-o>l&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,n){var r;const a=this.getLoadPosition();if(!Fa(a))return null;const l=this.lastCurrentTime>a||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,a,n,l)}getFwdBufferInfoAtPos(t,n,r,a){const i=wo.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 wo.bufferInfo(t,n,o)}}return i}getMaxBufferLength(t){const{config:n}=this;let r;return t?r=Math.max(8*n.maxBufferSize/t,n.maxBufferLength):r=n.maxBufferLength,Math.min(r,n.maxMaxBufferLength)}exceedsMaxBuffer(t,n,r){const a=t.nextStart;if(a&&r.start>a){const i=t.buffered;if(i){let l=t.len;const o=t.bufferedIndex;for(let c=i.length-1;c>o;c--)i[c].start=n}}return!1}reduceMaxBufferLength(t,n){const r=this.config,a=Math.max(Math.min(t-n,r.maxBufferLength),n),i=Math.max(t-n*3,r.maxMaxBufferLength/2,a);return i>=a?(r.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(t,n=Qa.MAIN){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,n):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(t,n){const r=n.fragments,a=r.length;if(!a)return null;const{config:i}=this,l=n.fragmentStart,o=i.lowLatencyMode&&!!n.partList;let c=null;if(n.live){const h=i.initialLiveManifestSize;if(a=l?(v=f,j=f===p?"config":"next load start"):g!==null?(v=g,j="live edge"):(v=t,j="buffer pos"),v=i){const c=l.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${a}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,l}get primaryPrefetch(){if(HJe(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(HJe(this.config)&&t.type!==Qa.SUBTITLE){const r=this.hls.interstitialsManager,a=r==null?void 0:r.bufferingItem;if(a){const l=a.event;if(l){if(l.appendInPlace||Math.abs(t.start-a.start)>1||a.start===0)return null}else if(t.end<=a.start&&(n==null?void 0:n.live)===!1||t.start>a.end&&a.nextEvent&&(a.nextEvent.appendInPlace||t.start-a.end>1))return null}const i=r==null?void 0:r.playerQueue;if(i)for(let l=i.length;l--;){const o=i[l].interstitial;if(o.appendInPlace&&t.start>=o.startTime&&t.end<=o.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return t!=null&&t.initSegment&&!t.initSegment.data&&!this.bitrateTest?t.initSegment:t}getNextPart(t,n,r){let a=-1,i=!1,l=!0;for(let o=0,c=t.length;o-1&&rr.start)return!0}return!1}getInitialLiveFragment(t){const n=t.fragments,r=this.fragPrevious;let a=null;if(r){if(t.hasProgramDateTime&&(a=Wan(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=lkt(t,r.cc,r.end),a&&this.log(`Live playlist, switching playlist, load frag with same CC: ${a.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(a=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return a}getFragmentAtPosition(t,n,r){const{config:a}=this;let{fragPrevious:i}=this,{fragments:l,endSN:o}=r;const{fragmentHint:c}=r,{maxFragLookUpTolerance:d}=a,u=r.partList,h=!!(this.loadingParts&&u!=null&&u.length&&c);h&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(l=l.concat(c),o=c.sn);let p;if(tn-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;p=BM(i,l,t,b)}else p=l[l.length-1];if(p){const g=p.sn-r.startSN,b=this.fragmentTracker.getState(p);if((b===Dm.OK||b===Dm.PARTIAL&&p.gap)&&(i=p),i&&p.sn===i.sn&&(!h||u[0].fragment.sn>p.sn||!r.live)&&p.level===i.level){const j=l[g+1];p.sn${t.startSN} fragments: ${a}`),c}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,n){let r=this.startPosition;r=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(t,n){this.transmuxer&&t.type===this.playlistType&&Mh(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!==ur.FRAG_LOADING_WAITING_RETRY)&&(this.state=ur.IDLE)}onFragmentOrKeyLoadError(t,n){var r;if(n.chunkMeta&&!n.frag){const j=this.getCurrentContext(n.chunkMeta);j&&(n.frag=j.frag)}const a=n.frag;if(!a||a.type!==t||!this.levels)return;if(this.fragContextChanged(a)){var i;this.warn(`Frag load error must match current frag to retry ${a.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const l=n.details===Pn.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=n.errorAction;if(!o){this.state=ur.ERROR;return}const{action:c,flags:d,retryCount:u=0,retryConfig:h}=o,p=!!h,f=p&&c===nf.RetryRequest,g=p&&!o.resolved&&d===$0.MoveAllAlternatesMatchingHost,b=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!f&&g&&Mh(a)&&!a.endList&&b&&!dkt(n))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((f||g)&&u=n||r&&!BTe(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=ur.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===ur.PARSING||this.state===ur.PARSED){const n=t.frag,r=t.parent,a=this.getFwdBufferInfo(this.mediaBuffer,r),i=a&&a.len>.5;i&&this.reduceMaxBufferLength(a.len,(n==null?void 0:n.duration)||10);const l=!i;return l&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),n&&(this.fragmentTracker.removeFragment(n),this.nextLoadPosition=n.start),this.resetLoadingState(),l}return!1}resetFragmentErrors(t){t===Qa.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ur.STOPPED&&(this.state=ur.IDLE)}afterBufferFlushed(t,n,r){if(!t)return;const a=wo.getBuffered(t);this.fragmentTracker.detectEvictedFragments(n,a,r),this.state===ur.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ur.STOPPED&&(this.state=ur.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,n=t?t.details:null;n!=null&&n.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(n,n.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level===-1?"":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,n,r,a){const i=r.details;if(!i){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((c,d)=>{const u=t.elementaryStreams[d];if(u){const h=u.endPTS-u.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${t.sn} ${d} duration reliably (${h})`),c||!1;const p=a?0:vkt(i,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(_t.LEVEL_PTS_UPDATED,{details:i,level:r,drift:p,type:d,frag:t,start:u.startPTS,end:u.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((r.fragmentError===0||c&&(r.fragmentError<2||t.endList))&&this.treatAsGap(t,r),c){const d=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=ur.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)})`),this.hls.trigger(_t.FRAG_PARSED,{frag:t,part:n})}playlistLabel(){return this.playlistType===Qa.MAIN?"level":"track"}fragInfo(t,n=!0,r){var a,i;return`${this.playlistLabel()} ${t.level} (${r?"part":"frag"}:[${((a=n&&!r?t.startPTS:(r||t).start)!=null?a:NaN).toFixed(3)}-${((i=n&&!r?t.endPTS:(r||t).end)!=null?i:NaN).toFixed(3)}]${r&&t.type==="main"?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(t,n){n&&n.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;(t=this.transmuxer)==null||t.reset()}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const n=this._state;n!==t&&(this._state=t,this.log(`${n}->${t}`))}get state(){return this._state}}function HJe(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class Ckt{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:n}=this;let r;if(t.length)t.length===1?r=t[0]:r=Iin(t,n);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function Iin(s,t){const n=new Uint8Array(t);let r=0;for(let a=0;a0)return s.subarray(n,n+r)}function zin(s,t,n,r){const a=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=t[n+2],l=i>>2&15;if(l>12){const f=new Error(`invalid ADTS sampling index:${l}`);s.emit(_t.ERROR,_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(i>>6&3)+1,c=t[n+3]>>6&3|(i&1)<<2,d="mp4a.40."+o,u=a[l];let h=l;(o===5||o===29)&&(h-=3);const p=[o<<3|(h&14)>>1,(h&1)<<7|c<<3];return Lc.log(`manifest codec:${r}, parsed codec:${d}, channels:${c}, rate:${u} (ADTS object type:${o} sampling index:${l})`),{config:p,samplerate:u,channelCount:c,codec:d,parsedCodec:d,manifestCodec:r}}function Ekt(s,t){return s[t]===255&&(s[t+1]&246)===240}function Akt(s,t){return s[t+1]&1?7:9}function X8e(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function Bin(s,t){return t+5=s.length)return!1;const r=X8e(s,t);if(r<=n)return!1;const a=t+r;return a===s.length||l0e(s,a)}return!1}function Mkt(s,t,n,r,a){if(!s.samplerate){const i=zin(t,n,r,a);if(!i)return;Yc(s,i)}}function Ikt(s){return 1024*9e4/s}function qin(s,t){const n=Akt(s,t);if(t+n<=s.length){const r=X8e(s,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function Pkt(s,t,n,r,a){const i=Ikt(s.samplerate),l=r+a*i,o=qin(t,n);let c;if(o){const{frameLength:h,headerLength:p}=o,f=p+h,g=Math.max(0,n+f-t.length);g?(c=new Uint8Array(f-p),c.set(t.subarray(n+p,t.length),0)):c=t.subarray(n+p,n+f);const b={unit:c,pts:l};return g||s.samples.push(b),{sample:b,length:f,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}}function Vin(s,t){return Q8e(s,t)&&pbe(s,t+6)+10<=s.length-t}function Hin(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function uke(s,t=0,n=1/0){return Gin(s,t,n,Uint8Array)}function Gin(s,t,n,r){const a=Win(s);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const l=Kin(s)?s.byteOffset:0,o=(l+s.byteLength)/i,c=(l+t)/i,d=Math.floor(Math.max(0,Math.min(c,o))),u=Math.floor(Math.min(d+Math.max(n,0),o));return new r(a,d,u-d)}function Win(s){return s instanceof ArrayBuffer?s:s.buffer}function Kin(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function Yin(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=vy(uke(s.data,1,r)),i=s.data[2+r],l=s.data.subarray(3+r).indexOf(0);if(l===-1)return;const o=vy(uke(s.data,3+r,l));let c;return a==="-->"?c=vy(uke(s.data,4+r+l)):c=Hin(s.data.subarray(4+r+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function Zin(s){if(s.size<2)return;const t=vy(s.data,!0),n=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:n.buffer}}function Qin(s){if(s.size<2)return;if(s.type==="TXXX"){let n=1;const r=vy(s.data.subarray(n),!0);n+=r.length+1;const a=vy(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=vy(s.data.subarray(1));return{key:s.type,info:"",data:t}}function Xin(s){if(s.type==="WXXX"){if(s.size<2)return;let n=1;const r=vy(s.data.subarray(n),!0);n+=r.length+1;const a=vy(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=vy(s.data);return{key:s.type,info:"",data:t}}function Jin(s){return s.type==="PRIV"?Zin(s):s.type[0]==="W"?Xin(s):s.type==="APIC"?Yin(s):Qin(s)}function eon(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),n=pbe(s,4),r=10;return{type:t,size:n,data:s.subarray(r,r+n)}}const qG=10,ton=10;function Lkt(s){let t=0;const n=[];for(;Q8e(s,t);){const r=pbe(s,t+6);s[t+5]>>6&1&&(t+=qG),t+=qG;const a=t+r;for(;t+ton0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Z0.audioId3,duration:Number.POSITIVE_INFINITY});a{if(Fa(s))return s*90;const r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r};let VG=null;const ron=[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],aon=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ion=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],oon=[0,1,1,4];function Rkt(s,t,n,r,a){if(n+24>t.length)return;const i=Okt(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 Okt(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=ron[c*14+a-1]*1e3,h=aon[(n===3?0:n===2?1:2)*3+i],p=o===3?1:2,f=ion[n][r],g=oon[r],b=f*8*g,v=Math.floor(f*d/h+l)*g;if(VG===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);VG=S?parseInt(S[1]):0}return!!VG&&VG<=87&&r===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:h,channelCount:p,frameLength:v,samplesPerFrame:b}}}function tDe(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function Fkt(s,t){return t+1{let n=0,r=5;t+=r;const a=new Uint32Array(1),i=new Uint32Array(1),l=new Uint8Array(1);for(;r>0;){l[0]=s[t];const o=Math.min(r,8),c=8-o;i[0]=4278190080>>>24+c<>c,n=n?n<t.length||t[n]!==11||t[n+1]!==119)return-1;const i=t[n+4]>>6;if(i>=3)return-1;const o=[48e3,44100,32e3][i],c=t[n+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+i]*2;if(n+u>t.length)return-1;const h=t[n+6]>>5;let p=0;h===2?p+=2:(h&1&&h!==1&&(p+=2),h&4&&(p+=2));const f=(t[n+6]<<8|t[n+7])>>12-p&1,b=[2,1,2,3,3,4,4,5][h]+f,v=t[n+5]>>3,j=t[n+5]&7,_=new Uint8Array([i<<6|v<<1|j>>2,(j&3)<<6|h<<3|f<<2|c>>4,c<<4&224]),S=1536/o*9e4,A=r+a*S,T=t.subarray(n,n+u);return s.config=_,s.channelCount=b,s.samplerate=o,s.samples.push({unit:T,pts:A}),u}class uon extends eDe{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=T$(t,0);let r=(n==null?void 0:n.length)||0;if(n&&t[r]===11&&t[r+1]===119&&J8e(n)!==void 0&&Bkt(t,r)<=16)return!1;for(let a=t.length;r{const l=van(i);if(hon.test(l.schemeIdUri)){const o=WJe(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:Z0.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=WJe(l,n);r.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:Z0.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(t,n,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function WJe(s,t){return Fa(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class pon{constructor(t,n,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new H8e(n,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,U4.cbc)}decryptAacSample(t,n,r){const a=t[n].unit;if(a.length<=16)return;const i=a.subarray(16,a.length-a.length%16),l=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(l).then(o=>{const c=new Uint8Array(o);a.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(t,n+1,r)}).catch(r)}decryptAacSamples(t,n,r){for(;;n++){if(n>=t.length){r();return}if(!(t[n].unit.length<32)&&(this.decryptAacSample(t,n,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const n=Math.floor((t.length-48)/160)*16+16,r=new Int8Array(n);let a=0;for(let i=32;i{i.data=this.getAvcDecryptedUnit(l,c),this.decrypter.isSync()||this.decryptAvcSamples(t,n,r+1,a)}).catch(a)}decryptAvcSamples(t,n,r,a){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;n++,r=0){if(n>=t.length){a();return}const i=t[n].units;for(;!(r>=i.length);r++){const l=i[r];if(!(l.data.length<=48||l.type!==1&&l.type!==5)&&(this.decryptAvcSample(t,n,r,a,l),!this.decrypter.isSync()))return}}}}class Ukt{constructor(){this.VideoSample=null}createVideoSample(t,n,r){return{key:t,frame:!1,pts:n,dts:r,units:[],length:0}}getLastNalUnit(t){var n;let r=this.VideoSample,a;if((!r||r.units.length===0)&&(r=t[t.length-1]),(n=r)!=null&&n.units){const i=r.units;a=i[i.length-1]}return a}pushAccessUnit(t,n){if(t.units.length&&t.frame){if(t.pts===void 0){const r=n.samples,a=r.length;if(a){const i=r[a-1];t.pts=i.pts,t.dts=i.dts}else{n.dropped++;return}}n.samples.push(t)}}parseNALu(t,n,r){const a=n.byteLength;let i=t.naluState||0;const l=i,o=[];let c=0,d,u,h,p=-1,f=0;for(i===-1&&(p=0,f=this.getNALuType(n,0),i=0,c=1);c=0){const g={data:n.subarray(p,u),type:f};o.push(g)}else{const g=this.getLastNalUnit(t.samples);g&&(l&&c<=4-l&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-l)),u>0&&(g.data=Qv(g.data,n.subarray(0,u)),g.state=0))}c=0&&i>=0){const g={data:n.subarray(p,a),type:f,state:i};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(t.samples);g&&(g.data=Qv(g.data,n))}return t.naluState=i,o}}class Dz{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&&Lc.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=n,this.bitsAvailable>0)this.word<<=n;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return n=t-n,n>0&&this.bitsAvailable?r<>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class fon extends Ukt{parsePES(t,n,r,a){const i=this.parseNALu(t,r.data,a);let l=this.VideoSample,o,c=!1;r.data=null,l&&i.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),i.forEach(d=>{var u,h;switch(d.type){case 1:{let b=!1;o=!0;const v=d.data;if(c&&v.length>4){const j=this.readSliceType(v);(j===2||j===4||j===7||j===9)&&(b=!0)}if(b){var p;(p=l)!=null&&p.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.frame=!0,l.key=b;break}case 5:o=!0,(u=l)!=null&&u.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0,l.frame=!0;break;case 6:{o=!0,$8e(d.data,1,r.pts,n.samples);break}case 7:{var f,g;o=!0,c=!0;const b=d.data,v=this.readSPS(b);if(!t.sps||t.width!==v.width||t.height!==v.height||((f=t.pixelRatio)==null?void 0:f[0])!==v.pixelRatio[0]||((g=t.pixelRatio)==null?void 0:g[1])!==v.pixelRatio[1]){t.width=v.width,t.height=v.height,t.pixelRatio=v.pixelRatio,t.sps=[b];const j=b.subarray(1,4);let _="avc1.";for(let S=0;S<3;S++){let A=j[S].toString(16);A.length<2&&(A="0"+A),_+=A}t.codec=_}break}case 8:o=!0,t.pps=[d.data];break;case 9:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:o=!0;break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,n){return t[n]&31}readSliceType(t){const n=new Dz(t);return n.readUByte(),n.readUEG(),n.readUEG()}skipScalingList(t,n){let r=8,a=8,i;for(let l=0;l{var u,h;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),l.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var p;(p=l)!=null&&p.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:o=!0,(u=l)!=null&&u.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0,l.frame=!0;break;case 39:o=!0,$8e(d.data,2,r.pts,n.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=Yc(t.params,this.readVPS(d.data)),this.initVPS=d.data),t.vps=[d.data];break;case 33:if(o=!0,c=!0,t.vps!==void 0&&t.vps[0]!==this.initVPS&&t.sps!==void 0&&!this.matchSPS(t.sps[0],d.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const f=this.readSPS(d.data);t.width=f.width,t.height=f.height,t.pixelRatio=f.pixelRatio,t.codec=f.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const g in f.params)t.params[g]=f.params[g]}this.pushParameterSet(t.sps,d.data,t.vps),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const f=this.readPPS(d.data);for(const g in f)t.params[g]=f[g]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,n,r){(r&&r[0]===this.initVPS||!r&&!t.length)&&t.push(n)}getNALuType(t,n){return(t[n]&126)>>>1}ebsp2rbsp(t){const n=new Uint8Array(t.byteLength);let r=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(n[r]=t[a],r++);return new Uint8Array(n.buffer,0,r)}pushAccessUnit(t,n){super.pushAccessUnit(t,n),this.initVPS&&(this.initVPS=null)}readVPS(t){const n=new Dz(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 Dz(this.ebsp2rbsp(t));n.readUByte(),n.readUByte(),n.readBits(4);const r=n.readBits(3);n.readBoolean();const a=n.readBits(2),i=n.readBoolean(),l=n.readBits(5),o=n.readUByte(),c=n.readUByte(),d=n.readUByte(),u=n.readUByte(),h=n.readUByte(),p=n.readUByte(),f=n.readUByte(),g=n.readUByte(),b=n.readUByte(),v=n.readUByte(),j=n.readUByte(),_=[],S=[];for(let Ne=0;Ne0)for(let Ne=r;Ne<8;Ne++)n.readBits(2);for(let Ne=0;Ne1&&n.readEG();for(let rt=0;rt0&&tt<16?(ye=at[tt-1],_e=Ge[tt-1]):tt===255&&(ye=n.readBits(16),_e=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(),Ee=n.readBoolean(),Ee&&(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG()),n.readBoolean()&&(Te=n.readBits(32),Ce=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const Ge=n.readBoolean(),dt=n.readBoolean();let Bt=!1;(Ge||dt)&&(Bt=n.readBoolean(),Bt&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),Bt&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let kt=0;kt<=r;kt++){Me=n.readBoolean();const Qt=Me||n.readBoolean();let ns=!1;Qt?n.readEG():ns=n.readBoolean();const $s=ns?1:n.readUEG()+1;if(Ge)for(let Ds=0;Ds<$s;Ds++)n.readUEG(),n.readUEG(),Bt&&(n.readUEG(),n.readUEG()),n.skipBits(1);if(dt)for(let Ds=0;Ds<$s;Ds++)n.readUEG(),n.readUEG(),Bt&&(n.readUEG(),n.readUEG()),n.skipBits(1)}}n.readBoolean()&&(n.readBoolean(),n.readBoolean(),n.readBoolean(),ie=n.readUEG())}let Ie=T,Fe=D;if(L){let Ne=1,He=1;A===1?Ne=He=2:A==2&&(Ne=2),Ie=T-Ne*F-Ne*M,Fe=D-He*V-He*z}const qe=a?["A","B","C"][a]:"",ve=o<<24|c<<16|d<<8|u;let Je=0;for(let Ne=0;Ne<32;Ne++)Je=(Je|(ve>>Ne&1)<<31-Ne)>>>0;let we=Je.toString(16);return l===1&&we==="2"&&(we="6"),{codecString:`hvc1.${qe}${l}.${we}.${i?"H":"L"}${j}.B0`,params:{general_tier_flag:i,general_profile_idc:l,general_profile_space:a,general_profile_compatibility_flags:[o,c,d,u],general_constraint_indicator_flags:[h,p,f,g,b,v],general_level_idc:j,bit_depth:W+8,bit_depth_luma_minus8:W,bit_depth_chroma_minus8:K,min_spatial_segmentation_idc:ie,chroma_format_idc:A,frame_rate:{fixed:Me,fps:Ce/Te}},width:Ie,height:Fe,pixelRatio:[ye,_e]}}readPPS(t){const n=new Dz(this.ebsp2rbsp(t));n.readUByte(),n.readUByte(),n.skipUEG(),n.skipUEG(),n.skipBits(2),n.skipBits(3),n.skipBits(2),n.skipUEG(),n.skipUEG(),n.skipEG(),n.skipBits(2),n.readBoolean()&&n.skipUEG(),n.skipEG(),n.skipEG(),n.skipBits(4);const a=n.readBoolean(),i=n.readBoolean();let l=1;return i&&a?l=0:i?l=3:a&&(l=2),{parallelismType:l}}matchSPS(t,n){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,n).substr(3)}}const xp=188;class lS{constructor(t,n,r,a){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=n,this.typeSupported=r,this.logger=a,this.videoParser=null}static probe(t,n){const r=lS.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(xp*5,n-xp)+1,a=0;for(;a1&&(l===0&&o>2||c+xp>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:KNt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?n:void 0}}resetInitSegment(t,n,r,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=lS.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=lS.createTrack("audio",a),this._id3Track=lS.createTrack("id3"),this._txtTrack=lS.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:n,_id3Track:r}=this;t&&(t.pesData=null),n&&(n.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,n,r=!1,a=!1){r||(this.sampleAes=null);let i;const l=this._videoTrack,o=this._audioTrack,c=this._id3Track,d=this._txtTrack;let u=l.pid,h=l.pesData,p=o.pid,f=c.pid,g=o.pesData,b=c.pesData,v=null,j=this.pmtParsed,_=this._pmtId,S=t.length;if(this.remainderData&&(t=Qv(this.remainderData,t),S=t.length,this.remainderData=null),S>4;let V;if(z>1){if(V=L+5+t[L+4],V===L+xp)continue}else V=L+4;switch(F){case u:M&&(h&&(i=KI(h,this.logger))&&(this.readyVideoParser(l.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(l,d,i,!1)),h={data:[],size:0}),h&&(h.data.push(t.subarray(V,L+xp)),h.size+=L+xp-V);break;case p:if(M){if(g&&(i=KI(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i);break}g={data:[],size:0}}g&&(g.data.push(t.subarray(V,L+xp)),g.size+=L+xp-V);break;case f:M&&(b&&(i=KI(b,this.logger))&&this.parseID3PES(c,i),b={data:[],size:0}),b&&(b.data.push(t.subarray(V,L+xp)),b.size+=L+xp-V);break;case 0:M&&(V+=t[V]+1),_=this._pmtId=gon(t,V);break;case _:{M&&(V+=t[V]+1);const W=yon(t,V,this.typeSupported,r,this.observer,this.logger);u=W.videoPid,u>0&&(l.pid=u,l.segmentCodec=W.segmentVideoCodec),p=W.audioPid,p>0&&(o.pid=p,o.segmentCodec=W.segmentAudioCodec),f=W.id3Pid,f>0&&(c.pid=f),v!==null&&!j&&(this.logger.warn(`MPEG-TS PMT found at ${L} after unknown PID '${v}'. Backtracking to sync byte @${A} to parse all TS packets.`),v=null,L=A-188),j=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=F;break}}else T++;T>0&>e(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=h,o.pesData=g,c.pesData=b;const D={audioTrack:o,videoTrack:l,id3Track:c,textTrack:d};return a&&this.extractRemainingSamples(D),D}flush(){const{remainderData:t}=this;this.remainderData=null;let n;return t?n=this.demux(t,-1,!1,!0):n={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(n),this.sampleAes?this.decrypt(n,this.sampleAes):n}extractRemainingSamples(t){const{audioTrack:n,videoTrack:r,id3Track:a,textTrack:i}=t,l=r.pesData,o=n.pesData,c=a.pesData;let d;if(l&&(d=KI(l,this.logger))?(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(r,i,d,!0),r.pesData=null)):r.pesData=l,o&&(d=KI(o,this.logger))){switch(n.segmentCodec){case"aac":this.parseAACPES(n,d);break;case"mp3":this.parseMPEGPES(n,d);break;case"ac3":this.parseAC3PES(n,d);break}n.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),n.pesData=o;c&&(d=KI(c,this.logger))?(this.parseID3PES(a,d),a.pesData=null):a.pesData=c}demuxSampleAes(t,n,r){const a=this.demux(t,r,!0,!this.config.progressive),i=this.sampleAes=new pon(this.observer,this.config,n);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new fon:t==="hevc"&&(this.videoParser=new xon))}decrypt(t,n){return new Promise(r=>{const{audioTrack:a,videoTrack:i}=t;a.samples&&a.segmentCodec==="aac"?n.decryptAacSamples(a.samples,0,()=>{i.samples?n.decryptAvcSamples(i.samples,0,0,()=>{r(t)}):r(t)}):i.samples&&n.decryptAvcSamples(i.samples,0,0,()=>{r(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,n){let r=0;const a=this.aacOverFlow;let i=n.data;if(a){this.aacOverFlow=null;const h=a.missing,p=a.sample.unit.byteLength;if(h===-1)i=Qv(a.sample.unit,i);else{const f=p-h;a.sample.unit.set(i.subarray(0,h),f),t.samples.push(a.sample),r=a.missing}}let l,o;for(l=r,o=i.length;l0;)o+=c}}parseID3PES(t,n){if(n.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=Yc({},n,{type:this._videoTrack?Z0.emsg:Z0.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}}function HTe(s,t){return((s[t+1]&31)<<8)+s[t+2]}function gon(s,t){return(s[t+10]&31)<<8|s[t+11]}function yon(s,t,n,r,a,i){const l={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[t+1]&15)<<8|s[t+2],c=t+3+o-4,d=(s[t+10]&15)<<8|s[t+11];for(t+=12+d;t0){let p=t+5,f=h;for(;f>2;){switch(s[p]){case 106:n.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=u,l.segmentAudioCodec="ac3");break}const b=s[p+1]+2;p+=b,f-=b}}break;case 194:case 135:return GTe(a,new Error("Unsupported EC-3 in M2TS found"),void 0,i),l;case 36:l.videoPid===-1&&(l.videoPid=u,l.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}t+=h+5}return l}function GTe(s,t,n,r){r.warn(`parsing error: ${t.message}`),s.emit(_t.ERROR,_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function hke(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function KI(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]=Qv(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(a=(r[4]<<8)+r[5],a&&a>s.size-6)return null;const u=r[7];u&192&&(l=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(o=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,l-o>60*9e4&&(t.warn(`${Math.round((l-o)/9e4)}s delta between PTS and DTS, align them`),l=o)):o=l),i=r[8];let h=i+9;if(s.size<=h)return null;s.size-=h;const p=new Uint8Array(s.size);for(let f=0,g=c.length;fb){h-=b;continue}else r=r.subarray(h),b-=h,h=0;p.set(r,n),n+=b}return a&&(a-=i+3),{data:p,pts:l,dts:o,len:a}}return null}class von{static getSilentFrame(t,n){switch(t){case"mp4a.40.2":if(n===1)return new Uint8Array([0,200,0,128,35,128]);if(n===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(n===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(n===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(n===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(n===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(n===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(n===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(n===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const Pk=Math.pow(2,32)-1;class Mn{static init(){Mn.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in Mn.types)Mn.types.hasOwnProperty(t)&&(Mn.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const n=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Mn.HDLR_TYPES={video:n,audio:r};const a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);Mn.STTS=Mn.STSC=Mn.STCO=i,Mn.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Mn.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Mn.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Mn.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const l=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);Mn.FTYP=Mn.box(Mn.types.ftyp,l,c,l,o),Mn.DINF=Mn.box(Mn.types.dinf,Mn.box(Mn.types.dref,a))}static box(t,...n){let r=8,a=n.length;const i=a;for(;a--;)r+=n[a].byteLength;const l=new Uint8Array(r);for(l[0]=r>>24&255,l[1]=r>>16&255,l[2]=r>>8&255,l[3]=r&255,l.set(t,4),a=0,r=8;a>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255,85,196,0,0]))}static mdia(t){return Mn.box(Mn.types.mdia,Mn.mdhd(t.timescale||0,t.duration||0),Mn.hdlr(t.type),Mn.minf(t))}static mfhd(t){return Mn.box(Mn.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?Mn.box(Mn.types.minf,Mn.box(Mn.types.smhd,Mn.SMHD),Mn.DINF,Mn.stbl(t)):Mn.box(Mn.types.minf,Mn.box(Mn.types.vmhd,Mn.VMHD),Mn.DINF,Mn.stbl(t))}static moof(t,n,r){return Mn.box(Mn.types.moof,Mn.mfhd(t),Mn.traf(r,n))}static moov(t){let n=t.length;const r=[];for(;n--;)r[n]=Mn.trak(t[n]);return Mn.box.apply(null,[Mn.types.moov,Mn.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(Mn.mvex(t)))}static mvex(t){let n=t.length;const r=[];for(;n--;)r[n]=Mn.trex(t[n]);return Mn.box.apply(null,[Mn.types.mvex,...r])}static mvhd(t,n){n*=t;const r=Math.floor(n/(Pk+1)),a=Math.floor(n%(Pk+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 Mn.box(Mn.types.mvhd,i)}static sdtp(t){const n=t.samples||[],r=new Uint8Array(4+n.length);let a,i;for(a=0;a>>8&255),n.push(l&255),n=n.concat(Array.prototype.slice.call(i));for(a=0;a>>8&255),r.push(l&255),r=r.concat(Array.prototype.slice.call(i));const o=Mn.box(Mn.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(r))),c=t.width,d=t.height,u=t.pixelRatio[0],h=t.pixelRatio[1];return Mn.box(Mn.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,Mn.box(Mn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Mn.box(Mn.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(t){const n=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...n,6,1,2])}static audioStsd(t){const n=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,n>>8&255,n&255,0,0])}static mp4a(t){return Mn.box(Mn.types.mp4a,Mn.audioStsd(t),Mn.box(Mn.types.esds,Mn.esds(t)))}static mp3(t){return Mn.box(Mn.types[".mp3"],Mn.audioStsd(t))}static ac3(t){return Mn.box(Mn.types["ac-3"],Mn.audioStsd(t),Mn.box(Mn.types.dac3,t.config))}static stsd(t){const{segmentCodec:n}=t;if(t.type==="audio"){if(n==="aac")return Mn.box(Mn.types.stsd,Mn.STSD,Mn.mp4a(t));if(n==="ac3"&&t.config)return Mn.box(Mn.types.stsd,Mn.STSD,Mn.ac3(t));if(n==="mp3"&&t.codec==="mp3")return Mn.box(Mn.types.stsd,Mn.STSD,Mn.mp3(t))}else if(t.pps&&t.sps){if(n==="avc")return Mn.box(Mn.types.stsd,Mn.STSD,Mn.avc1(t));if(n==="hevc"&&t.vps)return Mn.box(Mn.types.stsd,Mn.STSD,Mn.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/(Pk+1)),o=Math.floor(r%(Pk+1));return Mn.box(Mn.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,l>>24,l>>16&255,l>>8&255,l&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,a&255,0,0,i>>8&255,i&255,0,0]))}static traf(t,n){const r=Mn.sdtp(t),a=t.id,i=Math.floor(n/(Pk+1)),l=Math.floor(n%(Pk+1));return Mn.box(Mn.types.traf,Mn.box(Mn.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),Mn.box(Mn.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,l>>24,l>>16&255,l>>8&255,l&255])),Mn.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,Mn.box(Mn.types.trak,Mn.tkhd(t),Mn.mdia(t))}static trex(t){const n=t.id;return Mn.box(Mn.types.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,n){const r=t.samples||[],a=r.length,i=12+16*a,l=new Uint8Array(i);let o,c,d,u,h,p;for(n+=8+i,l.set([t.type==="video"?1:0,0,15,1,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),o=0;o>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,p>>>24&255,p>>>16&255,p>>>8&255,p&255],12+16*o);return Mn.box(Mn.types.trun,l)}static initSegment(t){Mn.types||Mn.init();const n=Mn.moov(t);return Qv(Mn.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][b].length&255]),l),l+=2,o.set(r[g][b],l),l+=r[g][b].length}const d=Mn.box(Mn.types.hvcC,o),u=t.width,h=t.height,p=t.pixelRatio[0],f=t.pixelRatio[1];return Mn.box(Mn.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,Mn.box(Mn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Mn.box(Mn.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,p&255,f>>24,f>>16&255,f>>8&255,f&255])))}}Mn.types=void 0;Mn.HDLR_TYPES=void 0;Mn.STTS=void 0;Mn.STSC=void 0;Mn.STCO=void 0;Mn.STSZ=void 0;Mn.VMHD=void 0;Mn.SMHD=void 0;Mn.STSD=void 0;Mn.FTYP=void 0;Mn.DINF=void 0;const qkt=9e4;function sDe(s,t,n=1,r=!1){const a=s*t*n;return r?Math.round(a):a}function bon(s,t,n=1,r=!1){return sDe(s,t,1/n,r)}function HF(s,t=!1){return sDe(s,1e3,1/qkt,t)}function _on(s,t=1){return sDe(s,qkt,1/t)}function KJe(s){const{baseTime:t,timescale:n,trackId:r}=s;return`${t/n} (${t}/${n}) trackId: ${r}`}const won=10*1e3,jon=1024,Non=1152,kon=1536;let YI=null,mke=null;function YJe(s,t,n,r){return{duration:t,size:n,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class ppe extends a1{constructor(t,n,r,a){if(super("mp4-remuxer",a),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=n,this.typeSupported=r,this.ISGenerated=!1,YI===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);YI=l?parseInt(l[1]):0}if(mke===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);mke=i?parseInt(i[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const n=this._initPTS;(!n||!t||t.trackId!==n.trackId||t.baseTime!==n.baseTime||t.timescale!==n.timescale)&&this.log(`Reset initPTS: ${n&&KJe(n)} > ${t&&KJe(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=U0(o,r),c=o-i),c>0?i:o},r);return n&&this.debug("PTS rollover detected"),a}remux(t,n,r,a,i,l,o,c){let d,u,h,p,f,g,b=i,v=i;const j=t.pid>-1,_=n.pid>-1,S=n.samples.length,A=t.samples.length>0,T=o&&S>0||S>1;if((!j||A)&&(!_||T)||this.ISGenerated||o){if(this.ISGenerated){var L,M,F,z;const Y=this.videoTrackConfig;(Y&&(n.width!==Y.width||n.height!==Y.height||((L=n.pixelRatio)==null?void 0:L[0])!==((M=Y.pixelRatio)==null?void 0:M[0])||((F=n.pixelRatio)==null?void 0:F[1])!==((z=Y.pixelRatio)==null?void 0:z[1]))||!Y&&T||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,n,i,l));const V=this.isVideoContiguous;let W=-1,K;if(T&&(W=Son(n.samples),!V&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,W>0){this.warn(`Dropped ${W} out of ${S} video samples due to a missing keyframe`);const Y=this.getVideoStartPts(n.samples);n.samples=n.samples.slice(W),n.dropped+=W,v+=(n.samples[0].pts-Y)/n.inputTimeScale,K=v}else W===-1&&(this.warn(`No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(A&&T){const Y=this.getVideoStartPts(n.samples),ne=(U0(t.samples[0].pts,Y)-Y)/n.inputTimeScale;b+=Math.max(0,ne),v+=Math.max(0,-ne)}if(A){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,n,i,l)),u=this.remuxAudio(t,b,this.isAudioContiguous,l,_||T||c===Qa.AUDIO?v:void 0),T){const Y=u?u.endPTS-u.startPTS:0;n.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,n,i,l)),d=this.remuxVideo(n,v,V,Y)}}else T&&(d=this.remuxVideo(n,v,V,0));d&&(d.firstKeyFrame=W,d.independent=W!==-1,d.firstKeyFramePTS=K)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=Vkt(r,i,this._initPTS,this._initDTS)),a.samples.length&&(p=Hkt(a,i,this._initPTS))),{audio:u,video:d,initSegment:h,independent:g,text:p,id3:f}}computeInitPts(t,n,r,a){const i=Math.round(r*n);let l=U0(t,i);if(l0?ie-1:ie].dts&&(_=!0)}_&&l.sort(function(ie,ye){const _e=ie.dts-ye.dts,Me=ie.pts-ye.pts;return _e||Me}),g=l[0].dts,b=l[l.length-1].dts;const A=b-g,T=A?Math.round(A/(c-1)):f||t.inputTimeScale/30;if(r){const ie=g-S,ye=ie>T,_e=ie<-1;if((ye||_e)&&(ye?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${HF(ie,!0)} ms (${ie}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${HF(-ie,!0)} ms (${ie}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!_e||S>=l[0].pts||YI)){g=S;const Me=l[0].pts-ie;if(ye)l[0].dts=g,l[0].pts=Me;else{let Te=!0;for(let Ce=0;CeMe&&Te);Ce++){const Ee=l[Ce].pts;if(l[Ce].dts-=ie,l[Ce].pts-=ie,Ce0?ye.dts-l[ie-1].dts:T;if(Te=ie>0?ye.pts-l[ie-1].pts:T,Ee.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ie=Math.floor(Ee.maxBufferHole*i),Fe=(a?v+a*i:this.nextAudioTs+u)-ye.pts;Fe>Ie?(f=Fe-De,f<0?f=De:W=!0,this.log(`It is approximately ${Fe/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=De}else f=De}const Ce=Math.round(ye.pts-ye.dts);K=Math.min(K,f),ee=Math.max(ee,f),Y=Math.min(Y,Te),ne=Math.max(ne,Te),o.push(YJe(ye.key,f,Me,Ce))}if(o.length){if(YI){if(YI<70){const ie=o[0].flags;ie.dependsOn=2,ie.isNonSync=0}}else if(mke&&ne-Y0&&(a&&Math.abs(S-(j+_))<9e3||Math.abs(U0(b[0].pts,S)-(j+_))<20*u),b.forEach(function(ne){ne.pts=U0(ne.pts,S)}),!r||j<0){const ne=b.length;if(b=b.filter(oe=>oe.pts>=0),ne!==b.length&&this.warn(`Removed ${b.length-ne} of ${ne} samples (initPTS ${_} / ${l})`),!b.length)return;i===0?j=0:a&&!g?j=Math.max(0,S-_):j=b[0].pts-_}if(t.segmentCodec==="aac"){const ne=this.config.maxAudioFramesDrift;for(let oe=0,pe=j+_;oe=ne*u&&ye0){L+=v;try{D=new Uint8Array(L)}catch(ye){this.observer.emit(_t.ERROR,_t.ERROR,{type:fi.MUX_ERROR,details:Pn.REMUX_ALLOC_ERROR,fatal:!1,error:ye,bytes:L,reason:`fail allocating audio mdat ${L}`});return}p||(new DataView(D.buffer).setUint32(0,L),D.set(Mn.types.mdat,4))}else return;D.set(ce,v);const ie=ce.byteLength;v+=ie,f.push(YJe(!0,d,ie,0)),T=de}const F=f.length;if(!F)return;const z=f[f.length-1];j=T-_,this.nextAudioTs=j+c*z.duration;const V=p?new Uint8Array(0):Mn.moof(t.sequenceNumber++,A/c,Yc({},t,{samples:f}));t.samples=[];const W=(A-_)/l,K=this.nextAudioTs/l,ee={data1:V,data2:D,startPTS:W,endPTS:K,startDTS:W,endDTS:K,type:"audio",hasAudio:!0,hasVideo:!1,nb:F};return this.isAudioContiguous=!0,ee}}function U0(s,t){let n;if(t===null)return s;for(t4294967296;)s+=n;return s}function Son(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class Con extends a1{constructor(t,n,r,a){super("passthrough-remuxer",a),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const n=this.initPTS;n&&t&&n.baseTime===t.baseTime&&n.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,n,r,a){this.audioCodec=n,this.videoCodec=r,this.generateInitSegment(t,a),this.emitInitSegment=!0}generateInitSegment(t,n){let{audioCodec:r,videoCodec:a}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:i,video:l}=this.initData=QNt(t);if(n)pan(t,n);else{const c=i||l;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}i&&(r=ZJe(i,td.AUDIO,this)),l&&(a=ZJe(l,td.VIDEO,this));const o={};i&&l?o.audiovideo={container:"video/mp4",codec:r+","+a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:i?o.audio={container:"audio/mp4",codec:r,encrypted:i.encrypted,initSegment:t,id:"audio"}:l?o.video={container:"video/mp4",codec:a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,n,r,a,i,l){var o,c;let{initPTS:d,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:a,id3:r,initSegment:void 0};Fa(u)||(u=this.lastEndTime=i||0);const p=n.samples;if(!p.length)return h;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(p),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const b=xan(p,g,this),v=g.audio?b[g.audio.id]:null,j=g.video?b[g.video.id]:null,_=HG(j,1/0),S=HG(v,1/0),A=HG(j,0,!0),T=HG(v,0,!0);let D=i,L=0;const M=v&&(!j||!d&&S<_||d&&d.trackId===g.audio.id),F=M?v:j;if(F){const pe=F.timescale,ce=F.start-i*pe,de=M?g.audio.id:g.video.id;D=F.start/pe,L=M?T-S:A-_,(l||!d)&&(Ton(d,D,i,L)||pe!==d.timescale)&&(d&&this.warn(`Timestamps at playlist time: ${l?"":"~"}${i} ${ce/pe} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${D-i} (${ce}/${pe}) trackId: ${de}`),d=null,f.initPTS=ce,f.timescale=pe,f.trackId=de)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${i}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=D,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const z=D-d.baseTime/d.timescale,V=z+L;L>0?this.lastEndTime=V:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const W=!!g.audio,K=!!g.video;let Y="";W&&(Y+="audio"),K&&(Y+="video");const ee=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),ne={data1:p,startPTS:z,startDTS:z,endPTS:V,endDTS:V,type:Y,hasAudio:W,hasVideo:K,nb:1,dropped:0,encrypted:ee};h.audio=W&&!K?ne:void 0,h.video=K?ne:void 0;const oe=j==null?void 0:j.sampleCount;if(oe){const pe=j.keyFrameIndex,ce=pe!==-1;ne.nb=oe,ne.dropped=pe===0||this.isVideoContiguous?0:ce?pe:oe,ne.independent=ce,ne.firstKeyFrame=pe,ce&&j.keyFrameStart&&(ne.firstKeyFramePTS=(j.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(h.independent=ce),this.isVideoContiguous||(this.isVideoContiguous=ce),ne.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${pe}/${oe} dropped: ${ne.dropped} start: ${ne.firstKeyFramePTS||"NA"}`)}return h.initSegment=f,h.id3=Vkt(r,i,d,d),a.samples.length&&(h.text=Hkt(a,i,d)),h}}function HG(s,t,n=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(n?s.duration:0))/s.timescale:t}function Ton(s,t,n,r){if(s===null)return!0;const a=Math.max(r,1),i=t-s.baseTime/s.timescale;return Math.abs(i-n)>a}function ZJe(s,t,n){const r=s.codec;return r&&r.length>4?r:t===td.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?e0e(r,!1):(n.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):(n.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}let S2;try{S2=self.performance.now.bind(self.performance)}catch{S2=Date.now}const fpe=[{demux:mon,remux:Con},{demux:lS,remux:ppe},{demux:con,remux:ppe},{demux:uon,remux:ppe}];fpe.splice(2,0,{demux:don,remux:ppe});class QJe{constructor(t,n,r,a,i,l){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=n,this.config=r,this.id=i,this.logger=l}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,n,r,a){const i=r.transmuxing;i.executeStart=S2();let l=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:u,trackSwitch:h,accurateTimeOffset:p,timeOffset:f,initSegmentChange:g}=a||o,{audioCodec:b,videoCodec:v,defaultInitPts:j,duration:_,initSegmentData:S}=c,A=Eon(l,n);if(A&&ZL(A.method)){const M=this.getDecrypter(),F=W8e(A.method);if(M.isSync()){let z=M.softwareDecrypt(l,A.key.buffer,A.iv.buffer,F);if(r.part>-1){const W=M.flush();z=W&&W.buffer}if(!z)return i.executeEnd=S2(),pke(r);l=new Uint8Array(z)}else return this.asyncResult=!0,this.decryptionPromise=M.webCryptoDecrypt(l,A.key.buffer,A.iv.buffer,F).then(z=>{const V=this.push(z,null,r);return this.decryptionPromise=null,V}),this.decryptionPromise}const T=this.needsProbing(u,h);if(T){const M=this.configureTransmuxer(l);if(M)return this.logger.warn(`[transmuxer] ${M.message}`),this.observer.emit(_t.ERROR,_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.FRAG_PARSING_ERROR,fatal:!1,error:M,reason:M.message}),i.executeEnd=S2(),pke(r)}(u||h||g||T)&&this.resetInitSegment(S,b,v,_,n),(u||g||T)&&this.resetInitialTimestamp(j),d||this.resetContiguity();const D=this.transmux(l,A,f,p,r);this.asyncResult=E$(D);const L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,i.executeEnd=S2(),D}flush(t){const n=t.transmuxing;n.executeStart=S2();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=S2();const h=[pke(t)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return E$(u)?(this.asyncResult=!0,u.then(h=>(this.flushRemux(l,h,t),l))):(this.flushRemux(l,u,t),this.asyncResult?Promise.resolve(l):l)}flushRemux(t,n,r){const{audioTrack:a,videoTrack:i,id3Track:l,textTrack:o}=n,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===Qa.MAIN?"level":"track"} ${r.level}`);const u=this.remuxer.remux(a,i,l,o,d,c,!0,this.id);t.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=S2()}resetInitialTimestamp(t){const{demuxer:n,remuxer:r}=this;!n||!r||(n.resetTimeStamp(t),r.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:n}=this;!t||!n||(t.resetContiguity(),n.resetNextTimestamp())}resetInitSegment(t,n,r,a,i){const{demuxer:l,remuxer:o}=this;!l||!o||(l.resetInitSegment(t,n,r,a),o.resetInitSegment(t,n,r,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,n,r,a,i){let l;return n&&n.method==="SAMPLE-AES"?l=this.transmuxSampleAes(t,n,r,a,i):l=this.transmuxUnencrypted(t,r,a,i),l}transmuxUnencrypted(t,n,r,a){const{audioTrack:i,videoTrack:l,id3Track:o,textTrack:c}=this.demuxer.demux(t,n,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,l,o,c,n,r,!1,this.id),chunkMeta:a}}transmuxSampleAes(t,n,r,a,i){return this.demuxer.demuxSampleAes(t,n,r).then(l=>({remuxResult:this.remuxer.remux(l.audioTrack,l.videoTrack,l.id3Track,l.textTrack,r,a,!1,this.id),chunkMeta:i}))}configureTransmuxer(t){const{config:n,observer:r,typeSupported:a}=this;let i;for(let h=0,p=fpe.length;h0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(n=t),n}const pke=s=>({remuxResult:{},chunkMeta:s});function E$(s){return"then"in s&&s.then instanceof Function}class Aon{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 Mon{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 XJe=0;class Gkt{constructor(t,n,r,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=XJe++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const d=c.data,u=this.hls;if(!(!u||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var h;const p=(h=this.workerContext)==null?void 0:h.objectURL;p&&self.URL.revokeObjectURL(p);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{u.logger[d.data.logType]&&u.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,u.trigger(d.event,d.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const d=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(_t.ERROR,{type:fi.OTHER_ERROR,details:Pn.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===_t.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new Z8e,this.observer.on(_t.FRAG_DECRYPTED,l),this.observer.on(_t.ERROR,l);const o=mJe(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||Din()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${n}"`),this.workerContext=Oin(i.workerPath)):(c.log(`injecting Web Worker for "${n}"`),this.workerContext=Rin());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:id(i)})}catch(u){c.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new QJe(this.observer,o,i,"",n,t.logger)}return}}this.transmuxer=new QJe(this.observer,o,i,"",n,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=XJe++;const n=this.hls.config,r=mJe(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:id(n)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),Fin(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const n=this.transmuxer;n&&(n.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,n,r,a,i,l,o,c,d,u){var h,p;d.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,b=l?l.start:i.start,v=i.decryptdata,j=this.frag,_=!(j&&i.cc===j.cc),S=!(j&&d.level===j.level),A=j?d.sn-j.sn:-1,T=this.part?d.part-this.part.index:-1,D=A===0&&d.id>1&&d.id===(j==null?void 0:j.stats.chunkCount),L=!S&&(A===1||A===0&&(T===1||D&&T<=0)),M=self.performance.now();(S||A||i.stats.parsing.start===0)&&(i.stats.parsing.start=M),l&&(T||!L)&&(l.stats.parsing.start=M);const F=!(j&&((h=i.initSegment)==null?void 0:h.url)===((p=j.initSegment)==null?void 0:p.url)),z=new Mon(_,L,c,S,b,F);if(!L||_||F){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===Qa.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${_} trackSwitch: ${S} contiguous: ${L} accurateTimeOffset: ${c} timeOffset: ${b} initSegmentChange: ${F}`);const V=new Aon(r,a,n,o,u);this.configureTransmuxer(V)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:v,chunkMeta:d,state:z},t instanceof ArrayBuffer?[t]:[]);else if(g){const V=g.push(t,v,d,z);E$(V)?V.then(W=>{this.handleTransmuxComplete(W)}).catch(W=>{this.transmuxerError(W,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(V)}}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);E$(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(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.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 JJe=100;class Ion extends Y8e{constructor(t,n,r){super(t,n,r,"audio-stream-controller",Qa.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_t.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(_t.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(_t.BUFFER_RESET,this.onBufferReset,this),t.on(_t.BUFFER_CREATED,this.onBufferCreated,this),t.on(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(_t.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(_t.FRAG_LOADING,this.onFragLoading,this),t.on(_t.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_t.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(_t.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(_t.BUFFER_RESET,this.onBufferReset,this),t.off(_t.BUFFER_CREATED,this.onBufferCreated,this),t.off(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(_t.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(_t.FRAG_LOADING,this.onFragLoading,this),t.off(_t.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){if(r===Qa.MAIN){const o=n.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:a,timescale:i,trackId:l},this.log(`InitPTS for cc: ${o} found from main: ${a/i} (${a}/${i}) trackId: ${l}`),this.mainAnchor=n,this.state===ur.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(n,d==null?void 0:d.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(n,c)):this.state===ur.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,n){var r;const a=((r=this.mainFragLoading)==null?void 0:r.frag)||null;if(n&&(a==null?void 0:a.cc)===n.cc)return;const i=(a||t).cc,l=this.getLevelDetails(),o=this.getLoadPosition(),c=lkt(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===ur.IDLE&&this.doTickIdle())}startLoad(t,n){if(!this.levels){this.startPosition=t,this.state=ur.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(JJe),r>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r,this.state=ur.IDLE):this.state=ur.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}doTick(){switch(this.state){case ur.IDLE:this.doTickIdle();break;case ur.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=ur.WAITING_INIT_PTS}break}case ur.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case ur.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=ur.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=ur.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:n,levels:r,media:a,trackId:i}=this,l=n.config;if(!this.buffering||!a&&!this.primaryPrefetch&&(this.startFragRequested||!l.startFragPrefetch)||!(r!=null&&r[i]))return;const o=r[i],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=ur.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,td.AUDIO,Qa.AUDIO));const u=this.getFwdBufferInfo(d,Qa.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){n.trigger(_t.BUFFER_EOS,{type:"audio"}),this.state=ur.ENDED;return}const h=u.len,p=n.maxBufferLength,f=c.fragments,g=f[0].start,b=this.getLoadPosition(),v=this.flushing?b:u.end;if(this.switchingTrack&&a){const S=b;c.PTSKnown&&Sg||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=g+.05)}if(h>=p&&!this.switchingTrack&&v_.end){const A=this.fragmentTracker.getFragAtPos(v,Qa.MAIN);A&&A.end>_.end&&(_=A,this.mainFragLoading={frag:A,targetBufferTime:null})}if(j.start>_.end)return}this.loadFragment(j,o,v)}onMediaDetaching(t,n){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,n)}onAudioTracksUpdated(t,{audioTracks:n}){this.resetTransmuxer(),this.levels=n.map(r=>new S$(r))}onAudioTrackSwitching(t,n){const r=!!n.url;this.trackId=n.id;const{fragCurrent:a}=this;a&&(a.abortRequests(),this.removeUnbufferedFrags(a.start)),this.resetLoadingState(),r?(this.switchingTrack=n,this.flushAudioIfNeeded(n),this.state!==ur.STOPPED&&(this.setInterval(JJe),this.state=ur.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(_t.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!==ur.STOPPED&&(this.state=ur.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${l} "${c.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const u=a[l];let h=0;if(i.live||(r=u.details)!=null&&r.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(u.details){var p;h=this.alignPlaylists(i,u.details,(p=this.levelLastLoaded)==null?void 0:p.details)}i.alignedSliding||(Skt(i,d),i.alignedSliding||o0e(i,d),h=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(_t.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:n.groupId}),this.state===ur.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=ur.IDLE),this.tick()}_handleFragmentLoadProgress(t){var n;const r=t.frag,{part:a,payload:i}=t,{config:l,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const d=c[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(r.start);return}const h=l.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let p=this.transmuxer;p||(p=this.transmuxer=new Gkt(this.hls,Qa.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[r.cc],g=(n=r.initSegment)==null?void 0:n.data;if(f!==void 0){const v=a?a.index:-1,j=v!==-1,_=new G8e(r.level,r.sn,r.stats.chunkCount,i.byteLength,v,j);p.push(i,g,h,"",r,a,u.totalduration,!1,_,f)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:b}=this.waitingData=this.waitingData||{frag:r,part:a,cache:new Ckt,complete:!1};b.push(new Uint8Array(i)),this.state!==ur.STOPPED&&(this.state=ur.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===Qa.MAIN&&Mh(n.frag)&&(this.mainFragLoading=n,this.state===ur.IDLE&&this.tick())}onFragBuffered(t,n){const{frag:r,part:a}=n;if(r.type!==Qa.AUDIO){!this.audioOnly&&r.type===Qa.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(Mh(r)){this.fragPrevious=r;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(_t.AUDIO_TRACK_SWITCHED,Ec({},i)))}this.fragBufferedComplete(r,a),this.media&&this.tick()}onError(t,n){var r;if(n.fatal){this.state=ur.ERROR;return}switch(n.details){case Pn.FRAG_GAP:case Pn.FRAG_PARSING_ERROR:case Pn.FRAG_DECRYPT_ERROR:case Pn.FRAG_LOAD_ERROR:case Pn.FRAG_LOAD_TIMEOUT:case Pn.KEY_LOAD_ERROR:case Pn.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Qa.AUDIO,n);break;case Pn.AUDIO_TRACK_LOAD_ERROR:case Pn.AUDIO_TRACK_LOAD_TIMEOUT:case Pn.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===ur.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===ol.AUDIO_TRACK&&(this.state=ur.IDLE);break;case Pn.BUFFER_ADD_CODEC_ERROR:case Pn.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case Pn.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Pn.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(t,{type:n}){n!==td.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:n}){if(n!==td.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===ur.ENDED&&(this.state=ur.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,n,Qa.AUDIO),this.tick())}}_handleTransmuxComplete(t){var n;const r="audio",{hls:a}=this,{remuxResult:i,chunkMeta:l}=t,o=this.getCurrentContext(l);if(!o){this.resetWhenMissingContext(l);return}const{frag:c,part:d,level:u}=o,{details:h}=u,{audio:p,text:f,id3:g,initSegment:b}=i;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=ur.PARSING,this.switchingTrack&&p&&this.completeAudioSwitch(this.switchingTrack),b!=null&&b.tracks){const v=c.initSegment||c;if(this.unhandledEncryptionError(b,c))return;this._bufferInitSegment(u,b.tracks,v,l),a.trigger(_t.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:r,tracks:b.tracks})}if(p){const{startPTS:v,endPTS:j,startDTS:_,endDTS:S}=p;d&&(d.elementaryStreams[td.AUDIO]={startPTS:v,endPTS:j,startDTS:_,endDTS:S}),c.setElementaryStreamInfo(td.AUDIO,v,j,_,S),this.bufferFragmentData(p,c,d,l)}if(g!=null&&(n=g.samples)!=null&&n.length){const v=Yc({id:r,frag:c,details:h},g);a.trigger(_t.FRAG_PARSING_METADATA,v)}if(f){const v=Yc({id:r,frag:c,details:h},f);a.trigger(_t.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(t,n,r,a){if(this.state!==ur.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const i=n.audio;i.id=Qa.AUDIO;const l=t.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${l}/${i.codec}]`),l&&l.split(",").length===1&&(i.levelCodec=l),this.hls.trigger(_t.BUFFER_CODECS,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(_t.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===Dm.NOT_LOADED||a===Dm.PARTIAL){var i;if(!Mh(t))this._loadInitSegment(t,n);else if((i=n.details)!=null&&i.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=ur.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==n.details.fragmentStart&&o0e(n.details,l)}else super.loadFragment(t,n,r)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o}=this.bufferedTrack;oM({name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,OE)||(s0e(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:n}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,n.trigger(_t.AUDIO_TRACK_SWITCHED,Ec({},t))}}class nDe extends a1{constructor(t,n){super(n,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,n,r){const a=n==null?void 0:n.renditionReports;if(a){let i=-1;for(let l=0;l=0&&u>n.partTarget&&(c+=1)}const d=r&&pJe(r);return new fJe(o,c>=0?c:void 0,d)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,n){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,n){if(n)try{return n.addDirectives(t)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return t}playlistLoaded(t,n,r){const{details:a,stats:i}=n,l=self.performance.now(),o=i.loading.first?Math.max(0,l-i.loading.first):0;a.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==a.appliedTimelineOffset){const u=Math.max(c||0,0);a.appliedTimelineOffset=u,a.fragments.forEach(h=>{h.setStart(h.playlistOffset+u)})}if(a.live||r!=null&&r.live){const u="levelInfo"in n?n.levelInfo:n.track;if(a.reloaded(r),r&&a.fragments.length>0){Nin(r,a,this);const _=a.playlistParsingError;if(_){this.warn(_);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var d;const{networkDetails:A}=n;S.trigger(_t.ERROR,{type:fi.NETWORK_ERROR,details:Pn.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:_,reason:_.message,level:n.level||void 0,parent:(d=a.fragments[0])==null?void 0:d.type,networkDetails:A,stats:i});return}a.playlistParsingError=null}}a.requestScheduled===-1&&(a.requestScheduled=i.loading.start);const h=this.hls.mainForwardBufferInfo,p=h?h.end-h.len:0,f=(a.edge-p)*1e3,g=_kt(a,f);if(a.requestScheduled+g0){if(F>a.targetduration*3)this.log(`Playlist last advanced ${M.toFixed(2)}s ago. Omitting segment and part directives.`),v=void 0,j=void 0;else if(r!=null&&r.tuneInGoal&&F-a.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${z} with playlist age: ${a.age}`),z=0;else{const V=Math.floor(z/a.targetduration);if(v+=V,j!==void 0){const W=Math.round(z%a.targetduration/a.partTarget);j+=W}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${M.toFixed(2)}s goal: ${z} skip sn ${V} to part ${j}`)}a.tuneInGoal=z}if(b=this.getDeliveryDirectives(a,n.deliveryDirectives,v,j),_||!L){a.requestScheduled=l,this.loadingPlaylist(u,b);return}}else(a.canBlockReload||a.canSkipUntil)&&(b=this.getDeliveryDirectives(a,n.deliveryDirectives,v,j));b&&v!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(u,b,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=pJe(t);return n!=null&&n.skip&&t.deltaUpdateFailed&&(r=n.msn,a=n.part,i=hpe.No),new fJe(r,a,i)}checkRetry(t){const n=t.details,r=n0e(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===nf.RetryRequest||!a.resolved&&i===nf.SendAlternateToPenaltyBox);if(c){var d;if(l>=o.maxNumRetry)return!1;if(r&&(d=t.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${n}" without delivery-directives`),this.loadPlaylist();else{const u=V8e(o,l);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${n}" in ${u}ms`)}t.levelRetry=!0,a.resolved=!0}return c}}function Wkt(s,t){if(s.length!==t.length)return!1;for(let n=0;ns[a]!==t[a])}function WTe(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class Pon extends nDe{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.LEVEL_LOADING,this.onLevelLoading,this),t.on(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(_t.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.LEVEL_LOADING,this.onLevelLoading,this),t.off(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(_t.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(_t.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,n){this.tracks=n.audioTracks||[]}onAudioTrackLoaded(t,n){const{id:r,groupId:a,details:i}=n,l=this.tracksInGroup[r];if(!l||l.groupId!==a){this.warn(`Audio track with id:${r} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=n.details,this.log(`Audio track ${r} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(t,n){this.switchLevel(n.level)}onLevelSwitching(t,n){this.switchLevel(n.level)}switchLevel(t){const n=this.hls.levels[t];if(!n)return;const r=n.audioGroups||null,a=this.groupIds;let i=this.currentTrack;if(!r||(a==null?void 0:a.length)!==(r==null?void 0:r.length)||r!=null&&r.some(o=>(a==null?void 0:a.indexOf(o))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(p=>!r||r.indexOf(p.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(p=>p.default)&&(this.selectDefaultTrack=!1),o.forEach((p,f)=>{p.id=f});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const p=dw(c,o,OE);if(p>-1)i=o[p];else{const f=dw(c,this.tracks);i=this.tracks[f]}}let d=this.findTrackId(i);d===-1&&i&&(d=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${r==null?void 0:r.join(",")}`),this.hls.trigger(_t.AUDIO_TRACKS_UPDATED,u);const h=this.trackId;if(d!==-1&&h===-1)this.setAudioTrack(d);else if(o.length&&h===-1){var l;const p=new Error(`No audio track selected for current audio group-ID(s): ${(l=this.groupIds)==null?void 0:l.join(",")} track count: ${o.length}`);this.warn(p.message),this.hls.trigger(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:p})}}}onError(t,n){n.fatal||!n.context||n.context.type===ol.AUDIO_TRACK&&n.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(n.context.groupId)!==-1)&&this.checkRetry(n)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const n=this.hls;if(n.config.audioPreference=t,t){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const a=this.currentTrack;if(a&&oM(t,a,OE))return a;const i=dw(t,this.tracksInGroup,OE);if(i>-1){const l=this.tracksInGroup[i];return this.setAudioTrack(i),l}else if(a){let l=n.loadLevel;l===-1&&(l=n.firstAutoLevel);const o=Han(t,n.levels,r,l,OE);if(o===-1)return null;n.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=dw(t,r);if(l>-1)return r[l]}}}return null}setAudioTrack(t){const n=this.tracksInGroup;if(t<0||t>=n.length){this.warn(`Invalid audio track id: ${t}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,a=n[t],i=a.details&&!a.details.live;if(t===this.trackId&&a===r&&i||(this.log(`Switching to audio-track ${t} "${a.name}" lang:${a.lang} group:${a.groupId} channels:${a.channels}`),this.trackId=t,this.currentTrack=a,this.hls.trigger(_t.AUDIO_TRACK_SWITCHING,Ec({},a)),i))return;const l=this.switchParams(a.url,r==null?void 0:r.details,a.details);this.loadPlaylist(l)}findTrackId(t){const n=this.tracksInGroup;for(let r=0;r{const r={label:"async-blocker",execute:n,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,t)})}prependBlocker(t){return new Promise(n=>{if(this.queues){const r={label:"async-blocker-prepend",execute:n,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(r)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var n;const r=(n=t[0])==null?void 0:n.label;(r==="async-blocker"||r==="async-blocker-prepend")&&(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(this.queues===null)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];if(n.length){const a=n[0];try{a.execute()}catch(i){var r;if(a.onError(i),this.queues===null||this.tracks===null)return;const l=(r=this.tracks[t])==null?void 0:r.buffer;l!=null&&l.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var n;return((n=this.queues)==null?void 0:n[t][0])||null}toString(){const{queues:t,tracks:n}=this;return t===null||n===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(t){var n,r;return(n=this.queues)!=null&&n[t]||(r=this.tracks)!=null&&r[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var n;const r=(n=this.tracks)==null?void 0:n[t],a=r==null?void 0:r.buffer;return a?`SourceBuffer${a.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(t){var n;return((n=this.queues)==null?void 0:n[t].map(r=>r.label).join(", "))||""}}const eet=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Kkt="HlsJsTrackRemovedError";class Don extends Error{constructor(t){super(t),this.name=Kkt}}class Ron extends a1{constructor(t,n){super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=r=>{var a;this.hls&&((a=this.mediaSource)==null?void 0:a.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:a,mediaSource:i}=this;r&&this.log("Media source opened"),!(!a||!i)&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(_t.MEDIA_ATTACHED,{media:a,mediaSource:i}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:r,_objectUrl:a}=this;r!==a&&this.error(`Media element src was set while attaching MediaSource (${a} > ${r})`)},this.hls=t,this.fragmentTracker=n,this.appendSource=ran($4(t.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.BUFFER_RESET,this.onBufferReset,this),t.on(_t.BUFFER_APPENDING,this.onBufferAppending,this),t.on(_t.BUFFER_CODECS,this.onBufferCodecs,this),t.on(_t.BUFFER_EOS,this.onBufferEos,this),t.on(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(_t.FRAG_PARSED,this.onFragParsed,this),t.on(_t.FRAG_CHANGED,this.onFragChanged,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.BUFFER_RESET,this.onBufferReset,this),t.off(_t.BUFFER_APPENDING,this.onBufferAppending,this),t.off(_t.BUFFER_CODECS,this.onBufferCodecs,this),t.off(_t.BUFFER_EOS,this.onBufferEos,this),t.off(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(_t.FRAG_PARSED,this.onFragParsed,this),t.off(_t.FRAG_CHANGED,this.onFragChanged,this),t.off(_t.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:n}=this;if(!t)return null;const r={};if(this.operationQueue){const i=this.isUpdating();i||this.operationQueue.removeBlockers();const l=this.isQueued();(i||l)&&this.warn(`Transfering MediaSource with${l?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const a=this.transferData;return!this.sourceBufferCount&&a&&a.mediaSource===n?Yc(r,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(r[l]=Yc({},this.tracks[l]),this.removeBuffer(l)),i[0]=i[1]=null}),{media:t,mediaSource:n,tracks:r}}initTracks(){const t={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,n){var r;let a=2;(n.audio&&!n.video||!n.altAudio)&&(a=1),this.bufferCodecEventsTotal=a,this.log(`${a} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&a&&this.bufferCreated()}onMediaAttaching(t,n){const r=this.media=n.media;this.transferData=this.overrides=void 0;const a=$4(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,tet(r),Oon(r,o),r.load()}catch{r.src=o}else r.src=o}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var n,r;this.log(`${((n=this.transferData)==null?void 0:n.mediaSource)===t?"transferred":"created"} media source: ${(r=t.constructor)==null?void 0:r.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,n=this.transferData;if(!n||!t)return;const r=this.tracks,a=n.tracks,i=a?Object.keys(a):null,l=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(a&&i&&l){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${id(r,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${id(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!VNt(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(_t.MEDIA_DETACHING,{}),this.onMediaAttaching(_t.MEDIA_ATTACHING,n),t.currentTime=u;return}this.transferData=void 0,i.forEach(c=>{const d=c,u=a[d];if(u){const h=u.buffer;if(h){const p=this.fragmentTracker,f=u.id;if(p.hasFragments(f)||p.hasParts(f)){const v=wo.getBuffered(h);p.detectEvictedFragments(d,v,f,null,!0)}const g=fke(d),b=[d,h];this.sourceBuffers[g]=b,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const n=(t=this.mediaSource)==null?void 0:t.readyState;return n==="open"||n==="ended"}onMediaDetaching(t,n){const r=!!n.transferMedia;this.transferData=this.overrides=void 0;const{media:a,mediaSource:i,_objectUrl:l}=this;if(i){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=i.readyState==="open";try{const c=i.sourceBuffers;for(let d=c.length;d--;)o&&c[d].abort(),i.removeSourceBuffer(c[d]);o&&i.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}a&&(a.removeEventListener("emptied",this._onMediaEmptied),r||(l&&self.URL.revokeObjectURL(l),this.mediaSrc===l?(a.removeAttribute("src"),this.appendSource&&tet(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(_t.MEDIA_DETACHED,n)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var n;const r=(n=this.tracks[t])==null?void 0:n.buffer;if(this.removeBuffer(t),r)try{var a;(a=this.mediaSource)!=null&&a.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(i){this.warn(`onBufferReset ${t}`,i)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[fke(t)]=[null,null];const n=this.tracks[t];n&&(n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Lon(this.tracks)}onBufferCodecs(t,n){var r;const a=this.tracks,i=Object.keys(n);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const l="audiovideo"in n&&(a.audio||a.video)||a.audiovideo&&("audio"in n||"video"in n),o=!l&&this.sourceBufferCount&&this.media&&i.some(c=>!a[c]);if(l||o){this.warn(`Unsupported transition between "${Object.keys(a)}" and "${i}" SourceBuffers`);return}i.forEach(c=>{var d,u;const h=n[c],{id:p,codec:f,levelCodec:g,container:b,metadata:v,supplemental:j}=h;let _=a[c];const S=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],A=S!=null&&S.buffer?S:_,T=(A==null?void 0:A.pendingCodec)||(A==null?void 0:A.codec),D=A==null?void 0:A.levelCodec;_||(_=a[c]={buffer:void 0,listeners:[],codec:f,supplemental:j,container:b,levelCodec:g,metadata:v,id:p});const L=upe(T,D),M=L==null?void 0:L.replace(eet,"$1");let F=upe(f,g);const z=(u=F)==null?void 0:u.replace(eet,"$1");F&&L&&M!==z&&(c.slice(0,5)==="audio"&&(F=e0e(F,this.appendSource)),this.log(`switching codec ${T} to ${F}`),F!==(_.pendingCodec||_.codec)&&(_.pendingCodec=F),_.container=b,this.appendChangeType(c,b,F))}),(this.tracksReady||this.sourceBufferCount)&&(n.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!n.video&&((r=n.audio)==null?void 0:r.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,n)=>{const r=this.tracks[n];return t[n]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t},{})}appendChangeType(t,n,r){const a=`${n};codecs=${r}`,i={label:`change-type=${a}`,execute:()=>{const l=this.tracks[t];if(l){const o=l.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${a}`),o.changeType(a),l.codec=r,l.container=n)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn(`Failed to change ${t} SourceBuffer type`,l)}};this.append(i,t,this.isPending(this.tracks[t]))}blockAudio(t){var n;const r=t.start,a=r+t.duration*.05;if(((n=this.fragmentTracker.getAppendedFrag(r,Qa.MAIN))==null?void 0:n.gap)===!0)return;const l={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>a||c!=null&&c.buffer&&wo.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,Qa.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:l,frag:t},this.append(l,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:n}=this;t&&n&&(this.blockedAudioAppend=null,n.unblockAudio(t.op))}onBufferAppending(t,n){const{tracks:r}=this,{data:a,type:i,parent:l,frag:o,part:c,chunkMeta:d,offset:u}=n,h=d.buffering[i],{sn:p,cc:f}=o,g=self.performance.now();h.start=g;const b=o.stats.buffering,v=c?c.stats.buffering:null;b.start===0&&(b.start=g),v&&v.start===0&&(v.start=g);const j=r.audio;let _=!1;i==="audio"&&(j==null?void 0:j.container)==="audio/mpeg"&&(_=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const S=r.video,A=S==null?void 0:S.buffer;if(A&&p!=="initSegment"){const L=c||o,M=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const z=L.start+L.duration*.05,V=A.buffered,W=this.currentOp("video");!V.length&&!W?this.blockAudio(L):!W&&!wo.isBuffered(A,z)&&this.lastVideoAppendEndz||F{var L;h.executeStart=self.performance.now();const M=(L=this.tracks[i])==null?void 0:L.buffer;M&&(_?this.updateTimestampOffset(M,T,.1,i,p,f):u!==void 0&&Fa(u)&&this.updateTimestampOffset(M,u,1e-6,i,p,f)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const L=self.performance.now();h.executeEnd=h.end=L,b.first===0&&(b.first=L),v&&v.first===0&&(v.first=L);const M={};this.sourceBuffers.forEach(([F,z])=>{F&&(M[F]=wo.getBuffered(z))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(_t.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:M})},onError:L=>{var M;const F={type:fi.MEDIA_ERROR,parent:o.type,details:Pn.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:L,err:L,fatal:!1},z=(M=this.media)==null?void 0:M.error;if(L.code===DOMException.QUOTA_EXCEEDED_ERR||L.name=="QuotaExceededError"||"quota"in L)F.details=Pn.BUFFER_FULL_ERROR;else if(L.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!z)F.errorAction=YL(!0);else if(L.name===Kkt&&this.sourceBufferCount===0)F.errorAction=YL(!0);else{const V=++this.appendErrors[i];this.warn(`Failed ${V}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${z||"no media error"})`),(V>=this.hls.config.appendErrorMaxRetry||z)&&(F.fatal=!0)}this.hls.trigger(_t.ERROR,F)}};this.log(`queuing "${i}" append sn: ${p}${c?" p: "+c.index:""} of ${o.type===Qa.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(D,i,this.isPending(this.tracks[i]))}getFlushOp(t,n,r){return this.log(`queuing "${t}" remove ${n}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(t,n,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(_t.BUFFER_FLUSHED,{type:t})},onError:a=>{this.warn(`Failed to remove ${n}-${r} from "${t}" SourceBuffer`,a)}}}onBufferFlushing(t,n){const{type:r,startOffset:a,endOffset:i}=n;r?this.append(this.getFlushOp(r,a,i),r):this.sourceBuffers.forEach(([l])=>{l&&this.append(this.getFlushOp(l,a,i),l)})}onFragParsed(t,n){const{frag:r,part:a}=n,i=[],l=a?a.elementaryStreams:r.elementaryStreams;l[td.AUDIOVIDEO]?i.push("audiovideo"):(l[td.AUDIO]&&i.push("audio"),l[td.VIDEO]&&i.push("video"));const o=()=>{const c=self.performance.now();r.stats.buffering.end=c,a&&(a.stats.buffering.end=c);const d=a?a.stats:r.stats;this.hls.trigger(_t.FRAG_BUFFERED,{frag:r,part:a,stats:d,id:r.type})};i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(o,i).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,n){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const n=this.tracks[t];if(n)return!n.ended||n.ending}return!1})}onBufferEos(t,n){var r;this.sourceBuffers.forEach(([l])=>{if(l){const o=this.tracks[l];(!n.type||n.type===l)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${l} buffer reached EOS`)))}});const a=((r=this.overrides)==null?void 0:r.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([l])=>{var o;return l&&!((o=this.tracks[l])!=null&&o.ended)})?a?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:l}=this;if(!l||l.readyState!=="open"){l&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${l.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),l.endOfStream(),this.hls.trigger(_t.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(_t.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===Pn.BUFFER_APPEND_ERROR&&n.frag){var r;const a=(r=n.errorAction)==null?void 0:r.nextAutoLevel;Fa(a)&&a!==n.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:n,media:r}=this;if(!r||n===null||!this.sourceBufferCount)return;const a=t.config,i=r.currentTime,l=n.levelTargetDuration,o=n.live&&a.liveBackBufferLength!==null?a.liveBackBufferLength:a.backBufferLength;if(Fa(o)&&o>=0){const d=Math.max(o,l),u=Math.floor(i/l)*l-d;this.flushBackBuffer(i,l,u)}const c=a.frontBufferFlushThreshold;if(Fa(c)&&c>0){const d=Math.max(a.maxBufferLength,c),u=Math.max(d,l),h=Math.floor(i/l)*l+u;this.flushFrontBuffer(i,l,h)}}flushBackBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const o=wo.getBuffered(i);if(o.length>0&&r>o.start(0)){var l;this.hls.trigger(_t.BACK_BUFFER_REACHED,{bufferEnd:r});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(_t.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(c!=null&&c.ended){this.log(`Cannot flush ${a} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(_t.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:a})}}})}flushFrontBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=wo.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(_t.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 Fa(i)?{duration:i}:null;const l=this.media.duration,o=Fa(r.duration)?r.duration:0;return a>o&&a>l||!Fa(l)?{duration:a}:null}updateMediaSource({duration:t,start:n,end:r}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(Fa(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}) ${id(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(_t.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(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.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":""} ${id(o)}`);try{const u=r.addSourceBuffer(d),h=fke(l),p=[l,u];n[h]=p,o.buffer=u}catch(u){var a;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(l),(a=this.operationQueue)==null||a.removeBlockers(),delete this.tracks[l],this.hls.trigger(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:l,mimeType:d,parent:o.id});return}this.trackSourceBuffer(l,o)}}this.bufferCreated()}getTrackCodec(t,n){const r=t.supplemental;let a=t.codec;r&&(n==="video"||n==="audiovideo")&&N$(r,"video")&&(a=San(a,r));const i=upe(a,t.levelCodec);return i?n.slice(0,5)==="audio"?e0e(i,this.appendSource):i:""}trackSourceBuffer(t,n){const r=n.buffer;if(!r)return;const a=this.getTrackCodec(n,t);this.tracks[t]={buffer:r,codec:a,container:n.container,levelCodec:n.levelCodec,supplemental:n.supplemental,metadata:n.metadata,id:n.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(i,l)=>{const o=l.removedRanges;o!=null&&o.length&&this.hls.trigger(_t.BUFFER_FLUSHED,{type:i})})}get mediaSrc(){var t,n;const r=((t=this.media)==null||(n=t.querySelector)==null?void 0:n.call(t,"source"))||this.media;return r==null?void 0:r.src}onSBUpdateStart(t){const n=this.currentOp(t);n&&n.onStart()}onSBUpdateEnd(t){var n;if(((n=this.mediaSource)==null?void 0:n.readyState)==="closed"){this.resetBuffer(t);return}const r=this.currentOp(t);r&&(r.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,n){var r;const a=new Error(`${t} SourceBuffer error. MediaSource readyState: ${(r=this.mediaSource)==null?void 0:r.readyState}`);this.error(`${a}`,n),this.hls.trigger(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:a,fatal:!1});const i=this.currentOp(t);i&&i.onError(a)}updateTimestampOffset(t,n,r,a,i,l){const o=n-t.timestampOffset;Math.abs(o)>=r&&(this.log(`Updating ${a} SourceBuffer timestampOffset to ${n} (sn: ${i} cc: ${l})`),t.timestampOffset=n)}removeExecutor(t,n,r){const{media:a,mediaSource:i}=this,l=this.tracks[t],o=l==null?void 0:l.buffer;if(!a||!i||!o){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(t);return}const c=Fa(a.duration)?a.duration:1/0,d=Fa(i.duration)?i.duration:1/0,u=Math.max(0,n),h=Math.min(r,c,d);h>u&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${u},${h}] from the ${t} SourceBuffer`),o.remove(u,h)):this.shiftAndExecuteNext(t)}appendExecutor(t,n){const r=this.tracks[n],a=r==null?void 0:r.buffer;if(!a)throw new Don(`Attempting to append to the ${n} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,a.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(n=>{this.warn(`SourceBuffer blocked callback ${n}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(n){this.warn(`Callback run without blocking ${this.operationQueue} ${n}`)}}isUpdating(){return this.sourceBuffers.some(([t,n])=>t&&n.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,n=this.sourceBufferTypes){if(!n.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:r}=this,a=n.map(l=>this.appendBlocker(l));return n.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(a).then(l=>{r===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(n=>{var r;const a=(r=this.tracks[n])==null?void 0:r.buffer;!a||a.updating||this.shiftAndExecuteNext(n)})}append(t,n,r){this.operationQueue&&this.operationQueue.append(t,n,r)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,n)=>t+(this.isPending(this.tracks[n])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[n])=>t+(n?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,n,r){const a=this.tracks[t];if(!a)return;const i=a.buffer;if(!i)return;const l=r.bind(this,t);a.listeners.push({event:n,listener:l}),i.addEventListener(n,l)}removeBufferListeners(t){const n=this.tracks[t];if(!n)return;const r=n.buffer;r&&(n.listeners.forEach(a=>{r.removeEventListener(a.event,a.listener)}),n.listeners.length=0)}}function tet(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(n=>{s.removeChild(n)})}function Oon(s,t){const n=self.document.createElement("source");n.type="video/mp4",n.src=t,s.appendChild(n)}function fke(s){return s==="audio"?1:0}class rDe{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(_t.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_t.BUFFER_CODECS,this.onBufferCodecs,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(_t.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_t.BUFFER_CODECS,this.onBufferCodecs,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,n){const r=this.hls.levels[n.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(t,n){this.media=n.media instanceof HTMLVideoElement?n.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,n){const r=this.hls;this.restrictedLevels=[],this.firstLevel=n.firstLevel,r.config.capLevelToPlayerSize&&n.video&&this.startCapping()}onLevelsUpdated(t,n){this.timer&&Fa(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,n){this.hls.config.capLevelToPlayerSize&&n.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const n=this.hls,r=this.getMaxLevel(t.length-1);r!==this.autoLevelCapping&&n.logger.log(`Setting autoLevelCapping to ${r}: ${t[r].height}p@${t[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),n.autoLevelCapping=r,n.autoLevelEnabled&&n.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=n.autoLevelCapping}}}getMaxLevel(t){const n=this.hls.levels;if(!n.length)return-1;const r=n.filter((a,i)=>this.isLevelAllowed(a)&&i<=t);return this.clientRect=null,rDe.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,n={width:0,height:0};if(t){const r=t.getBoundingClientRect();n.width=r.width,n.height=r.height,!n.width&&!n.height&&(n.width=r.right-r.left||t.width||0,n.height=r.bottom-r.top||t.height||0)}return this.clientRect=n,n}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(r=>t.bitrate===r.bitrate&&t.width===r.width&&t.height===r.height)}static getMaxLevelByMediaSize(t,n,r){if(!(t!=null&&t.length))return-1;const a=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let i=t.length-1;const l=Math.max(n,r);for(let o=0;o=l||c.height>=l)&&a(c,t[o+1])){i=o;break}}return i}}const Fon={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Cg=Fon,zon={HLS:"h"},Bon=zon;class Vw{constructor(t,n){Array.isArray(t)&&(t=t.map(r=>r instanceof Vw?r:new Vw(r))),this.value=t,this.params=n}}const $on="Dict";function Uon(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 qon(s,t,n,r){return new Error(`failed to ${s} "${Uon(t)}" as ${n}`,{cause:r})}function Hw(s,t,n){return qon("serialize",s,t,n)}class Ykt{constructor(t){this.description=t}}const set="Bare Item",Von="Boolean";function Hon(s){if(typeof s!="boolean")throw Hw(s,Von);return s?"?1":"?0"}function Gon(s){return btoa(String.fromCharCode(...s))}const Won="Byte Sequence";function Kon(s){if(ArrayBuffer.isView(s)===!1)throw Hw(s,Won);return`:${Gon(s)}:`}const Yon="Integer";function Zon(s){return s<-999999999999999||99999999999999912)throw Hw(s,Xon);const n=t.toString();return n.includes(".")?n:`${n}.0`}const eln="String",tln=/[\x00-\x1f\x7f]+/;function sln(s){if(tln.test(s))throw Hw(s,eln);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function nln(s){return s.description||s.toString().slice(7,-1)}const rln="Token";function net(s){const t=nln(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Hw(t,rln);return t}function KTe(s){switch(typeof s){case"number":if(!Fa(s))throw Hw(s,set);return Number.isInteger(s)?Zkt(s):Jon(s);case"string":return sln(s);case"symbol":return net(s);case"boolean":return Hon(s);case"object":if(s instanceof Date)return Qon(s);if(s instanceof Uint8Array)return Kon(s);if(s instanceof Ykt)return net(s);default:throw Hw(s,set)}}const aln="Key";function YTe(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Hw(s,aln);return s}function aDe(s){return s==null?"":Object.entries(s).map(([t,n])=>n===!0?`;${YTe(t)}`:`;${YTe(t)}=${KTe(n)}`).join("")}function Xkt(s){return s instanceof Vw?`${KTe(s.value)}${aDe(s.params)}`:KTe(s)}function iln(s){return`(${s.value.map(Xkt).join(" ")})${aDe(s.params)}`}function oln(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw Hw(s,$on);const n=s instanceof Map?s.entries():Object.entries(s),r=t!=null&&t.whitespace?" ":"";return Array.from(n).map(([a,i])=>{i instanceof Vw||(i=new Vw(i));let l=YTe(a);return i.value===!0?l+=aDe(i.params):(l+="=",Array.isArray(i.value)?l+=iln(i):l+=Xkt(i)),l}).join(`,${r}`)}function Jkt(s,t){return oln(s,t)}const P_="CMCD-Object",nh="CMCD-Request",v3="CMCD-Session",Lk="CMCD-Status",lln={br:P_,ab:P_,d:P_,ot:P_,tb:P_,tpb:P_,lb:P_,tab:P_,lab:P_,url:P_,pb:nh,bl:nh,tbl:nh,dl:nh,ltc:nh,mtp:nh,nor:nh,nrr:nh,rc:nh,sn:nh,sta:nh,su:nh,ttfb:nh,ttfbb:nh,ttlb:nh,cmsdd:nh,cmsds:nh,smrt:nh,df:nh,cs:nh,ts:nh,cid:v3,pr:v3,sf:v3,sid:v3,st:v3,v:v3,msd:v3,bs:Lk,bsd:Lk,cdn:Lk,rtp:Lk,bg:Lk,pt:Lk,ec:Lk,e:Lk},cln={REQUEST:nh};function dln(s){return Object.keys(s).reduce((t,n)=>{var r;return(r=s[n])===null||r===void 0||r.forEach(a=>t[a]=n),t},{})}function uln(s,t){const n={};if(!s)return n;const r=Object.keys(s),a=t?dln(t):{};return r.reduce((i,l)=>{var o;const c=lln[l]||a[l]||cln.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},n)}function hln(s){return["ot","sf","st","e","sta"].includes(s)}function mln(s){return typeof s=="number"?Fa(s):s!=null&&s!==""&&s!==!1}const eSt="event";function pln(s,t){const n=new URL(s),r=new URL(t);if(n.origin!==r.origin)return s;const a=n.pathname.split("/").slice(1),i=r.pathname.split("/").slice(1,-1);for(;a[0]===i[0];)a.shift(),i.shift();for(;i.length;)i.shift(),a.unshift("..");return a.join("/")+n.search+n.hash}const xpe=s=>Math.round(s),ZTe=(s,t)=>Array.isArray(s)?s.map(n=>ZTe(n,t)):s instanceof Vw&&typeof s.value=="string"?new Vw(ZTe(s.value,t),s.params):(t.baseUrl&&(s=pln(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),GG=s=>xpe(s/100)*100,fln=(s,t)=>{let n=s;return t.version>=2&&(s instanceof Vw&&typeof s.value=="string"?n=new Vw([s]):typeof s=="string"&&(n=[s])),ZTe(n,t)},xln={br:xpe,d:xpe,bl:GG,dl:GG,mtp:GG,nor:fln,rtp:GG,tb:xpe},tSt="request",sSt="response",iDe=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],gln=["e"],yln=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function fbe(s){return yln.test(s)}function vln(s){return iDe.includes(s)||gln.includes(s)||fbe(s)}const nSt=["d","dl","nor","ot","rtp","su"];function bln(s){return iDe.includes(s)||nSt.includes(s)||fbe(s)}const _ln=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function wln(s){return iDe.includes(s)||nSt.includes(s)||_ln.includes(s)||fbe(s)}const jln=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Nln(s){return jln.includes(s)||fbe(s)}const kln={[sSt]:wln,[eSt]:vln,[tSt]:bln};function rSt(s,t={}){const n={};if(s==null||typeof s!="object")return n;const r=t.version||s.v||1,a=t.reportingMode||tSt,i=r===1?Nln:kln[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===sSt||a===eSt;c&&!l.includes("ts")&&l.push("ts"),r>1&&!l.includes("v")&&l.push("v");const d=Yc({},xln,t.formatters),u={version:r,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(h=>{let p=s[h];const f=d[h];if(typeof f=="function"&&(p=f(p,u)),h==="v"){if(r===1)return;p=r}h=="pr"&&p===1||(c&&h==="ts"&&!Fa(p)&&(p=Date.now()),mln(p)&&(hln(h)&&typeof p=="string"&&(p=new Ykt(p)),n[h]=p))}),n}function Sln(s,t={}){const n={};if(!s)return n;const r=rSt(s,t),a=uln(r,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=Jkt(o,{whitespace:!1});return c&&(i[l]=c),i},n)}function Cln(s,t,n){return Yc(s,Sln(t,n))}const Tln="CMCD";function Eln(s,t={}){return s?Jkt(rSt(s,t),{whitespace:!1}):""}function Aln(s,t={}){if(!s)return"";const n=Eln(s,t);return encodeURIComponent(n)}function Mln(s,t={}){if(!s)return"";const n=Aln(s,t);return`${Tln}=${n}`}const ret=/CMCD=[^&#]+/;function Iln(s,t,n){const r=Mln(t,n);if(!r)return s;if(ret.test(s))return s.replace(ret,r);const a=s.includes("?")?"&":"?";return`${s}${a}${r}`}class Pln{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=a=>{try{this.apply(a,{ot:Cg.MANIFEST,su:!this.initialized})}catch(i){this.hls.logger.warn("Could not generate manifest CMCD data.",i)}},this.applyFragmentData=a=>{try{const{frag:i,part:l}=a,o=this.hls.levels[i.level],c=this.getObjectType(i),d={d:(l||i).duration*1e3,ot:c};(c===Cg.VIDEO||c===Cg.AUDIO||c==Cg.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const u=l?this.getNextPart(l):this.getNextFrag(i);u!=null&&u.url&&u.url!==i.url&&(d.nor=u.url),this.apply(a,d)}catch(i){this.hls.logger.warn("Could not generate segment CMCD data.",i)}},this.hls=t;const n=this.config=t.config,{cmcd:r}=n;r!=null&&(n.pLoader=this.createPlaylistLoader(),n.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||t.sessionId,this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHED,this.onMediaDetached,this),t.on(_t.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHED,this.onMediaDetached,this),t.off(_t.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,n){this.media=n.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,n){var r,a;this.audioBuffer=(r=n.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(a=n.tracks.video)==null?void 0:a.buffer}createData(){var t;return{v:1,sf:Bon.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,n={}){Yc(n,this.createData());const r=n.ot===Cg.INIT||n.ot===Cg.VIDEO||n.ot===Cg.MUXED;this.starved&&r&&(n.bs=!0,n.su=!0,this.starved=!1),n.su==null&&(n.su=this.buffering);const{includeKeys:a}=this;a&&(n=Object.keys(n).reduce((l,o)=>(a.includes(o)&&(l[o]=n[o]),l),{}));const i={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),Cln(t.headers,n,i)):t.url=Iln(t.url,n,i)}getNextFrag(t){var n;const r=(n=this.hls.levels[t.level])==null?void 0:n.details;if(r){const a=t.sn-r.startSN;return r.fragments[a+1]}}getNextPart(t){var n;const{index:r,fragment:a}=t,i=(n=this.hls.levels[a.level])==null||(n=n.details)==null?void 0:n.partList;if(i){const{sn:l}=a;for(let o=i.length-1;o>=0;o--){const c=i[o];if(c.index===r&&c.fragment.sn===l)return i[o+1]}}}getObjectType(t){const{type:n}=t;if(n==="subtitle")return Cg.TIMED_TEXT;if(t.sn==="initSegment")return Cg.INIT;if(n==="audio")return Cg.AUDIO;if(n==="main")return this.hls.audioTracks.length?Cg.VIDEO:Cg.MUXED}getTopBandwidth(t){let n=0,r;const a=this.hls;if(t===Cg.AUDIO)r=a.audioTracks;else{const i=a.maxAutoLevel,l=i>-1?i+1:a.levels.length;r=a.levels.slice(0,l)}return r.forEach(i=>{i.bitrate>n&&(n=i.bitrate)}),n>0?n:NaN}getBufferLength(t){const n=this.media,r=t===Cg.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!n?NaN:wo.bufferInfo(r,n.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:t}=this.config,n=this.applyPlaylistData,r=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new r(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,l,o){n(i),this.loader.load(i,l,o)}}}createFragmentLoader(){const{fLoader:t}=this.config,n=this.applyFragmentData,r=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new r(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,l,o){n(i),this.loader.load(i,l,o)}}}}const Lln=3e5;class Dln extends a1{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,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)===nf.SendAlternateToPenaltyBox&&r.flags===$0.MoveAllAlternatesMatchingHost){const a=this.levels;let i=this._pathwayPriority,l=this.pathwayId;if(n.context){const{groupId:o,pathwayId:c,type:d}=n.context;o&&a?l=this.getPathwayForGroupId(o,d,l):c&&(l=c)}l in this.penalizedPathways||(this.penalizedPathways[l]=performance.now()),!i&&a&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==l),n.details===Pn.BUFFER_APPEND_ERROR&&!n.fatal?r.resolved=!0:r.resolved||this.warn(`Could not resolve ${n.details} ("${n.error.message}") with content-steering for Pathway: ${l} levels: ${a&&a.length} priorities: ${id(i)} penalized: ${id(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]>Lln&&delete r[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,Nkt(n),this.hls.trigger(_t.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 Su(u.attrs);h["PATHWAY-ID"]=l;const p=h.AUDIO&&`${h.AUDIO}_clone_${l}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${l}`;p&&(r[h.AUDIO]=p,h.AUDIO=p),f&&(a[h.SUBTITLES]=f,h.SUBTITLES=f);const g=aSt(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),b=new S$({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 v=1;v{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":b,"PATHWAY-CLONES":v,"PATHWAY-PRIORITY":j}=g;if(b)try{this.uri=new self.URL(b,a).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${b}`);return}this.scheduleRefresh(this.uri||p.url),v&&this.clonePathways(v);const _={steeringManifest:g,url:a.toString()};this.hls.trigger(_t.STEERING_MANIFEST_LOADED,_),j&&this.updatePathwayPriority(j)},onError:(u,h,p,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(u.code===429){const b=this.loader;if(typeof(b==null?void 0:b.getResponseHeader)=="function"){const v=b.getResponseHeader("Retry-After");v&&(g=parseFloat(v)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(u,h,p)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${a}`),this.loader.load(i,c,d)}scheduleRefresh(t,n=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const a=(r=this.hls)==null?void 0:r.media;if(a&&!a.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},n)}}function aet(s,t,n,r){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=Yc({},l);return o.details=void 0,o.attrs=new Su(o.attrs),o.url=o.attrs.URI=aSt(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 aSt(s,t,n,r){const{HOST:a,PARAMS:i,[n]:l}=r;let o;t&&(o=l==null?void 0:l[t],o&&(s=o));const c=new self.URL(s);return a&&!o&&(c.host=a),i&&Object.keys(i).sort().forEach(d=>{d&&c.searchParams.set(d,i[d])}),c.href}class QL extends a1{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=QL.CDMCleanupPromise?[QL.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=n=>{const{initDataType:r,initData:a}=n,i=`"${n.type}" event: init data type: "${r}"`;if(this.debug(i),a!==null){if(!this.keyFormatPromise){let l=Object.keys(this.keySystemAccessPromises);l.length||(l=L7(this.config));const o=l.map(oke).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=mpe(l);if(r!=="sinf"||o!==Du.FAIRPLAY){this.log(`Ignoring "${n.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let c;try{const f=Im(new Uint8Array(a)),g=K8e(JSON.parse(f).sinf),b=JNt(g);if(!b)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(b.subarray(8,24))}catch(f){this.warn(`${i} Failed to parse sinf: ${f}`);return}const d=rf(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let p=u[d];for(let f=0;fthis.generateRequestWithPreferredKeySession(g,r,a,"encrypted-event-key-match")),p.catch(j=>this.handleError(j));break}}p||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(l=>this.handleError(l))}},this.onWaitingForKey=n=>{this.log(`"${n.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(_t.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(_t.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(_t.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(_t.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(_t.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(_t.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:n,widevineLicenseUrl:r}=this.config,a=n==null?void 0:n[t];if(a)return a.licenseUrl;if(t===Du.WIDEVINE&&r)return r}getLicenseServerUrlOrThrow(t){const n=this.getLicenseServerUrl(t);if(n===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return n}getServerCertificateUrl(t){const{drmSystems:n}=this.config,r=n==null?void 0:n[t];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const n=this.hls.levels,r=(l,o,c)=>!!l&&c.indexOf(l)===o,a=n.map(l=>l.audioCodec).filter(r),i=n.map(l=>l.videoCodec).filter(r);return a.length+i.length===0&&i.push("avc1.42e01e"),new Promise((l,o)=>{const c=d=>{const u=d.shift();this.getMediaKeysPromise(u,a,i).then(h=>l({keySystem:u,mediaKeys:h})).catch(h=>{d.length?c(d):h instanceof F0?o(h):o(new F0({type:fi.KEY_SYSTEM_ERROR,details:Pn.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 xkt===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=fin(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: ${id(i)}`),o=this.requestMediaKeySystemAccess(t,i);const c=l=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${t}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const u=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const h=c.mediaKeys=d.createMediaKeys().then(p=>(this.log(`Media-keys created for "${t}"`),c.hasMediaKeys=!0,u.then(f=>f?this.setMediaKeysServerCertificate(p,t,f):p)));return h.catch(p=>{this.error(`Failed to create media-keys for "${t}"}: ${p}`)}),h})}return o.then(()=>l.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:n,mediaKeys:r}){this.log(`Creating key-system session "${n}" keyId: ${rf(t.keyId||[])} keyUri: ${t.uri}`);const a=r.createSession(),i={decryptdata:t,keySystem:n,mediaKeys:r,mediaKeysSession:a,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const n=t.decryptdata;if(n.pssh){const r=this.createMediaKeySessionContext(t),a=WG(n),i="cenc";this.keyIdToKeySessionPromise[a]=this.generateRequestWithPreferredKeySession(r,i,n.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,n){const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${rf(t.decryptdata.keyId||[])} } (data length: ${n.byteLength})`),r.update(n)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>oke(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:n,mediaKeys:r})=>this.attemptSetMediaKeys(n,r))}selectKeySystem(t){return new Promise((n,r)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:a})=>{const i=oke(a);i?n(i):r(new Error(`Unable to find format for key-system "${a}"`))}).catch(r)})}selectKeySystemFormat(t){const n=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)),this.keyFormatPromise}getKeyFormatPromise(t){const n=L7(this.config),r=t.map(mpe).filter(a=>!!a&&n.indexOf(a)!==-1);return this.selectKeySystem(r)}getKeyStatus(t){const{mediaKeySessions:n}=this;for(let r=0;r(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(c,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:d,decryptdata:n}))))).then(c=>{const d="cenc",u=n.pssh?n.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,u,"playlist-key")});return o.catch(c=>this.handleError(c,t.frag)),this.keyIdToKeySessionPromise[r]=o,o}return l.catch(o=>{if(o instanceof F0){const c=Ec({},o.data);this.getKeyStatus(n)==="internal-error"&&(c.decryptdata=n);const d=new F0(c,o.message);this.handleError(d,t.frag)}}),l}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,n){if(this.hls)if(t instanceof F0){n&&(t.data.frag=n);const r=t.data.decryptdata;this.error(`${t.message}${r?` (${rf(r.keyId||[])})`:""}`),this.hls.trigger(_t.ERROR,t.data)}else this.error(t.message),this.hls.trigger(_t.ERROR,{type:fi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const n=WG(t),r=this.keyIdToKeySessionPromise[n];if(!r){const a=mpe(t.keyFormat),i=a?[a]:L7(this.config);return this.attemptKeySystemAccess(i)}return r}getKeySystemSelectionPromise(t){if(t.length||(t=L7(this.config)),t.length===0)throw new F0({type:fi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${id({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,n){if(this.mediaResolved=void 0,this.mediaKeys===n)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(n):new Promise((i,l)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return l(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=n,this.media.setMediaKeys(n).then(i).catch(l)}}));return this.mediaKeys=n,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),r.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>r.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,n,r,a){var i;const l=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(l)try{const g=l.call(this.hls,n,r,t);if(!g)throw new Error("Invalid response from configured generateRequest filter");n=g.initDataType,r=g.initData?g.initData:null,t.decryptdata.pssh=r?new Uint8Array(r):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(r===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=WG(t.decryptdata),c=t.decryptdata.uri;this.log(`Generating key-session request for "${a}" keyId: ${o} URI: ${c} (init data type: ${n} length: ${r.byteLength})`);const d=new Z8e,u=t._onmessage=g=>{const b=t.mediaKeysSession;if(!b){d.emit("error",new Error("invalid state"));return}const{messageType:v,message:j}=g;this.log(`"${v}" message event for session "${b.sessionId}" message size: ${j.byteLength}`),v==="license-request"||v==="license-renewal"?this.renewLicense(t,j).catch(_=>{d.eventNames().length?d.emit("error",_):this.handleError(_)}):v==="license-release"?t.keySystem===Du.FAIRPLAY&&this.updateKeySession(t,UTe("acknowledged")).then(()=>this.removeSession(t)).catch(_=>this.handleError(_)):this.warn(`unhandled media key message type "${v}"`)},h=(g,b)=>{b.keyStatus=g;let v;g.startsWith("usable")?d.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?v=iet(g,b.decryptdata):g==="expired"?v=new Error(`key expired (keyId: ${o})`):g==="released"?v=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),v&&(d.eventNames().length?d.emit("error",v):this.handleError(v))},p=t._onkeystatuseschange=g=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const v=this.getKeyStatuses(t);if(!Object.keys(v).some(A=>v[A]!=="status-pending"))return;if(v[o]==="expired"){this.log(`Expired key ${id(v)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let _=v[o];if(_)h(_,t);else{var S;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(S=t.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const T=this.getKeyStatus(t.decryptdata);if(T&&T!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${T} from other session.`),h(T,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),_="internal-error",h(_,t)},1e3)),this.log(`No status for keyId ${o} (${id(v)}).`)}};tg(t.mediaKeysSession,"message",u),tg(t.mediaKeysSession,"keystatuseschange",p);const f=new Promise((g,b)=>{d.on("error",b),d.on("resolved",g)});return t.mediaKeysSession.generateRequest(n,r).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new F0({type:fi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw g}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const n={};return t.mediaKeysSession.keyStatuses.forEach((r,a)=>{if(typeof a=="string"&&typeof r=="object"){const o=a;a=r,r=o}const i="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(t.keySystem===Du.PLAYREADY&&i.length===16){const o=rf(i);n[o]=r,pkt(i)}const l=rf(i);r==="internal-error"&&(this.bannedKeyIds[l]=r),this.log(`key status change "${r}" for keyStatuses keyId: ${l} key-session "${t.mediaKeysSession.sessionId}"`),n[l]=r}),n}fetchServerCertificate(t){const n=this.config,r=n.loader,a=new r(n),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((l,o)=>{const c={responseType:"arraybuffer",url:i},d=n.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(p,f,g,b)=>{l(p.data)},onError:(p,f,g,b)=>{o(new F0({type:fi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:Ec({url:c.url,data:void 0},p)},`"${t}" certificate request failed (${i}). Status: ${p.code} (${p.text})`))},onTimeout:(p,f,g)=>{o(new F0({type:fi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(p,f,g)=>{o(new Error("aborted"))}};a.load(c,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(t,n,r){return new Promise((a,i)=>{t.setServerCertificate(r).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${r.byteLength}) on "${n}"`),a(t)}).catch(l=>{i(new F0({type:fi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:l,fatal:!0},l.message))})})}renewLicense(t,n){return this.requestLicense(t,new Uint8Array(n)).then(r=>this.updateKeySession(t,new Uint8Array(r)).catch(a=>{throw new F0({type:fi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:a,fatal:!1},a.message)}))}unpackPlayReadyKeyMessage(t,n){const r=String.fromCharCode.apply(null,new Uint16Array(n.buffer));if(!r.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),n;const a=new DOMParser().parseFromString(r,"application/xml"),i=a.querySelectorAll("HttpHeader");if(i.length>0){let u;for(let h=0,p=i.length;h in key message");return UTe(atob(d))}setupLicenseXHR(t,n,r,a){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!r.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,n,r,a)}).catch(l=>{if(!r.decryptdata)throw l;return t.open("POST",n,!0),i.call(this.hls,t,n,r,a)}).then(l=>(t.readyState||t.open("POST",n,!0),{xhr:t,licenseChallenge:l||a})):(t.open("POST",n,!0),Promise.resolve({xhr:t,licenseChallenge:a}))}requestLicense(t,n){const r=this.config.keyLoadPolicy.default;return new Promise((a,i)=>{const l=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${l}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const d=this.config.licenseResponseCallback;if(d)try{c=d.call(this.hls,o,l,t)}catch(u){this.error(u)}a(c)}else{const c=r.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)i(new F0({type:fi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:o,response:{url:l,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${l}). Status: ${o.status} (${o.statusText})`));else{const u=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(t,n).then(a,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,l,t,n).then(({xhr:c,licenseChallenge:d})=>{t.keySystem==Du.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(c,d)),c.send(d)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,n){if(!this.config.emeEnabled)return;const r=n.media;this.media=r,tg(r,"encrypted",this.onMediaEncrypted),tg(r,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=r.mediaKeys}onMediaDetached(){const t=this.media;t&&($g(t,"encrypted",this.onMediaEncrypted),$g(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const n=this.mediaResolved;if(n&&n(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const r=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,N4.clearKeyUriToKeyIdMap();const i=a.length;QL.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(_t.ERROR,{type:fi.OTHER_ERROR,details:Pn.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${l}`)})}))||Promise.resolve())).catch(l=>{this.log(`Could not close sessions and clear media keys: ${l}`),this.hls&&this.hls.trigger(_t.ERROR,{type:fi.OTHER_ERROR,details:Pn.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${l}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:n}){if(!(!n||!this.config.emeEnabled)&&!this.keyFormatPromise){const r=n.reduce((a,i)=>(a.indexOf(i.keyFormat)===-1&&a.push(i.keyFormat),a),[]);this.log(`Selecting key-system from session-keys ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)}}removeSession(t){const{mediaKeysSession:n,licenseXhr:r,decryptdata:a}=t;if(n){this.log(`Remove licenses and keys and close session "${n.sessionId}" keyId: ${rf((a==null?void 0:a.keyId)||[])}`),t._onmessage&&(n.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(n.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:l}=t;l&&Object.keys(l).forEach(d=>self.clearTimeout(l[d]));const{drmSystemOptions:o}=this.config;return(gin(o)?new Promise((d,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),n.remove().then(d).catch(u)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(_t.ERROR,{type:fi.OTHER_ERROR,details:Pn.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>n.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(_t.ERROR,{type:fi.OTHER_ERROR,details:Pn.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}QL.CDMCleanupPromise=void 0;function WG(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return rf(s.keyId)}function Rln(s,t){if(s.keyId&&t.mediaKeysSession.keyStatuses.has(s.keyId))return t.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(t.decryptdata))return t.keyStatus}class F0 extends Error{constructor(t,n){super(n),this.data=void 0,t.error||(t.error=new Error(n)),this.data=t,t.err=t.error}}function iet(s,t){const n=s==="output-restricted",r=n?Pn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Pn.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new F0({type:fi.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?"HDCP level output restricted":`key status changed to "${s}"`)}class Oln{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,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(_t.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(_t.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=a,this.lastDroppedFrames=r,this.lastDecodedFrames=n}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const n=t.getVideoPlaybackQuality();this.checkFPS(t,n.totalVideoFrames,n.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}function iSt(s,t){let n;try{n=new Event("addtrack")}catch{n=document.createEvent("Event"),n.initEvent("addtrack",!1,!1)}n.track=s,t.dispatchEvent(n)}function oSt(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){Lc.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){Lc.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}n==="disabled"&&(s.mode=n)}function qP(s,t){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues)for(let r=s.cues.length;r--;)t&&s.cues[r].removeEventListener("enter",t),s.removeCue(s.cues[r]);n==="disabled"&&(s.mode=n)}function QTe(s,t,n,r){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=zln(s.cues,t,n);for(let l=0;ls[n].endTime)return-1;let r=0,a=n,i;for(;r<=a;)if(i=Math.floor((a+r)/2),ts[i].startTime&&r-1)for(let i=a,l=s.length;i=t&&o.endTime<=n)r.push(o);else if(o.startTime>n)return r}return r}function gpe(s){const t=[];for(let n=0;nthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let n=null;const r=gpe(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.LEVEL_LOADING,this.onLevelLoading,this),t.on(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(_t.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.LEVEL_LOADING,this.onLevelLoading,this),t.off(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(_t.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(_t.ERROR,this.onError,this)}onMediaAttached(t,n){this.media=n.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,n){const r=this.media;if(!r)return;const a=!!n.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,a)return;gpe(r.textTracks).forEach(l=>{qP(l)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,n){this.tracks=n.subtitleTracks}onSubtitleTrackLoaded(t,n){const{id:r,groupId:a,details:i}=n,l=this.tracksInGroup[r];if(!l||l.groupId!==a){this.warn(`Subtitle track with id:${r} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=n.details,this.log(`Subtitle track ${r} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(t,n){this.switchLevel(n.level)}onLevelSwitching(t,n){this.switchLevel(n.level)}switchLevel(t){const n=this.hls.levels[t];if(!n)return;const r=n.subtitleGroups||null,a=this.groupIds;let i=this.currentTrack;if(!r||(a==null?void 0:a.length)!==(r==null?void 0:r.length)||r!=null&&r.some(l=>(a==null?void 0:a.indexOf(l))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const l=this.tracks.filter(u=>!r||r.indexOf(u.groupId)!==-1);if(l.length)this.selectDefaultTrack&&!l.some(u=>u.default)&&(this.selectDefaultTrack=!1),l.forEach((u,h)=>{u.id=h});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=l;const o=this.hls.config.subtitlePreference;if(!i&&o){this.selectDefaultTrack=!1;const u=dw(o,l);if(u>-1)i=l[u];else{const h=dw(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(_t.SUBTITLE_TRACKS_UPDATED,d),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(t){const n=this.tracksInGroup,r=this.selectDefaultTrack;for(let a=0;a-1){const i=this.tracksInGroup[a];return this.setSubtitleTrack(a),i}else{if(r)return null;{const i=dw(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(_t.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:a,deliveryDirectives:n||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const n=gpe(t.textTracks),r=this.currentTrack;let a;if(r&&(a=n.filter(i=>WTe(r,i))[0],a||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(n).forEach(i=>{i.mode!=="disabled"&&i!==a&&(i.mode="disabled")}),a){const i=this.subtitleDisplay?"showing":"hidden";a.mode!==i&&(a.mode=i)}}setSubtitleTrack(t){const n=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(t<-1||t>=n.length||!Fa(t)){this.warn(`Invalid subtitle track id: ${t}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,a=n[t]||null;if(this.trackId=t,this.currentTrack=a,this.toggleTrackModes(),!a){this.hls.trigger(_t.SUBTITLE_TRACK_SWITCH,{id:t});return}const i=!!a.details&&!a.details.live;if(t===this.trackId&&a===r&&i)return;this.log(`Switching to subtitle-track ${t}`+(a?` "${a.name}" lang:${a.lang} group:${a.groupId}`:""));const{id:l,groupId:o="",name:c,type:d,url:u}=a;this.hls.trigger(_t.SUBTITLE_TRACK_SWITCH,{id:l,groupId:o,name:c,type:d,url:u});const h=this.switchParams(a.url,r==null?void 0:r.details,a.details);this.loadPlaylist(h)}}function $ln(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),n=t.toString();return URL.revokeObjectURL(t),n.slice(n.lastIndexOf("/")+1)}catch{let n=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const i=(n+Math.random()*16)%16|0;return n=Math.floor(n/16),(a=="x"?i:i&3|8).toString(16)})}}}function Rz(s){let t=5381,n=s.length;for(;n;)t=t*33^s.charCodeAt(--n);return(t>>>0).toString()}const XL=.025;let c0e=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function Uln(s,t,n){return`${s.identifier}-${n+1}-${Rz(t)}`}class qln{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 xke(t,n)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const n=this.dateRange.startTime,r=xke(n,t);return n-r<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,n=Fa(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 xke(t,n)}return t}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return Vln(this)}}function xke(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function mP(s){const t=s.timelineStart,n=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}class Hln{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(_t.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(n);this.interstitial=r,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(_t.LEVEL_LOADED,l),i.once(_t.AUDIO_TRACK_LOADED,l),i.once(_t.SUBTITLE_TRACK_LOADED,l),i.on(_t.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(_t.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(_t.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let n=this.assetItem.uri;try{n=lSt(n,t.config.primarySessionId||"").href}catch{}t.loadSource(n)}}bufferedInPlaceToEnd(t){var n;if(!this.appendInPlace)return!1;if((n=this.hls)!=null&&n.bufferedToEnd)return!0;if(!t)return!1;const r=Math.min(this._bufferedEosTime||1/0,this.duration),a=this.timelineOffset,i=wo.bufferInfo(t,a,0);return this.getAssetTime(i.end)>=r-.02}reachedPlayout(t){const r=this.interstitial.playoutLimit;return this.startOffset+t>=r}get destroyed(){var t;return!((t=this.hls)!=null&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return((t=this.hls)==null?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const n=wo.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: ${mP(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const oet=.033;class Gln extends a1{constructor(t,n){super("interstitials-sched",n),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,n){return this.events?this.events.reduce((r,a)=>t<=a.startOffset&&n>a.startOffset?(delete a.error,r+1):r,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,n){if(t.event)return this.findEventIndex(t.event.identifier);let r=-1;t.nextEvent?r=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(r=this.findEventIndex(t.previousEvent.identifier)+1);const a=this.items;if(a)for(a[r]||(n===void 0&&(n=t.start),r=this.findItemIndexAtTime(n));r>=0&&(i=a[r])!=null&&i.event;){var i;r--}return r}findItemIndexAtTime(t,n){const r=this.items;if(r)for(let a=0;ai.start&&t1)for(let i=0;io&&(n!o.includes(d.identifier)):[];l.length&&l.sort((d,u)=>{const h=d.cue.pre,p=d.cue.post,f=u.cue.pre,g=u.cue.post;if(h&&!f)return-1;if(f&&!h||p&&!g)return 1;if(g&&!p)return-1;if(!h&&!f&&!p&&!g){const b=d.startTime,v=u.startTime;if(b!==v)return b-v}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=l,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,c)}updateSchedule(t,n=[],r=!1){const a=this.events||[];if(a.length||n.length||this.length<2){const i=this.items,l=this.parseSchedule(a,t);(r||n.length||(i==null?void 0:i.length)!==l.length||l.some((c,d)=>Math.abs(c.playout.start-i[d].playout.start)>.005||Math.abs(c.playout.end-i[d].playout.end)>.005))&&(this.items=l,this.onScheduleUpdate(n,i))}}parseDateRanges(t,n,r){const a=[],i=Object.keys(t);for(let l=0;l!c.error&&!(c.cue.once&&c.hasPlayed)),t.length){this.resolveOffsets(t,n);let c=0,d=0;if(t.forEach((u,h)=>{const p=u.cue.pre,f=u.cue.post,g=t[h-1]||null,b=u.appendInPlace,v=f?i:u.startOffset,j=u.duration,_=u.timelineOccupancy===c0e.Range?j:0,S=u.resumptionOffset,A=(g==null?void 0:g.startTime)===v,T=v+u.cumulativeDuration;let D=b?T+j:v+S;if(p||!f&&v<=0){const M=d;d+=_,u.timelineStart=T;const F=l;l+=j,r.push({event:u,start:T,end:D,playout:{start:F,end:l},integrated:{start:M,end:d}})}else if(v<=i){if(!A){const z=v-c;if(z>oet){const V=c,W=d;d+=z;const K=l;l+=z;const Y={previousEvent:t[h-1]||null,nextEvent:u,start:V,end:V+z,playout:{start:K,end:l},integrated:{start:W,end:d}};r.push(Y)}else z>0&&g&&(g.cumulativeDuration+=z,r[r.length-1].end=v)}f&&(D=T),u.timelineStart=T;const M=d;d+=_;const F=l;l+=j,r.push({event:u,start:T,end:D,playout:{start:F,end:l},integrated:{start:M,end:d}})}else return;const L=u.resumeTime;f||L>i?c=i:c=L}),c{const d=o.cue.pre,u=o.cue.post,h=d?0:u?a:o.startTime;this.updateAssetDurations(o),l===h?o.cumulativeDuration=i:(i=0,l=h),!u&&o.snapOptions.in&&(o.resumeAnchor=BM(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+1XL?(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=BM(null,o.fragments,r);if(!d)return this.log(`"${t.identifier}" resumption ${r} does not align with any fragments in ${l} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=l==="audio"?.175:0;return Math.abs(d.start-r){const v=p.data,j=v==null?void 0:v.ASSETS;if(!Array.isArray(j)){const _=this.assignAssetListError(t,Pn.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,b);this.hls.trigger(_t.ERROR,_);return}t.assetListResponse=v,this.hls.trigger(_t.ASSET_LIST_LOADED,{event:t,assetListResponse:v,networkDetails:b})},onError:(p,f,g,b)=>{const v=this.assignAssetListError(t,Pn.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${p.code} ${p.text} (${f.url})`),f.url,b,g);this.hls.trigger(_t.ERROR,v)},onTimeout:(p,f,g)=>{const b=this.assignAssetListError(t,Pn.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,p,g);this.hls.trigger(_t.ERROR,b)}};return o.load(c,u,h),this.hls.trigger(_t.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,n,r,a,i,l){return t.error=r,{type:fi.NETWORK_ERROR,details:n,fatal:!1,interstitial:t,url:a,error:r,networkDetails:l,stats:i}}}function cet(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function ZI(s,t){return`[${s}] Advancing timeline position to ${t}`}class Kln extends a1{constructor(t,n){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const a=r-this.timelinePos;if(Math.abs(a)<1/7056e5)return;const l=a<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=r,this.bufferedPos=r;const o=this.playingItem;if(!o){this.checkBuffer();return}if(l&&this.schedule.resetErrorsInRange(r,r-a)&&this.updateSchedule(!0),this.checkBuffer(),l&&r=o.end){var c;const f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(r);if(g===-1&&(g=f+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${r} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&g>f){const b=this.schedule.findJumpRestrictedIndex(f+1,g);if(b>f){this.setSchedulePosition(b);return}}this.setSchedulePosition(g);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,f))}return}const u=d.timelineStart,h=d.duration||0;if(l&&r=u+h){var p;(p=o.event)!=null&&p.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,d)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const a=this.playingItem;if(!a||this.playingLastItem)return;if(r>=a.end){this.timelinePos=a.end;const o=this.findItemIndex(a);this.setSchedulePosition(o+1)}const i=this.playingAsset;if(!i)return;const l=i.timelineStart+(i.duration||0);r>=l&&this.setScheduleToAssetAtTime(r,i)},this.onScheduleUpdate=(r,a)=>{const i=this.schedule;if(!i)return;const l=this.playingItem,o=i.events||[],c=i.items||[],d=i.durations,u=r.map(b=>b.identifier),h=!!(o.length||u.length);(h||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(b=>$1(b))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let p=null,f=null;l&&(p=this.updateItem(l,this.timelinePos),this.itemsMatch(l,p)?this.playingItem=p:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),r.forEach(b=>{b.assetList.forEach(v=>{this.clearAssetPlayer(v.identifier,null)})}),this.playerQueue.forEach(b=>{if(b.interstitial.appendInPlace){const v=b.assetItem.timelineStart,j=b.timelineOffset-v;if(j)try{b.timelineOffset=v}catch(_){Math.abs(j)>XL&&this.warn(`${_} ("${b.assetId}" ${b.timelineOffset}->${v})`)}}}),h||a){if(this.hls.trigger(_t.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:d,removedIds:u}),this.isInterstitial(l)&&u.includes(l.event.identifier)){this.warn(`Interstitial "${l.event.identifier}" removed while playing`),this.primaryFallback(l.event);return}l&&this.trimInPlace(p,l),g&&f!==p&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=n,this.assetListLoader=new Wln(t),this.schedule=new Gln(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(_t.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(_t.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(_t.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(_t.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(_t.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(_t.BUFFER_APPENDED,this.onBufferAppended,this),t.on(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(_t.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(_t.MEDIA_ENDED,this.onMediaEnded,this),t.on(_t.ERROR,this.onError,this),t.on(_t.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(_t.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(_t.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(_t.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(_t.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(_t.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(_t.BUFFER_CODECS,this.onBufferCodecs,this),t.off(_t.BUFFER_APPENDED,this.onBufferAppended,this),t.off(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(_t.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(_t.MEDIA_ENDED,this.onMediaEnded,this),t.off(_t.ERROR,this.onError,this),t.off(_t.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;(t=this.getBufferingPlayer())==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.getBufferingPlayer())==null||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){$g(t,"play",this.onPlay),$g(t,"pause",this.onPause),$g(t,"seeking",this.onSeeking),$g(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,n){const r=this.media=n.media;tg(r,"seeking",this.onSeeking),tg(r,"timeupdate",this.onTimeupdate),tg(r,"play",this.onPlay),tg(r,"pause",this.onPause)}onMediaAttached(t,n){const r=this.effectivePlayingItem,a=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!a){this.clearScheduleState();const i=this.findItemIndex(r);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,n){const r=!!n.transferMedia,a=this.media;if(this.media=null,!r&&(a&&this.removeMediaListeners(a),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,n=()=>t.bufferingItem||t.waitingItem,r=h=>h&&t.getAssetPlayer(h.identifier),a=(h,p,f,g,b)=>{if(h){let v=h[p].start;const j=h.event;if(j){if(p==="playout"||j.timelineOccupancy!==c0e.Point){const _=r(f);(_==null?void 0:_.interstitial)===j&&(v+=_.assetItem.startOffset+_[b])}}else{const _=g==="bufferedPos"?l():t[g];v+=_-h.start}return v}return 0},i=(h,p)=>{var f;if(h!==0&&p!=="primary"&&(f=t.schedule)!=null&&f.length){var g;const b=t.schedule.findItemIndexAtTime(h),v=(g=t.schedule.items)==null?void 0:g[b];if(v){const j=v[p].start-v.start;return h+j}}return h},l=()=>{const h=t.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var p,f;return(p=t.primaryDetails)!=null&&p.live?t.primaryDetails.edge:((f=t.schedule)==null?void 0:f.durations[h])||0},c=(h,p)=>{var f,g;const b=t.effectivePlayingItem;if(b!=null&&(f=b.event)!=null&&f.restrictions.skip||!t.schedule)return;t.log(`seek to ${h} "${p}"`);const v=t.effectivePlayingItem,j=t.schedule.findItemIndexAtTime(h,p),_=(g=t.schedule.items)==null?void 0:g[j],S=t.getBufferingPlayer(),A=S==null?void 0:S.interstitial,T=A==null?void 0:A.appendInPlace,D=v&&t.itemsMatch(v,_);if(v&&(T||D)){const L=r(t.playingAsset),M=(L==null?void 0:L.media)||t.primaryMedia;if(M){const F=p==="primary"?M.currentTime:a(v,p,t.playingAsset,"timelinePos","currentTime"),z=h-F,V=(T?F:M.currentTime)+z;if(V>=0&&(!L||T||V<=L.duration)){M.currentTime=V;return}}}if(_){let L=h;if(p!=="primary"){const F=_[p].start,z=h-F;L=_.start+z}const M=!t.isInterstitial(_);if((!t.isInterstitial(v)||v.event.appendInPlace)&&(M||_.event.appendInPlace)){const F=t.media||(T?S==null?void 0:S.media:null);F&&(F.currentTime=L)}else if(v){const F=t.findItemIndex(v);if(j>F){const V=t.schedule.findJumpRestrictedIndex(F+1,j);if(V>F){t.setSchedulePosition(V);return}}let z=0;if(M)t.timelinePos=L,t.checkBuffer();else{const V=_.event.assetList,W=h-(_[p]||_).start;for(let K=V.length;K--;){const Y=V[K];if(Y.duration&&W>=Y.startOffset&&W{const h=t.effectivePlayingItem;if(t.isInterstitial(h))return h;const p=n();return t.isInterstitial(p)?p:null},u={get bufferedEnd(){const h=n(),p=t.bufferingItem;if(p&&p===h){var f;return a(p,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-p.playout.start||((f=t.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const h=d(),p=t.effectivePlayingItem;return p&&p===h?a(p,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-p.playout.start:0},set currentTime(h){const p=d(),f=t.effectivePlayingItem;f&&f===p&&c(h+f.playout.start,"playout")},get duration(){const h=d();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const p=(h=d())==null?void 0:h.event.assetList;return p?p.map(f=>t.getAssetPlayer(f.identifier)):[]},get playingIndex(){var h;const p=(h=d())==null?void 0:h.event;return p&&t.effectivePlayingAsset?p.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var h;return((h=t.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=t.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return n()},get bufferingIndex(){const h=n();return t.findItemIndex(h)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const h=t.effectivePlayingItem;return t.findItemIndex(h)},primary:{get bufferedEnd(){return l()},get currentTime(){const h=t.timelinePos;return h>0?h:0},set currentTime(h){c(h,"primary")},get duration(){return o("primary")},get seekableStart(){var h;return((h=t.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return a(n(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return a(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){c(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){var h;return i(((h=t.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{const h=t.effectivePlayingItem,p=h==null?void 0:h.event;if(p&&!p.restrictions.skip){const f=t.findItemIndex(h);if(p.appendInPlace){const g=h.playout.start+h.event.duration;c(g+.001,"playout")}else t.advanceAfterAssetEnded(p,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const n=this.playingItem,r=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!n||!r?!1:this.findItemIndex(n)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,n;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(n=a)==null?void 0:n.currentTime;if(!(i===void 0||!Fa(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} ${id(i)}`),this.detachedData=i}else n&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,n){var r,a;if(t.media===n)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(l.media)c&&(i=l.transferMedia(),this.detachedData=i),u="Primary";else if(d){const g=this.getBufferingPlayer();g?(i=g.transferMedia(),u=`${g}`):u="detached MediaSource"}else u="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${id(i)}`);else if(!this.detachedData||l.media===n){const g=this.playerQueue;g.length>1&&g.forEach(b=>{if(o&&b.interstitial.appendInPlace!==c){const v=b.interstitial;this.clearInterstitial(b.interstitial,null),v.appendInPlace=!1,v.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${v}`)}}),this.hls.detachMedia(),this.detachedData={media:n}}}const h=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed",p=h&&i?i:n;this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${u} (media.currentTime: ${n.currentTime})`);const f=this.schedule;if(p===i&&f){const g=o&&t.assetId===f.assetIdAtEnd;p.overrides={duration:f.duration,endOfStream:!o||g,cueRemoval:!o}}t.attachMedia(p)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,n=t==null?void 0:t.events;if(!n||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const r=this.timelinePos,a=this.effectivePlayingItem;if(r===-1){const i=this.hls.startPosition;if(this.timelinePos=i,n.length===0)this.setSchedulePosition(0);else if(n[0].cue.pre){this.log(ZI("checkStart (preroll)",i));const l=t.findEventIndex(n[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(ZI("checkStart",i));const l=this.timelinePos=i>0?i:0,o=t.findItemIndexAtTime(l);this.setSchedulePosition(o)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(a&&!this.playingItem){this.log(ZI("checkStart (playing item)",a.start));const i=t.findItemIndex(a);this.setSchedulePosition(i)}}advanceAssetBuffering(t,n){const r=t.event,a=r.findAssetIndex(n),i=gke(r,a);if(!r.isAssetPastPlayoutLimit(i))this.bufferedToEvent(t,i);else if(this.schedule){var l;const o=(l=this.schedule.items)==null?void 0:l[this.findItemIndex(t)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(t,n,r){const a=gke(t,r);if(t.isAssetPastPlayoutLimit(a)){if(this.schedule){const i=this.schedule.items;if(i){const l=n+1,o=i.length;if(l>=o){this.setSchedulePosition(-1);return}const c=t.resumeTime;this.timelinePos=0?a[t]:null;this.log(`setSchedulePosition ${t}, ${n} (${i&&$1(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const u=l.event,h=this.playingAsset,p=h==null?void 0:h.identifier,f=p?this.getAssetPlayer(p):null;if(f&&p&&(!this.eventItemsMatch(l,i)||n!==void 0&&p!==u.assetList[n].identifier)){var c;const g=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${u.assetList.length} ${mP(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(_t.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:g,event:u,schedule:a.slice(0),scheduleIndex:t,player:f}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(p,i),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${$1(l)}`),u.hasPlayed=!0,this.hls.trigger(_t.INTERSTITIAL_ENDED,{event:u,schedule:a.slice(0),scheduleIndex:t}),u.cue.once)){var d;this.updateSchedule();const g=(d=this.schedule)==null?void 0:d.items;if(i&&g){const b=this.findItemIndex(i);this.advanceSchedule(b,g,n,l,o)}return}}this.advanceSchedule(t,a,n,l,o)}advanceSchedule(t,n,r,a,i){const l=this.schedule;if(!l)return;const o=n[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{const h=u.interstitial,p=l.findEventIndex(h.identifier);(pt+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(r===void 0){r=l.findAssetIndex(u,this.timelinePos);const g=gke(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 p=this.preloadAssets(u,r);if(this.eventItemsMatch(o,h||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${$1(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(_t.INTERSTITIAL_STARTED,{event:u,schedule:n.slice(0),scheduleIndex:t})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=u.assetList[r];if(!f){this.advanceAfterAssetEnded(u,t,r||0);return}if(p||(p=this.getAssetPlayer(f.identifier)),p===null||p.destroyed){const g=u.assetList.length;this.warn(`asset ${r+1}/${g} player destroyed ${u}`),p=this.createAssetPlayer(u,f,r),p.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(p,r,n,t,c),this.shouldPlay&&cet(p.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&cet(this.hls.media)):i&&this.isInterstitial(a)&&(this.endedItem=null,this.playingItem=a,a.event.appendInPlace||this.attachPrimary(l.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var t;return(t=this.mediaSelection)==null?void 0:t.main.details}get primaryLive(){var t;return!!((t=this.primaryDetails)!=null&&t.live)}resumePrimary(t,n,r){var a,i;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${$1(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,n),this.log(ZI("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,t)}if(!r)return;const l=(i=this.schedule)==null?void 0:i.items;l&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${$1(t)}`),this.hls.trigger(_t.INTERSTITIALS_PRIMARY_RESUMED,{schedule:l.slice(0),scheduleIndex:n}),this.checkBuffer())}getPrimaryResumption(t,n){const r=t.start;if(this.primaryLive){const a=this.primaryDetails;if(n===0)return this.hls.startPosition;if(a&&(ra.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(t){const n=this.getAssetPlayer(t.identifier);return n!=null&&n.hls?n.hls.bufferedToEnd:wo.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,n,r){n?this.setBufferingItem(n):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const a=this.primaryMedia;if(!a)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,a),r&&this.startLoadingPrimaryAt(t,r)),r||(this.log(ZI("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,r))}startLoadingPrimaryAt(t,n){var r;const a=this.hls;!a.loadingEnabled||!a.media||Math.abs((((r=a.mainForwardBufferInfo)==null?void 0:r.start)||a.media.currentTime)-t)>.5?a.startLoad(t,n):a.bufferingEnabled||a.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),(t=this.schedule)==null||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(_t.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(_t.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=Ec(Ec({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=a,this.schedule.parseInterstitialDateRanges(a,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,n){const r=this.hls.audioTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=Ec(Ec({},this.altSelection),{},{audio:r});return}const i=Ec(Ec({},a),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(t,n){const r=this.hls.subtitleTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=Ec(Ec({},this.altSelection),{},{subtitles:r});return}const i=Ec(Ec({},a),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(t,n){const r=gJe(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(n)||a.setAudioOption(r)))}onSubtitleTrackSwitch(t,n){const r=gJe(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=wo.bufferInfo(this.primaryMedia,r,0);(a.end>r||(a.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${$1(t)} (was ${$1(n)})`),this.attachPrimary(r,null,!0),this.flushFrontBuffer(r))}}itemsMatch(t,n){return!!n&&(t===n||t.event&&n.event&&this.eventItemsMatch(t,n)||!t.event&&!n.event&&this.findItemIndex(t)===this.findItemIndex(n))}eventItemsMatch(t,n){var r;return!!n&&(t===n||t.event.identifier===((r=n.event)==null?void 0:r.identifier))}findItemIndex(t,n){return t&&this.schedule?this.schedule.findItemIndex(t,n):-1}updateSchedule(t=!1){var n;const r=this.mediaSelection;r&&((n=this.schedule)==null||n.updateSchedule(r,[],t))}checkBuffer(t){var n;const r=(n=this.schedule)==null?void 0:n.items;if(!r)return;const a=wo.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=a.len<1),this.updateBufferedPos(a.end,r,t)}updateBufferedPos(t,n,r){const a=this.schedule,i=this.bufferingItem;if(this.bufferedPos>t||!a)return;if(n.length===1&&this.itemsMatch(n[0],i)){this.bufferedPos=t;return}const l=this.playingItem,o=this.findItemIndex(l);let c=a.findItemIndexAtTime(t);if(this.bufferedPos=i.end||(d=p.event)!=null&&d.appendInPlace&&t+.01>=p.start)&&(c=h),this.isInterstitial(i)){const f=i.event;if(h-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=t,c>u&&c>o)this.bufferedToItem(p);else{const f=this.primaryDetails;this.primaryLive&&f&&t>f.edge-f.targetduration&&p.start{const i=this.getAssetPlayer(a.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(n))})}setBufferingItem(t){const n=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(t,n)&&r){const{items:a,events:i}=r;if(!a||!i)return n;const l=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const c=o?o.remaining:n?n.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${$1(t)}`+(n?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(l){const d=r.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((u,h)=>{const p=this.getAssetPlayer(u.identifier);p&&(h===d&&p.loadSource(),p.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(_t.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:a.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return n}bufferedToItem(t,n=0){const r=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,n);else if(r!==null){this.bufferingAsset=null;const a=this.detachedData;a?a.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t):this.preloadPrimary(t)}}}preloadPrimary(t){const n=this.findItemIndex(t),r=this.getPrimaryResumption(t,n);this.startLoadingPrimaryAt(r)}bufferedToEvent(t,n){const r=t.event,a=r.assetList.length===0&&!r.assetListLoader,i=r.cue.once;if(a||!i){const l=this.preloadAssets(r,n);if(l!=null&&l.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(l,o)}}}preloadAssets(t,n){const r=t.assetUrl,a=t.assetList.length,i=a===0&&!t.assetListLoader,l=t.cue.once;if(i){const c=t.timelineStart;if(t.appendInPlace){var o;const p=this.playingItem;!this.isInterstitial(p)&&(p==null||(o=p.nextEvent)==null?void 0:o.identifier)===t.identifier&&this.flushFrontBuffer(c+.25)}let d,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(t.cue.pre||t.cue.post)){const p=u-c;p>0&&(d=Math.round(p*1e3)/1e3)}if(this.log(`Load interstitial asset ${n+1}/${r?1:a} ${t}${d?` live-start: ${u} start-offset: ${d}`:""}`),r)return this.createAsset(t,0,0,c,t.duration,r);const h=this.assetListLoader.loadAssetList(t,d);h&&(t.assetListLoader=h)}else if(!l&&a){for(let d=n;d{this.hls.trigger(_t.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(t){const n=this.playerQueue;for(let r=0;r1){const T=n.duration;T&&A{if(A.live){var T;const M=new Error(`Interstitials MUST be VOD assets ${t}`),F={fatal:!0,type:fi.OTHER_ERROR,details:Pn.INTERSTITIAL_ASSET_ITEM_ERROR,error:M},z=((T=this.schedule)==null?void 0:T.findEventIndex(t.identifier))||-1;this.handleAssetItemError(F,t,z,r,M.message);return}const D=A.edge-A.fragmentStart,L=n.duration;(b||L===null||D>L)&&(b=!1,this.log(`Interstitial asset "${h}" duration change ${L} > ${D}`),n.duration=D,this.updateSchedule())};g.on(_t.LEVEL_UPDATED,(A,{details:T})=>v(T)),g.on(_t.LEVEL_PTS_UPDATED,(A,{details:T})=>v(T)),g.on(_t.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const j=(A,T)=>{const D=this.getAssetPlayer(h);if(D&&T.tracks){D.off(_t.BUFFER_CODECS,j),D.tracks=T.tracks;const L=this.primaryMedia;this.bufferingAsset===D.assetItem&&L&&!D.media&&this.bufferAssetPlayer(D,L)}};g.on(_t.BUFFER_CODECS,j);const _=()=>{var A;const T=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;const D=this.schedule.findEventIndex(t.identifier),L=(A=this.schedule.items)==null?void 0:A[D];this.isInterstitial(L)&&this.advanceAssetBuffering(L,n)};g.on(_t.BUFFERED_TO_END,_);const S=A=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,D,A)};return g.once(_t.MEDIA_ENDED,S(r)),g.once(_t.PLAYOUT_LIMIT_REACHED,S(1/0)),g.on(_t.ERROR,(A,T)=>{if(!this.schedule)return;const D=this.getAssetPlayer(h);if(T.details===Pn.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(T,t,this.schedule.findEventIndex(t.identifier),r,`Asset player error ${T.error} ${t}`)}),g.on(_t.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const T=new Error(`Asset player destroyed unexpectedly ${h}`),D={fatal:!0,type:fi.OTHER_ERROR,details:Pn.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(D,t,this.schedule.findEventIndex(t.identifier),r,T.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${mP(n)}`),this.hls.trigger(_t.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&&$1(n)}`),this.transferMediaFromPlayer(a,n),this.playerQueue.splice(r,1),a.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,n,r,a,i){const{interstitial:l,assetItem:o,assetId:c}=t,d=l.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==c)&&(u&&(this.clearAssetPlayer(u.identifier,r[a]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${n+1}/${d} ${mP(o)}`),this.hls.trigger(_t.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:n,event:l,schedule:r.slice(0),scheduleIndex:a,player:t})),this.bufferAssetPlayer(t,i)}bufferAssetPlayer(t,n){var r,a;if(!this.schedule)return;const{interstitial:i,assetItem:l}=t,o=this.schedule.findEventIndex(i.identifier),c=(r=this.schedule.items)==null?void 0:r[o];if(!c)return;t.loadSource(),this.setBufferingItem(c),this.bufferingAsset=l;const d=this.getBufferingPlayer();if(d===t)return;const u=i.appendInPlace;if(u&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;const h=(d==null?void 0:d.tracks)||((a=this.detachedData)==null?void 0:a.tracks)||this.requiredTracks;if(u&&l!==this.playingAsset){if(!t.tracks){this.log(`Waiting for track info before buffering ${t}`);return}if(h&&!VNt(h,t.tracks)){const p=new Error(`Asset ${mP(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),f={fatal:!0,type:fi.OTHER_ERROR,details:Pn.INTERSTITIAL_ASSET_ITEM_ERROR,error:p},g=i.findAssetIndex(l);this.handleAssetItemError(f,i,o,g,p.message);return}}this.transferMediaTo(t,n)}handleInPlaceStall(t){const n=this.schedule,r=this.primaryMedia;if(!n||!r)return;const a=r.currentTime,i=n.findAssetIndex(t,a),l=t.assetList[i];if(l){const o=this.getAssetPlayer(l.identifier);if(o){const c=o.currentTime||a-l.timelineStart,d=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${o} ${t} (media.currentTime: ${a})`),c&&(d/r.playbackRate<.5||o.bufferedInPlaceToEnd(r))&&o.hls){const u=n.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,u,i)}}}}advanceInPlace(t){const n=this.primaryMedia;n&&n.currentTime!b.error))n.error=g;else for(let b=a;b{const j=parseFloat(b.DURATION);this.createAsset(i,v,u,c+u,j,b.URI),u+=j}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${i}`);const h=this.waitingItem,p=(h==null?void 0:h.event.identifier)===l;this.updateSchedule();const f=(a=this.bufferingItem)==null?void 0:a.event;if(p){var g;const b=this.schedule.findEventIndex(l),v=(g=this.schedule.items)==null?void 0:g[b];if(v){if(!this.playingItem&&this.timelinePos>v.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==b){i.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),this.primaryFallback(i);return}this.setBufferingItem(v)}this.setSchedulePosition(b)}else if((f==null?void 0:f.identifier)===l){const b=i.assetList[0];if(b){const v=this.getAssetPlayer(b.identifier);if(f.appendInPlace){const j=this.primaryMedia;v&&j&&this.bufferAssetPlayer(v,j)}else v&&v.loadSource()}}}onError(t,n){if(this.schedule)switch(n.details){case Pn.ASSET_LIST_PARSING_ERROR:case Pn.ASSET_LIST_LOAD_ERROR:case Pn.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case Pn.BUFFER_STALLED_ERROR:{const r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace){this.handleInPlaceStall(r.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const det=500;class Yln extends Y8e{constructor(t,n,r){super(t,n,r,"subtitle-stream-controller",Qa.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_t.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(_t.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(_t.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(_t.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(_t.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_t.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(_t.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(_t.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(_t.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(_t.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,n){this.stopLoad(),this.state=ur.IDLE,this.setInterval(det),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,n){this.tracksBuffered=[],super.onMediaDetaching(t,n)}onLevelLoaded(t,n){this.mainDetails=n.details}onSubtitleFragProcessed(t,n){const{frag:r,success:a}=n;if(this.fragContextChanged(r)||(Mh(r)&&(this.fragPrevious=r),this.state=ur.IDLE),!a)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let l;const o=r.start;for(let d=0;d=i[d].start&&o<=i[d].end){l=i[d];break}const c=r.start+r.duration;l?l.end=c:(l={start:o,end:c},i.push(l)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(t,n){const{startOffset:r,endOffset:a}=n;if(r===0&&a!==Number.POSITIVE_INFINITY){const i=a-1;if(i<=0)return;n.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(l=>{for(let o=0;onew S$(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const a=new S$(r);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Qa.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,n){var r;if(this.currentTrackId=n.id,!((r=this.levels)!=null&&r.length)||this.currentTrackId===-1){this.clearInterval();return}const a=this.levels[this.currentTrackId];a!=null&&a.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,a&&this.state!==ur.STOPPED&&this.setInterval(det)}onSubtitleTrackLoaded(t,n){var r;const{currentTrackId:a,levels:i}=this,{details:l,id:o}=n;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=i[o];if(o>=i.length||!c)return;this.log(`Subtitle track ${o} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""},duration:${l.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(l.live||(r=c.details)!=null&&r.live){if(l.deltaUpdateFailed)return;const h=this.mainDetails;if(!h){this.startFragRequested=!1;return}const p=h.fragments[0];if(!c.details)l.hasProgramDateTime&&h.hasProgramDateTime?(o0e(l,h),d=l.fragmentStart):p&&(d=p.start,VTe(l,d));else{var u;d=this.alignPlaylists(l,c.details,(u=this.levelLastLoaded)==null?void 0:u.details),d===0&&p&&(d=p.start,VTe(l,d))}h&&!this.startFragRequested&&this.setStartPosition(h,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(_t.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:n.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===ur.IDLE&&(BM(null,l.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(t){const{frag:n,payload:r}=t,a=n.decryptdata,i=this.hls;if(!this.fragContextChanged(n)&&r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&ZL(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,W8e(a.method)).catch(o=>{throw i.trigger(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:n}),o}).then(o=>{const c=performance.now();i.trigger(_t.FRAG_DECRYPTED,{frag:n,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=ur.IDLE})}}doTick(){if(!this.media){this.state=ur.IDLE;return}if(this.state===ur.IDLE){const{currentTrackId:t,levels:n}=this,r=n==null?void 0:n[t];if(!r||!n.length||!r.details||this.waitForLive(r))return;const{config:a}=this,i=this.getLoadPosition(),l=wo.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,a.maxBufferHole),{end:o,len:c}=l,d=r.details,u=this.hls.maxBufferLength+d.levelTargetDuration;if(c>u)return;const h=d.fragments,p=h.length,f=d.edge;let g=null;const b=this.fragPrevious;if(of-_?0:_;g=BM(b,h,Math.max(h[0].start,o),S),!g&&b&&b.start{if(a=a>>>0,a>i-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${a}) is greater than the maximum bound (${i})`);return t[a][r]};this.buffered={get length(){return t.length},end(r){return n("end",r,t.length)},start(r){return n("start",r,t.length)}}}}const Qln={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},cSt=s=>String.fromCharCode(Qln[s]||s),H1=15,p2=100,Xln={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Jln={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ecn={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},tcn={25:2,26:4,29:6,30:8,31:10,27:13,28:15},scn=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class ncn{constructor(){this.time=null,this.verboseLevel=0}log(t,n){if(this.verboseLevel>=t){const r=typeof n=="function"?n():n;Lc.log(`${this.time} [${t}] ${r}`)}}}const b3=function(t){const n=[];for(let r=0;rp2&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=p2)}moveCursor(t){const n=this.pos+t;if(t>1)for(let r=this.pos+1;r=144&&this.backSpace();const n=cSt(t);if(this.pos>=p2){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 = "+id(t));let n=t.row-1;if(this.nrRollUpRows&&n"bkgData = "+id(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;i0&&(t?r="["+n.join(" | ")+"]":r=n.join(` `)),r}getTextAndFormat(){return this.rows}}class uet{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 yke(r),this.nonDisplayedMemory=new yke(r),this.lastOutputScreen=new yke(r),this.currRollUpRow=this.displayedMemory.rows[H1-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[H1-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: "+id(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 het{constructor(t,n,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=ocn(),this.logger=void 0;const a=this.logger=new ncn;this.channels=[null,new uet(t,n,a),new uet(t+1,r,a)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,n){this.channels[t].setHandler(n)}addData(t,n){this.logger.time=t;for(let r=0;r"["+b3([n[r],n[r+1]])+"] -> ("+b3([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(icn(a,i,c)){KG(null,null,c),this.logger.log(3,()=>"Repeated command ("+b3([a,i])+") is dropped");continue}KG(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 KG(null,null,c);if(!l&&(o=this.parseChars(a,i),o)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!l&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+b3([a,i])+" orig: "+b3([n[r],n[r+1]]))}}parseCmd(t,n){const r=(t===20||t===28||t===21||t===29)&&n>=32&&n<=47,a=(t===23||t===31)&&n>=33&&n<=35;if(!(r||a))return!1;const i=t===20||t===21||t===23?1:2,l=this.channels[i];return t===20||t===21||t===28||t===29?n===32?l.ccRCL():n===33?l.ccBS():n===34?l.ccAOF():n===35?l.ccAON():n===36?l.ccDER():n===37?l.ccRU(2):n===38?l.ccRU(3):n===39?l.ccRU(4):n===40?l.ccFON():n===41?l.ccRDC():n===42?l.ccTR():n===43?l.ccRTD():n===44?l.ccEDM():n===45?l.ccCR():n===46?l.ccENM():n===47&&l.ccEOC():l.ccTO(n-32),this.currentChannel=i,!0}parseMidrow(t,n){let r=0;if((t===17||t===25)&&n>=32&&n<=47){if(t===17?r=1:r=2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const a=this.channels[r];return a?(a.ccMIDROW(n),this.logger.log(3,()=>"MIDROW ("+b3([t,n])+")"),!0):!1}return!1}parsePAC(t,n){let r;const a=(t>=17&&t<=23||t>=25&&t<=31)&&n>=64&&n<=127,i=(t===16||t===24)&&n>=64&&n<=95;if(!(a||i))return!1;const l=t<=23?1:2;n>=64&&n<=95?r=l===1?Xln[t]:ecn[t]:r=l===1?Jln[t]:tcn[t];const o=this.channels[l];return o?(o.setPAC(this.interpretPAC(r,n)),this.currentChannel=l,!0):!1}interpretPAC(t,n){let r;const a={color:null,italics:!1,indent:null,underline:!1,row:t};return n>95?r=n-96:r=n-64,a.underline=(r&1)===1,r<=13?a.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(a.italics=!0,a.color="white"):a.indent=Math.floor((r-16)/2)*4,a}parseChars(t,n){let r,a=null,i=null;if(t>=25?(r=2,i=t-8):(r=1,i=t),i>=17&&i<=19){let l;i===17?l=n+80:i===18?l=n+112:l=n+144,this.logger.log(2,()=>"Special char '"+cSt(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 = "+b3(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=scn[i],n%2===1&&(l.background=l.background+"_semi")):n===45?l.background="transparent":(l.foreground="black",n===47&&(l.underline=!0));const o=t<=23?1:2;return this.channels[o].setBkgData(l),!0}reset(){for(let t=0;t100)throw new Error("Position must be between 0 and 100.");D=z,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},h,{get:function(){return L},set:function(z){const V=a(z);if(!V)throw new SyntaxError("An invalid or illegal string was specified.");L=V,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},h,{get:function(){return M},set:function(z){if(z<0||z>100)throw new Error("Size must be between 0 and 100.");M=z,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},h,{get:function(){return F},set:function(z){const V=a(z);if(!V)throw new SyntaxError("An invalid or illegal string was specified.");F=V,this.hasBeenReset=!0}})),u.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class lcn{decode(t,n){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function uSt(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 ccn{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 hSt(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 XTe=new oDe(0,0,""),YG=XTe.align==="middle"?"middle":"center";function dcn(s,t,n){const r=s;function a(){const o=uSt(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 ccn;hSt(o,function(p,f){let g;switch(p){case"region":for(let b=n.length-1;b>=0;b--)if(n[b].id===f){d.set(p,n[b].region);break}break;case"vertical":d.alt(p,f,["rl","lr"]);break;case"line":g=f.split(","),d.integer(p,g[0]),d.percent(p,g[0])&&d.set("snapToLines",!1),d.alt(p,g[0],["auto"]),g.length===2&&d.alt("lineAlign",g[1],["start",YG,"end"]);break;case"position":g=f.split(","),d.percent(p,g[0]),g.length===2&&d.alt("positionAlign",g[1],["start",YG,"end","line-left","line-right","auto"]);break;case"size":d.percent(p,f);break;case"align":d.alt(p,f,["start",YG,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&XTe.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",YG);let h=d.get("position","auto");h==="auto"&&XTe.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 mSt(s){return s.replace(//gi,` `)}class ucn{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new lcn,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=mSt(i);l")===-1){n.cue.id=i;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{dcn(i,n.cue,n.regionList)}catch{n.cue=null,n.state="BADCUE";continue}n.state="CUETEXT";continue;case"CUETEXT":{const o=i.indexOf("-->")!==-1;if(!i||o&&(l=!0)){n.oncue&&n.cue&&n.oncue(n.cue),n.cue=null,n.state="ID";continue}if(n.cue===null)continue;n.cue.text&&(n.cue.text+=` `),n.cue.text+=i}continue;case"BADCUE":i||(n.state="ID")}}}catch{n.state==="CUETEXT"&&n.cue&&n.oncue&&n.oncue(n.cue),n.cue=null,n.state=n.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||t.state==="HEADER")&&(t.buffer+=` `,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(n){t.onparsingerror&&t.onparsingerror(n)}return t.onflush&&t.onflush(),this}}const hcn=/\r\n|\n\r|\n|\r/g,vke=function(t,n,r=0){return t.slice(r,r+n.length)===n},mcn=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(!Fa(n)||!Fa(r)||!Fa(a)||!Fa(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return n+=1e3*r,n+=60*1e3*a,n+=60*60*1e3*i,n};function lDe(s,t,n){return Rz(s.toString())+Rz(t.toString())+Rz(n)}const pcn=function(t,n,r){let a=t[n],i=t[a.prevCC];if(!i||!i.new&&a.new){t.ccOffset=t.presentationOffset=a.start,a.new=!1;return}for(;(l=i)!=null&&l.new;){var l;t.ccOffset+=a.start-i.start,a.new=!1,a=i,i=t[a.prevCC]}t.presentationOffset=r};function fcn(s,t,n,r,a,i,l){const o=new ucn,c=vy(new Uint8Array(s)).trim().replace(hcn,` `).split(` `),d=[],u=t?_on(t.baseTime,t.timescale):0;let h="00:00.000",p=0,f=0,g,b=!0;o.oncue=function(v){const j=n[r];let _=n.ccOffset;const S=(p-u)/9e4;if(j!=null&&j.new&&(f!==void 0?_=n.ccOffset=j.start:pcn(n,r,S)),S){if(!t){g=new Error("Missing initPTS for VTT MPEGTS");return}_=S-n.presentationOffset}const A=v.endTime-v.startTime,T=U0((v.startTime+_-f)*9e4,a*9e4)/9e4;v.startTime=Math.max(T,0),v.endTime=Math.max(T+A,0);const D=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(D)),v.id||(v.id=lDe(v.startTime,v.endTime,D)),v.endTime>0&&d.push(v)},o.onparsingerror=function(v){g=v},o.onflush=function(){if(g){l(g);return}i(d)},c.forEach(v=>{if(b)if(vke(v,"X-TIMESTAMP-MAP=")){b=!1,v.slice(16).split(",").forEach(j=>{vke(j,"LOCAL:")?h=j.slice(6):vke(j,"MPEGTS:")&&(p=parseInt(j.slice(7)))});try{f=mcn(h)/1e3}catch(j){g=j}return}else v===""&&(b=!1);o.parse(v+` `)}),o.flush()}const bke="stpp.ttml.im1t",pSt=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,fSt=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,xcn={left:"start",center:"center",right:"end",start:"start",end:"end"};function met(s,t,n,r){const a=sl(new Uint8Array(s),["mdat"]);if(a.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>vy(o)),l=bon(t.baseTime,1,t.timescale);try{i.forEach(o=>n(gcn(o,l)))}catch(o){r(o)}}function gcn(s,t){const a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!a)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},l=Object.keys(i).reduce((h,p)=>(h[p]=a.getAttribute(`ttp:${p}`)||i[p],h),{}),o=a.getAttribute("xml:space")!=="preserve",c=pet(_ke(a,"styling","style")),d=pet(_ke(a,"layout","region")),u=_ke(a,"body","[begin]");return[].map.call(u,h=>{const p=xSt(h,o);if(!p||!h.hasAttribute("begin"))return null;const f=jke(h.getAttribute("begin"),l),g=jke(h.getAttribute("dur"),l);let b=jke(h.getAttribute("end"),l);if(f===null)throw fet(h);if(b===null){if(g===null)throw fet(h);b=f+g}const v=new oDe(f-t,b-t,p);v.id=lDe(v.startTime,v.endTime,v.text);const j=d[h.getAttribute("region")],_=c[h.getAttribute("style")],S=ycn(j,_,c),{textAlign:A}=S;if(A){const T=xcn[A];T&&(v.lineAlign=T),v.align=A}return Yc(v,S),v}).filter(h=>h!==null)}function _ke(s,t,n){const r=s.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function pet(s){return s.reduce((t,n)=>{const r=n.getAttribute("xml:id");return r&&(t[r]=n),t},{})}function xSt(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?xSt(r,t):t?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function ycn(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=wke(t,r,c)||wke(s,r,c)||wke(a,r,c);return d&&(o[c]=d),o},{})}function wke(s,t,n){return s&&s.hasAttributeNS(t,n)?s.getAttributeNS(t,n):null}function fet(s){return new Error(`Could not parse ttml timestamp ${s}`)}function jke(s,t){if(!s)return null;let n=uSt(s);return n===null&&(pSt.test(s)?n=vcn(s,t):fSt.test(s)&&(n=bcn(s,t))),n}function vcn(s,t){const n=pSt.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 bcn(s,t){const n=fSt.exec(s),r=Number(n[1]);switch(n[2]){case"h":return r*3600;case"m":return r*60;case"ms":return r*1e3;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}class ZG{constructor(t,n){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=n}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,n,r){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=n,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class _cn{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=get(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_t.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(_t.FRAG_LOADING,this.onFragLoading,this),t.on(_t.FRAG_LOADED,this.onFragLoaded,this),t.on(_t.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(_t.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(_t.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(_t.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(_t.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_t.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(_t.FRAG_LOADING,this.onFragLoading,this),t.off(_t.FRAG_LOADED,this.onFragLoaded,this),t.off(_t.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(_t.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(_t.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(_t.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new ZG(this,"textTrack1"),n=new ZG(this,"textTrack2"),r=new ZG(this,"textTrack3"),a=new ZG(this,"textTrack4");this.cea608Parser1=new het(1,t,n),this.cea608Parser2=new het(3,r,a)}addCues(t,n,r,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=wcn(c[0],c[1],n,r);if(d>=0&&(c[0]=Math.min(c[0],n),c[1]=Math.max(c[1],r),l=!0,d/(r-n)>.5))return}if(l||i.push([n,r]),this.config.renderTextTracksNatively){const o=this.captionsTracks[t];this.Cues.newCue(o,n,r,a)}else{const o=this.Cues.newCue(null,n,r,a);this.hls.trigger(_t.CUES_PARSED,{type:"captions",cues:o,track:t})}}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){const{unparsedVttFrags:o}=this;r===Qa.MAIN&&(this.initPTS[n.cc]={baseTime:a,timescale:i,trackId:l}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(_t.FRAG_LOADED,c):this.hls.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,n){const{media:r}=this;if(r)for(let a=0;a{qP(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=get(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const n=t.textTracks;if(n)for(let r=0;ri.textCodec===bke);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(Wkt(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const l=this.media,o=l?gpe(l.textTracks):null;if(this.tracks.forEach((c,d)=>{let u;if(o){let h=null;for(let p=0;pd!==null).map(d=>d.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const l=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(_t.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}}onManifestLoaded(t,n){this.config.enableCEA708Captions&&n.captions&&n.captions.forEach(r=>{const a=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!a)return;const i=`textTrack${a[1]}`,l=this.captionsProperties[i];l&&(l.label=r.name,r.lang&&(l.languageCode=r.lang),l.media=r)})}closedCaptionsForLevel(t){const n=this.hls.levels[t.level];return n==null?void 0:n.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,n){if(this.enabled&&n.frag.type===Qa.MAIN){var r,a;const{cea608Parser1:i,cea608Parser2:l,lastSn:o}=this,{cc:c,sn:d}=n.frag,u=(r=(a=n.part)==null?void 0:a.index)!=null?r:-1;i&&l&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||c!==this.lastCc)&&(i.reset(),l.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(t,n){const{frag:r,payload:a}=n;if(r.type===Qa.SUBTITLE)if(a.byteLength){const i=r.decryptdata,l="stats"in n;if(i==null||!i.encrypted||l){const o=this.tracks[r.level],c=this.vttCCs;c[r.cc]||(c[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),o&&o.textCodec===bke?this._parseIMSC1(r,a):this._parseVTTs(n)}}else this.hls.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,n){const r=this.hls;met(n,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{r.logger.log(`Failed to parse IMSC1: ${a}`),r.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:a})})}_parseVTTs(t){var n;const{frag:r,payload:a}=t,{initPTS:i,unparsedVttFrags:l}=this,o=i.length-1;if(!i[r.cc]&&o===-1){l.push(t);return}const c=this.hls,d=(n=r.initSegment)!=null&&n.data?Qv(r.initSegment.data,new Uint8Array(a)).buffer:a;fcn(d,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),c.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},u=>{const h=u.message==="Missing initPTS for VTT MPEGTS";h?l.push(t):this._fallbackToIMSC1(r,a),c.logger.log(`Failed to parse VTT cue: ${u}`),!(h&&o>r.cc)&&c.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(t,n){const r=this.tracks[t.level];r.textCodec||met(n,this.initPTS[t.cc],()=>{r.textCodec=bke,this._parseIMSC1(t,n)},()=>{r.textCodec="wvtt"})}_appendCues(t,n){const r=this.hls;if(this.config.renderTextTracksNatively){const a=this.textTracks[n];if(!a||a.mode==="disabled")return;t.forEach(i=>oSt(a,i))}else{const a=this.tracks[n];if(!a)return;const i=a.default?"default":"subtitles"+n;r.trigger(_t.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,n){const{frag:r}=n;r.type===Qa.SUBTITLE&&this.onFragLoaded(_t.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===Qa.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let i=0;iQTe(o[c],n,r))}if(this.config.renderTextTracksNatively&&n===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>QTe(o[c],n,a))}}}extractCea608Data(t){const n=[[],[]],r=t[0]&31;let a=2;for(let i=0;i=16?c--:c++;const f=mSt(d.trim()),g=lDe(t,n,f);s!=null&&(h=s.cues)!=null&&h.getCueById(g)||(l=new u(t,n,f),l.id=g,l.line=p+1,l.align="left",l.position=10+Math.min(80,Math.floor(c*8/32)*10),a.push(l))}return s&&a.length&&(a.sort((p,f)=>p.line==="auto"||f.line==="auto"?0:p.line>8&&f.line>8?f.line-p.line:p.line-f.line),a.forEach(p=>oSt(s,p))),a}};function kcn(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Scn=/(\d+)-(\d+)\/(\d+)/;class yet{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Acn,this.controller=new self.AbortController,this.stats=new B8e}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,n,r){const a=this.stats;if(a.loading.start)throw new Error("Loader can only be used once.");a.loading.start=self.performance.now();const i=Ccn(t,this.controller.signal),l=t.responseType==="arraybuffer",o=l?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=n.loadPolicy;this.context=t,this.config=n,this.callbacks=r,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),n.timeout=c&&Fa(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},n.timeout),(E$(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var p;this.response=this.loader=h;const f=Math.max(self.performance.now(),a.loading.start);if(self.clearTimeout(this.requestTimeout),n.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},d-(f-a.loading.start)),!h.ok){const{status:b,statusText:v}=h;throw new Mcn(v||"fetch, bad network response",b,h)}a.loading.first=f,a.total=Ecn(h.headers)||a.total;const g=(p=this.callbacks)==null?void 0:p.onProgress;return g&&Fa(n.highWaterMark)?this.loadProgressively(h,a,t,n.highWaterMark,g):l?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var p,f;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);const b=h[o];b&&(a.loaded=a.total=b);const v={url:g.url,data:h,code:g.status},j=(p=this.callbacks)==null?void 0:p.onProgress;j&&!Fa(n.highWaterMark)&&j(a,t,h,g),(f=this.callbacks)==null||f.onSuccess(v,a,t,g)}).catch(h=>{var p;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const f=h&&h.code||0,g=h?h.message:null;(p=this.callbacks)==null||p.onError({code:f,text:g},t,h?h.details:null,a)})}getCacheAge(){let t=null;if(this.response){const n=this.response.headers.get("age");t=n?parseFloat(n):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,n,r,a=0,i){const l=new Ckt,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 Ccn(s,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Yc({},s.headers))};return s.rangeEnd&&n.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),n}function Tcn(s){const t=Scn.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Ecn(s){const t=s.get("Content-Range");if(t){const r=Tcn(t);if(Fa(r))return r}const n=s.get("Content-Length");if(n)return parseInt(n)}function Acn(s,t){return new self.Request(s.url,t)}class Mcn extends Error{constructor(t,n,r){super(t),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const Icn=/^age:\s*[\d.]+\s*$/im;class ySt{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new B8e,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,n,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=n,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:t,context:n}=this;if(!t||!n)return;const r=this.loader=new self.XMLHttpRequest,a=this.stats;a.loading.first=0,a.loaded=0,a.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return i(r,n.url)}).catch(l=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",n.url,!0),i(r,n.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,n,t)}).catch(l=>{var o;(o=this.callbacks)==null||o.onError({code:r.status,text:l.message},n,r,a)}):this.openAndSendXhr(r,n,t)}openAndSendXhr(t,n,r){t.readyState||t.open("GET",n.url,!0);const a=n.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:l}=r.loadPolicy;if(a)for(const o in a)t.setRequestHeader(o,a[o]);n.rangeEnd&&t.setRequestHeader("Range","bytes="+n.rangeStart+"-"+(n.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=n.responseType,self.clearTimeout(this.requestTimeout),r.timeout=i&&Fa(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 b=n.responseType==="arraybuffer"?g.byteLength:g.length;r.loaded=r.total=b,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const v=(l=this.callbacks)==null?void 0:l.onProgress;v&&v(r,t,g,n);const j={url:n.responseURL,data:g,code:d};(o=this.callbacks)==null||o.onSuccess(j,r,t,n);return}}const h=i.loadPolicy.errorRetry,p=r.retry,f={url:t.url,data:void 0,code:d};if(r0e(h,p,!1,f))this.retry(h);else{var c;Lc.error(`${d} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:d,text:n.statusText},t,n,r)}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,n=this.stats.retry;if(r0e(t,n,!0))this.retry(t);else{var r;Lc.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const a=this.callbacks;a&&(this.abortInternal(),a.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:n,stats:r}=this;this.retryDelay=V8e(t,r.retry),r.retry++,Lc.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${n==null?void 0:n.url}, retrying ${r.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const n=this.stats;n.loaded=t.loaded,t.lengthComputable&&(n.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Icn.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 Pcn={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Lcn=Ec(Ec({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:ySt,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Gan,bufferController:Ron,capLevelController:rDe,errorController:Qan,fpsController:Oln,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:xkt,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:Pcn},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},Dcn()),{},{subtitleStreamController:Yln,subtitleTrackController:Bln,timelineController:_cn,audioStreamController:Ion,audioTrackController:Pon,emeController:QL,cmcdController:Pln,contentSteeringController:Dln,interstitialsController:Kln});function Dcn(){return{cueHandler:Ncn,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 Rcn(s,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=JTe(s),a=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return a.forEach(l=>{const o=`${l==="level"?"playlist":l}LoadPolicy`,c=t[o]===void 0,d=[];i.forEach(u=>{const h=`${l}Loading${u}`,p=t[h];if(p!==void 0&&c){d.push(h);const f=r[o].default;switch(t[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=p,f.maxTimeToFirstByteMs=p;break;case"MaxRetry":f.errorRetry.maxNumRetry=p,f.timeoutRetry.maxNumRetry=p;break;case"RetryDelay":f.errorRetry.retryDelayMs=p,f.timeoutRetry.retryDelayMs=p;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=p,f.timeoutRetry.maxRetryDelayMs=p;break}}}),d.length&&n.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${id(t[o])}`)}),Ec(Ec({},r),t)}function JTe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(JTe):Object.keys(s).reduce((t,n)=>(t[n]=JTe(s[n]),t),{}):s}function Ocn(s,t){const n=s.loader;n!==yet&&n!==ySt?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):kcn()&&(s.loader=yet,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const ype=2,Fcn=.1,zcn=.05,Bcn=100;class $cn extends ukt{constructor(t,n){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(_t.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=n,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,n){this.setInterval(Bcn),this.mediaSource=n.mediaSource;const r=this.media=n.media;tg(r,"playing",this.onMediaPlaying),tg(r,"waiting",this.onMediaWaiting),tg(r,"ended",this.onMediaEnded)}onMediaDetaching(t,n){this.clearInterval();const{media:r}=this;r&&($g(r,"playing",this.onMediaPlaying),$g(r,"waiting",this.onMediaWaiting),$g(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,n){this.buffered=n.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const n=this.media.currentTime;this.poll(n,this.lastCurrentTime),this.lastCurrentTime=n}poll(t,n){var r,a;const i=(r=this.hls)==null?void 0:r.config;if(!i)return;const l=this.media;if(!l)return;const{seeking:o}=l,c=this.seeking&&!o,d=!this.seeking&&o,u=l.paused&&!o||l.ended||l.playbackRate===0;if(this.seeking=o,t!==n){n&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!u&&t>n&&this.nudgeOnVideoHole(t,n)),this.waiting===0&&this.stallResolved(t);return}if(d||c){c&&this.stallResolved(t);return}if(u){this.nudgeRetry=0,this.stallResolved(t),!this.ended&&l.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(_t.MEDIA_ENDED,{stalled:!1}));return}if(!wo.getBuffered(l).length){this.nudgeRetry=0;return}const h=wo.bufferInfo(l,t,0),p=h.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const D=vet(this.hls.inFlightFragments,t),L=h.len>ype,M=!p||D||p-t>ype&&!f.getPartialFragment(t);if(L||M)return;this.moved=!1}const g=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(h.len>0)&&!p)return;const L=Math.max(p,h.start||0)-t,F=!!(g!=null&&g.live)?g.targetduration*2:ype,z=QG(t,f);if(L>0&&(L<=F||z)){l.paused||this._trySkipBufferHole(z);return}}const b=i.detectStallWithCurrentTimeMs,v=self.performance.now(),j=this.waiting;let _=this.stalled;if(_===null)if(j>0&&v-j=b||j)&&this.hls){var A;if(((A=this.mediaSource)==null?void 0:A.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(_t.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const T=wo.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(T,S,t)}stallResolved(t){const n=this.stalled;if(n&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-n;this.log(`playback not stuck anymore @${t}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(_t.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=wo.bufferedInfo(wo.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&n>=i.start){const l=wo.timeRangesToArray(a),o=wo.bufferedInfo(l,n,0).bufferedIndex;if(o>-1&&oo)&&u-d<1&&t-d<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${d} -> ${u} buffered index: ${c}`);this.warn(h.message),this.media.currentTime+=1e-6;let p=QG(t,this.fragmentTracker);p&&"fragment"in p?p=p.fragment:p||(p=void 0);const f=wo.bufferInfo(this.media,t,0);this.hls.trigger(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:p,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(t,n,r){var a,i;const{fragmentTracker:l,media:o}=this,c=(a=this.hls)==null?void 0:a.config;if(!o||!l||!c)return;const d=(i=this.hls)==null?void 0:i.latestLevelDetails,u=QG(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,Qa.MAIN),l=r.getFragAtPos(a,Qa.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 (${id(t)})`);this.warn(l.message),n.trigger(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.BUFFER_STALLED_ERROR,fatal:!1,error:l,buffer:t.len,bufferInfo:t,stalled:{start:i}})}}_trySkipBufferHole(t){var n;const{fragmentTracker:r,media:a}=this,i=(n=this.hls)==null?void 0:n.config;if(!a||!r||!i)return 0;const l=a.currentTime,o=wo.bufferInfo(a,l,0),c=l0&&o.len<1&&a.readyState<3,p=c-l;if(p>0&&(u||h)){if(p>i.maxBufferHole){let g=!1;if(l===0){const b=r.getAppendedFrag(0,Qa.MAIN);b&&c"u"))return self.VTTCue||self.TextTrackCue}function Nke(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,id(a?Ec({type:a},r):r))}return i}const XG=(()=>{const s=eEe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class qcn{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(_t.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(_t.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(_t.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,n){var r;this.media=n.media,((r=n.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var t;const n=(t=this.hls)==null?void 0:t.latestLevelDetails;n&&this.updateDateRangeCues(n)}onMediaDetaching(t,n){this.media=null,!n.transferMedia&&(this.id3Track&&(this.removeCues&&qP(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const n=this.getID3Track(t.textTracks);return n.mode="hidden",n}getID3Track(t){if(this.media){for(let n=0;nXG&&(h=XG),h-u<=0&&(h=u+Ucn);for(let f=0;fu.type===Z0.audioId3&&c:a==="video"?d=u=>u.type===Z0.emsg&&o:d=u=>u.type===Z0.audioId3&&c||u.type===Z0.emsg&&o,QTe(i,n,r,d)}}onLevelUpdated(t,{details:n}){this.updateDateRangeCues(n,!0)}onLevelPtsUpdated(t,n){Math.abs(n.drift)>.01&&this.updateDateRangeCues(n.details)}updateDateRangeCues(t,n){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:a,enableDateRangeMetadataCues:i,interstitialsController:l}=this.hls.config;if(!i)return;const o=eEe();if(r&&a&&!l){const{fragmentStart:b,fragmentEnd:v}=t;let j=this.assetCue;j?(j.startTime=b,j.endTime=v):o&&(j=this.assetCue=Nke(o,b,v,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),j&&(j.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(j),j.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=t,u=Object.keys(d);let h=this.dateRangeCuesAppended;if(c&&n){var p;if((p=c.cues)!=null&&p.length){const b=Object.keys(h).filter(v=>!u.includes(v));for(let v=b.length;v--;){var f;const j=b[v],_=(f=h[j])==null?void 0:f.cues;delete h[j],_&&Object.keys(_).forEach(S=>{const A=_[S];if(A){A.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(A)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const g=t.fragments[t.fragments.length-1];if(!(u.length===0||!Fa(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let b=0;b{if(W!==j.id){const K=d[W];if(K.class===j.class&&K.startDate>j.startDate&&(!V||j.startDate.01&&(W.startTime=_,W.endTime=D);else if(o){let K=j.attr[V];uin(V)&&(K=HNt(K));const ee=Nke(o,_,D,{key:V,data:K},Z0.dateRange);ee&&(ee.id=v,this.id3Track.addCue(ee),A[V]=ee,l&&(V==="X-ASSET-LIST"||V==="X-ASSET-URL")&&ee.addEventListener("enter",this.onEventCueEnter))}}h[v]={cues:A,dateRange:j,durationKnown:T}}}}}class Vcn{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:n}=this,r=this.levelDetails;if(!n||!r)return;this.currentTime=n.currentTime;const a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:l}=this.config;if(!i||l===1||!r.live)return;const o=this.targetLatency;if(o===null)return;const c=a-o,d=Math.min(this.maxLatency,o+r.targetduration);if(c.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,l)),p=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,f=Math.min(h,Math.max(1,p));this.changeMediaPlaybackRate(n,f)}else n.playbackRate!==1&&n.playbackRate!==0&&this.changeMediaPlaybackRate(n,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const n=this.levelDetails;return n?t.liveMaxLatencyDurationCount*n.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:n,partHoldBack:r,targetduration:a}=t,{liveSyncDuration:i,liveSyncDurationCount:l,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let d=o&&r||n;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=i!==void 0?i:l*a);const u=a;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),n=this.targetLatency;if(t===null||n===null)return null;const r=this.levelDetails;if(r===null)return null;const a=r.edge,i=t-n-this.edgeStalled,l=a-r.totalduration,o=a-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(l,i),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null)return 0;const n=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-n,0)}get forwardBufferLength(){const{media:t}=this,n=this.levelDetails;if(!t||!n)return 0;const r=t.buffered.length;return(r?t.buffered.end(r-1):n.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(_t.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(_t.ERROR,this.onError,this))}onMediaAttached(t,n){this.media=n.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:n}){n.advanced&&this.onTimeupdate(),!n.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,n){var r;n.details===Pn.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,n){var r,a;t.playbackRate!==n&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(a=this.targetLatency)==null?void 0:a.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${n}`),t.playbackRate=n)}estimateLiveEdge(){const t=this.levelDetails;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}class Hcn extends nDe{constructor(t,n){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=n,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_t.FRAG_BUFFERED,this.onFragBuffered,this),t.on(_t.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_t.FRAG_BUFFERED,this.onFragBuffered,this),t.off(_t.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(n=>{n.loadError=0,n.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,n){this.resetLevels()}onManifestLoaded(t,n){const r=this.hls.config.preferManagedMediaSource,a=[],i={},l={};let o=!1,c=!1,d=!1;n.levels.forEach(u=>{const h=u.attrs;let{audioCodec:p,videoCodec:f}=u;p&&(u.audioCodec=p=e0e(p,r)||void 0),f&&(f=u.videoCodec=Can(f));const{width:g,height:b,unknownCodecs:v}=u,j=(v==null?void 0:v.length)||0;if(o||(o=!!(g&&b)),c||(c=!!f),d||(d=!!p),j||p&&!this.isAudioSupported(p)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:_,"FRAME-RATE":S,"HDCP-LEVEL":A,"PATHWAY-ID":T,RESOLUTION:D,"VIDEO-RANGE":L}=h,F=`${`${T||"."}-`}${u.bitrate}-${D}-${S}-${_}-${L}-${A}`;if(i[F])if(i[F].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const z=l[F]+=1;u.attrs["PATHWAY-ID"]=new Array(z+1).join(".");const V=this.createLevel(u);i[F]=V,a.push(V)}else i[F].addGroupId("audio",h.AUDIO),i[F].addGroupId("text",h.SUBTITLES);else{const z=this.createLevel(u);i[F]=z,l[F]=1,a.push(z)}}),this.filterAndSortMediaOptions(a,n,o,c,d)}createLevel(t){const n=new S$(t),r=t.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const a=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(a.message),n.supportedResult=nkt(a,[])}return n}isAudioSupported(t){return N$(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return N$(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,n,r,a,i){var l;let o=[],c=[],d=t;const u=((l=n.stats)==null?void 0:l.parsing)||{};if((r||a)&&i&&(d=d.filter(({videoCodec:_,videoRange:S,width:A,height:T})=>(!!_||!!(A&&T))&&Oan(S))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let _="no level with compatible codecs found in manifest",S=_;n.levels.length&&(S=`one or more CODECS in variant not supported: ${id(n.levels.map(T=>T.attrs.CODECS).filter((T,D,L)=>L.indexOf(T)===D))}`,this.warn(S),_+=` (${S})`);const A=new Error(_);this.hls.trigger(_t.ERROR,{type:fi.MEDIA_ERROR,details:Pn.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:A,reason:S})}}),u.end=performance.now();return}n.audioTracks&&(o=n.audioTracks.filter(_=>!_.audioCodec||this.isAudioSupported(_.audioCodec)),_et(o)),n.subtitles&&(c=n.subtitles,_et(c));const h=d.slice(0);d.sort((_,S)=>{if(_.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(_.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&_.height!==S.height)return _.height-S.height;if(_.frameRate!==S.frameRate)return _.frameRate-S.frameRate;if(_.videoRange!==S.videoRange)return t0e.indexOf(_.videoRange)-t0e.indexOf(S.videoRange);if(_.videoCodec!==S.videoCodec){const A=uJe(_.videoCodec),T=uJe(S.videoCodec);if(A!==T)return T-A}if(_.uri===S.uri&&_.codecSet!==S.codecSet){const A=Jge(_.codecSet),T=Jge(S.codecSet);if(A!==T)return T-A}return _.averageBitrate!==S.averageBitrate?_.averageBitrate-S.averageBitrate:0});let p=h[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==h.length)){for(let _=0;_A&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const g=i&&!a,b=this.hls.config,v=!!(b.audioStreamController&&b.audioTrackController),j={levels:d,audioTracks:o,subtitleTracks:c,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:i,video:a,altAudio:v&&!g&&o.some(_=>!!_.url)};u.end=performance.now(),this.hls.trigger(_t.MANIFEST_PARSED,j)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const 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(_t.ERROR,{type:fi.OTHER_ERROR,details:Pn.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(_t.LEVEL_SWITCHING,c);const d=l.details;if(!d||d.live){const u=this.switchParams(l.uri,a==null?void 0:a.details,d);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const 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===ol.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(t,{frag:n}){if(n!==void 0&&n.type===Qa.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(_t.LEVEL_LOADING,{url:r,level:a,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:n||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t){var n;if(this._levels.length===1)return;const r=this._levels.filter((i,l)=>l!==t?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(o=>o.level=-1)),!1));Nkt(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(_t.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(_t.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function _et(s){const t={};s.forEach(n=>{const r=n.groupId||"";n.id=t[r]=t[r]||0,t[r]++})}function vSt(){return self.SourceBuffer||self.WebKitSourceBuffer}function bSt(){if(!$4())return!1;const t=vSt();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function Gcn(){if(!bSt())return!1;const s=$4();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(k$(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(k$(t,"audio"))))}function Wcn(){var s;const t=vSt();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const Kcn=100;class Ycn extends Y8e{constructor(t,n,r){super(t,n,r,"stream-controller",Qa.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const a=this.media,i=a?a.currentTime:null;if(i===null||!Fa(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,Qa.MAIN,0);if(l===null||l.len===0){this.warn(`Main forward buffer length at ${i} on "seeked" event ${l?l.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.LEVEL_LOADING,this.onLevelLoading,this),t.on(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_t.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(_t.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(_t.BUFFER_CREATED,this.onBufferCreated,this),t.on(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_t.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_t.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(_t.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(_t.BUFFER_CREATED,this.onBufferCreated,this),t.off(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_t.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,n){if(this.levels){const{lastCurrentTime:r,hls:a}=this;if(this.stopLoad(),this.setInterval(Kcn),this.level=-1,!this.startFragRequested){let i=a.startLevel;i===-1&&(a.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=a.firstAutoLevel),a.nextLoadLevel=i,this.level=a.loadLevel,this._hasEnoughToStart=!!n}r>0&&t===-1&&!n&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r),this.state=ur.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=ur.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ur.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=ur.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=ur.IDLE;break}break}case ur.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===ur.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 b={};this.altAudio===2&&(b.type="video"),this.hls.trigger(_t.BUFFER_EOS,b),this.state=ur.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===ur.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=ur.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,h=this.getMaxBufferLength(l.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const p=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(p,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&Mh(f)&&this.fragmentTracker.getState(f)!==Dm.OK){var g;const v=((g=this.backtrackFragment)!=null?g:f).sn-d.startSN,j=d.fragments[v-1];j&&f.cc===j.cc&&(f=j,this.fragmentTracker.removeFragment(j))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,p)){if(!f.gap){const v=this.audioOnly&&!this.altAudio?td.AUDIO:td.VIDEO,j=(v===td.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;j&&this.afterBufferFlushed(j,v,Qa.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,Qa.MAIN,h)}f&&(this.exceedsMaxBuffer(o,h,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,l,p)))}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);a===Dm.NOT_LOADED||a===Dm.PARTIAL?Mh(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,n)):super.loadFragment(t,n,r):this._loadInitSegment(t,n):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Qa.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var t;(((t=this.getLevelDetails())==null?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:t,media:n}=this;if(n!=null&&n.readyState){let r;const a=this.getAppendedFrag(n.currentTime);a&&a.start>1&&this.flushMainBuffer(0,a.start-1);const i=this.getLevelDetails();if(i!=null&&i.live){const o=this.getMainFwdBufferInfo();if(!o||o.len=l-n.maxFragLookUpTolerance&&i<=o;if(a!==null&&r.duration>a&&(i{this.hls&&this.hls.trigger(_t.AUDIO_TRACK_SWITCHED,n)}),r.trigger(_t.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(_t.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(t,n){const r=s0e(n.url,this.hls);if(r){const a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=r?2:0,this.tick()}onBufferCreated(t,n){const r=n.tracks;let a,i,l=!1;for(const o in r){const c=r[o];if(c.id==="main"){if(i=o,a=c,o==="video"){const d=r[o];d&&(this.videoBuffer=d.buffer)}}else l=!0}l&&a?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=a.buffer):this.mediaBuffer=this.media}onFragBuffered(t,n){const{frag:r,part:a}=n,i=r.type===Qa.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===ur.PARSED&&(this.state=ur.IDLE);return}const o=a?a.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Mh(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a)}const l=this.media;l&&(!this._hasEnoughToStart&&wo.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,n){var r;if(n.fatal){this.state=ur.ERROR;return}switch(n.details){case Pn.FRAG_GAP:case Pn.FRAG_PARSING_ERROR:case Pn.FRAG_DECRYPT_ERROR:case Pn.FRAG_LOAD_ERROR:case Pn.FRAG_LOAD_TIMEOUT:case Pn.KEY_LOAD_ERROR:case Pn.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Qa.MAIN,n);break;case Pn.LEVEL_LOAD_ERROR:case Pn.LEVEL_LOAD_TIMEOUT:case Pn.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===ur.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===ol.LEVEL&&(this.state=ur.IDLE);break;case Pn.BUFFER_ADD_CODEC_ERROR:case Pn.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case Pn.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 Pn.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=ur.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:n}){if(n!==td.AUDIO||!this.altAudio){const r=(n===td.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n,Qa.MAIN),this.tick())}}onLevelsUpdated(t,n){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=n.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const n=t.currentTime;let r=this.startPosition;if(r>=0&&n0&&(c{const{hls:a}=this,i=r==null?void 0:r.frag;if(!i||this.fragContextChanged(i))return;n.fragmentError=0,this.state=ur.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const l=i.stats;l.parsing.start=l.parsing.end=l.buffering.start=l.buffering.end=self.performance.now(),a.trigger(_t.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===ur.STOPPED||this.state===ur.ERROR||(this.warn(r),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const n=this.playlistType,{hls:r}=this,{remuxResult:a,chunkMeta:i}=t,l=this.getCurrentContext(i);if(!l){this.resetWhenMissingContext(i);return}const{frag:o,part:c,level:d}=l,{video:u,text:h,id3:p,initSegment:f}=a,{details:g}=d,b=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=ur.PARSING,f){const v=f.tracks;if(v){const A=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,v,A,i),r.trigger(_t.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:n,tracks:v})}const j=f.initPTS,_=f.timescale,S=this.initPTS[o.cc];if(Fa(j)&&(!S||S.baseTime!==j||S.timescale!==_)){const A=f.trackId;this.initPTS[o.cc]={baseTime:j,timescale:_,trackId:A},r.trigger(_t.INIT_PTS_FOUND,{frag:o,id:n,initPTS:j,timescale:_,trackId:A})}}if(u&&g){b&&u.type==="audiovideo"&&this.logMuxedErr(o);const v=g.fragments[o.sn-1-g.startSN],j=o.sn===g.startSN,_=!v||o.cc>v.cc;if(a.independent!==!1){const{startPTS:S,endPTS:A,startDTS:T,endDTS:D}=u;if(c)c.elementaryStreams[u.type]={startPTS:S,endPTS:A,startDTS:T,endDTS:D};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!_&&(this.couldBacktrack=!0),u.dropped&&u.independent){const L=this.getMainFwdBufferInfo(),M=(L?L.end:this.getLoadPosition())+this.config.maxBufferHole,F=u.firstKeyFramePTS?u.firstKeyFramePTS:S;if(!j&&Mype&&(o.gap=!0);o.setElementaryStreamInfo(u.type,S,A,T,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,i,j||_)}else if(j||_)o.gap=!0;else{this.backtrack(o);return}}if(b){const{startPTS:v,endPTS:j,startDTS:_,endDTS:S}=b;c&&(c.elementaryStreams[td.AUDIO]={startPTS:v,endPTS:j,startDTS:_,endDTS:S}),o.setElementaryStreamInfo(td.AUDIO,v,j,_,S),this.bufferFragmentData(b,o,c,i)}if(g&&p!=null&&p.samples.length){const v={id:n,frag:o,details:g,samples:p.samples};r.trigger(_t.FRAG_PARSING_METADATA,v)}if(g&&h){const v={id:n,frag:o,details:g,samples:h.samples};r.trigger(_t.FRAG_PARSING_USERDATA,v)}}logMuxedErr(t){this.warn(`${Mh(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,n,r,a){if(this.state!==ur.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=upe(i.codec,d);u==="mp4a"&&(u="mp4a.40.5");const h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const p=i.metadata;p&&"channelCount"in p&&(p.channelCount||1)!==1&&h.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&i.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),i.levelCodec=u,i.id=Qa.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=Qa.MAIN;const d=l.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":l.codec="hvc1.1.6.L120.90";break;case"av01":l.codec="av01.0.04M.08";break;case"avc1":l.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${l.container}, codecs[level/parsed]=[${t.videoCodec||""}/${d}]${l.codec!==d?" parsed-corrected="+l.codec:""}${l.supplemental?" supplemental="+l.supplemental:""}`),delete n.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete n.video,delete n.audio);const c=Object.keys(n);if(c.length){if(this.hls.trigger(_t.BUFFER_CODECS,n),!this.hls)return;c.forEach(d=>{const h=n[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(_t.BUFFER_APPENDING,{type:d,data:h,frag:r,part:null,chunkMeta:a,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,Qa.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=ur.IDLE}checkFragmentChanged(){const t=this.media;let n=null;if(t&&t.readyState>1&&t.seeking===!1){const r=t.currentTime;if(wo.isBuffered(t,r)?n=this.getAppendedFrag(r):wo.isBuffered(t,r+.1)&&(n=this.getAppendedFrag(r+.1)),n){this.backtrackFragment=null;const a=this.fragPlaying,i=n.level;(!a||n.sn!==a.sn||a.level!==i)&&(this.fragPlaying=n,this.hls.trigger(_t.FRAG_CHANGED,{frag:n}),(!a||a.level!==i)&&this.hls.trigger(_t.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return Fa(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var t;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(Fa(n)){const r=this.getLevelDetails(),a=this.currentFrag||(r?BM(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 Zcn extends a1{constructor(t,n){super("key-loader",n),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const r in this.keyIdToKeyInfo){const a=this.keyIdToKeyInfo[r].loader;if(a){var n;if(t&&t!==((n=a.context)==null?void 0:n.frag.type))return;a.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[t];(n.mediaKeySessionContext||n.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[t].loader;n&&n.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,n=Pn.KEY_LOAD_ERROR,r,a,i){return new k2({type:fi.NETWORK_ERROR,details:n,fatal:!1,frag:t,response:i,error:r,networkDetails:a})}loadClear(t,n,r){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(n.length)for(let a=0,i=n.length;a{if(!this.emeController)return;l.setKeyFormat(o);const c=mpe(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=L7(this.config);if(a.length)return this.emeController.getKeySystemAccess(a)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(n=>this.loadInternal(t,n)):this.loadInternal(t)}loadInternal(t,n){var r,a;n&&t.setKeyFormat(n);const i=t.decryptdata;if(!i){const d=new Error(n?`Expected frag.decryptdata to be defined after setting format ${n}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,Pn.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,Pn.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=kke(i);let c=this.keyIdToKeyInfo[o];if((r=c)!=null&&r.decryptdata.key)return i.key=c.decryptdata.key,Promise.resolve({frag:t,keyInfo:c});if(this.emeController&&(a=c)!=null&&a.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(u=>{const{keyInfo:h}=u;return i.key=h.decryptdata.key,{frag:t,keyInfo:h}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${i.keyId?" keyId: "+rf(i.keyId):""} URI: ${i.uri} from ${t.type} ${t.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.keyFormat==="identity"?this.loadKeyHTTP(c,t):this.loadKeyEME(c,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,t);default:return Promise.reject(this.createKeyLoadError(t,Pn.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t,n){const r={frag:n,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var a;if(!t.decryptdata.keyId&&(a=n.initSegment)!=null&&a.data){const l=fan(n.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${rf(o)}`),N4.setKeyIdForUri(t.decryptdata.uri,o)):(o=N4.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${rf(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!Mh(n))return Promise.resolve(r);const i=this.emeController.loadKey(r);return(t.keyLoadPromise=i.then(l=>(t.mediaKeySessionContext=l,r))).catch(l=>{throw t.keyLoadPromise=null,"data"in l&&(l.data.frag=n),l})}return Promise.resolve(r)}loadKeyHTTP(t,n){const r=this.config,a=r.loader,i=new a(r);return n.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((l,o)=>{const c={keyInfo:t,frag:n,responseType:"arraybuffer",url:t.decryptdata.uri},d=r.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(p,f,g,b)=>{const{frag:v,keyInfo:j}=g,_=kke(j.decryptdata);if(!v.decryptdata||j!==this.keyIdToKeyInfo[_])return o(this.createKeyLoadError(v,Pn.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),b));j.decryptdata.key=v.decryptdata.key=new Uint8Array(p.data),v.keyLoader=null,j.loader=null,l({frag:v,keyInfo:j})},onError:(p,f,g,b)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Pn.KEY_LOAD_ERROR,new Error(`HTTP Error ${p.code} loading key ${p.text}`),g,Ec({url:c.url,data:void 0},p)))},onTimeout:(p,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Pn.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(p,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Pn.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};i.load(c,u,h)})}resetLoader(t){const{frag:n,keyInfo:r,url:a}=t,i=r.loader;n.keyLoader===i&&(n.keyLoader=null,r.loader=null);const l=kke(r.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function kke(s){if(s.keyFormat!==lf.FAIRPLAY){const t=s.keyId;if(t)return rf(t)}return s.uri}function wet(s){const{type:t}=s;switch(t){case ol.AUDIO_TRACK:return Qa.AUDIO;case ol.SUBTITLE_TRACK:return Qa.SUBTITLE;default:return Qa.MAIN}}function Ske(s,t){let n=s.url;return(n===void 0||n.indexOf("data:")===0)&&(n=t.url),n}class Qcn{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.LEVEL_LOADING,this.onLevelLoading,this),t.on(_t.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(_t.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(_t.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.LEVEL_LOADING,this.onLevelLoading,this),t.off(_t.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(_t.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(_t.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const 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:ol.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:ol.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:ol.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:ol.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,n){const r=this.loaders[ol.LEVEL];if(r){const a=r.context;a&&!n.levels.some(i=>i===a.levelOrTrack)&&(r.abort(),delete this.loaders[ol.LEVEL])}}load(t){var n;const r=this.hls.config;let a=this.getInternalLoader(t);if(a){const d=this.hls.logger,u=a.context;if(u&&u.levelOrTrack===t.levelOrTrack&&(u.url===t.url||u.deliveryDirectives&&!t.deliveryDirectives)){u.url===t.url?d.log(`[playlist-loader]: ignore ${t.url} ongoing request`):d.log(`[playlist-loader]: ignore ${t.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),a.abort()}let i;if(t.type===ol.MANIFEST?i=r.manifestLoadPolicy.default:i=Yc({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),Fa((n=t.deliveryDirectives)==null?void 0:n.part)){let d;if(t.type===ol.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===ol.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===ol.SUBTITLE_TRACK&&t.id!==null&&(d=this.hls.subtitleTracks[t.id].details),d){const u=d.partTarget,h=d.targetduration;if(u&&h){const p=Math.max(u*3,h*.8)*1e3;i=Yc({},i,{maxTimeToFirstByteMs:Math.min(p,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(p,i.maxTimeToFirstByteMs)})}}}const l=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:(d,u,h,p)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=d.data;u.parsing.start=performance.now(),uw.isMediaPlaylist(g)||h.type!==ol.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,h,p||null,f):this.handleMasterPlaylist(d,u,h,p)},onError:(d,u,h,p)=>{this.handleNetworkError(u,h,!1,d,p)},onTimeout:(d,u,h)=>{this.handleNetworkError(u,h,!0,void 0,d)}};a.load(t,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:n},forceStartLoad:r}=this.hls;(t||r)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${n}`),this.hls.startLoad(n))}handleMasterPlaylist(t,n,r,a){const i=this.hls,l=t.data,o=Ske(t,r),c=uw.parseMasterPlaylist(l,o);if(c.playlistParsingError){n.parsing.end=performance.now(),this.handleManifestParsingError(t,r,c.playlistParsingError,a,n);return}const{contentSteering:d,levels:u,sessionData:h,sessionKeys:p,startTimeOffset:f,variableList:g}=c;this.variableList=g,u.forEach(_=>{const{unknownCodecs:S}=_;if(S){const{preferManagedMediaSource:A}=this.hls.config;let{audioCodec:T,videoCodec:D}=_;for(let L=S.length;L--;){const M=S[L];N$(M,"audio",A)?(_.audioCodec=T=T?`${T},${M}`:M,wD.audio[T.substring(0,4)]=2,S.splice(L,1)):N$(M,"video",A)&&(_.videoCodec=D=D?`${D},${M}`:M,wD.video[D.substring(0,4)]=2,S.splice(L,1))}}});const{AUDIO:b=[],SUBTITLES:v,"CLOSED-CAPTIONS":j}=uw.parseMasterPlaylistMedia(l,o,c);b.length&&!b.some(S=>!S.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),b.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Su({}),bitrate:0,url:""})),i.trigger(_t.MANIFEST_LOADED,{levels:u,audioTracks:b,subtitles:v,captions:j,contentSteering:d,url:o,stats:n,networkDetails:a,sessionData:h,sessionKeys:p,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,n,r,a,i){const l=this.hls,{id:o,level:c,type:d}=r,u=Ske(t,r),h=Fa(c)?c:Fa(o)?o:0,p=wet(r),f=uw.parseLevelPlaylist(t.data,u,h,p,0,this.variableList);if(d===ol.MANIFEST){const g={attrs:new Su({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=n.loading.start+_kt(f,0),l.trigger(_t.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:u,stats:n,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}n.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,t,n,r,a,i)}handleManifestParsingError(t,n,r,a,i){this.hls.trigger(_t.ERROR,{type:fi.NETWORK_ERROR,details:Pn.MANIFEST_PARSING_ERROR,fatal:n.type===ol.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===ol.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===ol.AUDIO_TRACK||t.type===ol.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=Pn.UNKNOWN,d=!1;const u=this.getInternalLoader(t);switch(t.type){case ol.MANIFEST:c=r?Pn.MANIFEST_LOAD_TIMEOUT:Pn.MANIFEST_LOAD_ERROR,d=!0;break;case ol.LEVEL:c=r?Pn.LEVEL_LOAD_TIMEOUT:Pn.LEVEL_LOAD_ERROR,d=!1;break;case ol.AUDIO_TRACK:c=r?Pn.AUDIO_TRACK_LOAD_TIMEOUT:Pn.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case ol.SUBTITLE_TRACK:c=r?Pn.SUBTITLE_TRACK_LOAD_TIMEOUT:Pn.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(t.type);const h={type:fi.NETWORK_ERROR,details:c,fatal:d,url:t.url,loader:u,context:t,error:o,networkDetails:n,stats:i};if(a){const p=(n==null?void 0:n.url)||t.url;h.response=Ec({url:p,data:void 0},a)}this.hls.trigger(_t.ERROR,h)}handlePlaylistLoaded(t,n,r,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:u,id:h,groupId:p,deliveryDirectives:f}=a,g=Ske(n,a),b=wet(a);let v=typeof a.level=="number"&&b===Qa.MAIN?d:void 0;const j=t.playlistParsingError;if(j){if(this.hls.logger.warn(`${j} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(_t.ERROR,{type:fi.NETWORK_ERROR,details:Pn.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:j,reason:j.message,response:n,context:a,level:v,parent:b,networkDetails:i,stats:r});return}t.playlistParsingError=null}if(!t.fragments.length){const _=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(_t.ERROR,{type:fi.NETWORK_ERROR,details:Pn.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:_,reason:_.message,response:n,context:a,level:v,parent:b,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 ol.MANIFEST:case ol.LEVEL:if(v){if(!u)v=0;else if(u!==o.levels[v]){const _=o.levels.indexOf(u);_>-1&&(v=_)}}o.trigger(_t.LEVEL_LOADED,{details:t,levelInfo:u||o.levels[0],level:v||0,id:h||0,stats:r,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:c===ol.MANIFEST});break;case ol.AUDIO_TRACK:o.trigger(_t.AUDIO_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:p||"",stats:r,networkDetails:i,deliveryDirectives:f});break;case ol.SUBTITLE_TRACK:o.trigger(_t.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:p||"",stats:r,networkDetails:i,deliveryDirectives:f});break}}}class nw{static get version(){return C$}static isMSESupported(){return bSt()}static isSupported(){return Gcn()}static getMediaSource(){return $4()}static get Events(){return _t}static get MetadataSchema(){return Z0}static get ErrorTypes(){return fi}static get ErrorDetails(){return Pn}static get DefaultConfig(){return nw.defaultConfig?nw.defaultConfig:Lcn}static set DefaultConfig(t){nw.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Z8e,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const n=this.logger=nan(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=Rcn(nw.DefaultConfig,t,n);this.userConfig=t,r.progressive&&Ocn(r,n);const{abrController:a,bufferController:i,capLevelController:l,errorController:o,fpsController:c}=r,d=new o(this),u=this.abrController=new a(this),h=new Xan(this),p=r.interstitialsController,f=p?this.interstitialsController=new p(this,nw):null,g=this.bufferController=new i(this,h),b=this.capLevelController=new l(this),v=new c(this),j=new Qcn(this),_=r.contentSteeringController,S=_?new _(this):null,A=this.levelController=new Hcn(this,S),T=new qcn(this),D=new Zcn(this.config,this.logger),L=this.streamController=new Ycn(this,h,D),M=this.gapController=new $cn(this,h);b.setStreamController(L),v.setStreamController(L);const F=[j,A,L];f&&F.splice(1,0,f),S&&F.splice(1,0,S),this.networkControllers=F;const z=[u,g,M,b,v,T,h];this.audioTrackController=this.createController(r.audioTrackController,F);const V=r.audioStreamController;V&&F.push(this.audioStreamController=new V(this,h,D)),this.subtitleTrackController=this.createController(r.subtitleTrackController,F);const W=r.subtitleStreamController;W&&F.push(this.subtititleStreamController=new W(this,h,D)),this.createController(r.timelineController,z),D.emeController=this.emeController=this.createController(r.emeController,z),this.cmcdController=this.createController(r.cmcdController,z),this.latencyController=this.createController(Vcn,z),this.coreComponents=z,F.push(d);const K=d.onErrorOut;typeof K=="function"&&this.on(_t.ERROR,K,d),this.on(_t.MANIFEST_LOADED,j.onManifestLoaded,j)}createController(t,n){if(t){const r=new t(this);return n&&n.push(r),r}return null}on(t,n,r=this){this._emitter.on(t,n,r)}once(t,n,r=this){this._emitter.once(t,n,r)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,n,r=this,a){this._emitter.off(t,n,r,a)}listeners(t){return this._emitter.listeners(t)}emit(t,n,r){return this._emitter.emit(t,n,r)}trigger(t,n){if(this.config.debug)return this.emit(t,t,n);try{return this.emit(t,t,n)}catch(r){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const a=t===_t.ERROR;this.trigger(_t.ERROR,{type:fi.OTHER_ERROR,details:Pn.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(_t.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(n=>n.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(n=>n.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const i=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(_t.ERROR,{type:fi.OTHER_ERROR,details:Pn.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(_t.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(_t.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(_t.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const n=this.media,r=this._url,a=this._url=z8e.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${a}`),n&&r&&(r!==a||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(n)),this.trigger(_t.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,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={[Qa.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[Qa.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[Qa.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,n=t==null?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),n&&this.startLoad(n))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=$ln()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const n=!!t;n!==this.config.capLevelToPlayerSize&&(n?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=n)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){Ran(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:n}}=this;if(!t)return 0;const r=t.length;for(let a=0;a=n)return a;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:n,maxHdcpLevel:r}=this;let a;if(n===-1&&t!=null&&t.length?a=t.length-1:a=n,r)for(let i=a;i--;){const l=t[i].attrs["HDCP-LEVEL"];if(l&&l<=r)return i}return a}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var n;return((n=this.audioTrackController)==null?void 0:n.setAudioOption(t))||null}setSubtitleOption(t){var n;return((n=this.subtitleTrackController)==null?void 0:n.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const n=this.audioTrackController;n&&(n.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const n=this.subtitleTrackController;n&&(n.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const n=this.subtitleTrackController;n&&(n.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,n=this.allAudioTracks){const r=ikt(n);return rkt(t,r,navigator.mediaCapabilities)}}nw.defaultConfig=void 0;const Xcn=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function VP(s){return!!s&&Xcn.test(s)&&!/\.mp4($|\?)/i.test(s)}function Jcn(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function edn(s,t){if(!s)return null;const n=Jcn(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 tdn(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const tEe=N.forwardRef(function({sourceUrl:t,thumbnailUrl:n,autoPlay:r,muted:a,loop:i,playsInline:l=!0,...o},c){const d=N.useRef(null),[u,h]=N.useState(null),p=N.useMemo(()=>edn(t,{autoplay:!!r,muted:!!a,loop:!!i}),[t,r,a,i]);N.useEffect(()=>{let g=!1;if(!t){h(null);return}if(!VP(t)){h(t);return}if(!p){h(null);return}return h(null),fetch(p).then(async b=>{if(!b.ok)throw new Error(`Failed to load Bunny embed (${b.status})`);const v=await b.text();return tdn(v)}).then(b=>{g||h(b)}).catch(()=>{g||h(null)}),()=>{g=!0}},[p,t]),N.useEffect(()=>{const g=d.current;if(!g||!u)return;let b=null;const v=()=>{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 _=()=>v();return g.addEventListener("loadedmetadata",_),()=>{g.removeEventListener("loadedmetadata",_),g.removeAttribute("src"),g.load()}}return nw.isSupported()?(b=new nw({enableWorker:!0,lowLatencyMode:!0}),b.loadSource(u),b.attachMedia(g),b.on(nw.Events.MANIFEST_PARSED,v),()=>{b==null||b.destroy(),g.removeAttribute("src"),g.load()}):void 0}g.src=u;const j=()=>v();return g.addEventListener("loadedmetadata",j),()=>{g.removeEventListener("loadedmetadata",j),g.removeAttribute("src"),g.load()}},[r,i,a,u]),N.useEffect(()=>{const g=d.current;if(g){if(g.muted=!!a,g.loop=!!i,r&&u){const b=g.play();b&&b.catch(()=>{});return}g.pause()}},[r,i,a,u]);const f=g=>{if(d.current=g,typeof c=="function"){c(g);return}c&&(c.current=g)};return e.jsx("video",{ref:f,poster:n||void 0,autoPlay:r,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),sdn={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 ndn(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function jet(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 cDe({config:s,appSlug:t="video_greeter",preview:n=!1,embedded:r=!1}){const[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!0),[u,h]=N.useState(!1),[p,f]=N.useState("portrait"),[g,b]=N.useState(!1),[v,j]=N.useState(!1),[_,S]=N.useState({name:"",email:"",phone:""}),[A,T]=N.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),D=N.useRef(null),L=N.useRef(null),M=N.useRef(!1),F=async(Ne,He)=>{if(!n)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:Ne,visitor_token:ndn(),page_url:typeof window<"u"?window.location.href:null,metadata:He||{}})}catch{}};N.useEffect(()=>{if(u)return;const Ne=typeof window<"u"?window.location.pathname:"/",He=s.targeting||{mode:"all"};if(He.mode==="include"&&!jet(He.include,Ne)||He.mode==="exclude"&&jet(He.exclude,Ne))return;const $e=s.trigger||{type:"immediate"};if($e.type==="immediate"||n){i(!0);return}if($e.type==="delay"){const Ye=($e.value||3)*1e3,Ke=setTimeout(()=>i(!0),Ye);return()=>clearTimeout(Ke)}if($e.type==="scroll"){const Ye=($e.value||25)/100,Ke=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Ye&&(i(!0),window.removeEventListener("scroll",Ke))};return window.addEventListener("scroll",Ke,{passive:!0}),()=>window.removeEventListener("scroll",Ke)}if($e.type==="exit_intent"){const Ye=Ke=>{Ke.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",Ye),()=>document.removeEventListener("mouseleave",Ye)}},[u,s.targeting,s.trigger,n]),N.useEffect(()=>{a&&!M.current&&(M.current=!0,F("impression"))},[a]),N.useEffect(()=>{if(l&&L.current&&!VP(s.video_url)){L.current.currentTime=0,L.current.muted=!1,d(!1);const Ne=L.current.play();Ne&&Ne.catch(()=>{})}else l&&VP(s.video_url)&&d(!1)},[l,s.video_url]),N.useEffect(()=>{if(!s.thumbnail_url)return;let Ne=!1;const He=new Image;return He.onload=()=>{Ne||f(He.naturalWidth>He.naturalHeight?"landscape":"portrait")},He.src=s.thumbnail_url,()=>{Ne=!0}},[s.thumbnail_url]),N.useEffect(()=>{const Ne=()=>{T({width:window.innerWidth,height:window.innerHeight})};return Ne(),window.addEventListener("resize",Ne),()=>window.removeEventListener("resize",Ne)},[]);const z=()=>{o(!0),F("expand")},V=Ne=>{Ne.stopPropagation(),h(!0),o(!1)},W=Ne=>{F("cta_click",{cta_id:Ne.id,label:Ne.label,url:Ne.url})},K=async Ne=>{if(Ne.preventDefault(),n){b(!0);return}if(!(!_.email||!_.name)){j(!0);try{const{error:He}=await q.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(He)throw He;F("lead_capture",{email:_.email}),b(!0)}catch(He){console.error("lead submit failed",He)}finally{j(!1)}}};if(!a||u||!s.video_url&&!s.video_embed_url)return null;const Y=sdn[p][s.size||"md"],ee=r?"absolute left-2 bottom-2":n?s.position==="bottom-right"?"absolute right-4 bottom-4":"absolute left-4 bottom-4":s.position==="bottom-right"?"fixed right-4 bottom-4 md:right-6 md:bottom-6":"fixed left-4 bottom-4 md:left-6 md:bottom-6",ne=s.shape==="circle"?"rounded-full":"rounded-2xl",oe=n?p==="landscape"?"w-[280px]":"w-[220px]":p==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",pe=p==="landscape"?"aspect-video":"aspect-[9/16]",ce=s.agent||{},de=s.lead_form_fields||["name","email","phone"],ie=!!(s.show_socials&&(ce.instagram_url||ce.facebook_url||ce.linkedin_url)),ye=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!g?72+de.length*42:0)+(g?40:0)+(ie?34:0),_e=Math.max(300,A.height-32),Me=Math.max(220,A.width-32),Te=Math.max(150,_e-ye),Ce=Math.floor(p==="landscape"?Te*(16/9):Te*(9/16)),Ee=p==="landscape"?Math.max(220,Math.min(420,Me,Ce)):Math.max(180,Math.min(340,Me,Ce)),De=r?"bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col":`${oe} max-h-[calc(100dvh-2rem)] bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col`,Ie=r?{width:`${Ee}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Fe=r?"p-3 space-y-2.5":"p-4 space-y-3",qe=r?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",ve=r?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",Je=r?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",we=r?"w-full px-3 py-1.5 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400":"w-full px-3 py-2 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400",it=r?"w-full flex items-center justify-center gap-2 px-3 py-2 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60":"w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60";return e.jsx("div",{"data-vg-widget":!0,"data-expanded":l?"true":"false",className:`${ee} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:De,style:Ie,children:[e.jsxs("div",{className:`relative bg-black ${pe}`,children:[VP(s.video_url)?e.jsx(tEe,{ref:L,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:Ne=>{const{videoWidth:He,videoHeight:$e}=Ne.currentTarget;He&&$e&&f(He>$e?"landscape":"portrait")},onEnded:()=>F("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:L,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,playsInline:!0,controls:!1,className:"w-full h-full object-cover",onEnded:()=>F("watch_complete"),onLoadedMetadata:Ne=>{const{videoWidth:He,videoHeight:$e}=Ne.currentTarget;He&&$e&&f(He>$e?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{L.current&&(L.current.muted=!L.current.muted,d(L.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(q9,{className:"w-4 h-4"}):e.jsx(U9,{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(Fn,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:Fe,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ce.avatar_url&&e.jsx("img",{src:ce.avatar_url,alt:ce.name||"",className:qe}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:ve,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:Je,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(Ne=>{var He;return e.jsxs("a",{href:Ne.url,target:(He=Ne.url)!=null&&He.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>W(Ne),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 ${Ne.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:Ne.label}),e.jsx(tr,{className:"w-3.5 h-3.5 opacity-60"})]},Ne.id)})}),s.lead_form_enabled&&!g&&e.jsxs("form",{onSubmit:K,className:"space-y-2 pt-1",children:[de.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:_.name,onChange:Ne=>S({..._,name:Ne.target.value}),className:we}),de.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:_.email,onChange:Ne=>S({..._,email:Ne.target.value}),className:we}),de.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:_.phone,onChange:Ne=>S({..._,phone:Ne.target.value}),className:we}),e.jsxs("button",{type:"submit",disabled:v,className:it,children:[e.jsx(cr,{className:"w-3.5 h-3.5"}),v?"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&&(ce.instagram_url||ce.facebook_url||ce.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[ce.instagram_url&&e.jsx("a",{href:ce.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"instagram"}),children:e.jsx(mu,{className:"w-4 h-4"})}),ce.facebook_url&&e.jsx("a",{href:ce.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"facebook"}),children:e.jsx(Oh,{className:"w-4 h-4"})}),ce.linkedin_url&&e.jsx("a",{href:ce.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"linkedin"}),children:e.jsx(bf,{className:"w-4 h-4"})})]})]})]}):e.jsxs("div",{className:"relative animate-in fade-in slide-in-from-bottom-4 duration-500",children:[e.jsxs("button",{onClick:z,className:`relative ${ne} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:Y.w,height:Y.h},"aria-label":"Play video greeting",children:[VP(s.video_url)?e.jsx(tEe,{ref:D,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-cover pointer-events-none",onLoadedMetadata:Ne=>{const{videoWidth:He,videoHeight:$e}=Ne.currentTarget;He&&$e&&f(He>$e?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:D,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover",onLoadedMetadata:Ne=>{const{videoWidth:He,videoHeight:$e}=Ne.currentTarget;He&&$e&&f(He>$e?"landscape":"portrait")}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),e.jsx("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 w-12 h-12 rounded-full bg-white/95 flex items-center justify-center shadow-lg pointer-events-none",children:e.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})}),e.jsx("span",{className:"absolute top-2 right-2 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider bg-red-500 text-white rounded-full animate-pulse",children:"Live"})]}),e.jsx("button",{onClick:V,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(Fn,{className:"w-3.5 h-3.5"})})]})})}function dDe({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_video_greeter_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(cDe,{config:t}):null}const _St="eip_last_shown",Net="eip_visitor_token";function rdn(){try{let s=localStorage.getItem(Net);return s||(s=crypto.randomUUID(),localStorage.setItem(Net,s)),s}catch{return}}function adn(s){try{const t=Number(localStorage.getItem(_St)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function idn(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 wSt({config:s,preview:t=!1,forceOpen:n=!1}){const[r,a]=N.useState(n),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({name:"",email:"",phone:""}),h=N.useRef(!1),p=N.useRef(!1),f=async(D,L={})=>{if(!t)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:D,visitor_token:rdn(),page_url:window.location.href,metadata:L})}catch{}};N.useEffect(()=>{if(t||!idn(s.targeting)||!adn(s.frequency_days))return;const D=/Mobi|Android/i.test(navigator.userAgent),L={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,M=W=>{if(!h.current){h.current=!0,a(!0);try{localStorage.setItem(_St,String(Date.now()))}catch{}f("impression",{reason:W})}},F=W=>{W.clientY<=L&&M("mouse_leave")},z=()=>{s.enable_mobile_back&&D&&M("back_button")};if(s.enable_mobile_back&&D){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",z)}else document.addEventListener("mouseleave",F);let V;return s.enable_time_fallback&&(V=window.setTimeout(()=>M("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",F),window.removeEventListener("popstate",z),V&&window.clearTimeout(V)}},[s,t]),N.useEffect(()=>{r&&!p.current&&!t&&!h.current&&(p.current=!0)},[r,t]);const g=()=>{a(!1),t||f("close")},b=async D=>{if(D.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:L}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"exit_intent",name:d.name,email:d.email,phone:d.phone||void 0,page_url:window.location.href}});if(L)throw L;f("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(L){console.error("exit intent submit failed",L)}finally{c(!1)}}};if(!r)return null;const v=s.form_fields||["name","email"],j=s.agent||{},_=[j.first_name,j.last_name].filter(Boolean).join(" "),S=s.use_agent_photo&&j.avatar_url||s.image_url,A=s.theme_color||"#f97316",T=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:T,style:{background:t?"transparent":"rgba(0,0,0,0.6)"},children:e.jsxs("div",{className:"relative w-full max-w-md bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:D=>D.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${A}, ${Cke(A,-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(Fn,{className:"w-4 h-4"})}),e.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[S&&e.jsx("img",{src:S,alt:_||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${A}33`,"--tw-ring-color":A}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${A}1A`,color:A},children:[e.jsx(un,{className:"w-3 h-3"}),s.offer_label]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.headline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.subheadline})]}),i?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${A}10`,color:A},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:A},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:b,className:"space-y-2.5",children:[v.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:D=>u({...d,name:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A},required:!0}),v.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:D=>u({...d,email:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A},required:!0}),v.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:D=>u({...d,phone:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A}}),e.jsx("button",{type:"submit",disabled:o,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60",style:{background:`linear-gradient(135deg, ${A}, ${Cke(A,-20)})`},children:o?"Sending...":s.cta_label}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):e.jsx("a",{href:s.cta_url||"#",onClick:()=>f("cta_click",{url:s.cta_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 transition",style:{background:`linear-gradient(135deg, ${A}, ${Cke(A,-20)})`},children:s.cta_label}),_&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",_]})]})]})})}function Cke(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 uDe({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_exit_intent_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(wSt,{config:t}):null}const ket="lm_dismissed",Cet="lm_visitor_token";function odn(){try{let s=localStorage.getItem(Cet);return s||(s=crypto.randomUUID(),localStorage.setItem(Cet,s)),s}catch{return}}function ldn(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 hDe({config:s,preview:t=!1}){const[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState({name:"",email:"",phone:""}),p=N.useRef(!1),f=async(S,A={})=>{if(!t)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:S,visitor_token:odn(),page_url:window.location.href,metadata:A})}catch{}};N.useEffect(()=>{if(t){r(!0);return}if(!ldn(s.targeting))return;try{if(sessionStorage.getItem(ket))return}catch{}const S=()=>{p.current||(p.current=!0,r(!0),f("impression"))};if(s.trigger_type==="immediate")S();else if(s.trigger_type==="delay"){const A=window.setTimeout(S,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(A)}else if(s.trigger_type==="scroll"){const A=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&S()};return window.addEventListener("scroll",A,{passive:!0}),()=>window.removeEventListener("scroll",A)}},[s,t]);const g=()=>{r(!1);try{sessionStorage.setItem(ket,"1")}catch{}t||f("close")},b=async S=>{if(S.preventDefault(),t){o(!0);return}if(!(!u.email||!u.name)){d(!0);try{const{error:A}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:u.name,email:u.email,phone:u.phone||void 0,page_url:window.location.href}});if(A)throw A;f("lead_capture",{email:u.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const T=document.createElement("a");T.href=s.download_url,T.target="_blank",T.rel="noopener",T.download="",document.body.appendChild(T),T.click(),T.remove()},600)}catch(A){console.error("lead magnet submit failed",A)}finally{d(!1)}}};if(!n)return null;const v=s.theme_color||"#2563eb",j=t?s.position==="bottom-left"?"absolute left-4 bottom-4":"absolute right-4 bottom-4":s.position==="bottom-left"?"fixed left-4 bottom-4 md:left-6 md:bottom-6":"fixed right-4 bottom-4 md:right-6 md:bottom-6";if(s.display_style==="bar")return e.jsxs("div",{className:t?"absolute left-0 right-0 bottom-0 z-10":"fixed left-0 right-0 bottom-0 z-[75]",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${v}, ${GF(v,-20)})`},children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap",children:[e.jsx(Bi,{className:"w-5 h-5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:s.title}),e.jsx("p",{className:"text-xs text-white/80 truncate",children:s.description})]}),e.jsx("button",{onClick:()=>{i(!0),f("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:v},children:s.download_label}),e.jsx("button",{onClick:g,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(Fn,{className:"w-4 h-4"})})]})}),a&&_()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),f("expand")},className:`${j} z-[75] group flex items-center gap-3 pl-3 pr-4 py-3 rounded-2xl shadow-2xl hover:shadow-3xl transition-all hover:scale-[1.03] animate-in fade-in slide-in-from-bottom-4 duration-500`,style:{background:`linear-gradient(135deg, ${v}, ${GF(v,-20)})`,paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center text-white",children:e.jsx($u,{className:"w-5 h-5"})}),e.jsxs("div",{className:"text-left text-white",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider opacity-90 font-semibold",children:s.badge_label}),e.jsx("div",{className:"text-sm font-bold leading-tight max-w-[180px] truncate",children:s.title})]}),e.jsx("button",{onClick:S=>{S.stopPropagation(),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(Fn,{className:"w-3 h-3"})})]}),a&&_()]});return _();function _(){const S=s.form_fields||["name","email"],A=s.agent||{},T=[A.first_name,A.last_name].filter(Boolean).join(" ");return e.jsx("div",{className:t?"absolute inset-0 flex items-center justify-center p-4 z-20":"fixed inset-0 z-[85] flex items-center justify-center p-4",style:{background:t?"transparent":"rgba(0,0,0,0.6)"},onClick:()=>i(!1),children:e.jsxs("div",{className:"relative w-full max-w-lg bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:D=>D.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${v}, ${GF(v,-25)})`},children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:s.title,className:"w-full h-full object-cover opacity-90"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Nr,{className:"w-20 h-20 text-white/40"})}),e.jsxs("div",{className:"absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-white shadow",style:{color:v},children:[e.jsx(Bi,{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(Fn,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.description})]}),l?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${v}10`},children:[e.jsx(Da,{className:"w-8 h-8 mx-auto",style:{color:v}}),e.jsx("p",{className:"text-sm font-medium",style:{color:v},children:s.success_message}),s.download_url&&e.jsx("a",{href:s.download_url,target:"_blank",rel:"noopener",className:"inline-block mt-2 text-xs underline",style:{color:v},children:"Click here if download didn't start"})]}):s.form_enabled?e.jsxs("form",{onSubmit:b,className:"space-y-2.5",children:[S.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:u.name,onChange:D=>h({...u,name:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":v},required:!0}),S.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:u.email,onChange:D=>h({...u,email:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":v},required:!0}),S.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:u.phone,onChange:D=>h({...u,phone:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":v}}),e.jsxs("button",{type:"submit",disabled:c,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60 inline-flex items-center justify-center gap-2",style:{background:`linear-gradient(135deg, ${v}, ${GF(v,-20)})`},children:[e.jsx(Da,{className:"w-4 h-4"}),c?"Sending...":s.download_label]}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We'll email you a copy too. No spam — promise."})]}):e.jsx("a",{href:s.download_url||"#",target:"_blank",rel:"noopener",onClick:()=>f("cta_click",{url:s.download_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg",style:{background:`linear-gradient(135deg, ${v}, ${GF(v,-20)})`},children:s.download_label}),T&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",T]})]})]})})}}function GF(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 mDe({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_lead_magnet_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(hDe,{config:t}):null}function cdn({children:s,siteConfig:t}){var _e,Me,Te,Ce,Ee,De,Ie,Fe,qe;const n=Jl(),r=In(),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState([]),[p,f]=N.useState([]),[g,b]=N.useState(null),v=N.useRef(null),j=N.useRef(null),{user:_,profile:S,signOut:A}=hbe();O8e(t,_==null?void 0:_.id),F8e(t,_==null?void 0:_.id);const T=((_e=t.agent)==null?void 0:_e.full_name)||"Agent",D=t.siteTitle||`${T} Real Estate`,L=n.pathname==="/search",M=n.pathname==="/",F=t.leadRegistrationMode!=="disabled";N.useEffect(()=>{(async()=>{const{data:Je}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});h(Je||[])})()},[t.id]),N.useEffect(()=>{(async()=>{const{data:Je}=await q.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});f(Je||[])})()},[t.id]),N.useEffect(()=>{const ve=Je=>{v.current&&!v.current.contains(Je.target)&&d(!1),j.current&&!j.current.contains(Je.target)&&b(null)};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[]);const z=qNt(t),V=t==null?void 0:t.bookingUrl,W=z?p.filter(ve=>{const Je=String(ve.target_url||"").toLowerCase(),we=String(ve.label||"").toLowerCase();return Je!=="/search"&&!Je.startsWith("/search?")&&!we.includes("search")}):p,K=W.length>0,Y=[{to:"/",label:"Home"},...z?[]:[{to:"/search",label:"Search"}],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],ee=K?[]:Y,ne=W.filter(ve=>!ve.parent_id),oe=ve=>W.filter(Je=>Je.parent_id===ve),pe=M?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",ce=t.siteTitle||`${T} - Real Estate`,de=t.siteTagline||`Browse homes and listings with ${T}`,ie=t.ogImageUrl||((Me=t.agent)==null?void 0:Me.avatar_url)||"",ye=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${L?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(D8e,{siteConfig:t,pagePath:n.pathname}),e.jsx(R8e,{siteConfig:t}),e.jsxs(Yo,{children:[e.jsx("title",{children:ce}),e.jsx("meta",{name:"description",content:de}),e.jsx("meta",{property:"og:title",content:ce}),e.jsx("meta",{property:"og:description",content:de}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ye+n.pathname}),ie&&e.jsx("meta",{property:"og:image",content:ie}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ce}),e.jsx("meta",{name:"twitter:description",content:de}),ie&&e.jsx("meta",{name:"twitter:image",content:ie}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${ye}${n.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${M?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${pe}`,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(Ln,{to:"/",className:"flex items-center gap-3",children:[((Te=t.agent)==null?void 0:Te.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:T,className:"h-10 w-10 rounded-full object-cover ring-2 ring-white/20"}),e.jsx("div",{children:e.jsx("span",{className:"font-bold text-lg leading-none tracking-tight",children:D})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[t.bookingUrl&&e.jsx(iN,{bookingUrl:t.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),ee.map(ve=>e.jsx(Ln,{to:ve.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname===ve.to?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:ve.label},ve.to)),K&&ne.map(ve=>{if(ve.item_type==="dropdown"){const Je=oe(ve.id);return e.jsxs("div",{ref:j,className:"relative",children:[e.jsxs("button",{onClick:()=>b(g===ve.id?null:ve.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[ve.label," ",e.jsx(io,{className:`h-3.5 w-3.5 transition-transform ${g===ve.id?"rotate-180":""}`})]}),g===ve.id&&Je.length>0&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:Je.map(we=>e.jsx(JG,{item:we,onClick:()=>b(null),className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors block"},we.id))})]},ve.id)}return e.jsx(JG,{item:ve,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},ve.id)}),u.length>0&&e.jsxs("div",{ref:v,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname.startsWith("/homes-for-sale-in-")?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"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(io,{className:`h-3.5 w-3.5 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:u.map(ve=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${ve.city_slug}`),d(!1)},className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors",children:ve.city_name},ve.city_slug))})]}),_?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(Ln,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(yi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(Ln,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(Xi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((Ce=S==null?void 0:S.name)==null?void 0:Ce.split(" ")[0])||"Account"})]})]}):F?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${M?"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 ${M?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx(Fn,{className:"h-5 w-5"}):e.jsx(n4,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${M?"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(iN,{bookingUrl:t.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),ee.map(ve=>e.jsx(Ln,{to:ve.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===ve.to?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:ve.label},ve.to)),K&&ne.map(ve=>{if(ve.item_type==="dropdown"){const Je=oe(ve.id);return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${M?"text-white/40":"text-gray-400"}`,children:ve.label}),Je.map(we=>e.jsx(JG,{item:we,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},we.id))]},ve.id)}return e.jsx(JG,{item:ve,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},ve.id)}),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${M?"text-white/40":"text-gray-400"}`,children:"Cities"}),u.map(ve=>e.jsx(Ln,{to:`/homes-for-sale-in-${ve.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===`/homes-for-sale-in-${ve.city_slug}`?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:ve.city_name},ve.city_slug))]}),_?e.jsxs(e.Fragment,{children:[e.jsx(Ln,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"My Account"}),e.jsx("button",{onClick:async()=>{await A(),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"Sign Out"})]}):F?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${M?"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}),!L&&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:[((Ee=t.agent)==null?void 0:Ee.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:T,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:T}),e.jsx("p",{className:"text-sm text-gray-500",children:((De=t.agent)==null?void 0:De.title)||"Real Estate Professional"})]})]}),((Ie=t.agent)==null?void 0:Ie.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(Pr,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Fe=t.agent)==null?void 0:Fe.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(Hs,{className:"h-3.5 w-3.5"})," ",t.agent.email]})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3 text-sm",children:[ee.map(ve=>e.jsx("li",{children:e.jsx(Ln,{to:ve.to,className:"hover:text-white transition-colors",children:ve.label})},ve.to)),V&&e.jsx("li",{children:e.jsx("a",{href:V,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-gray-500 leading-relaxed mb-4",children:z?"Have a real estate question or need a trusted connection? Get in touch today.":"Ready to find your dream home? Get in touch today for a personalized consultation."}),e.jsx(Ln,{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:[T," · ",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()," ",T,". Powered by LevelUp."]})]})]})]})}),!L&&((qe=t.agent)==null?void 0:qe.avatar_url)&&e.jsx(ddn,{agent:t.agent,bookingUrl:V}),l&&e.jsx(L8e,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(dDe,{slug:t.subdomainSlug}),e.jsx(uDe,{slug:t.subdomainSlug}),e.jsx(mDe,{slug:t.subdomainSlug})]})}function ddn({agent:s,bookingUrl:t}){var i;const[n,r]=N.useState(!1),a=In();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(Pr,{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(Hs,{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(Fn,{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 JG({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(Ln,{to:r,className:t,onClick:n,children:s.label})}const Tet={california:"California DRE License",ca:"California DRE License"};function sEe(s){const t=(s||"").trim();if(!t)return"Real Estate License";const n=t.toLowerCase();return Tet[n]?Tet[n]:`${t.replace(/\b\w/g,a=>a.toUpperCase())} Real Estate License`}function Eet(s){if(s)return s.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function udn({children:s,siteConfig:t}){var ye,_e,Me,Te,Ce,Ee,De;const n=Jl(),r=In(),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState([]),[p,f]=N.useState(!1),g=N.useRef(null),{user:b,profile:v,signOut:j}=hbe();O8e(t,b==null?void 0:b.id),F8e(t,b==null?void 0:b.id);const _=((ye=t.agent)==null?void 0:ye.full_name)||"Agent",S=Eet(t.agentLicenseNumber),A=Eet(t.brokerageLicenseNumber),T=t.siteTitle||`${_} Real Estate`,D=t.brokerageLegalName?`${_} | ${t.brokerageLegalName}`:_,L=Ie=>{if(!Ie)return Ie;const Fe=_.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),qe=new RegExp(`^\\s*${Fe}\\s*[|\\-–—:]\\s*`,"i");return Ie.replace(qe,"").trim()},M=T&&T!==`${_} Real Estate`?T:null,F=M?L(M):null,z=F&&F.toLowerCase()!==_.toLowerCase()?F:null,V=n.pathname==="/search",W=n.pathname==="/",K=t.leadRegistrationMode!=="disabled",Y="#c9a96e",ee=t.bookingUrl;N.useEffect(()=>{const Ie=()=>f(window.scrollY>80);return window.addEventListener("scroll",Ie,{passive:!0}),()=>window.removeEventListener("scroll",Ie)},[]),N.useEffect(()=>{(async()=>{const{data:Fe}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});h(Fe||[])})()},[t.id]),N.useEffect(()=>{const Ie=Fe=>{g.current&&!g.current.contains(Fe.target)&&d(!1)};return document.addEventListener("mousedown",Ie),()=>document.removeEventListener("mousedown",Ie)},[]);const ne=[{to:"/",label:"Home"},{to:"/search",label:"Search"},{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],oe=t.siteTitle||`${_} - Real Estate`,pe=t.siteTagline||`Browse homes and listings with ${_}`,ce=t.ogImageUrl||((_e=t.agent)==null?void 0:_e.avatar_url)||"",de=`https://${t.subdomainSlug||""}.thelocalmove.com`,ie=W?p?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return e.jsxs("div",{className:`flex flex-col ${V?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(D8e,{siteConfig:t,pagePath:n.pathname}),e.jsx(R8e,{siteConfig:t}),e.jsxs(Yo,{children:[e.jsx("title",{children:oe}),e.jsx("meta",{name:"description",content:pe}),e.jsx("meta",{property:"og:title",content:oe}),e.jsx("meta",{property:"og:description",content:pe}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:de+n.pathname}),ce&&e.jsx("meta",{property:"og:image",content:ce}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:oe}),e.jsx("meta",{name:"twitter:description",content:pe}),ce&&e.jsx("meta",{name:"twitter:image",content:ce}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${de}${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:`${W?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${ie}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-20",children:[e.jsx(Ln,{to:"/",className:"flex items-center gap-3 min-w-0",children:e.jsxs("span",{className:"flex flex-col leading-none max-w-[320px] xl:max-w-[420px]",children:[e.jsx("span",{className:"block whitespace-normal text-white text-xl tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:D}),z&&e.jsx("span",{className:"mt-1 text-[11px] tracking-[0.18em] uppercase text-white/70",children:z})]})}),e.jsxs("nav",{className:"hidden lg:flex items-center gap-1",children:[ne.map(Ie=>e.jsx(Ln,{to:Ie.to,className:`px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname===Ie.to?"text-white":"text-white/40 hover:text-white"}`,children:Ie.label},Ie.to)),u.length>0&&e.jsxs("div",{ref:g,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",e.jsx(io,{className:`h-3 w-3 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:u.map(Ie=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${Ie.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:Ie.city_name},Ie.city_slug))})]}),b?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(Ln,{to:"/account",className:"flex items-center gap-1.5 px-3 py-2 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:[e.jsx(yi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(Ln,{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(Xi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((Me=v==null?void 0:v.name)==null?void 0:Me.split(" ")[0])||"Account"})]})]}):K?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(iN,{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(Fn,{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(iN,{bookingUrl:ee,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),ne.map(Ie=>e.jsx(Ln,{to:Ie.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${n.pathname===Ie.to?"text-white":"text-white/40 hover:text-white"}`,children:Ie.label},Ie.to)),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Y},children:"Cities"}),u.map(Ie=>e.jsx(Ln,{to:`/homes-for-sale-in-${Ie.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:Ie.city_name},Ie.city_slug))]}),b?e.jsxs(e.Fragment,{children:[e.jsx(Ln,{to:"/account",onClick:()=>i(!1),className:"block px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"My Account"}),e.jsx("button",{onClick:async()=>{await j(),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign Out"})]}):K?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}),!V&&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:_}),e.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((Te=t.agent)==null?void 0:Te.title)||"Real Estate Professional"}),(S||A)&&e.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[S&&e.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[sEe(t.licenseState)," #",S]}),A&&e.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",A]})]}),((Ce=t.agent)==null?void 0:Ce.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(Pr,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((Ee=t.agent)==null?void 0:Ee.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(Hs,{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:Y},children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3",children:[ne.map(Ie=>e.jsx("li",{children:e.jsx(Ln,{to:Ie.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:Ie.label})},Ie.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:BR},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:Y},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(iN,{bookingUrl:ee,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),e.jsx(Ln,{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:[_," · ",t.brokerageLegalName]}),S&&e.jsxs("span",{children:[sEe(t.licenseState)," #",S]}),A&&e.jsxs("span",{children:["Brokerage #",A]})]}),t.mlsDisclaimerText&&e.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[t.mlsLogoUrl&&e.jsx("img",{src:t.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-70"}),e.jsx("p",{className:"text-[11px] text-white/70 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[11px] text-white/70 tracking-wider uppercase",children:[t.equalHousingEnabled&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:e.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),e.jsx("span",{children:"Equal Housing Opportunity"})]}),e.jsxs("span",{children:["© ",new Date().getFullYear()," ",_,". Powered by LevelUp."]})]})]})]})}),!V&&((De=t.agent)==null?void 0:De.avatar_url)&&e.jsx(hdn,{agent:t.agent,agentLicense:S,siteConfig:t,accentColor:Y}),l&&e.jsx(L8e,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:Y}),e.jsx(dDe,{slug:t.subdomainSlug}),e.jsx(uDe,{slug:t.subdomainSlug}),e.jsx(mDe,{slug:t.subdomainSlug})]})}function hdn({agent:s,agentLicense:t,siteConfig:n,accentColor:r}){var o;const[a,i]=N.useState(!1),l=In();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:sEe(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(Pr,{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(Hs,{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(Fn,{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 WF="#2c1810",L_="#b8860b";function mdn({children:s,siteConfig:t}){var M,F,z;const n=Jl();In();const[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState([]),[h,p]=N.useState(!1),f=N.useRef(null),{user:g,profile:b,signOut:v}=hbe();O8e(t,g==null?void 0:g.id),F8e(t,g==null?void 0:g.id);const j=((M=t.agent)==null?void 0:M.full_name)||"Agent",_=t.siteTitle||`${j} Land & Ranch`,S=n.pathname==="/",A=t.leadRegistrationMode!=="disabled";N.useEffect(()=>{const V=()=>p(window.scrollY>80);return window.addEventListener("scroll",V,{passive:!0}),()=>window.removeEventListener("scroll",V)},[]),N.useEffect(()=>{(async()=>{const{data:W}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");W&&u(W)})()},[t.id]),N.useEffect(()=>{const V=W=>{f.current&&!f.current.contains(W.target)&&c(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[]);const T=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],D=h||!S?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",L=h||!S?WF:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(Yo,{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(D8e,{siteConfig:t}),e.jsx(R8e,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${D}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[e.jsxs(Ln,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(sL,{className:"w-7 h-7",style:{color:L_}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:L,fontFamily:"'Playfair Display', Georgia, serif"},children:_})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[T.map(V=>e.jsx(Ln,{to:V.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:n.pathname===V.path?L_:L},children:V.label},V.path)),d.length>0&&e.jsxs("div",{ref:f,className:"relative",children:[e.jsxs("button",{onClick:()=>c(!o),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:L},children:["Areas ",e.jsx(io,{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(V=>e.jsx(Ln,{to:`/homes-for-sale-in-${V.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:WF},onClick:()=>c(!1),children:V.city_name},V.city_slug))})]}),g?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(Ln,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:L_,color:L},children:[e.jsx(Xi,{className:"w-4 h-4 inline mr-1.5"}),(b==null?void 0:b.name)||"Account"]})}):A?e.jsx("button",{onClick:()=>l(!0),className:"ml-3 px-5 py-2.5 text-sm font-semibold text-white rounded-full hover:shadow-lg transition-all hover:scale-105",style:{backgroundColor:L_},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!r),className:"md:hidden p-2",style:{color:L},children:r?e.jsx(Fn,{className:"w-6 h-6"}):e.jsx(n4,{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:[T.map(V=>e.jsx(Ln,{to:V.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:n.pathname===V.path?L_:WF},onClick:()=>a(!1),children:V.label},V.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(V=>e.jsx(Ln,{to:`/homes-for-sale-in-${V.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:WF},onClick:()=>a(!1),children:V.city_name},V.city_slug))]}),!g&&A&&e.jsx("button",{onClick:()=>{l(!0),a(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:L_},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:WF},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(sL,{className:"w-6 h-6",style:{color:L_}}),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:T.map(V=>e.jsx(Ln,{to:V.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:V.label},V.path))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Contact"}),e.jsxs("div",{className:"space-y-3",children:[((F=t.agent)==null?void 0:F.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[e.jsx(Pr,{className:"w-4 h-4",style:{color:L_}}),t.agent.phone]}),((z=t.agent)==null?void 0:z.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[e.jsx(Hs,{className:"w-4 h-4",style:{color:L_}}),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:L_}})]})]})}),i&&e.jsx(L8e,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(dDe,{slug:t.subdomainSlug}),e.jsx(uDe,{slug:t.subdomainSlug}),e.jsx(mDe,{slug:t.subdomainSlug})]})}function pdn(){const{pathname:s}=Jl();return N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[s]),null}const fdn=N.lazy(()=>vi(()=>import("./LeadSiteHome-yHxLdQqt.js"),__vite__mapDeps([0,1,2,3]))),xdn=N.lazy(()=>vi(()=>import("./LeadSiteLuxuryHome-CDGnn4fH.js"),__vite__mapDeps([4,2,3]))),gdn=N.lazy(()=>vi(()=>import("./LeadSiteLandRanchHome-Da2uUjBN.js"),__vite__mapDeps([5,1,2,3]))),ydn=N.lazy(()=>vi(()=>import("./LeadSiteSearch-DHez-h-6.js"),__vite__mapDeps([6,1,7,3,8]))),vdn=N.lazy(()=>vi(()=>import("./LeadSiteLuxurySearch-t_Pv0y9B.js"),__vite__mapDeps([9,1,7,3,8]))),bdn=N.lazy(()=>vi(()=>import("./LeadSiteListingDetail-CIY2k5DJ.js"),__vite__mapDeps([10,11,3,12]))),_dn=N.lazy(()=>vi(()=>import("./LeadSiteLuxuryListingDetail-BVmc6ZiE.js"),__vite__mapDeps([13,11,3,12]))),wdn=N.lazy(()=>vi(()=>import("./LeadSiteAbout-R3qHYpEX.js"),[])),jdn=N.lazy(()=>vi(()=>import("./LeadSiteLuxuryAbout-du3p1AWH.js"),[])),Ndn=N.lazy(()=>vi(()=>import("./LeadSiteContact-CZR6cZv9.js"),[])),kdn=N.lazy(()=>vi(()=>import("./LeadSiteLuxuryContact-BCNgFisG.js"),[])),Sdn=N.lazy(()=>vi(()=>import("./LeadSiteConsumerDashboard-BkfQg-QZ.js"),[])),Aet=N.lazy(()=>vi(()=>import("./LeadSiteBlog-B4mzQENq.js"),[])),Cdn=N.lazy(()=>vi(()=>import("./LeadSiteCommunity-BmN1KmYt.js"),[])),Tdn=N.lazy(()=>vi(()=>import("./LeadSiteSellers-3oP7I89O.js"),[])),Edn=N.lazy(()=>vi(()=>import("./LeadSiteCityPage-BCxz70Do.js"),__vite__mapDeps([14,3,8]))),Adn=N.lazy(()=>vi(()=>import("./LeadSiteSubdivisionPage-ypCe2AN1.js"),__vite__mapDeps([15,3]))),Mdn=N.lazy(()=>vi(()=>import("./LeadSiteCustomPage-BUpW4e1t.js"),[]));function Idn(){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 Pdn(){var d;const{siteConfig:s,themeConfig:t,isLoading:n,error:r}=Mrn();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?mdn:a?udn:cdn,o=qNt(s,t),c=i?e.jsx(gdn,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(xdn,{siteConfig:s,themeConfig:t??void 0}):e.jsx(fdn,{siteConfig:s,themeConfig:t??void 0});return e.jsxs(Prn,{siteConfig:s,children:[e.jsx(pdn,{}),e.jsxs(l,{siteConfig:s,children:[e.jsx(N.Suspense,{fallback:e.jsx(Idn,{}),children:e.jsxs(sfe,{children:[e.jsx(is,{path:"/",element:c}),e.jsx(is,{path:"/search",element:o?e.jsx(f4,{to:"/contact",replace:!0}):a?e.jsx(vdn,{siteConfig:s}):e.jsx(ydn,{siteConfig:s})}),e.jsx(is,{path:"/listing/:mlsNumber",element:o?e.jsx(f4,{to:"/contact",replace:!0}):a?e.jsx(_dn,{siteConfig:s}):e.jsx(bdn,{siteConfig:s})}),e.jsx(is,{path:"/about",element:a?e.jsx(jdn,{siteConfig:s}):e.jsx(wdn,{siteConfig:s})}),e.jsx(is,{path:"/contact",element:a?e.jsx(kdn,{siteConfig:s}):e.jsx(Ndn,{siteConfig:s})}),e.jsx(is,{path:"/account",element:e.jsx(Sdn,{siteConfig:s})}),e.jsx(is,{path:"/blog",element:e.jsx(Aet,{siteConfig:s,isLuxury:a})}),e.jsx(is,{path:"/blog/:slug",element:e.jsx(Aet,{siteConfig:s,isLuxury:a})}),e.jsx(is,{path:"/sell",element:e.jsx(Tdn,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(is,{path:"/community",element:e.jsx(Cdn,{siteConfig:s,isLuxury:a})}),e.jsx(is,{path:"/schedule",element:e.jsx(zrn,{bookingUrl:s.bookingUrl,agentName:((d=s.agent)==null?void 0:d.full_name)||"your agent"})}),e.jsx(is,{path:"/p/:pageSlug",element:e.jsx(Mdn,{siteConfig:s})}),e.jsx(is,{path:"/*",element:e.jsx(Ldn,{siteConfig:s,referralMode:o})})]})}),e.jsx(Frn,{bookingUrl:s.bookingUrl})]})]})}function Ldn({siteConfig:s,referralMode:t}){const n=Jl(),r=n.pathname.match(/^\/homes-in-(.+)$/);if(r)return e.jsx(Adn,{siteConfig:s,subdivisionSlug:r[1]});const a=n.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(Edn,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}function Ddn(){const{user:s,loading:t}=gs(),{data:n,isLoading:r}=lt({queryKey:["feature-entitlement","levelup_attract",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await q.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key","levelup_attract").maybeSingle();if(i)throw i;return a?{hasAccess:a.enabled&&(!a.expires_at||new Date(a.expires_at).getTime()>Date.now()),tier:a.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:!!(n!=null&&n.hasAccess),tier:(n==null?void 0:n.tier)??null,isLoading:t||r}}function Rdn({children:s}){const{user:t,loading:n}=gs(),{hasAccess:r,isLoading:a}=Ddn(),i=Jl();return N.useEffect(()=>{!n&&!a&&t&&!r&&ae.error("LevelUp Attract isn't available for your account yet.")},[n,a,t,r]),n||t&&a?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t?r?e.jsx(e.Fragment,{children:s}):e.jsx(f4,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(f4,{to:"/auth",replace:!0}))}function JU(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:["attract-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await q.from("attract_settings").select("*").eq("user_id",s.id).maybeSingle();if(l)throw l;return i}}),r=gt({mutationFn:async i=>{const l={...i,user_id:s.id},{data:o,error:c}=await q.from("attract_settings").upsert(l,{onConflict:"user_id"}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ae.success("Settings saved")},onError:i=>ae.error(i.message)}),a=gt({mutationFn:async()=>{const{error:i}=await q.from("attract_settings").update({onboarding_completed_at:null}).eq("user_id",s.id);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ae.success("Onboarding reset — run it again anytime")}});return{settings:n.data,isLoading:n.isLoading,save:r,upsert:r,resetOnboarding:a}}const jSt="v1",ed={recency:22,consistency:16,value_delivered:14,kit_engagement:16,event_participation:12,follow_up_discipline:10,pipeline_momentum:10};Object.values(ed).reduce((s,t)=>s+t,0);const NSt=864e5,Mm=(s,t=new Date)=>Math.floor((new Date(t).getTime()-new Date(s).getTime())/NSt),kSt=["touch_logged","call","text","email","dm","meeting","note"];function Odn(s,t,n=new Date){var b,v,j;const a=t.activities.filter(_=>_.agent_id===s.id).filter(_=>kSt.includes(_.activity_type)).sort((_,S)=>+new Date(S.created_at)-+new Date(_.created_at)),i=s.last_touch_at||((b=a[0])==null?void 0:b.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[v=_.share_id]||(d[v]=[])).push(_);const u=t.attendees.filter(_=>_.agent_id===s.id),h=t.followUps.filter(_=>_.agent_id===s.id),p=h.filter(_=>!_.completed_at),f=t.stageChanges.filter(_=>_.agent_id===s.id).sort((_,S)=>+new Date(S.created_at)-+new Date(_.created_at)),g=new Set(a.filter(_=>Mm(_.created_at,n)<=180).map(_=>_.created_at.slice(0,7)));return{agent:s,touches:a,lastTouchAt:i,daysSinceTouch:i?Mm(i,n):null,touches90:a.filter(_=>Mm(_.created_at,n)<=90).length,touches30:a.filter(_=>Mm(_.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((_,S)=>_+(S.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:p,overdueFollowUps:p.filter(_=>_.due_at&&new Date(_.due_at)!!_.completed_at),stageChanges:f,lastStageChangeAt:((j=f[0])==null?void 0:j.created_at)||null,daysSinceStageChange:f[0]?Mm(f[0].created_at,n):null,scoreEvents:t.scoreEvents.filter(_=>_.agent_id===s.id)}}const vpe=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined"],bpe=["not_right_now","not_a_fit","long_term_relationship"];function Fdn(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=ed.recency,c=`Last meaningful touch ${l} day(s) ago.`,r.push("Recent personal contact")):l<=21?(o=ed.recency*.85,c=`Last touch ${l} days ago.`,r.push("Contact is still fresh")):l<=45?(o=ed.recency*.6,c=`Last touch ${l} days ago.`,i.push("Reach out within the next week to keep momentum.")):l<=90?(o=ed.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=ed.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:ed.recency,earned:Math.round(o),detail:c,direction:o>=ed.recency*.6?"positive":"negative"});const d=Math.min(s.distinctTouchMonths,6),u=ed.consistency*(d/6),h=s.touches30>6;n.push({key:"consistency",label:"Consistency of touches",weight:ed.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>=ed.consistency*.5?"positive":"neutral"}),d>=4&&r.push("Consistent rhythm across months"),d<=1&&i.push("Aim for at least one touch per month rather than bursts."),h&&a.push(`${s.touches30} touches in the last 30 days — give them room to breathe`);const p=s.shares.length,f=ed.value_delivered*Math.min(p/3,1);n.push({key:"value_delivered",label:"Value delivered",weight:ed.value_delivered,earned:Math.round(f),detail:p?`${p} resource kit share(s) sent.`:"No resource kit shared yet.",direction:p?"positive":"neutral"}),p?r.push(`${p} resource kit share(s) delivered`):i.push("Share a relevant Resource Kit — value first, no ask.");const 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),b=Math.min(g,ed.kit_engagement);n.push({key:"kit_engagement",label:"Kit engagement",weight:ed.kit_engagement,earned:b,detail:p?`${s.totalKitOpens} open(s), ${s.downloads} download(s), ${s.ctaClicks} link click(s), ${s.questions} question(s), ${s.meetingRequests} meeting request(s).`:"Nothing shared yet, so no engagement to measure.",direction:b>0?"positive":"neutral"}),s.meetingRequests>0&&r.push("They asked for a conversation"),p&&s.totalKitOpens===0&&(a.push("Shared kit has never been opened"),i.push("Follow up personally — the kit link was never opened."));const v=Math.min(s.attended,2)*5+(s.attendees.length?2:0)-Math.min(s.noShows,2)*2,j=Math.max(0,Math.min(v,ed.event_participation));n.push({key:"event_participation",label:"Event participation",weight:ed.event_participation,earned:j,detail:s.attendees.length?`${s.attended} attended, ${s.noShows} no-show(s), ${s.attendees.length} total invitation(s)/registration(s).`:"Never invited to an event.",direction:j>0?"positive":"neutral"}),s.attended>0&&r.push(`${s.attended} event(s) attended`),s.attendees.length||i.push("Invite them to your next event or mastermind."),s.noShows>0&&a.push(`${s.noShows} no-show(s)`);const _=s.completedFollowUps.length+s.openFollowUps.length;let S=_===0?ed.follow_up_discipline*.4:ed.follow_up_discipline*(s.completedFollowUps.length/_);S-=Math.min(s.overdueFollowUps.length,3)*2,S=Math.max(0,Math.min(S,ed.follow_up_discipline)),n.push({key:"follow_up_discipline",label:"Follow-up discipline",weight:ed.follow_up_discipline,earned:Math.round(S),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 A=vpe.indexOf(s.agent.stage);let T=0,D;if(bpe.includes(s.agent.stage))T=ed.pipeline_momentum*.3,D="Relationship is intentionally parked — long-term nurture.";else if(A<0)T=ed.pipeline_momentum*.3,D=`Stage "${s.agent.stage}" is outside the advancing ladder.`;else{const F=ed.pipeline_momentum*(A/(vpe.length-1)),z=s.daysSinceStageChange!==null&&s.daysSinceStageChange>60;T=z?F*.5:F,D=`Stage ${A+1} of ${vpe.length}`+(s.daysSinceStageChange!==null?`, last moved ${s.daysSinceStageChange} days ago.`:", never moved."),z&&(a.push("Stage has not moved in over 60 days"),i.push("Have the next real conversation that would justify a stage move."))}n.push({key:"pipeline_momentum",label:"Pipeline momentum",weight:ed.pipeline_momentum,earned:Math.round(T),detail:D,direction:T>ed.pipeline_momentum*.5?"positive":"neutral"});let L=n.reduce((F,z)=>F+z.earned,0);s.agent.temperature==="hot"&&(L+=4,r.push("You marked this relationship hot")),s.agent.temperature==="cold"&&(L-=4,a.push("You marked this relationship cold")),h&&(L-=3),L=Math.max(0,Math.min(100,Math.round(L)));const M=L>=75?"thriving":L>=55?"healthy":L>=35?"cooling":"at_risk";return{agent_id:s.agent.id,score:L,band:M,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:{...ed},engine_version:jSt,calculated_at:t.toISOString()}}const SSt=[{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"}],zdn={urgent:100,high:70,medium:40,low:15},hv=(s,t=new Date)=>new Date(t.getTime()+s*NSt).toISOString(),F_=s=>s.first_name||"there",Bdn=3;function mv(s,t,n={}){var o,c;const r=F_(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 $dn(s,t,n=new Date){const r=[],a=s.agent;if(a.stage==="not_a_fit")return r;const i=s.daysSinceTouch!==null&&s.daysSinceTouch{var j;return(j=t.kits.find(_=>_.id===v))==null?void 0:j.title},o=v=>{r.push({...v,message_source:"rules",rank_score:v.rank_score??zdn[v.priority]})},c=s.shares.find(v=>v.engagement_level==="high_intent");if(s.meetingRequests>0||s.questions>0||c){const v=c?l(c.kit_id):void 0,j=[s.meetingRequests>0&&`${s.meetingRequests} meeting request(s) submitted`,s.questions>0&&`${s.questions} question(s) asked inside a shared kit`,c&&`Kit engagement is classified High Intent (${c.open_count} opens)`,s.downloads>0&&`${s.downloads} file download(s)`].filter(Boolean);o({agent_id:a.id,rec_key:"high_intent",signal_group:"high_intent",signal_label:"High-intent engagement",action_type:"respond_to_intent",channel:s.meetingRequests>0?"call":"text",title:`Call ${F_(a)} — they are actively engaging`,reasons:j,priority:"urgent",suggested_due_at:hv(1,n),draft_message:mv("high_intent",s,{kitTitle:v}),suggested_kit_id:(c==null?void 0:c.kit_id)??null,source_signals:{meeting_requests:s.meetingRequests,questions:s.questions,downloads:s.downloads,share_id:c==null?void 0:c.id},rank_score:100+s.meetingRequests*5})}const d=s.shares.find(v=>v.last_opened_at&&v.first_opened_at&&Mm(v.last_opened_at,n)<=7&&Mm(v.first_opened_at,v.last_opened_at)>=14&&(v.open_count||0)>1);d&&(s.daysSinceTouch===null||s.daysSinceTouch>21)&&o({agent_id:a.id,rec_key:"renewed_interest",signal_group:"renewed_interest",signal_label:"Renewed interest",action_type:"reengage",channel:"text",title:`${F_(a)} came back to a kit you shared`,reasons:[`Re-opened "${l(d.kit_id)??"a shared kit"}" ${Mm(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:hv(2,n),draft_message:mv("renewed_interest",s,{kitTitle:l(d.kit_id)}),suggested_kit_id:d.kit_id,source_signals:{share_id:d.id,open_count:d.open_count},rank_score:88});const u=s.attendees.filter(v=>v.checked_in_at&&Mm(v.checked_in_at,n)<=7&&v.followup_status!=="done").sort((v,j)=>+new Date(j.checked_in_at)-+new Date(v.checked_in_at))[0];if(u){const v=t.events.find(_=>_.id===u.event_id),j=Math.round((n.getTime()-new Date(u.checked_in_at).getTime())/36e5);o({agent_id:a.id,rec_key:`event_follow_up:${u.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"event_follow_up",channel:"call",title:`Follow up on ${(v==null?void 0:v.title)??"the event"} — ${j}h since they attended`,reasons:[`Checked in to "${(v==null?void 0:v.title)??"event"}" ${j} hours ago`,`Follow-up status is "${u.followup_status??"pending"}"`,j<=48?"Inside the 48-hour window where follow-up matters most":"Past the ideal 48-hour window — still worth doing today"],priority:j<=48?"urgent":"high",suggested_due_at:hv(j<=48?1:0,n),draft_message:mv("event_follow_up",s,{eventTitle:v==null?void 0:v.title}),suggested_event_id:u.event_id,suggested_kit_id:(v==null?void 0:v.resource_kit_id)??null,source_signals:{attendee_id:u.id,hours_since:j},rank_score:j<=48?96:74})}else{const v=s.attendees.find(j=>j.no_show_at&&Mm(j.no_show_at,n)<=10);if(v){const j=t.events.find(_=>_.id===v.event_id);o({agent_id:a.id,rec_key:`event_no_show:${v.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"no_show_recovery",channel:"text",title:`${F_(a)} missed ${(j==null?void 0:j.title)??"an event"} — recover gracefully`,reasons:[`Registered but did not attend "${(j==null?void 0:j.title)??"event"}"`,"No-show recovery works best within a week, with zero guilt"],priority:"medium",suggested_due_at:hv(2,n),draft_message:mv("event_no_show",s,{eventTitle:j==null?void 0:j.title}),suggested_event_id:v.event_id,source_signals:{attendee_id:v.id},rank_score:52})}}const h=s.shares.find(v=>v.first_opened_at&&Mm(v.first_opened_at,n)>=3&&Mm(v.first_opened_at,n)<=30&&(s.daysSinceTouch===null||s.lastTouchAt&&new Date(s.lastTouchAt)!v.first_opened_at&&Mm(v.created_at,n)>=5&&v.status==="active");h?o({agent_id:a.id,rec_key:`resource_follow_up:${h.id}`,signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"resource_follow_up",channel:"text",title:`Close the loop on "${l(h.kit_id)??"the kit"}"`,reasons:[`Opened ${Mm(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:hv(2,n),draft_message:mv("resource_follow_up",s,{kitTitle:l(h.kit_id)}),suggested_kit_id:h.kit_id,source_signals:{share_id:h.id},rank_score:78}):p&&o({agent_id:a.id,rec_key:`resource_unopened:${p.id}`,signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"resource_nudge",channel:"text",title:`Shared kit never opened — nudge ${F_(a)} personally`,reasons:[`Shared ${Mm(p.created_at,n)} days ago and never opened`,"A personal message beats a resend"],priority:"medium",suggested_due_at:hv(2,n),draft_message:mv("resource_unopened",s,{kitTitle:l(p.kit_id)}),suggested_kit_id:p.kit_id,source_signals:{share_id:p.id},rank_score:46});const f=s.overdueFollowUps.sort((v,j)=>+new Date(v.due_at)-+new Date(j.due_at))[0];if(f){const v=Mm(f.due_at,n);o({agent_id:a.id,rec_key:`overdue:${f.id}`,signal_group:"overdue_commitment",signal_label:"Overdue commitment",action_type:"clear_overdue",channel:f.touch_type||"call",title:`Overdue ${v} day(s): ${f.title}`,reasons:[`Follow-up "${f.title}" was due ${v} day(s) ago`,`Priority: ${f.priority??"medium"}`],priority:v>7?"urgent":"high",suggested_due_at:hv(0,n),draft_message:mv("overdue_commitment",s,{followUpTitle:f.title}),source_signals:{follow_up_id:f.id,days_late:v},rank_score:92+Math.min(v,8)})}const g=vpe.indexOf(a.stage);if(!bpe.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 ${F_(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:hv(4,n),draft_message:mv("ready_deeper",s),source_signals:{stage:a.stage,attended:s.attended},rank_score:72}),s.daysSinceTouch===null&&Mm(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 ${F_(a)}`,reasons:[`Added to your pipeline ${Mm(a.created_at,n)} days ago`,"No touch, kit, or event activity logged"],priority:"medium",suggested_due_at:hv(3,n),draft_message:mv("no_touch",s),source_signals:{created_at:a.created_at},rank_score:48});else if(s.daysSinceTouch!==null){const v=a.temperature==="hot"?14:a.temperature==="cold"?90:45;if(s.daysSinceTouch>v){const j=s.daysSinceTouch>v*2;o({agent_id:a.id,rec_key:j?"no_touch_long":"going_cold",signal_group:j?"no_touch":"going_cold",signal_label:j?"No meaningful touch recently":"Relationship going cold",action_type:"check_in",channel:"personal_check_in",title:`${F_(a)} has been quiet for ${s.daysSinceTouch} days`,reasons:[`Last meaningful touch ${s.daysSinceTouch} days ago`,`Your cadence for a "${a.temperature??"warm"}" relationship is ${v} days`,s.touches90?`${s.touches90} touch(es) in the last 90 days`:"No touches in the last 90 days"],priority:j?"high":"medium",suggested_due_at:hv(3,n),draft_message:mv(j?"no_touch":"going_cold",s),source_signals:{days_since_touch:s.daysSinceTouch,threshold:v},rank_score:j?62:44})}}if(!s.shares.length&&!bpe.includes(a.stage)&&t.primaryPillar==="provide"){const v=t.kits.find(j=>j.status==="published"&&(!j.audience||!a.production_context||!0));v&&o({agent_id:a.id,rec_key:"share_first_kit",signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"share_kit",channel:"resource_share",title:`Share "${v.title}" with ${F_(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:hv(5,n),draft_message:mv("share_value",s,{kitTitle:v.title}),suggested_kit_id:v.id,source_signals:{pillar:"provide"},rank_score:38})}if(!s.attendees.length&&!bpe.includes(a.stage)&&t.primaryPillar==="connect"){const v=t.events.filter(j=>j.status==="published"&&j.starts_at&&new Date(j.starts_at)>n).sort((j,_)=>+new Date(j.starts_at)-+new Date(_.starts_at))[0];v&&o({agent_id:a.id,rec_key:`invite_event:${v.id}`,signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"invite_to_event",channel:"event_invitation",title:`Invite ${F_(a)} to ${v.title}`,reasons:["Never invited to an event",`"${v.title}" is published and upcoming`,"Your 90-day plan primary pillar is Connect"],priority:"medium",suggested_due_at:hv(4,n),draft_message:mv("event_invite_nudge",s,{eventTitle:v.title,eventWhen:v.starts_at?new Date(v.starts_at).toLocaleDateString():void 0}),suggested_event_id:v.id,source_signals:{pillar:"connect",event_id:v.id},rank_score:40})}return(i?r.filter(v=>v.priority==="urgent"):r).sort((v,j)=>j.rank_score-v.rank_score).slice(0,3)}const Met=[{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"]}],Udn={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 qdn(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:kSt.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 Vdn(s,t,n){return s.shares.slice().sort((r,a)=>+new Date(a.created_at)-+new Date(r.created_at)).map(r=>{var p;const a=s.shareEvents[r.id]??[],i=a.filter(f=>f.event_type==="file_download").length,l=a.filter(f=>f.event_type==="primary_cta_click"||f.event_type==="external_link_click").length,o=a.filter(f=>f.event_type==="question_submitted").length,c=a.filter(f=>f.event_type==="meeting_requested").length,d=r.engagement_level==="high_intent"||c>0?"High Intent":r.engagement_level==="engaged"||i>0||l>0||o>0?"Engaged":r.first_opened_at?"Viewed":"Sent",u=t.followUps.filter(f=>f.agent_id===s.agent.id&&new Date(f.created_at)>=new Date(r.created_at)).sort((f,g)=>+new Date(f.created_at)-+new Date(g.created_at))[0]??null,h=s.stageChanges.filter(f=>new Date(f.created_at)>new Date(r.created_at)).sort((f,g)=>+new Date(f.created_at)-+new Date(g.created_at))[0]??null;return{share:r,kitTitle:((p=t.kits.find(f=>f.id===r.kit_id))==null?void 0:p.title)??"Resource kit",shareUrl:`${n}/attract-kit/${r.share_token}`,events:a,firstViewedAt:r.first_opened_at??null,lastViewedAt:r.last_opened_at??null,visits:r.open_count??0,downloads:i,ctaClicks:l,questions:o,meetingRequests:c,classification:d,followUp:u,stageAdvancedAfter:h}})}function Hdn(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 Vc=q;function Gdn(){const{user:s}=gs();return lt({queryKey:["attract-intel-data",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{var g,b;const[t,n,r,a,i,l,o,c,d,u,h,p]=await Promise.all([Vc.from("attract_agents").select("*").order("updated_at",{ascending:!1}),Vc.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(2e3),Vc.from("attract_follow_ups").select("*").order("created_at",{ascending:!1}).limit(2e3),Vc.from("attract_kit_shares").select("*").order("created_at",{ascending:!1}).limit(1e3),Vc.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Vc.from("attract_event_attendees").select("*").order("created_at",{ascending:!1}).limit(2e3),Vc.from("attract_events").select("id, title, starts_at, status, resource_kit_id, public_slug").limit(500),Vc.from("attract_pipeline_history").select("*").order("created_at",{ascending:!1}).limit(2e3),Vc.from("attract_score_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Vc.from("attract_resource_kits").select("id, title, audience, pillar, status, is_template").eq("is_template",!1),Vc.from("attract_event_notes").select("*").order("created_at",{ascending:!1}).limit(1e3),Vc.from("attract_settings").select("primary_pillar, attraction_style, ninety_day_plan").eq("user_id",s.id).maybeSingle()]),f=[t,n,r,a,i,l,o,c,d,u,h].find(v=>v.error);if(f)throw f.error;return{agents:t.data??[],activities:n.data??[],followUps:r.data??[],shares:a.data??[],kitEvents:i.data??[],attendees:l.data??[],events:o.data??[],stageChanges:c.data??[],scoreEvents:d.data??[],kits:u.data??[],eventNotes:h.data??[],primaryPillar:((g=p==null?void 0:p.data)==null?void 0:g.primary_pillar)??((b=p==null?void 0:p.data)==null?void 0:b.attraction_style)??null}}})}function p6(){const s=Gdn(),t=N.useMemo(()=>{if(!s.data)return[];const r=new Date;return s.data.agents.map(a=>{const i=Odn(a,s.data,r),l=Fdn(i,r),o=$dn(i,s.data,r);return{agent:a,signals:i,score:l,recommendations:o,primary:o[0]??null}})},[s.data]),n=N.useMemo(()=>new Map(t.map(r=>[r.agent.id,r])),[t]);return{...s,dataset:s.data,intel:t,byId:n}}function Wdn(s){const{dataset:t,byId:n,isLoading:r,error:a,refetch:i}=p6(),l=s?n.get(s)??null:null,o=N.useMemo(()=>l&&t?qdn(l.signals,t,t.eventNotes??[]):[],[l,t]),c=N.useMemo(()=>l&&t?Vdn(l.signals,t,typeof window<"u"?window.location.origin:""):[],[l,t]),d=N.useMemo(()=>l&&t?Hdn(l.signals,t):null,[l,t]);return{item:l,dataset:t,timeline:o,valueShared:c,nextKit:d,isLoading:r,error:a,refetch:i}}function CSt(){const{user:s}=gs(),t=Gt();return gt({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:jSt,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 pDe(){const{user:s}=gs();return lt({queryKey:["attract-recommendations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Vc.from("attract_recommendations").select("*").order("rank_score",{ascending:!1});if(n)throw n;return t??[]}})}function fDe(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{if(!s)return{inserted:0,refreshed:0};const r=n.flatMap(u=>u.recommendations),{data:a,error:i}=await Vc.from("attract_recommendations").select("id, agent_id, rec_key, status, snoozed_until");if(i)throw i;const l=new Map((a??[]).map(u=>[`${u.agent_id}|${u.rec_key}`,u])),o=[],c=[],d=new Date;for(const u of r){const h=`${u.agent_id}|${u.rec_key}`,p=l.get(h),f={user_id:s.id,agent_id:u.agent_id,rec_key:u.rec_key,signal_group:u.signal_group,action_type:u.action_type,channel:u.channel,title:u.title,reasons:u.reasons,priority:u.priority,rank_score:u.rank_score,suggested_due_at:u.suggested_due_at,draft_message:u.draft_message,message_source:u.message_source,suggested_kit_id:u.suggested_kit_id??null,suggested_event_id:u.suggested_event_id??null,source_signals:u.source_signals};p?p.status==="open"?c.push({id:p.id,patch:{...f,generated_at:d.toISOString()}}):p.status==="snoozed"&&p.snoozed_until&&new Date(p.snoozed_until)<=d&&c.push({id:p.id,patch:{...f,status:"open",snoozed_until:null,generated_at:d.toISOString()}}):o.push(f)}if(o.length){const{error:u}=await Vc.from("attract_recommendations").insert(o);if(u)throw u}for(const u of c)await Vc.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 TSt(){const{user:s}=gs(),t=Gt(),n=()=>{t.invalidateQueries({queryKey:["attract-recommendations"]}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]})},r=gt({mutationFn:async({id:c,patch:d})=>{const{error:u}=await Vc.from("attract_recommendations").update(d).eq("id",c);if(u)throw u},onSuccess:n,onError:c=>ae.error(c.message)}),a=gt({mutationFn:async c=>{const{error:d}=await Vc.from("attract_recommendations").update({status:"dismissed",dismissed_at:new Date().toISOString()}).eq("id",c);if(d)throw d},onSuccess:()=>{n(),ae.success("Dismissed")}}),i=gt({mutationFn:async({id:c,days:d})=>{const u=new Date(Date.now()+d*864e5).toISOString(),{error:h}=await Vc.from("attract_recommendations").update({status:"snoozed",snoozed_until:u}).eq("id",c);if(h)throw h},onSuccess:()=>{n(),ae.success("Snoozed")}}),l=gt({mutationFn:async c=>{if(c.follow_up_id){const{data:h}=await Vc.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 Vc.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 Vc.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=gt({mutationFn:async({rec:c,note:d})=>{const u=new Date().toISOString(),{error:h}=await Vc.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 Vc.from("attract_follow_ups").update({completed_at:u}).eq("id",c.follow_up_id).is("completed_at",null),await Vc.from("attract_score_events").insert({user_id:s.id,agent_id:c.agent_id,category:"follow_up",points:2,description:`Completed: ${c.title}`});const{error:p}=await Vc.from("attract_recommendations").update({status:"completed",completed_at:u}).eq("id",c.id);if(p)throw p},onSuccess:()=>{n(),t.invalidateQueries({queryKey:["attract-score"]}),ae.success("Logged — timeline and score updated")},onError:c=>ae.error(c.message)});return{update:r,dismiss:a,snooze:i,createFollowUp:l,logCompleted:o}}function Kdn(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{const{error:r}=await Vc.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 Iet={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 xDe({score:s,className:t}){const n=Iet[s.band]??Iet.cooling;return e.jsxs(ze,{variant:"outline",className:Et("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 ESt({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(xDe,{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:Et("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(mo,{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(bb,{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(xb,{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 Pet({className:s}){const{intel:t}=p6(),[n,r]=N.useState(""),[a,i]=N.useState(!1),l=In(),o=N.useMemo(()=>{const c=n.trim().toLowerCase();return c?t.filter(d=>{const u=d.agent;return[u.first_name,u.last_name,u.brokerage,u.city,u.email,...u.tags??[]].filter(Boolean).join(" ").toLowerCase().includes(c)}).slice(0,6):[]},[t,n]);return e.jsxs("div",{className:Et("relative",s),children:[e.jsx(_r,{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(xDe,{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 Tke=[{to:"/attract",label:"Dashboard",icon:t4,exact:!0},{to:"/attract/opportunities",label:"Opportunities",icon:zA},{to:"/attract/pipeline",label:"Agent Pipeline",icon:_n},{to:"/attract/plan",label:"90-Day Plan",icon:wc},{section:"The Four Pillars"},{to:"/attract/produce",label:"Produce",icon:mo,tag:"Through Production"},{to:"/attract/influence",label:"Influence",icon:un,tag:"Through Influence"},{to:"/attract/influence/speaking",label:"Speaking Calendar",icon:Bv},{to:"/attract/provide",label:"Provide",icon:AA,tag:"Through Value"},{to:"/attract/provide/masterclasses",label:"Masterclasses",icon:_d},{to:"/attract/connect",label:"Connect",icon:mb,tag:"Through Events"},{to:"/attract/events",label:"Events",icon:mb},{section:"Systems"},{to:"/attract/landing-page",label:"Attraction Page",icon:tN},{to:"/attract/follow-up",label:"Follow-Up Center",icon:pu},{to:"/attract/digest",label:"Weekly Digest",icon:Hs},{to:"/attract/resources",label:"Resources",icon:Wg},{to:"/attract/templates",label:"Templates & Scripts",icon:_w},{to:"/attract/reports",label:"Reports",icon:yo},{to:"/attract/settings",label:"Settings",icon:Vo}];function Ydn(){const s=Jl(),{settings:t,isLoading:n}=JU(),r=!n&&!!t&&!t.onboarding_completed_at,a=s.pathname==="/attract/onboarding";if(r&&!a&&!s.pathname.startsWith("/attract/settings"))return e.jsx(f4,{to:"/attract/onboarding",replace:!0});const l=Tke.filter(o=>!("section"in o)).slice(0,5);return e.jsxs("div",{className:"attract-root min-h-screen bg-[#F7F7FB] text-slate-900",children:[e.jsx("style",{children:` .attract-root { --a-primary: 139 92 246; --a-primary-strong: 109 40 217; --a-indigo: 79 70 229; --a-teal: 20 184 166; --a-green: 22 163 74; --a-orange: 249 115 22; --a-rose: 244 63 94; } .attract-root .btn-primary { background: linear-gradient(135deg, rgb(var(--a-primary)) 0%, rgb(var(--a-indigo)) 100%); } `}),e.jsxs("div",{className:"flex min-h-screen",children:[e.jsxs("aside",{className:"hidden lg:flex w-72 flex-col bg-[#0B0F1E] text-slate-200 border-r border-white/5",children:[e.jsxs("div",{className:"px-6 py-6 border-b border-white/10",children:[e.jsxs(nF,{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(Wr,{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(tN,{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(Pet,{})}),e.jsx("nav",{className:"flex-1 overflow-y-auto py-3 px-3",children:Tke.map((o,c)=>{if("section"in o)return e.jsx("div",{className:"px-3 mt-5 mb-1.5 text-[10px] uppercase tracking-[0.14em] text-slate-500 font-semibold",children:o.section},c);const d=o.icon;return e.jsxs(nF,{to:o.to,end:o.exact,className:({isActive:u})=>Et("group flex items-center gap-3 px-3 py-2.5 rounded-xl text-[13.5px] font-medium transition-all",u?"bg-gradient-to-r from-violet-600/30 to-indigo-600/10 text-white ring-1 ring-inset ring-violet-500/40":"text-slate-300 hover:bg-white/5 hover:text-white"),children:[e.jsx(d,{className:"h-4 w-4 flex-shrink-0 opacity-80 group-hover:opacity-100"}),e.jsx("span",{className:"flex-1",children:o.label}),o.tag&&e.jsx("span",{className:"text-[9.5px] uppercase tracking-wider text-slate-500 group-hover:text-slate-400",children:o.tag})]},o.to)})}),e.jsx("div",{className:"px-4 py-4 border-t border-white/5",children:e.jsxs("div",{className:"rounded-xl bg-white/5 p-3",children:[e.jsx("div",{className:"text-[11px] font-medium text-violet-300",children:"Beta preview"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 mt-1 leading-snug",children:"Build relationships first. Personalize every message and verify brokerage and compensation info before sharing."})]})})]}),e.jsxs("div",{className:"lg:hidden fixed top-0 inset-x-0 z-40 bg-[#0B0F1E] text-white px-4 py-3 flex items-center gap-3 border-b border-white/10",children:[e.jsx(nF,{to:"/dashboard",className:"text-slate-400",children:e.jsx(Wr,{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(tN,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold tracking-tight",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Attract through value"})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur border-t border-white/10 flex",children:[l.map(o=>{const c=o.icon;return e.jsxs(nF,{to:o.to,end:o.exact,className:({isActive:d})=>Et("flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px]",d?"text-white":"text-slate-400"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"truncate max-w-[70px]",children:o.label})]},o.to)}),e.jsxs(ug,{children:[e.jsx(oU,{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(Xf,{className:"h-4 w-4"}),e.jsx("span",{children:"More"})]})}),e.jsx(ox,{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(Pet,{className:"mb-4"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"All sections"}),Tke.map((o,c)=>{if("section"in o)return e.jsx("div",{className:"mt-4 mb-1 text-[10px] uppercase tracking-widest text-slate-500 font-semibold",children:o.section},c);const d=o.icon;return e.jsxs(nF,{to:o.to,end:o.exact,className:({isActive:u})=>Et("flex items-center gap-3 rounded-xl px-3 py-3 text-[13.5px] font-medium",u?"bg-violet-600/30 text-white":"text-slate-300 hover:bg-white/5"),children:[e.jsx(d,{className:"h-4 w-4 opacity-80"}),e.jsx("span",{children:o.label})]},o.to)})]})})]})]}),e.jsx("main",{className:"flex-1 min-w-0 pt-16 lg:pt-0 pb-24 lg:pb-0",children:e.jsx("div",{className:"max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-10 py-6 lg:py-10",children:e.jsx(Bat,{})},s.pathname)})]})]})}function KF({label:s,value:t,delta:n,icon:r,tone:a="violet"}){const i={violet:"from-violet-500 to-indigo-600",teal:"from-teal-500 to-cyan-600",green:"from-emerald-500 to-green-600",orange:"from-orange-500 to-amber-600",rose:"from-rose-500 to-pink-600"};return e.jsx(fe,{className:"p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-slate-500",children:s}),e.jsx("div",{className:"mt-2 text-[26px] font-semibold tracking-tight text-slate-900",children:t}),n&&e.jsxs("div",{className:"mt-1 text-[11.5px] font-medium text-emerald-600 flex items-center gap-1",children:[e.jsx(JP,{className:"h-3 w-3"}),n]})]}),e.jsx("div",{className:Et("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 Zdn(){const{user:s}=gs();return lt({queryKey:["attract-score",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_score_events").select("category, points, description, created_at");if(n)throw n;const r=t??[],a=r.reduce((l,o)=>l+(o.points??0),0),i={};for(const l of r)i[l.category]=(i[l.category]??0)+l.points;return{total:Math.min(a,100),rows:r,byCategory:i}}})}const Qdn=[{key:"relationships_added",label:"Relationships Added",icon:W0,target:15},{key:"follow_ups_completed",label:"Follow-Ups Completed",icon:xr,target:15},{key:"resources_shared",label:"Resources Shared",icon:Hl,target:15},{key:"content_posted",label:"Agent Content Posted",icon:qd,target:15},{key:"events_connections",label:"Events / Connections",icon:mb,target:20},{key:"brokerage_conversations",label:"Brokerage Conversations",icon:pL,target:20}];function Xdn(){const{data:s}=Zdn(),t=(s==null?void 0:s.total)??0,n=(s==null?void 0:s.byCategory)??{},r=2*Math.PI*54,a=t/100*r;return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Your Attract Score"}),e.jsx("div",{className:"text-[19px] font-semibold text-slate-900 mt-1",children:"Great progress! Keep building relationships and providing value."})]}),e.jsx(mo,{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:Qdn.map(i=>{const l=n[i.key]??0,o=Math.min(100,Math.round(l/i.target*100)),c=i.icon;return e.jsxs("div",{className:"grid grid-cols-[16px_1fr_60px_auto] items-center gap-2.5",children:[e.jsx(c,{className:"h-4 w-4 text-slate-500"}),e.jsx("span",{className:"text-[12.5px] text-slate-700 truncate",children:i.label}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500",style:{width:`${o}%`}})}),e.jsx("span",{className:"text-[11px] tabular-nums text-slate-500 font-medium w-8 text-right",children:l})]},i.key)})})]}),e.jsx("div",{className:"mt-5 flex justify-end",children:e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",children:"View Score Breakdown"})})]})}const YF=q;function d0(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:["attract-agents",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("attract_agents").select("*").order("updated_at",{ascending:!1});if(u)throw u;return d??[]}}),r=()=>{["attract-agents","attract-intel","attract-intelligence","attract-agent-intel","attract-activities","attract-followups","attract-recommendations","attract-score","attract_milestones","attract-daily-plan"].forEach(d=>t.invalidateQueries({queryKey:[d]}))},a=gt({mutationFn:async d=>{const u={...d,user_id:s.id},{data:h,error:p}=d.id?await q.from("attract_agents").update(u).eq("id",d.id).select().single():await q.from("attract_agents").insert(u).select().single();if(p)throw p;return h},onSuccess:()=>{r(),ae.success("Saved")},onError:d=>ae.error(d.message)}),i=gt({mutationFn:async({id:d,to_stage:u,from_stage:h})=>{const{error:p}=await q.from("attract_agents").update({stage:u}).eq("id",d);if(p)throw p;await q.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:h??null,to_stage:u})},onSuccess:()=>r(),onError:d=>ae.error(d.message)}),l=gt({mutationFn:async({id:d,values:u,changedLabels:h,previousStage:p})=>{const{stage:f,...g}=u;if(Object.keys(g).length){const{error:b}=await YF.from("attract_agents").update(g).eq("id",d);if(b)throw b}if(f&&f!==p){const{error:b}=await YF.from("attract_agents").update({stage:f}).eq("id",d);if(b)throw b;await YF.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:p??null,to_stage:f})}h.length&&await YF.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=gt({mutationFn:async({id:d,archived:u})=>{const{error:h}=await YF.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=gt({mutationFn:async d=>{const{error:u}=await q.from("attract_agents").delete().eq("id",d);if(u)throw u},onSuccess:()=>{r(),ae.success("Contact permanently deleted")},onError:d=>ae.error(d.message)});return{agents:n.data??[],activeAgents:(n.data??[]).filter(d=>!d.is_archived),isLoading:n.isLoading,upsertAgent:a,saveAgentDetails:l,moveStage:i,archiveAgent:o,deleteAgent:c}}const Eke=[{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 Jdn(){const{agents:s}=d0(),t=Math.max(1,...Eke.map(n=>s.filter(r=>r.stage===n.key).length));return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Pipeline Overview"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Where relationships live right now"})]}),e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"rounded-full gap-1",children:e.jsxs(Ln,{to:"/attract/pipeline",children:["View Full Pipeline ",e.jsx(ga,{className:"h-3.5 w-3.5"})]})})]}),e.jsx("div",{className:"space-y-2",children:Eke.map((n,r)=>{const a=s.filter(o=>o.stage===n.key).length,i=30+a/t*70,l=.35+(1-r/Eke.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 eun(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:["attract-daily-plan",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q.from("attract_daily_plan").select("*").order("sort_order");if(i)throw i;return a??[]}}),r=gt({mutationFn:async a=>{const i=!a.completed,{error:l}=await q.from("attract_daily_plan").update({completed:i,progress:i?a.target:0}).eq("id",a.id);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["attract-daily-plan"]})});return{items:n.data??[],isLoading:n.isLoading,toggle:r}}function ASt(s=!0){const{intel:t,isLoading:n}=p6(),r=CSt(),a=fDe(),i=N.useRef(!1);return N.useEffect(()=>{if(!s||n||i.current||!t.length)return;const o=sessionStorage.getItem("attract-intel-sync"),c=new Date().toISOString().slice(0,13);if(o===c){i.current=!0;return}i.current=!0,sessionStorage.setItem("attract-intel-sync",c),r.mutate({items:t,silent:!0}),a.mutate(t)},[s,n,t]),{runNow:()=>{r.mutate({items:t}),a.mutate(t)},isSyncing:r.isPending||a.isPending}}function tun(){const{items:s,toggle:t}=eun(),{data:n=[]}=pDe(),{byId:r}=p6(),{logCompleted:a}=TSt();ASt();const i=s.filter(u=>u.completed).length,l=s.length?Math.round(i/s.length*100):0,o=Date.now(),c=n.filter(u=>u.status==="open"||u.status==="snoozed"&&u.snoozed_until&&+new Date(u.snoozed_until)<=o).sort((u,h)=>h.rank_score-u.rank_score).slice(0,3),d=u=>{var p;const h=(p=r.get(u))==null?void 0:p.agent;return h?[h.first_name,h.last_name].filter(Boolean).join(" "):"this relationship"};return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Today's Attraction Plan"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small daily reps compound."})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:[i,e.jsxs("span",{className:"text-slate-400 text-base",children:["/",s.length]})]}),e.jsx("div",{className:"text-[11px] text-slate-500 uppercase tracking-wider",children:"complete"})]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mb-4 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500 transition-all",style:{width:`${l}%`}})}),e.jsx("ul",{className:"space-y-1.5",children:s.map(u=>e.jsxs("li",{onClick:()=>t.mutate(u),className:"group flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx(hi,{checked:u.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:`flex-1 text-[13.5px] ${u.completed?"line-through text-slate-400":"text-slate-800"}`,children:u.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[u.progress,"/",u.target]}),u.completed&&e.jsx(xr,{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(Ln,{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(ze,{variant:"outline",className:Et("rounded-full text-[10.5px] capitalize",u.priority==="urgent"&&"bg-rose-50 text-rose-700 border-rose-200"),children:u.priority}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full h-7 px-2 text-[11.5px]",onClick:()=>a.mutate({rec:u}),disabled:a.isPending,children:"Done"})]})]})},u.id))}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No recommendations right now — Attract only surfaces conversations backed by a real signal."})]}),e.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"text-violet-700 hover:text-violet-900",asChild:!0,children:e.jsxs(Ln,{to:"/attract/opportunities",children:["All opportunities ",e.jsx(za,{className:"h-3.5 w-3.5 ml-1.5"})]})}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-violet-700 hover:text-violet-900",asChild:!0,children:e.jsx(Ln,{to:"/attract/plan",children:"View full plan"})})]})]})}function MSt(s=12){const{user:t}=gs(),n=lt({queryKey:["attract-activities",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(s);if(a)throw a;return r??[]}});return{activities:n.data??[],isLoading:n.isLoading}}const sun={agent_joined:un,resource_shared:Hl,presentation:oy,conversation:pL,social_engagement:yi,new_agent:Fo,content_posted:qd,follow_up:pu};function nun(){const{activities:s}=MSt(8);return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Recent Activity"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Momentum from the past few days"})]}),e.jsxs("ol",{className:"relative space-y-4",children:[s.map(t=>{const n=sun[t.activity_type]??un;return e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-violet-50 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx(n,{className:"h-4 w-4 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:t.title}),t.description&&e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:t.description}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-0.5",children:[Go(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 xbe(s){const{user:t}=gs();return lt({queryKey:["attract-events",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let n=q.from("attract_events").select("*").eq("is_template",!1).order("starts_at",{ascending:!0});const{data:r,error:a}=await n;if(a)throw a;return r??[]}})}function gDe(s){return lt({queryKey:["attract-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_events").select("*").eq("id",s).single();if(n)throw n;return t}})}function ISt(s){return lt({queryKey:["attract-event-attendees",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_attendees").select("*, attract_agents(id, first_name, last_name, primary_pillar, stage)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function run(s){return lt({queryKey:["attract-event-invitations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_invitations").select("*, attract_agents(id, first_name, last_name)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function aun(s){return lt({queryKey:["attract-event-notes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_notes").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function PSt(){return lt({queryKey:["attract-event-templates"],queryFn:async()=>{const{data:s,error:t}=await q.from("attract_event_templates").select("*").order("title");if(t)throw t;return s??[]}})}function LSt(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,title:n.title||"Untitled event",starts_at:n.starts_at||new Date(Date.now()+7*864e5).toISOString(),status:"draft",...n},{data:a,error:i}=await q.from("attract_events").insert(r).select().single();if(i)throw i;return a},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function DSt(){const s=Gt();return gt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await q.from("attract_events").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-events"]}),s.invalidateQueries({queryKey:["attract-event",t.id]})}})}function iun(){const s=Gt();return gt({mutationFn:async t=>{const{error:n}=await q.from("attract_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["attract-events"]})})}function RSt(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,...n},{data:a,error:i}=n.id?await q.from("attract_event_attendees").update(r).eq("id",n.id).select().single():await q.from("attract_event_attendees").insert(r).select().single();if(i)throw i;return a},onSuccess:n=>{t.invalidateQueries({queryKey:["attract-event-attendees",n.event_id]}),t.invalidateQueries({queryKey:["attract-event",n.event_id]})}})}function oun(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_event_notes").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-notes",n.event_id]})})}function lun(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_event_invitations").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-invitations",n.event_id]})})}function cun(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_events").select("*").eq("id",n).single();if(a)throw a;const{id:i,public_slug:l,check_in_token:o,published_at:c,registration_count:d,attendance_count:u,created_at:h,updated_at:p,...f}=r,{data:g,error:b}=await q.from("attract_events").insert({...f,title:r.title+" (Copy)",status:"draft"}).select().single();if(b)throw b;return g},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function gbe(s){return`${window.location.origin}/attract-event/${s}`}function dun(s,t){return`${window.location.origin}/attract-event-checkin/${s}?a=${encodeURIComponent(t)}`}function OSt(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 uun(){const{data:s=[]}=xbe(),t=s.slice(0,3);return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Upcoming Events"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Places where relationships happen"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full gap-1",children:[e.jsx(As,{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:ks(r,"MMM")}),e.jsx("div",{className:"text-xl font-semibold leading-tight",children:ks(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:ks(r,"p")}),"·",n.event_type==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vr,{className:"h-3 w-3"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(Ca,{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(mb,{className:"h-6 w-6 mx-auto text-slate-300 mb-2"}),e.jsx("div",{className:"text-sm",children:"No upcoming events yet."})]})]})]})}function FSt(){const{user:s}=gs(),t=lt({queryKey:["attract-resources",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_resources").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}}),n=lt({queryKey:["attract-resource-shares",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_resource_shares").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}});return{resources:t.data??[],shares:n.data??[],isLoading:t.isLoading}}function hun(){const{shares:s}=FSt(),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:Hl,tone:"text-violet-600 bg-violet-50"},{label:"Emails Sent",value:t.emails,icon:cr,tone:"text-teal-600 bg-teal-50"},{label:"Agent Opens",value:t.opens,icon:dL,tone:"text-emerald-600 bg-emerald-50"},{label:"Clicks",value:t.clicks,icon:oc,tone:"text-orange-600 bg-orange-50"}];return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Value Shared This Week"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small gifts, measured."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:n.map(r=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3.5",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${r.tone}`,children:e.jsx(r.icon,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900 mt-2 leading-none",children:r.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-1",children:r.label})]},r.label))})]})}function mun(){const{agents:s}=d0(),t=s.filter(r=>r.stage==="joined").sort((r,a)=>(a.joined_at??"").localeCompare(r.joined_at??"")),n=t.reduce((r,a)=>r+(Number(a.est_revenue_share)||0),0);return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Agents Joined"}),e.jsxs("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:["Est. annual rev share ",e.jsx("span",{className:"text-violet-700",children:gc(n)})]})]}),e.jsx(un,{className:"h-5 w-5 text-violet-500"})]}),e.jsxs("ul",{className:"space-y-2.5",children:[t.map(r=>{var a;return e.jsxs("li",{className:"flex items-center gap-3 p-2.5 rounded-xl hover:bg-slate-50",children:[e.jsxs("div",{className:"h-9 w-9 rounded-full bg-gradient-to-br from-violet-500 to-indigo-600 text-white grid place-items-center text-[13px] font-semibold flex-shrink-0",children:[r.first_name[0],((a=r.last_name)==null?void 0:a[0])??""]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 truncate",children:[r.brokerage," · ",r.city,", ",r.state]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[13px] font-semibold text-emerald-600 tabular-nums",children:r.est_revenue_share?gc(Number(r.est_revenue_share)):"—"}),e.jsx("div",{className:"text-[10.5px] text-slate-400",children:r.joined_at?Go(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 eq(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:["attract-followups",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q.from("attract_follow_ups").select("*").order("due_at",{ascending:!0,nullsFirst:!1});if(i)throw i;return a??[]}}),r=gt({mutationFn:async a=>{const{error:i}=await q.from("attract_follow_ups").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>t.invalidateQueries({queryKey:["attract-followups"]})});return{followUps:n.data??[],isLoading:n.isLoading,complete:r}}function pun(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 Let={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 fun(){const{user:s}=gs(),t=In(),{agents:n}=d0(),{followUps:r}=eq(),{settings:a}=JU();N.useState(!1);const i=N.useMemo(()=>{const d=Sf(new Date),u=n.filter(v=>!["joined","not_a_fit","not_right_now"].includes(v.stage)).length,h=n.filter(v=>new Date(v.created_at)>Ul(d,-30)).length,p=r.filter(v=>!v.completed_at&&v.due_at&&Rl(new Date(v.due_at),d)).length,f=r.filter(v=>!v.completed_at&&v.due_at&&jb(new Date(v.due_at),d)).length,b=n.filter(v=>v.stage==="joined").reduce((v,j)=>v+(Number(j.est_revenue_share)||0),0);return{inPipeline:u,newRels:h,dueToday:p,overdue:f,revShare:b}},[n,r]),l=(a==null?void 0:a.primary_pillar)||(a==null?void 0:a.attraction_style)||"balanced",o=Let[l]??Let.balanced,c=a==null?void 0:a.ninety_day_plan;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-8",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"LevelUp Attract"}),e.jsxs("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:["Good to see you, ",pun(s),"."]}),e.jsxs("p",{className:"text-slate-600 mt-1.5",children:["Here's your attraction overview for today · ",ks(new Date,"EEEE, MMM d")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(us,{defaultValue:"week",children:[e.jsx(cs,{className:"w-[150px] rounded-full bg-white",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"week",children:"This Week"}),e.jsx(Ze,{value:"month",children:"This Month"}),e.jsx(Ze,{value:"90",children:"Last 90 Days"})]})]}),e.jsx(B,{variant:"outline",size:"icon",className:"rounded-full",children:e.jsx(lm,{className:"h-4 w-4"})}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700 gap-1.5 shadow-sm",children:[e.jsx(As,{className:"h-4 w-4"})," Add New ",e.jsx(io,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(cc,{align:"end",className:"w-64",children:[e.jsx(I4,{children:"Quick add"}),e.jsx(Qg,{}),e.jsxs(Xr,{onClick:()=>t("/attract/pipeline?new=1"),children:[e.jsx(Fo,{className:"h-4 w-4 mr-2"})," Add Agent to Pipeline"]}),e.jsxs(Xr,{onClick:()=>t("/attract/produce/transaction-tracker"),children:[e.jsx(ua,{className:"h-4 w-4 mr-2"})," Log a Transaction"]}),e.jsxs(Xr,{onClick:()=>t("/attract/influence/content-studio"),children:[e.jsx(Rm,{className:"h-4 w-4 mr-2"})," Create Authority Content"]}),e.jsxs(Xr,{onClick:()=>t("/attract/follow-up"),children:[e.jsx(pu,{className:"h-4 w-4 mr-2"})," Add Follow-Up"]}),e.jsxs(Xr,{onClick:()=>t("/attract/events/new"),children:[e.jsx(Fg,{className:"h-4 w-4 mr-2"})," Plan an Event"]}),e.jsxs(Xr,{onClick:()=>t("/attract/resources"),children:[e.jsx(Wg,{className:"h-4 w-4 mr-2"})," Add Resource"]})]})]})]})]}),e.jsx(fe,{className:"p-4 rounded-2xl mb-6 bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-white grid place-items-center text-violet-700 shadow-sm",children:e.jsx(wc,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:"Today's move"}),e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:o.label}),c&&e.jsxs("div",{className:"text-[12px] text-slate-600 mt-0.5",children:["Weekly goal: ",c.weekly_targets.new_relationships," new relationships · ",c.weekly_targets.content_pieces," content pieces"]})]}),e.jsx(B,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>t(o.to),children:o.cta})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-4 mb-6",children:[e.jsx(KF,{label:"Agents in Pipeline",value:i.inPipeline,delta:"+3 this week",icon:W0,tone:"violet"}),e.jsx(KF,{label:"New Relationships",value:i.newRels,delta:"+2 this week",icon:mo,tone:"teal"}),e.jsx(KF,{label:"Follow-Ups Due Today",value:i.dueToday,icon:e9,tone:"orange"}),e.jsx(KF,{label:"Overdue Follow-Ups",value:i.overdue,icon:Dl,tone:"rose"}),e.jsx(KF,{label:"Est. Revenue Share",value:gc(i.revShare,!0),delta:"annualized",icon:Zl,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(Xdn,{}),e.jsx(Jdn,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(nun,{}),e.jsx(uun,{})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(tun,{}),e.jsx(hun,{}),e.jsx(mun,{})]})]}),e.jsx("div",{className:"mt-8 rounded-2xl overflow-hidden bg-gradient-to-r from-violet-600 via-indigo-600 to-violet-700 p-6 md:p-7 text-white shadow-lg",children:e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] opacity-80 mb-1",children:"Your 90-day promise"}),e.jsx("div",{className:"text-lg md:text-xl font-semibold",children:(c==null?void 0:c.outcome)??"Show up for agents the way you'd want someone to show up for you."}),e.jsx("div",{className:"text-white/80 mt-1 text-[13.5px]",children:"Small daily reps compound. Keep the rhythm."})]}),e.jsx(B,{asChild:!0,variant:"secondary",className:"rounded-full bg-white text-violet-700 hover:bg-white/90",children:e.jsx(Ln,{to:"/attract/plan",children:"View 90-Day Plan"})})]})})]})}function Ku({eyebrow:s,title:t,description:n,actions:r,className:a}){return e.jsxs("div",{className:Et("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 f6(){return e.jsxs("div",{className:"rounded-2xl border border-violet-200 bg-violet-50/60 px-5 py-3.5 text-[13px] text-violet-900 flex items-start gap-3",children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-violet-600 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-white text-[11px] font-bold",children:"✓"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Build relationships first."})," ","Personalize every message and verify brokerage and compensation information before sharing."]})]})}const xun=["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"],gun={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"},gp=s=>typeof s=="string"&&s.trim()===""?null:s,QI=s=>{const t=s.trim();return t?/^https?:\/\//i.test(t)?t:`https://${t}`:null},yun=s=>{const t=s.trim();if(!t)return null;const n=t.replace(/[^\d]/g,"");return n.length===10?`(${n.slice(0,3)}) ${n.slice(3,6)}-${n.slice(6)}`:t},ZF=s=>(s??"").replace(/[^\d]/g,""),vun=s=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()),eW=s=>s?String(s).slice(0,10):"";function Det(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:eW(s.birthday_on),work_anniversary_on:eW(s.work_anniversary_on),license_anniversary_on:eW(s.license_anniversary_on),next_follow_up_at:eW(s.next_follow_up_at)}}function XI({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 nu({label:s,value:t,onChange:n,className:r,...a}){return e.jsxs("div",{className:r,children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:s}),e.jsx(ge,{className:"mt-1",value:t,onChange:i=>n(i.target.value),...a})]})}function zSt({agent:s,open:t,onOpenChange:n,onDeleted:r}){const{agents:a,saveAgentDetails:i,archiveAgent:l,deleteAgent:o}=d0(),[c,d]=N.useState({}),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,b]=N.useState(!1);N.useEffect(()=>{s&&t&&(d(Det(s)),b(!1))},[s==null?void 0:s.id,t]);const v=N.useMemo(()=>s?Det(s):{},[s]),j=N.useMemo(()=>Object.keys(c).filter(M=>String(c[M]??"")!==String(v[M]??"")),[c,v]),_=j.length>0,S=(M,F)=>d(z=>({...z,[M]:F}));if(!s)return null;const A=M=>{if(!M&&_){h(!0);return}n(M)},T=()=>{var V;const M=(V=c.email)==null?void 0:V.trim().toLowerCase(),F=ZF(c.phone),z=`${c.first_name} ${c.last_name}`.trim().toLowerCase();return a.filter(W=>{var K;return W.id===s.id||W.is_archived?!1:!!(M&&((K=W.email)==null?void 0:K.toLowerCase())===M||F.length>=10&&ZF(W.phone)===F||z&&`${W.first_name} ${W.last_name??""}`.trim().toLowerCase()===z)})},D=()=>{var W,K,Y;if(!((W=c.first_name)!=null&&W.trim())){ae.error("First name is required");return}if((K=c.email)!=null&&K.trim()&&!vun(c.email)){ae.error("That email address looks incomplete");return}const M=T(),F=M.some(ee=>{var ne,oe;return((ne=c.email)==null?void 0:ne.trim())&&((oe=ee.email)==null?void 0:oe.toLowerCase())===c.email.trim().toLowerCase()||ZF(c.phone).length>=10&&ZF(ee.phone)===ZF(c.phone)});if(M.length&&!g){b(!0),ae.warning(F?`${M[0].first_name} ${M[0].last_name??""} already uses this email or phone. Save again to confirm.`:"A contact named the same already exists. Save again to confirm.");return}const z={first_name:c.first_name.trim(),last_name:gp(c.last_name),preferred_name:gp(c.preferred_name),email:(Y=c.email)!=null&&Y.trim()?c.email.trim().toLowerCase():null,phone:yun(c.phone??""),website_url:QI(c.website_url??""),instagram_url:QI(c.instagram_url??""),linkedin_url:QI(c.linkedin_url??""),facebook_url:QI(c.facebook_url??""),other_url:QI(c.other_url??""),photo_url:QI(c.photo_url??""),brokerage:gp(c.brokerage),team_name:gp(c.team_name),city:gp(c.city),state:gp(c.state),postal_code:gp(c.postal_code),market_area:gp(c.market_area),source:gp(c.source),relationship_owner:gp(c.relationship_owner),temperature:c.temperature,primary_pillar:c.primary_pillar==="none"?null:c.primary_pillar,tags:String(c.tags??"").split(",").map(ee=>ee.trim()).filter(Boolean),goals:gp(c.goals),challenges:gp(c.challenges),interests:gp(c.interests),production_context:gp(c.production_context),notes:gp(c.notes),birthday_on:gp(c.birthday_on),work_anniversary_on:gp(c.work_anniversary_on),license_anniversary_on:gp(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},V={};if(j.forEach(ee=>{ee in z&&(V[ee]=z[ee])}),!Object.keys(V).length){n(!1);return}i.mutate({id:s.id,values:V,changedLabels:j.map(ee=>gun[ee]??ee),previousStage:s.stage},{onSuccess:()=>n(!1)})},L=T();return e.jsxs(e.Fragment,{children:[e.jsx(ug,{open:t,onOpenChange:A,children:e.jsxs(ox,{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(r0,{className:"space-y-1 text-left",children:[e.jsxs(a0,{className:"text-white text-lg",children:["Edit ",[s.first_name,s.last_name].filter(Boolean).join(" ")]}),e.jsx(lU,{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:[!!L.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(Dl,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Possible duplicate: ",L.slice(0,3).map(M=>`${M.first_name} ${M.last_name??""}`.trim()).join(", "),". You can still save — just double-check first."]})]}),e.jsxs(XI,{title:"Basic info",children:[e.jsx(nu,{label:"First name *",value:c.first_name,onChange:M=>S("first_name",M)}),e.jsx(nu,{label:"Last name",value:c.last_name,onChange:M=>S("last_name",M)}),e.jsx(nu,{label:"Preferred name",value:c.preferred_name,onChange:M=>S("preferred_name",M),placeholder:"What they go by"}),e.jsx(nu,{label:"Photo / headshot URL",value:c.photo_url,onChange:M=>S("photo_url",M),placeholder:"https://…"})]}),e.jsxs(XI,{title:"Contact & social",children:[e.jsx(nu,{label:"Email",type:"email",value:c.email,onChange:M=>S("email",M)}),e.jsx(nu,{label:"Phone",value:c.phone,onChange:M=>S("phone",M)}),e.jsx(nu,{label:"Website",value:c.website_url,onChange:M=>S("website_url",M)}),e.jsx(nu,{label:"Instagram",value:c.instagram_url,onChange:M=>S("instagram_url",M)}),e.jsx(nu,{label:"LinkedIn",value:c.linkedin_url,onChange:M=>S("linkedin_url",M)}),e.jsx(nu,{label:"Facebook",value:c.facebook_url,onChange:M=>S("facebook_url",M)}),e.jsx(nu,{label:"Other link",value:c.other_url,onChange:M=>S("other_url",M),className:"sm:col-span-2"})]}),e.jsxs(XI,{title:"Brokerage & market",children:[e.jsx(nu,{label:"Brokerage",value:c.brokerage,onChange:M=>S("brokerage",M)}),e.jsx(nu,{label:"Team",value:c.team_name,onChange:M=>S("team_name",M)}),e.jsx(nu,{label:"City",value:c.city,onChange:M=>S("city",M)}),e.jsx(nu,{label:"State",value:c.state,onChange:M=>S("state",M)}),e.jsx(nu,{label:"ZIP / postal code",value:c.postal_code,onChange:M=>S("postal_code",M)}),e.jsx(nu,{label:"Market / service area",value:c.market_area,onChange:M=>S("market_area",M)})]}),e.jsxs(XI,{title:"Relationship intelligence",hint:"These drive scoring, recommendations, filters and reports.",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Pipeline stage"}),e.jsxs(us,{value:c.stage,onValueChange:M=>S("stage",M),children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(ds,{children:xun.map(M=>e.jsx(Ze,{value:M,className:"capitalize",children:M.replace(/_/g," ")},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Temperature"}),e.jsxs(us,{value:c.temperature,onValueChange:M=>S("temperature",M),children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(ds,{children:["cold","warm","hot"].map(M=>e.jsx(Ze,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Primary pillar"}),e.jsxs(us,{value:c.primary_pillar,onValueChange:M=>S("primary_pillar",M),children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"Not set"}),["produce","influence","provide","connect"].map(M=>e.jsx(Ze,{value:M,className:"capitalize",children:M},M))]})]})]}),e.jsx(nu,{label:"Source",value:c.source,onChange:M=>S("source",M),placeholder:"Event, referral, social…"}),e.jsx(nu,{label:"Relationship owner",value:c.relationship_owner,onChange:M=>S("relationship_owner",M),placeholder:"You, or a teammate"}),e.jsx(nu,{label:"Tags (comma separated)",value:c.tags,onChange:M=>S("tags",M),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(M=>M.trim()).filter(Boolean).map(M=>e.jsx(ze,{variant:"outline",className:"rounded-full text-[11px]",children:M},M))})]}),e.jsxs(XI,{title:"Important dates",hint:"Birthdays and anniversaries feed Milestones & Celebrations automatically — no duplicate entry needed.",children:[e.jsx(nu,{label:"Birthday",type:"date",value:c.birthday_on,onChange:M=>S("birthday_on",M)}),e.jsx(nu,{label:"Work anniversary",type:"date",value:c.work_anniversary_on,onChange:M=>S("work_anniversary_on",M)}),e.jsx(nu,{label:"License anniversary",type:"date",value:c.license_anniversary_on,onChange:M=>S("license_anniversary_on",M)}),e.jsx(nu,{label:"Next follow-up",type:"date",value:c.next_follow_up_at,onChange:M=>S("next_follow_up_at",M)})]}),e.jsxs(XI,{title:"Notes",children:[e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Goals"}),e.jsx(Ts,{className:"mt-1",rows:2,value:c.goals,onChange:M=>S("goals",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Challenges"}),e.jsx(Ts,{className:"mt-1",rows:2,value:c.challenges,onChange:M=>S("challenges",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Interests"}),e.jsx(Ts,{className:"mt-1",rows:2,value:c.interests,onChange:M=>S("interests",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Production context"}),e.jsx(Ts,{className:"mt-1",rows:2,value:c.production_context,onChange:M=>S("production_context",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Personal notes"}),e.jsx(Ts,{className:"mt-1",rows:4,value:c.notes,onChange:M=>S("notes",M.target.value)})]})]}),e.jsxs("section",{className:"rounded-xl ring-1 ring-rose-200 bg-rose-50/60 p-4 space-y-3",children:[e.jsx("h3",{className:"text-[11px] uppercase tracking-wider font-semibold text-rose-700",children:"Danger zone"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>l.mutate({id:s.id,archived:!s.is_archived},{onSuccess:()=>n(!1)}),children:[e.jsx(im,{className:"h-3.5 w-3.5 mr-1.5"}),s.is_archived?"Restore to pipeline":"Remove from pipeline (archive)"]}),e.jsxs(B,{variant:"destructive",size:"sm",className:"rounded-full",onClick:()=>f(!0),children:[e.jsx(bn,{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…":_?`${j.length} unsaved change${j.length>1?"s":""}`:"All changes saved"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"ghost",className:"rounded-full",onClick:()=>A(!1),children:[e.jsx(Fn,{className:"h-4 w-4 mr-1"})," Cancel"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",disabled:!_||i.isPending,onClick:D,children:[i.isPending&&e.jsx(ss,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save changes"]})]})]})]})}),e.jsx(Oo,{open:u,onOpenChange:h,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Discard unsaved changes?"}),e.jsxs(Mo,{children:["You have ",j.length," unsaved change(s) on this contact."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep editing"}),e.jsx(jo,{onClick:()=>{h(!1),n(!1)},children:"Discard"})]})]})}),e.jsx(Oo,{open:p,onOpenChange:f,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this contact permanently?"}),e.jsx(Mo,{children:"This removes their timeline, follow-ups, pipeline history, scores and recommendations. Event, kit and transaction records will stay but will no longer be linked to anyone. This cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{className:"bg-rose-600 hover:bg-rose-700",onClick:()=>o.mutate(s.id,{onSuccess:()=>{f(!1),n(!1),r==null||r()}}),children:"Delete forever"})]})]})})]})}const tW=[{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"}],Ret={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 bun(){const s=In(),{agents:t,isLoading:n,upsertAgent:r,moveStage:a,archiveAgent:i,deleteAgent:l}=d0(),[o,c]=N.useState("kanban"),[d,u]=N.useState(""),[h,p]=N.useState(!1),[f,g]=N.useState(!1),[b,v]=N.useState(),[j,_]=N.useState(null),[S,A]=N.useState(null),[T,D]=N.useState(null),[L,M]=N.useState(null),{gmailEmail:F}=bh(),z=t.filter(K=>!!K.is_archived!==h?!1:d?`${K.first_name} ${K.last_name??""} ${K.brokerage??""} ${K.city??""} ${(K.tags??[]).join(" ")} ${K.email??""}`.toLowerCase().includes(d.toLowerCase()):!0),V=j?t.find(K=>K.id===j.id)??j:null,W=({agent:K})=>e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 -mr-1",onClick:Y=>Y.stopPropagation(),"aria-label":"Agent actions",children:e.jsx(Lg,{className:"h-3.5 w-3.5"})})}),e.jsxs(cc,{align:"end",onClick:Y=>Y.stopPropagation(),children:[e.jsxs(Xr,{onClick:()=>A(K),children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-2"})," Edit contact"]}),e.jsxs(Xr,{onClick:()=>s(`/attract/agents/${K.id}`),children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-2"})," Open relationship"]}),e.jsx(Qg,{}),e.jsxs(Xr,{onClick:()=>i.mutate({id:K.id,archived:!K.is_archived}),children:[e.jsx(im,{className:"h-3.5 w-3.5 mr-2"})," ",K.is_archived?"Restore to pipeline":"Remove from pipeline"]})]})]});return e.jsxs("div",{children:[e.jsx(Ku,{eyebrow:"Agent Pipeline",title:"Where relationships live",description:"Move agents through relationship-first stages. Never a target — always a real conversation.",actions:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex bg-white border rounded-full p-0.5",children:[e.jsxs(B,{size:"sm",variant:o==="kanban"?"default":"ghost",className:"rounded-full h-8 px-3",onClick:()=>c("kanban"),children:[e.jsx(vf,{className:"h-3.5 w-3.5 mr-1"})," Board"]}),e.jsxs(B,{size:"sm",variant:o==="list"?"default":"ghost",className:"rounded-full h-8 px-3",onClick:()=>c("list"),children:[e.jsx(Ep,{className:"h-3.5 w-3.5 mr-1"})," List"]})]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:opacity-95",onClick:()=>{v(void 0),g(!0)},children:[e.jsx(As,{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(_r,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(ge,{value:d,onChange:K=>u(K.target.value),placeholder:"Search name, brokerage, city, tag, email…",className:"pl-9 rounded-full bg-white"})]}),e.jsxs(B,{variant:h?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>p(K=>!K),children:[e.jsx(im,{className:"h-3.5 w-3.5 mr-1.5"})," ",h?"Viewing archived":"Archived"]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[z.length," agents"]})]}),e.jsx("div",{className:"mb-4",children:e.jsx(f6,{})}),n?e.jsx("div",{className:"py-24 text-center text-slate-500",children:"Loading pipeline…"}):o==="kanban"?e.jsxs(mi,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:tW.length*300},children:tW.map(K=>{const Y=z.filter(ee=>ee.stage===K.key);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:ee=>{ee.preventDefault(),ee.dataTransfer.dropEffect="move"},onDrop:ee=>{if(ee.preventDefault(),T){const ne=t.find(oe=>oe.id===T);ne&&ne.stage!==K.key&&a.mutate({id:T,to_stage:K.key,from_stage:ne.stage}),D(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:K.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:K.label}),e.jsx(ze,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:Y.length})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{v(K.key),g(!0)},children:e.jsx(As,{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:[Y.map(ee=>e.jsxs("div",{draggable:!0,onDragStart:()=>D(ee.id),onClick:()=>_(ee),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:K.color},children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[ee.first_name," ",ee.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 flex items-center gap-1 mt-0.5 truncate",children:[e.jsx(Ga,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:ee.brokerage??"—"})]})]}),ee.temperature&&e.jsxs(ze,{variant:"outline",className:`text-[9.5px] px-1.5 py-0 ${Ret[ee.temperature]}`,children:[e.jsx(D9,{className:"h-2.5 w-2.5 mr-0.5"}),ee.temperature]}),e.jsx(W,{agent:ee})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-[11px] text-slate-500",children:[e.jsx(Ca,{className:"h-3 w-3"}),e.jsxs("span",{className:"truncate",children:[ee.city,ee.state&&`, ${ee.state}`]})]}),ee.next_follow_up_at&&e.jsxs("div",{className:"mt-1.5 text-[10.5px] text-violet-700 font-medium",children:["Next touch · ",ks(new Date(ee.next_follow_up_at),"MMM d")]})]},ee.id)),Y.length===0&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drop an agent here"})]})]},K.key)})}),e.jsx(cU,{orientation:"horizontal"})]}):e.jsx(fe,{className:"rounded-2xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-[11px] uppercase tracking-wider text-slate-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-3",children:"Agent"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Brokerage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Location"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Stage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Temp"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Next Follow-Up"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Actions"})]})}),e.jsxs("tbody",{children:[z.map(K=>{const Y=tW.find(ee=>ee.key===K.stage);return e.jsxs("tr",{onClick:()=>_(K),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:[K.first_name," ",K.last_name]}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:K.brokerage}),e.jsxs("td",{className:"px-4 py-3 text-slate-600",children:[K.city,", ",K.state]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ze,{style:{background:Y==null?void 0:Y.color,color:"white"},children:Y==null?void 0:Y.label})}),e.jsx("td",{className:"px-4 py-3",children:K.temperature&&e.jsx(ze,{variant:"outline",className:Ret[K.temperature],children:K.temperature})}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:K.next_follow_up_at?ks(new Date(K.next_follow_up_at),"MMM d"):"—"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(W,{agent:K})})]},K.id)}),z.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-10 text-center text-slate-500",children:"No agents match this view."})})]})]})}),e.jsx(_un,{open:f,onOpenChange:g,defaultStage:b,onSubmit:K=>r.mutate(K,{onSuccess:()=>g(!1)})}),e.jsx(zSt,{agent:S?t.find(K=>K.id===S.id)??S:null,open:!!S,onOpenChange:K=>!K&&A(null),onDeleted:()=>_(null)}),e.jsx(ug,{open:!!j,onOpenChange:K=>!K&&_(null),children:e.jsx(ox,{className:"w-full sm:max-w-lg overflow-y-auto",children:V&&e.jsxs(e.Fragment,{children:[e.jsxs(r0,{children:[e.jsxs(a0,{className:"text-xl",children:[V.first_name," ",V.last_name]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 flex items-center gap-2",children:[e.jsx(Ga,{className:"h-3.5 w-3.5"})," ",V.brokerage??"—"," · ",V.city,", ",V.state]})]}),e.jsxs("div",{className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"gap-1.5 bg-gradient-to-r from-violet-600 to-indigo-600 text-white",onClick:()=>A(V),children:[e.jsx(ja,{className:"h-3.5 w-3.5"})," Edit contact"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${V.id}`),children:[e.jsx(tr,{className:"h-3.5 w-3.5"})," Open relationship"]}),V.email&&e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>M(V),children:[e.jsx(Hs,{className:"h-3.5 w-3.5"})," Email"]}),V.phone&&e.jsx(B,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,children:e.jsxs("a",{href:`tel:${V.phone}`,children:[e.jsx(Pr,{className:"h-3.5 w-3.5"})," Call"]})}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${V.id}`),children:[e.jsx(Ci,{className:"h-3.5 w-3.5"})," Log touch"]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Stage"}),e.jsxs(us,{value:V.stage,onValueChange:K=>a.mutate({id:V.id,to_stage:K,from_stage:V.stage}),children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(ds,{children:tW.map(K=>e.jsx(Ze,{value:K.key,children:K.label},K.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Temperature"}),e.jsxs(us,{value:V.temperature??"warm",onValueChange:K=>r.mutate({id:V.id,first_name:V.first_name,temperature:K}),children:[e.jsx(cs,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(ds,{children:["cold","warm","hot"].map(K=>e.jsx(Ze,{value:K,className:"capitalize",children:K},K))})]})]}),!!(V.tags??[]).length&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:(V.tags??[]).map(K=>e.jsx(ze,{variant:"outline",className:"rounded-full",children:K},K))}),e.jsx(Ake,{label:"Notes",value:V.notes}),e.jsx(Ake,{label:"Goals",value:V.goals}),e.jsx(Ake,{label:"Challenges",value:V.challenges}),e.jsxs("div",{className:"pt-4 border-t flex justify-between",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>i.mutate({id:V.id,archived:!V.is_archived}),children:[e.jsx(im,{className:"h-4 w-4 mr-1"})," ",V.is_archived?"Restore":"Remove from pipeline"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-rose-600",onClick:()=>A(V),children:[e.jsx(bn,{className:"h-4 w-4 mr-1"})," Delete…"]})]})]})]})})}),(L==null?void 0:L.email)&&e.jsx(Ty,{open:!!L,onOpenChange:K=>!K&&M(null),contact:{id:L.id,first_name:L.preferred_name||L.first_name,last_name:L.last_name||"",email:L.email},gmailEmail:F,sendSource:"attract",logTouchpoint:!1})]})}function Ake({label:s,value:t}){return e.jsxs("div",{children:[e.jsx(se,{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 _un({open:s,onOpenChange:t,defaultStage:n,onSubmit:r}){const[a,i]=N.useState({first_name:"",last_name:"",brokerage:"",city:"",state:"",temperature:"warm",primary_pillar:"connect",stage:n??"new_connection",notes:""});return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{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(se,{children:"First name *"}),e.jsx(ge,{value:a.first_name,onChange:l=>i({...a,first_name:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last name"}),e.jsx(ge,{value:a.last_name,onChange:l=>i({...a,last_name:l.target.value})})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Current brokerage"}),e.jsx(ge,{value:a.brokerage,onChange:l=>i({...a,brokerage:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"City"}),e.jsx(ge,{value:a.city,onChange:l=>i({...a,city:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(ge,{value:a.state,onChange:l=>i({...a,state:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Temperature"}),e.jsxs(us,{value:a.temperature,onValueChange:l=>i({...a,temperature:l}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"cold",children:"Cold"}),e.jsx(Ze,{value:"warm",children:"Warm"}),e.jsx(Ze,{value:"hot",children:"Hot"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Primary pillar"}),e.jsxs(us,{value:a.primary_pillar,onValueChange:l=>i({...a,primary_pillar:l}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"produce",children:"Produce"}),e.jsx(Ze,{value:"influence",children:"Influence"}),e.jsx(Ze,{value:"provide",children:"Provide"}),e.jsx(Ze,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Notes"}),e.jsx(Ts,{rows:3,value:a.notes,onChange:l=>i({...a,notes:l.target.value})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{disabled:!a.first_name,className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>r(a),children:"Add Agent"})]})]})})}const wun={call:Pr,email:Hs,coffee:ry,gift:Bi,text:Hs,event:cm};function jun(){const{followUps:s,complete:t}=eq(),{agents:n}=d0(),r=N.useMemo(()=>{const l=Sf(new Date),o=[],c=[],d=[],u=[],h=[];for(const p of s){if(p.completed_at){h.push(p);continue}if(!p.due_at){u.push(p);continue}const f=new Date(p.due_at);jb(f,l)?o.push(p):df(f)?c.push(p):KUt(f)?d.push(p):u.push(p)}return{overdue:o,today:c,tomorrow:d,later:u,done:h}},[s]),a=new Map(n.map(l=>[l.id,l])),i=[{label:"Overdue",value:r.overdue.length,tone:"text-rose-600 bg-rose-50",icon:Gi},{label:"Due Today",value:r.today.length,tone:"text-orange-600 bg-orange-50",icon:gr},{label:"Completed This Week",value:r.done.filter(l=>l.completed_at&&new Date(l.completed_at)>Ul(new Date,-7)).length,tone:"text-emerald-600 bg-emerald-50",icon:xr}];return e.jsxs("div",{children:[e.jsx(Ku,{eyebrow:"Follow-Up Center",title:"One list. One rhythm. One relationship at a time.",description:"Everything you promised to do — organized so it never feels like a to-do list."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:i.map(l=>e.jsxs(fe,{className:"p-5 rounded-2xl flex items-center gap-4",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900",children:l.value}),e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:l.label})]})]},l.label))}),e.jsx("div",{className:"mb-6",children:e.jsx(f6,{})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(QF,{title:"Overdue",items:r.overdue,agentMap:a,onComplete:l=>t.mutate(l),tone:"rose"}),e.jsx(QF,{title:"Today",items:r.today,agentMap:a,onComplete:l=>t.mutate(l),tone:"orange"}),e.jsx(QF,{title:"Tomorrow",items:r.tomorrow,agentMap:a,onComplete:l=>t.mutate(l),tone:"violet"}),e.jsx(QF,{title:"Later This Week",items:r.later,agentMap:a,onComplete:l=>t.mutate(l),tone:"slate"}),r.done.length>0&&e.jsx(QF,{title:"Recently Completed",items:r.done.slice(0,5),agentMap:a,onComplete:()=>{},tone:"emerald",done:!0})]})]})}function QF({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(ze,{variant:"secondary",className:"text-[10px]",children:t.length})]}),e.jsx(fe,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:t.map(o=>{const c=n.get(o.agent_id),d=wun[o.touch_type??""]??Hs;return e.jsxs("div",{className:`flex items-start gap-3 p-4 hover:bg-slate-50 ${i?"opacity-60":""}`,children:[e.jsx(hi,{checked:!!o.completed_at,onCheckedChange:()=>r(o.id),className:"mt-1"}),e.jsx("div",{className:"h-8 w-8 rounded-lg grid place-items-center flex-shrink-0",style:{background:`${l[a]}18`,color:l[a]},children:e.jsx(d,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:o.title}),c&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["for ",c.first_name," ",c.last_name," · ",c.brokerage]}),o.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1",children:o.notes})]}),o.due_at&&e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:ks(new Date(o.due_at),"MMM d")}),e.jsx(B,{variant:"ghost",size:"sm",children:"Snooze"})]},o.id)})})]})}const Nun={pdf:Nr,link:El,video:vr,tool:wb,guide:$u},kun={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 Sun(){const{resources:s,isLoading:t}=FSt(),[n,r]=N.useState(""),[a,i]=N.useState("all"),l=Array.from(new Set(s.map(c=>c.category).filter(Boolean))),o=s.filter(c=>(a==="all"||c.category===a)&&(!n||`${c.title} ${c.description??""}`.toLowerCase().includes(n.toLowerCase())));return e.jsxs("div",{children:[e.jsx(Ku,{eyebrow:"Resource Library",title:"The stack you share with future teammates.",description:"Every resource, script, and tool you use — ready to share in one click.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(As,{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(_r,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(ge,{value:n,onChange:c=>r(c.target.value),placeholder:"Search resources…",className:"pl-9 rounded-full bg-white"})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsx(B,{size:"sm",variant:a==="all"?"default":"outline",className:"rounded-full h-8",onClick:()=>i("all"),children:"All"}),l.map(c=>e.jsx(B,{size:"sm",variant:a===c?"default":"outline",className:"rounded-full h-8 capitalize",onClick:()=>i(c),children:c},c))]})]}),t?e.jsx("div",{className:"py-24 text-center text-slate-500",children:"Loading resources…"}):o.length===0?e.jsx(fe,{className:"p-12 text-center rounded-2xl",children:e.jsx("div",{className:"text-slate-500",children:"No resources yet. Add your first shareable asset above."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:o.map(c=>{const d=Nun[c.resource_type]??Nr;return e.jsxs(fe,{className:"p-5 rounded-2xl hover:shadow-md transition-all group",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 grid place-items-center text-violet-600",children:e.jsx(d,{className:"h-5 w-5"})}),c.category&&e.jsx(ze,{className:`${kun[c.category]??"bg-slate-100 text-slate-700"} border-0 capitalize`,children:c.category})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"font-semibold text-slate-900",children:c.title}),c.description&&e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 line-clamp-2",children:c.description})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-slate-100 flex items-center justify-between text-[12px] text-slate-500",children:[e.jsx("div",{children:"Shared 0×"}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full gap-1",children:[e.jsx(Hl,{className:"h-3.5 w-3.5"})," Share"]})]})]},c.id)})})]})}const Cun=[{category:"First Touch",icon:Ci,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:Hs,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:ry,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:Pr,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 Tun(){const s=t=>{navigator.clipboard.writeText(t),ae.success("Template copied")};return e.jsxs("div",{children:[e.jsx(Ku,{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:Cun.map(t=>{const n=t.icon;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl grid place-items-center",style:{background:`${t.color}18`,color:t.color},children:e.jsx(n,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:t.category}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[t.items.length," templates"]})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.items.map(r=>e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"font-semibold text-slate-900",children:r.title}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:t.category})]}),e.jsx("p",{className:"mt-3 text-[13.5px] text-slate-700 leading-relaxed whitespace-pre-wrap",children:r.body}),e.jsx("div",{className:"mt-4 pt-4 border-t border-slate-100 flex justify-end",children:e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full gap-1",onClick:()=>s(r.body),children:[e.jsx(ta,{className:"h-3.5 w-3.5"})," Copy"]})})]},r.title))})]},t.category)})})]})}const Eun={produce:"#7c3aed",influence:"#4f46e5",provide:"#0d9488",connect:"#9333ea"};function Aun(){const{agents:s}=d0(),{activities:t}=MSt(180),n=N.useMemo(()=>Array.from({length:12},(l,o)=>Km(Y9(new Date,(11-o)*7))).map(l=>{const o=Ul(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:Eun[l]}))},[t]),a=N.useMemo(()=>["new_connection","building_relationship","engaging_with_value","active_conversation","brokerage_presentation","joined"].map(l=>({stage:l.replace(/_/g," "),count:s.filter(o=>o.stage===l).length})),[s]);return e.jsxs("div",{children:[e.jsx(Ku,{eyebrow:"Reports & Insights",title:"See the compounding effect.",description:"Attraction is a long game. These reports show you the small consistent trend lines that matter."}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(fe,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Weekly Activity"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Attraction activities · Last 12 weeks"}),e.jsx(Sw,{width:"100%",height:260,children:e.jsxs(fLe,{data:n,children:[e.jsx(Bw,{dataKey:"week",tick:{fontSize:11}}),e.jsx($w,{tick:{fontSize:11}}),e.jsx(kp,{}),e.jsx(i6,{type:"monotone",dataKey:"activities",stroke:"#7c3aed",strokeWidth:2.5,dot:{r:3}})]})})]}),e.jsxs(fe,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Pillar Balance"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Where you're investing time"}),e.jsx(Sw,{width:"100%",height:260,children:e.jsxs(gLe,{children:[e.jsx(Bb,{data:r,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:55,outerRadius:90,paddingAngle:2,children:r.map((i,l)=>e.jsx(gR,{fill:i.color},l))}),e.jsx(kp,{}),e.jsx(JA,{})]})})]}),e.jsxs(fe,{className:"p-6 rounded-2xl lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Pipeline Distribution"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Agents by stage"}),e.jsx(Sw,{width:"100%",height:280,children:e.jsxs(xLe,{data:a,children:[e.jsx(Bw,{dataKey:"stage",tick:{fontSize:10}}),e.jsx($w,{tick:{fontSize:11}}),e.jsx(kp,{}),e.jsx(zw,{dataKey:"count",fill:"#4f46e5",radius:[8,8,0,0]})]})})]})]})]})}function Mun(){const{settings:s,upsert:t,resetOnboarding:n}=JU(),[r,a]=N.useState({});N.useEffect(()=>{s&&a(s)},[s]);const i=l=>a({...r,...l});return e.jsxs("div",{className:"max-w-3xl",children:[e.jsx(Ku,{eyebrow:"Attract Settings",title:"Your attraction philosophy.",description:"A one-time setup that keeps every touch you send true to who you are."}),e.jsxs(fe,{className:"p-5 rounded-2xl mb-6 flex flex-col md:flex-row md:items-center gap-4 bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-white text-violet-700 grid place-items-center shadow-sm",children:e.jsx(wc,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[13.5px] font-semibold text-slate-900",children:"Your 90-day plan"}),e.jsx("div",{className:"text-[12.5px] text-slate-600",children:s!=null&&s.onboarding_completed_at?`Primary pillar: ${s.primary_pillar??s.attraction_style??"balanced"} · Outcome: ${s.ninety_day_outcome??"—"}`:"You haven't completed onboarding yet."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{asChild:!0,variant:"outline",className:"rounded-full",children:e.jsx(Ln,{to:"/attract/plan",children:"View plan"})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>n.mutate(),children:[e.jsx(Fh,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Your voice & story"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"Used to personalize scripts, invites, and shared content."}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Elevator introduction"}),e.jsx(Ts,{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(se,{children:"Focus market"}),e.jsx(ge,{value:r.focus_market??"",onChange:l=>i({focus_market:l.target.value}),placeholder:"Orange County, CA"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Annual attraction goal"}),e.jsx(ge,{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(se,{children:'Your "why" for attraction'}),e.jsx(Ts,{rows:3,value:r.why_statement??"",onChange:l=>i({why_statement:l.target.value}),placeholder:"Because the right agents in the right room change everyone's business..."})]})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Cadence & rhythm"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"How often should we remind you to show up for agents at each stage?"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Hot leads follow-up"}),e.jsxs(us,{value:String(r.hot_cadence_days??3),onValueChange:l=>i({hot_cadence_days:Number(l)}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"1",children:"Every day"}),e.jsx(Ze,{value:"3",children:"Every 3 days"}),e.jsx(Ze,{value:"7",children:"Every week"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Warm leads follow-up"}),e.jsxs(us,{value:String(r.warm_cadence_days??14),onValueChange:l=>i({warm_cadence_days:Number(l)}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"7",children:"Weekly"}),e.jsx(Ze,{value:"14",children:"Every 2 weeks"}),e.jsx(Ze,{value:"30",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Long-term nurture"}),e.jsxs(us,{value:String(r.longterm_cadence_days??60),onValueChange:l=>i({longterm_cadence_days:Number(l)}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"30",children:"Monthly"}),e.jsx(Ze,{value:"60",children:"Every 2 months"}),e.jsx(Ze,{value:"90",children:"Quarterly"})]})]})]}),e.jsx("div",{className:"flex flex-col justify-end",children:e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-slate-50 p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900",children:"Weekly digest email"}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:"Every Sunday at 6pm"})]}),e.jsx(vn,{checked:r.weekly_digest_enabled??!0,onCheckedChange:l=>i({weekly_digest_enabled:l})})]})})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl bg-gradient-to-br from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"The Attract Trust Reminder"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 leading-relaxed",children:"Attract is never a sales funnel. Every touch you make here should be something you'd be proud of if the agent saw every note you'd taken about them. Real relationships. On a rhythm. For years."})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 px-8",onClick:()=>t.mutate(r),disabled:t.isPending,children:"Save Settings"})})]})]})}const nEe=[{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."}],rEe={live:"Live",partial:"Partial",placeholder:"Placeholder",integration_required:"Integration required"},BSt={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 Iun({tool:s,accent:t}){const[n,r]=N.useState(!1),a=In(),i=s.icon,l=!!s.to,o=nEe.find(u=>u.key===s.key),c=(o==null?void 0:o.status)??(l?"live":"placeholder"),d=()=>{l&&s.to?a(s.to):r(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{onClick:d,className:"group p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm hover:shadow-md cursor-pointer transition-all hover:-translate-y-0.5 relative",children:[e.jsxs("div",{className:`absolute top-3 right-3 inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider rounded-full px-2 py-0.5 border ${BSt[c]}`,children:[c==="live"&&e.jsx(un,{className:"h-2.5 w-2.5"}),rEe[c]]}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl grid place-items-center flex-shrink-0",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.title}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 leading-relaxed",children:s.description}),e.jsxs("div",{className:"mt-3 inline-flex items-center gap-1 text-[12.5px] font-semibold",style:{color:t},children:[s.cta??(l?"Open Tool":"Preview")," ",e.jsx(ga,{className:"h-3.5 w-3.5 group-hover:translate-x-0.5 transition-transform"})]})]})]})]}),e.jsx(bs,{open:n,onOpenChange:r,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{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(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>r(!1),children:"Close"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{ae.success("Added to your plan"),r(!1)},children:"Add to My Plan"})]})]})})]})}function yDe({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(Iun,{tool:c,accent:a},c.key))})]})}function Oet(){return e.jsx(yDe,{pillar:"01",title:"Produce",accent:"#7c3aed",icon:vo,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:ua,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:nx,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:vc,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:iy,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:mo,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:ua,title:"Client Testimonials",description:"A permission-tracked library of client quotes that make future agent conversations easier.",to:"/attract/produce/testimonials"}]})}function Fet(){return e.jsx(yDe,{pillar:"02",title:"Influence",accent:"#4f46e5",icon:un,tagline:"Show up in ways that draw the right agents to you.",intro:"Influence is earned by helping publicly and consistently. These tools give you simple ways to teach, speak, and be seen — so the right agents come to you first.",stats:[{label:"Speaking Slots",value:4},{label:"Podcast Guests",value:2},{label:"Masterclasses",value:6},{label:"Reach",value:"12.4k"}],tools:[{key:"content_studio",icon:_w,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:Tl,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:Bv,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:_d,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:vr,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:_n,title:"Agent Roundtables",description:"Host small-group conversations using the Connect Event Engine — value first, no pitching.",to:"/attract/events/new"}]})}const pP=["attract-kits"],XF=s=>["attract-kit-items",s],JF=s=>["attract-kit-shares",s??"all"],Pun=s=>["attract-kit-events",s??"all"],Lun=["attract-kit-templates"];function $R(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:[...pP,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_resource_kits").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=gt({mutationFn:async o=>{if(!s)throw new Error("not authenticated");const{data:c,error:d}=await q.from("attract_resource_kits").insert({user_id:s.id,title:o.title||"Untitled Kit",...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:pP})}),a=gt({mutationFn:async({id:o,patch:c})=>{const{data:d,error:u}=await q.from("attract_resource_kits").update(c).eq("id",o).select("*").single();if(u)throw u;return d},onSuccess:()=>t.invalidateQueries({queryKey:pP})}),i=gt({mutationFn:async o=>{const{error:c}=await q.from("attract_resource_kits").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:pP})}),l=gt({mutationFn:async o=>{const{data:c,error:d}=await q.rpc("duplicate_attract_kit",{_kit_id:o});if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:pP})});return{kits:n.data??[],isLoading:n.isLoading,create:r,update:a,remove:i,duplicate:l}}function $St(s){return lt({queryKey:["attract-kit",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_resource_kits").select("*").eq("id",s).single();if(n)throw n;return t}})}function Dun(s){const t=Gt(),n=lt({queryKey:XF(s??""),enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_resource_kit_items").select("*").eq("kit_id",s).order("sort_order");if(c)throw c;return o??[]}}),r=gt({mutationFn:async o=>{var u;const{data:c,error:d}=await q.from("attract_resource_kit_items").insert({kit_id:s,type:"text",title:"New item",sort_order:((u=n.data)==null?void 0:u.length)??0,...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:XF(s??"")})}),a=gt({mutationFn:async({id:o,patch:c})=>{const{error:d}=await q.from("attract_resource_kit_items").update(c).eq("id",o);if(d)throw d},onSuccess:()=>t.invalidateQueries({queryKey:XF(s??"")})}),i=gt({mutationFn:async o=>{const{error:c}=await q.from("attract_resource_kit_items").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:XF(s??"")})}),l=gt({mutationFn:async o=>{await Promise.all(o.map((c,d)=>q.from("attract_resource_kit_items").update({sort_order:d}).eq("id",c)))},onSuccess:()=>t.invalidateQueries({queryKey:XF(s??"")})});return{items:n.data??[],isLoading:n.isLoading,add:r,update:a,remove:i,reorder:l}}function USt(s){const{user:t}=gs(),n=Gt(),r=lt({queryKey:JF(s),enabled:!!t,queryFn:async()=>{let l=q.from("attract_kit_shares").select("*").order("created_at",{ascending:!1});s&&(l=l.eq("kit_id",s));const{data:o,error:c}=await l;if(c)throw c;return o??[]}}),a=gt({mutationFn:async l=>{if(!t)throw new Error("not authenticated");const{data:o,error:c}=await q.from("attract_kit_shares").insert({owner_user_id:t.id,...l}).select("*").single();if(c)throw c;return o},onSuccess:l=>{var o;n.invalidateQueries({queryKey:JF(s)}),n.invalidateQueries({queryKey:JF()});try{(o=navigator.clipboard)==null||o.writeText(VSt(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=gt({mutationFn:async l=>{const{error:o}=await q.from("attract_kit_shares").update({status:"revoked"}).eq("id",l);if(o)throw o},onSuccess:()=>{n.invalidateQueries({queryKey:JF(s)}),n.invalidateQueries({queryKey:JF()}),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 qSt(s){return lt({queryKey:Pun(s),queryFn:async()=>{let t=q.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(500);s&&(t=t.eq("kit_id",s));const{data:n,error:r}=await t;if(r)throw r;return n??[]}})}function Run(){return lt({queryKey:Lun,queryFn:async()=>{const{data:s,error:t}=await q.from("attract_kit_templates").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function Oun(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("clone_attract_kit_template",{_template_id:t});if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:pP})})}function VSt(s){return`${typeof window<"u"?window.location.origin:""}/attract-kit/${s}`}function zet(){const{kits:s}=$R(),{data:t=[]}=qSt(),{followUps:n}=eq(),r=N.useMemo(()=>{const l=o=>t.filter(c=>c.event_type===o).length;return{published:s.filter(o=>o.status==="published").length,drafts:s.filter(o=>o.status==="draft").length,views:l("page_view"),downloads:l("file_download"),cta:l("primary_cta_click"),questions:l("question_submitted")}},[s,t]),a=t.slice(0,8),i=n.filter(l=>!l.completed_at&&l.touch_type==="kit_engagement").slice(0,6);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ku,{eyebrow:"Pillar 03 · Provide",title:"Give more value than any agent expected.",description:"Package the value you already share into beautiful, trackable kits. See exactly which value creates conversations.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(Ln,{to:"/attract/provide/kits/templates",children:[e.jsx(Wg,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsx(B,{asChild:!0,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsxs(Ln,{to:"/attract/provide/kits/new",children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"New kit"]})})]})}),e.jsx(fe,{className:"p-6 md:p-8 rounded-2xl bg-gradient-to-br from-teal-50 via-violet-50 to-indigo-50 border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white grid place-items-center shadow-sm",children:e.jsx(AA,{className:"h-6 w-6 text-teal-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Resource Kits — the flagship of Provide"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 mt-1 max-w-3xl",children:"Bundle 3–7 pieces of real value (scripts, checklists, videos, tools) into a beautiful shareable kit. Send a personalized link to an agent, then let engagement recommend the next relationship touch. No pressure. Just real value that compounds."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx(B,{asChild:!0,size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsx(Ln,{to:"/attract/provide/kits/new",children:"Start a kit"})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ln,{to:"/attract/provide/kits/templates",children:"Browse 10 starter kits"})})]})]})]})}),e.jsx(fe,{className:"p-6 rounded-2xl border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 grid place-items-center",children:e.jsx(un,{className:"h-6 w-6 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Masterclass Builder"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 mt-1 max-w-3xl",children:"Turn what you already know into a 45-minute teaching moment. Build the curriculum, workbook, promotion drafts and run-of-show — then convert it into a Connect event or a Resource Kit in one click."}),e.jsx("div",{className:"flex gap-2 mt-4",children:e.jsx(B,{asChild:!0,size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsx(Ln,{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(JI,{label:"Published",value:r.published}),e.jsx(JI,{label:"Drafts",value:r.drafts}),e.jsx(JI,{label:"Views",value:r.views,icon:Ir}),e.jsx(JI,{label:"Downloads",value:r.downloads,icon:Da}),e.jsx(JI,{label:"CTA clicks",value:r.cta,icon:oc}),e.jsx(JI,{label:"Questions",value:r.questions,icon:Ql})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Recent kit engagement"}),e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Live signals from agents opening your value."})]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(Ln,{to:"/attract/provide/kits",children:["View kits ",e.jsx(za,{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:Go(new Date(l.created_at),{addSuffix:!0})})]},l.id))})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Recommended follow-ups"}),i.length===0?e.jsx("div",{className:"text-sm text-slate-500 py-6 text-center border border-dashed rounded-xl",children:"We'll surface follow-ups here as agents engage."}):e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsx("div",{className:"font-medium text-slate-900 line-clamp-2",children:l.title}),l.due_at&&e.jsxs("div",{className:"text-slate-500 text-[11px] mt-1",children:["Due ",Go(new Date(l.due_at),{addSuffix:!0})]})]},l.id))})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"My kits"}),e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs(Ln,{to:"/attract/provide/kits",children:["See all ",e.jsx(za,{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(Ln,{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(Ln,{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(ze,{variant:"outline",className:"capitalize",children:l.status}),l.pillar&&e.jsx(ze,{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(f6,{})]})}function JI({label:s,value:t,icon:n}){return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[n&&e.jsx(n,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"mt-1 text-[20px] font-semibold tabular-nums text-slate-900",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function Bet(){return e.jsx(yDe,{pillar:"04",title:"Connect",accent:"#9333ea",icon:MA,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:ry,title:"Coffee & Meetings",description:"The coffees to book this month, tracked as follow-ups in your Follow-Up Center.",to:"/attract/follow-up"},{key:"event_engine",icon:yr,title:"Attraction Events",description:"Design intimate gatherings — happy hours, dinners, mastermind lunches — with registration and check-in.",to:"/attract/events"},{key:"milestones",icon:hu,title:"Milestones & Celebrations",description:"Never miss a birthday, license anniversary, or business milestone for a prospective agent.",to:"/attract/connect/milestones"},{key:"checkins",icon:Ql,title:"Personal Check-Ins",description:"Relationship-first check-ins surfaced by your intelligence layer, ranked by signal.",to:"/attract/opportunities"},{key:"circles",icon:W0,title:"Agent Circles",description:"Small peer groups you host quarterly — built on the Connect Event Engine.",to:"/attract/events/new"}]})}const Fun=[{key:"coffee",label:"Coffee & Conversation",icon:ry,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:W0,tone:"from-violet-500 to-indigo-500",description:"4–6 agents share what is actually working right now."},{key:"mastermind",label:"Mastermind",icon:un,tone:"from-fuchsia-500 to-pink-500",description:"A quarterly small group solving each other’s biggest questions."},{key:"workshop",label:"Workshop / Webinar",icon:wc,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:V9,tone:"from-rose-500 to-red-500",description:"The relationship-first gathering. No agenda, just presence."},{key:"networking_plan",label:"Networking Game Plan",icon:MA,tone:"from-teal-500 to-emerald-500",description:"Not an event — a plan for the next 5 rooms you will walk into."}];function zun(){const s=In(),{data:t=[]}=xbe(),{followUps:n}=eq(),{agents:r}=d0(),a=N.useMemo(()=>{const l=new Date,o=Ul(l,7),c=t.filter(p=>p.status==="published"&&Uv(new Date(p.starts_at),l)),d=t.filter(p=>p.status==="draft").length,u=t.reduce((p,f)=>p+(Uv(new Date(f.created_at),Ul(l,-7))?f.registration_count:0),0),h=n.filter(p=>!p.completed_at&&p.due_at&&jb(new Date(p.due_at),o)&&(p.touch_type==="event_followup"||p.touch_type==="event_no_show")).length;return{upcoming:c,draftsNeedingInvites:d,regs:u,dueSoon:h}},[t,n]),i=a.upcoming[0];return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Pillar 04 · Connect"}),e.jsx("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:"Real events. Small rooms. Long relationships."}),e.jsx("p",{className:"text-slate-600 mt-1.5 max-w-2xl",children:"Build the room, invite personally, host with care, capture one honest note, and follow up within 48 hours."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>s("/attract/events"),children:[e.jsx(yr,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700",onClick:()=>s("/attract/events/new"),children:[e.jsx(As,{className:"h-4 w-4 mr-2"})," Create an event"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Upcoming events",value:a.upcoming.length,icon:yr,tone:"text-violet-700 bg-violet-100"},{label:"Drafts needing invites",value:a.draftsNeedingInvites,icon:cr,tone:"text-amber-700 bg-amber-100"},{label:"Registrations this week",value:a.regs,icon:mo,tone:"text-emerald-700 bg-emerald-100"},{label:"48-hour follow-ups due",value:a.dueSoon,icon:pu,tone:"text-rose-700 bg-rose-100"}].map(l=>e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:`h-9 w-9 rounded-xl grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-4.5 w-4.5"})}),e.jsx("div",{className:"text-[26px] font-semibold tabular-nums mt-3",children:l.value}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:l.label})]},l.label))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"lg:col-span-2 p-6 rounded-2xl border-slate-200 bg-gradient-to-br from-slate-900 to-slate-800 text-white overflow-hidden relative",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-white/60 mb-2",children:"Your next event"}),i?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl md:text-2xl font-semibold",children:i.title}),e.jsxs("div",{className:"text-white/70 mt-1",children:[ks(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(ze,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[i.registration_count," registered"]}),i.capacity&&e.jsxs(ze,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[Math.max(0,i.capacity-i.registration_count)," seats left"]})]}),e.jsxs("div",{className:"mt-5 flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:()=>s(`/attract/events/${i.id}`),children:["Open command center ",e.jsx(za,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full bg-transparent text-white border-white/30 hover:bg-white/10",onClick:()=>s(`/attract/events/${i.id}/checkin`),children:"Mobile check-in"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-semibold",children:"No upcoming events yet"}),e.jsx("div",{className:"text-white/70 mt-1",children:"Start with a small coffee. One conversation is enough."}),e.jsx(B,{size:"sm",className:"mt-5 rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:()=>s("/attract/events/new?type=coffee"),children:"Plan a coffee"})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-amber-200 bg-amber-50",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-amber-700 font-semibold mb-2",children:"Reminder"}),e.jsx("div",{className:"text-[15px] text-slate-900 leading-relaxed",children:"Build relationships first. Personalize every invitation and follow-up, and verify brokerage and compensation information before sharing."})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold",children:"Quick starts"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"What kind of room do you want to build?"})]}),e.jsxs(Ln,{to:"/attract/events/new",className:"text-[13px] text-violet-700 hover:underline flex items-center gap-1",children:["Start from scratch ",e.jsx(ga,{className:"h-3.5 w-3.5"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:Fun.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(za,{className:"h-3 w-3"})]})]},l.key))})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold",children:"Personal connection goals"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"This week"})]}),e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>s("/attract/follow-up"),children:"Open Follow-Up Center"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[{label:"Coffees booked",target:3,actual:a.upcoming.filter(l=>(l.event_type_key||l.event_type)==="coffee").length,icon:ry,tone:"text-amber-600 bg-amber-50"},{label:"Roundtables/masterminds",target:1,actual:a.upcoming.filter(l=>["roundtable","mastermind"].includes(l.event_type_key||l.event_type)).length,icon:un,tone:"text-violet-600 bg-violet-50"},{label:"People in pipeline",target:r.length,actual:r.length,icon:W0,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 Bun(){const s=In(),{data:t=[],isLoading:n}=xbe(),r=cun(),a=iun(),[i,l]=N.useState("all"),[o,c]=N.useState(""),d=N.useMemo(()=>t.filter(u=>!(i!=="all"&&u.status!==i||o&&!u.title.toLowerCase().includes(o.toLowerCase()))),[t,i,o]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Connect · Events"}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"Events"}),e.jsx("p",{className:"text-slate-600 mt-1",children:"Every room you have built — drafted, live, and complete."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ge,{placeholder:"Search events",className:"pl-9 rounded-full w-[240px] bg-white",value:o,onChange:u=>c(u.target.value)})]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700",onClick:()=>s("/attract/events/new"),children:[e.jsx(As,{className:"h-4 w-4 mr-2"})," New event"]})]})]}),e.jsxs($r,{value:i,onValueChange:u=>l(u),children:[e.jsxs(Ur,{className:"rounded-full bg-white border border-slate-200",children:[e.jsxs(Zt,{value:"all",className:"rounded-full",children:["All (",t.length,")"]}),e.jsxs(Zt,{value:"draft",className:"rounded-full",children:["Drafts (",t.filter(u=>u.status==="draft").length,")"]}),e.jsxs(Zt,{value:"published",className:"rounded-full",children:["Published (",t.filter(u=>u.status==="published").length,")"]}),e.jsxs(Zt,{value:"completed",className:"rounded-full",children:["Completed (",t.filter(u=>u.status==="completed").length,")"]})]}),e.jsx(ls,{value:i,className:"mt-5",children:n?e.jsx(fe,{className:"p-12 rounded-2xl text-center text-slate-500",children:"Loading events…"}):d.length===0?e.jsxs(fe,{className:"p-12 rounded-2xl text-center border-dashed",children:[e.jsx(yr,{className:"h-8 w-8 text-slate-300 mx-auto"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mt-3",children:"No events here yet"}),e.jsx("div",{className:"text-slate-500 mt-1",children:"Start with a small coffee or a mastermind — one conversation is enough."}),e.jsxs(B,{className:"mt-4 rounded-full",onClick:()=>s("/attract/events/new"),children:[e.jsx(As,{className:"h-4 w-4 mr-2"})," Create your first event"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5",children:d.map(u=>e.jsxs(fe,{className:"group rounded-2xl border-slate-200 bg-white overflow-hidden hover:shadow-md transition",children:[e.jsxs("div",{className:"h-32 bg-gradient-to-br from-violet-500 to-indigo-600 relative",children:[u.cover_image_url&&e.jsx("img",{src:u.cover_image_url,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),e.jsxs("div",{className:"absolute top-3 left-3 flex gap-2",children:[e.jsx(ze,{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(ze,{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:ks(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(vr,{className:"h-3.5 w-3.5"})," Virtual"]}):u.format==="hybrid"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vr,{className:"h-3.5 w-3.5"})," Hybrid"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"})," ",u.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_n,{className:"h-3.5 w-3.5"})," ",u.registration_count,u.capacity?` / ${u.capacity}`:""]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>r.mutate(u.id),children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-1"})," Duplicate"]}),u.status==="published"&&u.public_slug&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>{navigator.clipboard.writeText(gbe(u.public_slug)),ae.success("Registration link copied")},children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"})," Link"]})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-rose-600 hover:bg-rose-50",onClick:()=>{confirm("Delete this event?")&&a.mutate(u.id)},children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})]},u.id))})})]})]})}const $un=[{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 $et(){const{eventId:s}=_i(),t=In(),[n]=yl(),r=n.get("type"),a=!!s,{data:i}=gDe(s),{data:l=[]}=PSt(),{kits:o}=$R(),c=LSt(),d=DSt(),[u,h]=N.useState({title:"",description:"",event_type_key:r||"coffee",intended_audience:"",related_pillar:"connect",starts_at:new Date(Date.now()+7*864e5).toISOString().slice(0,16),ends_at:"",timezone:"America/New_York",format:"in_person",location:"",address:"",virtual_url:"",capacity:"",waitlist_enabled:!0,host_name:"",cohosts:[],agenda:[],learning_outcomes:[],registration_questions:[],confirmation_message:"",resource_kit_id:null,kit_delivery_trigger:"after_attendance",followup_hours:48});N.useEffect(()=>{i&&h({...i,starts_at:i.starts_at?i.starts_at.slice(0,16):"",ends_at:i.ends_at?i.ends_at.slice(0,16):"",capacity:i.capacity??"",cohosts:i.cohosts||[],agenda:i.agenda||[],learning_outcomes:i.learning_outcomes||[],registration_questions:i.registration_questions||[]})},[i]);const p=j=>h(_=>({..._,...j})),f=N.useMemo(()=>l.slice(0,4),[l]),g=j=>{p({title:j.title,description:j.description,event_type_key:j.event_type_key,related_pillar:j.related_pillar,intended_audience:j.intended_audience,agenda:j.suggested_agenda||[],learning_outcomes:j.suggested_outcomes||[],registration_questions:j.suggested_questions||[],confirmation_message:j.suggested_confirmation}),ae.success(`Loaded "${j.title}"`)},b=async(j={})=>{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:j.publish?"published":u.status||"draft"};if(a)await d.mutateAsync({id:s,patch:_}),ae.success(j.publish?"Published":"Saved");else{const S=await c.mutateAsync(_);ae.success(j.publish?"Event published":"Draft saved"),t(`/attract/events/${S.id}${j.publish?"":"/edit"}`,{replace:!0})}},v=i!=null&&i.public_slug?gbe(i.public_slug):null;return e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/events"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[v&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(v),ae.success("Registration link copied")},children:[e.jsx(tl,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>b(),children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs(B,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({publish:!0}),children:[e.jsx(nx,{className:"h-4 w-4 mr-2"})," ",(i==null?void 0:i.status)==="published"?"Update published":"Publish"]})]})]}),!a&&f.length>0&&e.jsxs(fe,{className:"p-5 rounded-2xl border-violet-200 bg-gradient-to-br from-violet-50 to-indigo-50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(un,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:"Start from a premium template"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:f.map(j=>e.jsxs("button",{onClick:()=>g(j),className:"text-left rounded-xl bg-white/70 border border-white p-3 hover:bg-white transition",children:[e.jsx("div",{className:"text-[13.5px] font-semibold text-slate-900",children:j.title}),e.jsx("div",{className:"text-[12px] text-slate-600 line-clamp-2 mt-0.5",children:j.description})]},j.id))})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 1"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Event basics"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Title"}),e.jsx(ge,{value:u.title,onChange:j=>p({title:j.target.value}),placeholder:"Coffee & Systems Roundtable"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Event type"}),e.jsxs(us,{value:u.event_type_key,onValueChange:j=>p({event_type_key:j}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:$un.map(j=>e.jsx(Ze,{value:j.key,children:j.label},j.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Related pillar"}),e.jsxs(us,{value:u.related_pillar||"connect",onValueChange:j=>p({related_pillar:j}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"produce",children:"Produce"}),e.jsx(Ze,{value:"influence",children:"Influence"}),e.jsx(Ze,{value:"provide",children:"Provide"}),e.jsx(Ze,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Intended audience"}),e.jsx(ge,{value:u.intended_audience||"",onChange:j=>p({intended_audience:j.target.value}),placeholder:"Producing agents 1–5 years in"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{rows:4,value:u.description||"",onChange:j=>p({description:j.target.value}),placeholder:"What is this event and why does it matter?"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Starts at"}),e.jsx(ge,{type:"datetime-local",value:u.starts_at||"",onChange:j=>p({starts_at:j.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Ends at"}),e.jsx(ge,{type:"datetime-local",value:u.ends_at||"",onChange:j=>p({ends_at:j.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Time zone"}),e.jsxs(us,{value:u.timezone||"America/New_York",onValueChange:j=>p({timezone:j}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Phoenix"].map(j=>e.jsx(Ze,{value:j,children:j},j))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Format"}),e.jsxs(us,{value:u.format,onValueChange:j=>p({format:j}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"in_person",children:"In person"}),e.jsx(Ze,{value:"virtual",children:"Virtual"}),e.jsx(Ze,{value:"hybrid",children:"Hybrid"})]})]})]}),u.format!=="virtual"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{children:"Venue / location name"}),e.jsx(ge,{value:u.location||"",onChange:j=>p({location:j.target.value}),placeholder:"Rise Coffee — Downtown"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Address"}),e.jsx(ge,{value:u.address||"",onChange:j=>p({address:j.target.value}),placeholder:"123 Main St, City, ST"})]})]}),u.format!=="in_person"&&e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Virtual meeting URL"}),e.jsx(ge,{value:u.virtual_url||"",onChange:j=>p({virtual_url:j.target.value}),placeholder:"https://zoom.us/…"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Capacity (optional)"}),e.jsx(ge,{type:"number",value:u.capacity,onChange:j=>p({capacity:j.target.value}),placeholder:"No limit"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-6",children:[e.jsx(vn,{checked:u.waitlist_enabled,onCheckedChange:j=>p({waitlist_enabled:j}),id:"wl"}),e.jsx(se,{htmlFor:"wl",className:"cursor-pointer",children:"Allow waitlist if full"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Host name (as shown publicly)"}),e.jsx(ge,{value:u.host_name||"",onChange:j=>p({host_name:j.target.value}),placeholder:"Jeremy from LevelUp"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cover image URL"}),e.jsx(ge,{value:u.cover_image_url||"",onChange:j=>p({cover_image_url:j.target.value}),placeholder:"https://…"})]})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 2"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Experience & agenda"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{children:"Agenda"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>p({agenda:[...u.agenda||[],{time:"",item:""}]}),children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"})," Add item"]})]}),e.jsxs("div",{className:"space-y-2",children:[(u.agenda||[]).map((j,_)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{className:"w-24",value:j.time||"",onChange:S=>{const A=[...u.agenda];A[_]={...A[_],time:S.target.value},p({agenda:A})},placeholder:"0:00"}),e.jsx(ge,{value:j.item||"",onChange:S=>{const A=[...u.agenda];A[_]={...A[_],item:S.target.value},p({agenda:A})},placeholder:"What happens here"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p({agenda:u.agenda.filter((S,A)=>A!==_)}),children:e.jsx(Fn,{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(cl,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{children:"What attendees will receive"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>p({learning_outcomes:[...u.learning_outcomes||[],""]}),children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"})," Add outcome"]})]}),e.jsx("div",{className:"space-y-2",children:(u.learning_outcomes||[]).map((j,_)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:j,onChange:S=>{const A=[...u.learning_outcomes];A[_]=S.target.value,p({learning_outcomes:A})},placeholder:"One clear, honest outcome"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p({learning_outcomes:u.learning_outcomes.filter((S,A)=>A!==_)}),children:e.jsx(Fn,{className:"h-4 w-4"})})]},_))})]})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 3"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Registration page"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{children:"Registration questions"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>p({registration_questions:[...u.registration_questions||[],{key:`q${(u.registration_questions||[]).length+1}`,label:"",type:"text"}]}),children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"})," Add question"]})]}),e.jsx("div",{className:"space-y-2",children:(u.registration_questions||[]).map((j,_)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ge,{className:"flex-1",value:j.label,onChange:S=>{const A=[...u.registration_questions];A[_]={...A[_],label:S.target.value,key:j.key||`q${_+1}`},p({registration_questions:A})},placeholder:"Question shown to registrants"}),e.jsxs(us,{value:j.type,onValueChange:S=>{const A=[...u.registration_questions];A[_]={...A[_],type:S},p({registration_questions:A})},children:[e.jsx(cs,{className:"w-32",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"text",children:"Short text"}),e.jsx(Ze,{value:"long",children:"Long text"})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p({registration_questions:u.registration_questions.filter((S,A)=>A!==_)}),children:e.jsx(Fn,{className:"h-4 w-4"})})]},_))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Confirmation message (shown after registration)"}),e.jsx(Ts,{rows:3,value:u.confirmation_message||"",onChange:j=>p({confirmation_message:j.target.value}),placeholder:"You are in — come with one honest question."})]})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 4"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Resource Kit & 48-hour follow-up"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Attach a Resource Kit"}),e.jsxs(us,{value:u.resource_kit_id||"none",onValueChange:j=>p({resource_kit_id:j==="none"?null:j}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"None"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"None"}),(o||[]).map(j=>e.jsx(Ze,{value:j.id,children:j.title},j.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Deliver kit"}),e.jsxs(us,{value:u.kit_delivery_trigger||"after_attendance",onValueChange:j=>p({kit_delivery_trigger:j}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"on_registration",children:"On registration"}),e.jsx(Ze,{value:"on_confirmation",children:"On confirmation"}),e.jsx(Ze,{value:"on_check_in",children:"At check-in"}),e.jsx(Ze,{value:"after_attendance",children:"After attendance"}),e.jsx(Ze,{value:"manual",children:"Only manually"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Default follow-up window (hours)"}),e.jsx(ge,{type:"number",value:u.followup_hours??48,onChange:j=>p({followup_hours:Number(j.target.value)})})]})]}),!u.resource_kit_id&&e.jsx("div",{className:"text-[12px] text-amber-700 bg-amber-50 border border-amber-200 rounded-lg p-3 mt-4",children:"Tip: attach a Resource Kit so attendees leave with something valuable — and so follow-ups have a natural reason."})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 5"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-3",children:"Review & publish"}),e.jsxs("div",{className:"text-[13px] text-slate-600 leading-relaxed",children:["Publishing generates a premium public registration page at"," ",e.jsxs("code",{className:"bg-slate-100 px-1.5 py-0.5 rounded text-slate-800",children:["/attract-event/",(i==null?void 0:i.public_slug)||""]})," ","and enables the personal invitation flow. You can unpublish or cancel at any time."]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[(!u.title||!u.starts_at)&&e.jsx(ze,{variant:"secondary",className:"bg-rose-50 text-rose-700 border-rose-200",children:"Add title and start time"}),(u.agenda||[]).length===0&&e.jsx(ze,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No agenda yet"}),(u.learning_outcomes||[]).length===0&&e.jsx(ze,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No stated outcomes"}),!u.resource_kit_id&&e.jsx(ze,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No Resource Kit attached"})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-5",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>b(),children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({publish:!0}),children:[e.jsx(nx,{className:"h-4 w-4 mr-2"})," Publish"]})]})]})]})}const _pe=s=>s?[s.first_name,s.last_name].filter(Boolean).join(" "):"";function Uun(){const{eventId:s}=_i(),t=In(),{data:n}=gDe(s),{data:r=[]}=ISt(s),{data:a=[]}=run(s),{data:i=[]}=aun(s),{agents:l}=d0(),{data:o=[]}=PSt(),c=RSt(),d=oun(),u=lun(),h=DSt(),p=N.useMemo(()=>{const b=r.length,v=r.filter(F=>F.status==="registered"||F.status==="confirmed").length,j=r.filter(F=>F.status==="attended").length,_=r.filter(F=>F.status==="no_show").length,S=r.filter(F=>F.status==="waitlisted").length,A=v+j+_,T=A>0?Math.round(j/A*100):0,D=a.length>0?Math.round(a.filter(F=>F.viewed_at).length/a.length*100):0,L=r.filter(F=>F.followup_status==="done").length,M=j>0?Math.round(L/j*100):0;return{total:b,registered:v,attended:j,noShow:_,waitlist:S,attendRate:T,invView:D,followed:L,followedRate:M}},[r,a]);if(!n)return e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"});const f=n.public_slug?gbe(n.public_slug):null,g=()=>{const b=new Blob([OSt(n)],{type:"text/calendar"}),v=URL.createObjectURL(b),j=document.createElement("a");j.href=v,j.download=`${n.public_slug||"event"}.ics`,j.click(),URL.revokeObjectURL(v)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/events"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:g,children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-2"})," ICS"]}),f&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(f),ae.success("Link copied")},children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),f&&e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:f,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-2"})," Preview page"]})}),e.jsxs(B,{size:"sm",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(ly,{className:"h-3.5 w-3.5 mr-2"})," Check-in mode"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Edit"})]})]}),e.jsx(fe,{className:"p-6 rounded-2xl border-slate-200 bg-gradient-to-br from-slate-900 to-slate-800 text-white",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ze,{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(ze,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.related_pillar}),n.event_type_key&&e.jsx(ze,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.event_type_key.replace("_"," ")})]}),e.jsx("div",{className:"text-2xl md:text-3xl font-semibold",children:n.title}),e.jsxs("div",{className:"text-white/70 mt-1 flex items-center gap-4 flex-wrap",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(yr,{className:"h-4 w-4"})," ",ks(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(vr,{className:"h-4 w-4"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ca,{className:"h-4 w-4"})," ",n.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(_n,{className:"h-4 w-4"})," ",n.registration_count," registered",n.capacity?` / ${n.capacity}`:""]})]})]}),n.status==="draft"&&e.jsx(B,{className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:async()=>{await h.mutateAsync({id:n.id,patch:{status:"published"}}),ae.success("Published")},children:"Publish now"}),n.status==="published"&&new Date(n.starts_at){await h.mutateAsync({id:n.id,patch:{status:"completed"}}),ae.success("Marked completed")},children:"Mark completed"})]})}),e.jsxs($r,{defaultValue:"overview",children:[e.jsxs(Ur,{className:"rounded-full bg-white border border-slate-200 flex-wrap h-auto",children:[e.jsx(Zt,{value:"overview",className:"rounded-full",children:"Overview"}),e.jsxs(Zt,{value:"invitations",className:"rounded-full",children:["Invitations (",a.length,")"]}),e.jsxs(Zt,{value:"registrations",className:"rounded-full",children:["Registrations (",r.length,")"]}),e.jsxs(Zt,{value:"notes",className:"rounded-full",children:["Notes (",i.length,")"]}),e.jsx(Zt,{value:"kit",className:"rounded-full",children:"Resource Kit"}),e.jsx(Zt,{value:"followup",className:"rounded-full",children:"48-hour follow-up"}),e.jsx(Zt,{value:"analytics",className:"rounded-full",children:"Analytics"})]}),e.jsxs(ls,{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(pv,{icon:_n,label:"Registered",value:p.registered+p.attended}),e.jsx(pv,{icon:Lr,label:"Attended",value:p.attended}),e.jsx(pv,{icon:yo,label:"Attendance rate",value:`${p.attendRate}%`}),e.jsx(pv,{icon:pu,label:"Follow-up completion",value:`${p.followedRate}%`})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Agenda"}),(n.agenda||[]).length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"No agenda yet"}):e.jsx("ul",{className:"space-y-2",children:n.agenda.map((b,v)=>e.jsxs("li",{className:"flex gap-3 text-[14px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:b.time||""}),e.jsx("span",{className:"text-slate-800",children:b.item})]},v))}),(n.learning_outcomes||[]).length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mt-6 mb-2",children:"What attendees receive"}),e.jsx("ul",{className:"space-y-1.5",children:n.learning_outcomes.map((b,v)=>e.jsxs("li",{className:"text-[13.5px] text-slate-700 flex gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",b]},v))})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Share"}),f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Registration page"}),e.jsx("div",{className:"text-[12.5px] font-mono bg-slate-50 border border-slate-200 rounded-lg p-2 break-all",children:f}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full mt-2 w-full",onClick:()=>{navigator.clipboard.writeText(f),ae.success("Copied")},children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]})]}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"Publish the event to generate a shareable registration link."}),n.check_in_token&&e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Check-in mode"}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full w-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(ly,{className:"h-3.5 w-3.5 mr-2"})," Open check-in"]})]})]})]})]}),e.jsx(ls,{value:"invitations",className:"mt-5",children:e.jsx(qun,{eventId:n.id,eventSlug:n.public_slug,agents:l,invitations:a,templates:o,onCreate:u.mutate})}),e.jsx(ls,{value:"registrations",className:"mt-5",children:e.jsx(Vun,{eventId:n.id,attendees:r,onUpsert:c.mutate,checkInToken:n.check_in_token})}),e.jsx(ls,{value:"notes",className:"mt-5",children:e.jsx(Hun,{eventId:n.id,attendees:r,notes:i,onCreate:d.mutate})}),e.jsx(ls,{value:"kit",className:"mt-5",children:e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Resource Kit"}),n.resource_kit_id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"A Resource Kit is attached to this event."}),e.jsxs("div",{className:"text-[13px] text-slate-600 mt-1",children:["Deliver trigger: ",e.jsx("span",{className:"font-medium capitalize",children:(n.kit_delivery_trigger||"after_attendance").replace(/_/g," ")})]}),e.jsx(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>t(`/attract/provide/kits/${n.resource_kit_id}/analytics`),children:"Open kit analytics"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] text-slate-700",children:"No kit attached yet. Attach one so attendees leave with something valuable."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx(B,{className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Attach a kit"}),e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>t("/attract/provide/kits/new"),children:"Create a new kit"})]})]})]})}),e.jsx(ls,{value:"followup",className:"mt-5",children:e.jsx(Gun,{eventId:n.id,attendees:r,onUpsert:c.mutate})}),e.jsxs(ls,{value:"analytics",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(pv,{icon:cr,label:"Invitations sent",value:a.length}),e.jsx(pv,{icon:tr,label:"Invitation view rate",value:`${p.invView}%`}),e.jsx(pv,{icon:_n,label:"Registered",value:p.registered+p.attended}),e.jsx(pv,{icon:Lr,label:"Attended",value:p.attended}),e.jsx(pv,{icon:yo,label:"Attendance rate",value:`${p.attendRate}%`}),e.jsx(pv,{icon:pu,label:"Follow-up complete (48h)",value:`${p.followedRate}%`}),e.jsx(pv,{icon:_w,label:"Notes captured",value:i.length}),e.jsx(pv,{icon:Fo,label:"Meetings requested",value:r.filter(b=>b.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 pv({icon:s,label:t,value:n}){return e.jsxs(fe,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 text-[12px]",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("div",{className:"text-[24px] font-semibold tabular-nums text-slate-900 mt-2",children:n})]})}function qun({eventId:s,eventSlug:t,agents:n,invitations:r,templates:a,onCreate:i}){const[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState("email"),[g,b]=N.useState(""),v=a==null?void 0:a[0],j=()=>{if(!v)return;const S=p==="sms"?v.suggested_invitation_sms:p==="dm"?v.suggested_invitation_dm:v.suggested_invitation_email,A=t?`${window.location.origin}/attract-event/${t}`:"";b((S||"").replaceAll("{{first_name}}",(c||"friend").split(" ")[0]).replaceAll("{{link}}",A).replaceAll("{{date}}",""))},_=()=>{if(!c||p==="email"&&!u){ae.error("Add a name and email");return}const S=n.find(A=>A.id===l);i({event_id:s,agent_id:l||null,recipient_name:c||_pe(S),recipient_email:u||(S==null?void 0:S.email),channel:p,message_body:g,status:"sent"}),d(""),h(""),b(""),o(""),ae.success("Invitation logged")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Log a personal invitation"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Attract agent (optional)"}),e.jsxs(us,{value:l||"none",onValueChange:S=>{o(S==="none"?"":S);const A=n.find(T=>T.id===S);A&&(d(_pe(A)),h(A.email||""))},children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Pick an agent"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"Guest (not in pipeline)"}),n.map(S=>e.jsx(Ze,{value:S.id,children:_pe(S)},S.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Channel"}),e.jsxs(us,{value:p,onValueChange:f,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"email",children:"Email"}),e.jsx(Ze,{value:"sms",children:"Text message"}),e.jsx(Ze,{value:"dm",children:"DM"}),e.jsx(Ze,{value:"call",children:"Phone call"}),e.jsx(Ze,{value:"in_person",children:"In person"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Recipient name"}),e.jsx(ge,{value:c,onChange:S=>d(S.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Recipient email"}),e.jsx(ge,{value:u,onChange:S=>h(S.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(se,{children:"Message"}),v&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-xs",onClick:j,children:[e.jsx(un,{className:"h-3 w-3 mr-1"})," Draft from template"]})]}),e.jsx(Ts,{rows:5,value:g,onChange:S=>b(S.target.value),placeholder:"Write it like you would to a friend."})]})]}),e.jsxs("div",{className:"flex justify-between items-center mt-4",children:[e.jsx("div",{className:"text-[12px] text-slate-500",children:"Never auto-sent. This just logs that you invited them."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>{g&&(navigator.clipboard.writeText(g),ae.success("Copied"))},children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-2"})," Copy message"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:_,children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-2"})," Log invitation"]})]})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Recent invitations"}),r.length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"None yet."}):e.jsx("div",{className:"space-y-2 max-h-[520px] overflow-auto",children:r.map(S=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900",children:S.recipient_name||S.recipient_email}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:S.status})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:["via ",S.channel," · ",Go(new Date(S.sent_at))," ago",S.view_count>0?` · viewed ${S.view_count}×`:""]})]},S.id))})]})]})}function Vun({eventId:s,attendees:t,onUpsert:n,checkInToken:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),c=()=>{if(!a){ae.error("Add a name");return}n({event_id:s,guest_name:a,guest_email:l||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),i(""),o(""),ae.success("Walk-in added")};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs(fe,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Add a walk-in guest"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(ge,{placeholder:"Name",value:a,onChange:d=>i(d.target.value)}),e.jsx(ge,{placeholder:"Email (optional)",value:l,onChange:d=>o(d.target.value)}),e.jsxs(B,{className:"rounded-full md:col-span-2",onClick:c,children:[e.jsx(Fo,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]}),e.jsx(fe,{className:"rounded-2xl border-slate-200 bg-white overflow-hidden",children:t.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400",children:"No registrations yet"}):e.jsx("div",{className:"divide-y divide-slate-100",children:t.map(d=>e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:d.guest_name||_pe(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(ze,{variant:"secondary",className:"capitalize",children:d.status}),e.jsxs(us,{value:d.status,onValueChange:u=>n({id:d.id,event_id:s,status:u,checked_in_at:u==="attended"&&!d.checked_in_at?new Date().toISOString():d.checked_in_at}),children:[e.jsx(cs,{className:"h-8 w-40 text-xs",children:e.jsx(hs,{})}),e.jsx(ds,{children:["invited","registered","confirmed","waitlisted","attended","no_show","cancelled"].map(u=>e.jsx(Ze,{value:u,className:"text-xs",children:u.replace("_"," ")},u))})]}),r&&d.personalized_token&&e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full text-xs",onClick:()=>{navigator.clipboard.writeText(dun(r,d.personalized_token)),ae.success("Check-in link copied")},children:e.jsx(ta,{className:"h-3.5 w-3.5"})})]})]},d.id))})})]})}function Hun({eventId:s,attendees:t,notes:n,onCreate:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState("warm"),[u,h]=N.useState(!1),[p,f]=N.useState(""),g=()=>{if(!l.trim()){ae.error("Add a note");return}const b=t.find(v=>v.id===a);r({event_id:s,attendee_id:a||null,agent_id:(b==null?void 0:b.agent_id)||null,note:l,temperature:c,recommended_next_action:p||null,wants_one_on_one:u}),o(""),i(""),f(""),h(!1),ae.success("Note captured")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Capture one honest note"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Attendee (optional)"}),e.jsxs(us,{value:a||"none",onValueChange:b=>i(b==="none"?"":b),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Anyone in the room"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"General note"}),t.map(b=>e.jsx(Ze,{value:b.id,children:b.guest_name||b.guest_email},b.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Note"}),e.jsx(Ts,{rows:4,value:l,onChange:b=>o(b.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(se,{children:"Relationship temperature"}),e.jsxs(us,{value:c,onValueChange:d,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:["cold","warm","hot"].map(b=>e.jsx(Ze,{value:b,children:b},b))})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Recommended next action"}),e.jsx(ge,{value:p,onChange:b=>f(b.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:b=>h(b.target.checked)}),"They should get a one-on-one conversation"]})]}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:g,children:[e.jsx(As,{className:"h-4 w-4 mr-2"})," Save note"]})})]}),e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Notes from this event"}),n.length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"None yet."}):e.jsx("div",{className:"space-y-3 max-h-[520px] overflow-auto",children:n.map(b=>{const v=t.find(j=>j.id===b.attendee_id);return e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:(v==null?void 0:v.guest_name)||"General"}),e.jsx("div",{className:"text-[13px] text-slate-700 mt-1 whitespace-pre-wrap",children:b.note}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 flex-wrap text-[11px] text-slate-500",children:[b.temperature&&e.jsx(ze,{variant:"secondary",className:"capitalize",children:b.temperature}),b.wants_one_on_one&&e.jsx(ze,{className:"bg-emerald-500",children:"Wants 1:1"}),b.recommended_next_action&&e.jsxs("span",{children:["Next: ",b.recommended_next_action]})]})]},b.id)})})]})]})}function Gun({eventId:s,attendees:t,onUpsert:n}){const r=N.useMemo(()=>({attended_engaged:t.filter(l=>l.status==="attended"&&l.temperature==="hot"),attended_no_notes:t.filter(l=>l.status==="attended"),no_show:t.filter(l=>l.status==="no_show"),meeting_requested:t.filter(l=>l.meeting_requested),not_followed:t.filter(l=>l.status==="attended"&&l.followup_status!=="done")}),[t]),a=(l,o)=>n({id:l,event_id:s,followup_status:o}),i=({title:l,list:o,color:c})=>e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:`h-2 w-2 rounded-full ${c}`}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:l}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:["(",o.length,")"]})]}),o.length===0?e.jsx("div",{className:"text-[12px] text-slate-400",children:"Nobody here."}):e.jsx("div",{className:"space-y-2",children:o.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-slate-100 p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:d.guest_name||d.guest_email}),e.jsxs("div",{className:"text-[11.5px] text-slate-500",children:[d.status," · followup: ",d.followup_status||"pending"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full h-8",onClick:()=>a(d.id,"in_progress"),children:"In progress"}),e.jsx(B,{size:"sm",className:"rounded-full h-8 bg-emerald-600 hover:bg-emerald-700",onClick:()=>a(d.id,"done"),children:e.jsx(Lr,{className:"h-3 w-3"})})]})]},d.id))})]});return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(i,{title:"Attended and engaged",list:r.attended_engaged,color:"bg-emerald-500"}),e.jsx(i,{title:"Attended (no notes yet)",list:r.attended_no_notes,color:"bg-violet-500"}),e.jsx(i,{title:"Registered but no-show",list:r.no_show,color:"bg-amber-500"}),e.jsx(i,{title:"Meeting requested",list:r.meeting_requested,color:"bg-pink-500"}),e.jsx(i,{title:"Not yet followed up",list:r.not_followed,color:"bg-rose-500"})]})}var tq={},Wun=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},HSt={},My={};let vDe;const Kun=[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];My.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};My.getSymbolTotalCodewords=function(t){return Kun[t]};My.getBCHDigit=function(s){let t=0;for(;s!==0;)t++,s>>>=1;return t};My.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');vDe=t};My.isKanjiModeEnabled=function(){return typeof vDe<"u"};My.toSJIS=function(t){return vDe(t)};var ybe={};(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}}})(ybe);function GSt(){this.buffer=[],this.length=0}GSt.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 Yun=GSt;function sq(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)}sq.prototype.set=function(s,t,n,r){const a=s*this.size+t;this.data[a]=n,r&&(this.reservedBit[a]=!0)};sq.prototype.get=function(s,t){return this.data[s*this.size+t]};sq.prototype.xor=function(s,t,n){this.data[s*this.size+t]^=n};sq.prototype.isReserved=function(s,t){return this.reservedBit[s*this.size+t]};var Zun=sq,WSt={};(function(s){const t=My.getSymbolSize;s.getRowColCoords=function(r){if(r===1)return[];const a=Math.floor(r/7)+2,i=t(r),l=i===145?26:Math.ceil((i-13)/(2*a-2))*2,o=[i-7];for(let c=1;c=0&&a<=7},s.from=function(a){return s.isValid(a)?parseInt(a,10):void 0},s.getPenaltyN1=function(a){const i=a.size;let l=0,o=0,c=0,d=null,u=null;for(let h=0;h=5&&(l+=t.N1+(o-5)),d=f,o=1),f=a.get(p,h),f===u?c++:(c>=5&&(l+=t.N1+(c-5)),u=f,c=1)}o>=5&&(l+=t.N1+(o-5)),c>=5&&(l+=t.N1+(c-5))}return l},s.getPenaltyN2=function(a){const i=a.size;let l=0;for(let o=0;o=10&&(o===1488||o===93)&&l++,c=c<<1&2047|a.get(u,d),u>=10&&(c===1488||c===93)&&l++}return l*t.N3},s.getPenaltyN4=function(a){let i=0;const l=a.data.length;for(let c=0;c=0;){const l=i[0];for(let c=0;c0){const i=new Uint8Array(this.degree);return i.set(r,a),i}return r};var Xun=bDe,XSt={},xC={},_De={};_De.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var oj={};const JSt="[0-9]+",Jun="[A-Z $%*+\\-./:]+";let M$="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";M$=M$.replace(/u/g,"\\u");const ehn="(?:(?![A-Z0-9 $%*+\\-./:]|"+M$+`)(?:.|[\r ]))+`;oj.KANJI=new RegExp(M$,"g");oj.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");oj.BYTE=new RegExp(ehn,"g");oj.NUMERIC=new RegExp(JSt,"g");oj.ALPHANUMERIC=new RegExp(Jun,"g");const thn=new RegExp("^"+M$+"$"),shn=new RegExp("^"+JSt+"$"),nhn=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");oj.testKanji=function(t){return thn.test(t)};oj.testNumeric=function(t){return shn.test(t)};oj.testAlphanumeric=function(t){return nhn.test(t)};(function(s){const t=_De,n=oj;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}}})(xC);(function(s){const t=My,n=vbe,r=ybe,a=xC,i=_De,l=7973,o=t.getBCHDigit(l);function c(p,f,g){for(let b=1;b<=40;b++)if(f<=s.getCapacity(b,g,p))return b}function d(p,f){return a.getCharCountIndicator(p,f)+4}function u(p,f){let g=0;return p.forEach(function(b){const v=d(b.mode,f);g+=v+b.getBitsLength()}),g}function h(p,f){for(let g=1;g<=40;g++)if(u(p,g)<=s.getCapacity(g,f,a.MIXED))return g}s.from=function(f,g){return i.isValid(f)?parseInt(f,10):g},s.getCapacity=function(f,g,b){if(!i.isValid(f))throw new Error("Invalid QR Code version");typeof b>"u"&&(b=a.BYTE);const v=t.getSymbolTotalCodewords(f),j=n.getTotalCodewordsCount(f,g),_=(v-j)*8;if(b===a.MIXED)return _;const S=_-d(b,f);switch(b){case a.NUMERIC:return Math.floor(S/10*3);case a.ALPHANUMERIC:return Math.floor(S/11*2);case a.KANJI:return Math.floor(S/13);case a.BYTE:default:return Math.floor(S/8)}},s.getBestVersionForData=function(f,g){let b;const v=r.from(g,r.M);if(Array.isArray(f)){if(f.length>1)return h(f,v);if(f.length===0)return 1;b=f[0]}else b=f;return c(b.mode,b.getLength(),v)},s.getEncodedBits=function(f){if(!i.isValid(f)||f<7)throw new Error("Invalid QR Code version");let g=f<<12;for(;t.getBCHDigit(g)-o>=0;)g^=l<=0;)a^=t4t<0&&(r=this.data.substr(n),a=parseInt(r,10),t.put(a,i*3+1))};var ihn=ND;const ohn=xC,Mke=["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 kD(s){this.mode=ohn.ALPHANUMERIC,this.data=s}kD.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};kD.prototype.getLength=function(){return this.data.length};kD.prototype.getBitsLength=function(){return kD.getBitsLength(this.data.length)};kD.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Mke.indexOf(this.data[n])*45;r+=Mke.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(Mke.indexOf(this.data[n]),6)};var lhn=kD;const chn=xC;function SD(s){this.mode=chn.BYTE,typeof s=="string"?this.data=new TextEncoder().encode(s):this.data=new Uint8Array(s)}SD.getBitsLength=function(t){return t*8};SD.prototype.getLength=function(){return this.data.length};SD.prototype.getBitsLength=function(){return SD.getBitsLength(this.data.length)};SD.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 mhn=CD,n4t={exports:{}};(function(s){var t={single_source_shortest_paths:function(n,r,a){var i={},l={};l[r]=0;var o=t.PriorityQueue.make();o.push(r,0);for(var c,d,u,h,p,f,g,b,v;!o.empty();){c=o.pop(),d=c.value,h=c.cost,p=n[d]||{};for(u in p)p.hasOwnProperty(u)&&(f=p[u],g=h+f,b=l[u],v=typeof l[u]>"u",(v||b>g)&&(l[u]=g,o.push(u,g),i[u]=d))}if(typeof a<"u"&&typeof l[a]>"u"){var j=["Could not find a path from ",r," to ",a,"."].join("");throw new Error(j)}return i},extract_shortest_path_from_predecessor_list:function(n,r){for(var a=[],i=r;i;)a.push(i),n[i],i=n[i];return a.reverse(),a},find_path:function(n,r,a){var i=t.single_source_shortest_paths(n,r,a);return t.extract_shortest_path_from_predecessor_list(i,a)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,a={},i;n=n||{};for(i in r)r.hasOwnProperty(i)&&(a[i]=r[i]);return a.queue=[],a.sorter=n.sorter||r.default_sorter,a},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var a={value:n,cost:r};this.queue.push(a),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};s.exports=t})(n4t);var phn=n4t.exports;(function(s){const t=xC,n=ihn,r=lhn,a=dhn,i=mhn,l=oj,o=My,c=phn;function d(j){return unescape(encodeURIComponent(j)).length}function u(j,_,S){const A=[];let T;for(;(T=j.exec(S))!==null;)A.push({data:T[0],index:T.index,mode:_,length:T[0].length});return A}function h(j){const _=u(l.NUMERIC,t.NUMERIC,j),S=u(l.ALPHANUMERIC,t.ALPHANUMERIC,j);let A,T;return o.isKanjiModeEnabled()?(A=u(l.BYTE,t.BYTE,j),T=u(l.KANJI,t.KANJI,j)):(A=u(l.BYTE_KANJI,t.BYTE,j),T=[]),_.concat(S,A,T).sort(function(L,M){return L.index-M.index}).map(function(L){return{data:L.data,mode:L.mode,length:L.length}})}function p(j,_){switch(_){case t.NUMERIC:return n.getBitsLength(j);case t.ALPHANUMERIC:return r.getBitsLength(j);case t.KANJI:return i.getBitsLength(j);case t.BYTE:return a.getBitsLength(j)}}function f(j){return j.reduce(function(_,S){const A=_.length-1>=0?_[_.length-1]:null;return A&&A.mode===S.mode?(_[_.length-1].data+=S.data,_):(_.push(S),_)},[])}function g(j){const _=[];for(let S=0;S=0&&o<=6&&(c===0||c===6)||c>=0&&c<=6&&(o===0||o===6)||o>=2&&o<=4&&c>=2&&c<=4?s.set(i+o,l+c,!0,!0):s.set(i+o,l+c,!1,!0))}}function jhn(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 Lke(s,t,n){const r=s.size,a=bhn.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 Shn(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 Chn(s,t,n){const r=new fhn;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),_hn.getCharCountIndicator(c.mode,s)),c.write(r)});const a=_be.getSymbolTotalCodewords(s),i=oEe.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&&khn(c,t),Shn(c,l),isNaN(r)&&(r=iEe.getBestMask(c,Lke.bind(null,c,n))),iEe.applyMask(r,c),Lke(c,n,r),{modules:c,version:t,errorCorrectionLevel:n,maskPattern:r,segments:a}}HSt.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=Ike.M,a,i;return typeof n<"u"&&(r=Ike.from(n.errorCorrectionLevel,Ike.M),a=u0e.from(n.version),i=iEe.from(n.maskPattern),n.toSJISFunc&&_be.setToSJISFunction(n.toSJISFunc)),Ehn(t,a,r,i)};var r4t={},wDe={};(function(s){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(i){return[i,i]}))),r.length===6&&r.push("F","F");const a=parseInt(r.join(""),16);return{r:a>>24&255,g:a>>16&255,b:a>>8&255,a:a&255,hex:"#"+r.slice(0,6).join("")}}s.getOptions=function(r){r||(r={}),r.color||(r.color={});const a=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,i=r.width&&r.width>=21?r.width:void 0,l=r.scale||4;return{width:i,scale:i?4:l,margin:a,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},s.getScale=function(r,a){return a.width&&a.width>=r+a.margin*2?a.width/(r+a.margin*2):a.scale},s.getImageWidth=function(r,a){const i=s.getScale(r,a);return Math.floor((r+a.margin*2)*i)},s.qrToImageData=function(r,a,i){const l=a.modules.size,o=a.modules.data,c=s.getScale(l,i),d=Math.floor((l+i.margin*2)*c),u=i.margin*c,h=[i.color.light,i.color.dark];for(let p=0;p=u&&f>=u&&p"u"&&(!l||!l.getContext)&&(c=l,l=void 0),l||(d=r()),c=t.getOptions(c);const u=t.getImageWidth(i.modules.size,c),h=d.getContext("2d"),p=h.createImageData(u,u);return t.qrToImageData(p.data,i,c),n(h,d,u),h.putImageData(p,0,0),d},s.renderToDataURL=function(i,l,o){let c=o;typeof c>"u"&&(!l||!l.getContext)&&(c=l,l=void 0),c||(c={});const d=s.render(i,l,c),u=c.type||"image/png",h=c.rendererOpts||{};return d.toDataURL(u,h.quality)}})(r4t);var a4t={};const Ahn=wDe;function Vet(s,t){const n=s.a/255,r=t+'="'+s.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Dke(s,t,n){let r=s+t;return typeof n<"u"&&(r+=" "+n),r}function Mhn(s,t,n){let r="",a=0,i=!1,l=0;for(let o=0;o0&&c>0&&s[o-1]||(r+=i?Dke("M",c+n,.5+d+n):Dke("m",a,0),a=0,i=!1),c+1':"",d="',u='viewBox="0 0 '+o+" "+o+'"',p=''+c+d+` `;return typeof r=="function"&&r(null,p),p};const Ihn=Wun,lEe=HSt,i4t=r4t,Phn=a4t;function jDe(s,t,n,r,a){const i=[].slice.call(arguments,1),l=i.length,o=typeof i[l-1]=="function";if(!o&&!Ihn())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=lEe.create(n,r);c(s(u,t,r))}catch(u){d(u)}})}try{const c=lEe.create(n,r);a(null,s(c,t,r))}catch(c){a(c)}}tq.create=lEe.create;tq.toCanvas=jDe.bind(null,i4t.render);tq.toDataURL=jDe.bind(null,i4t.renderToDataURL);tq.toString=jDe.bind(null,function(s,t,n){return Phn.render(s,n)});function Lhn(){const{eventId:s}=_i(),t=In(),{data:n}=gDe(s),{data:r=[]}=ISt(s),a=RSt(),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),f=n!=null&&n.public_slug?gbe(n.public_slug):"";N.useEffect(()=>{f&&tq.toDataURL(f,{width:320,margin:1}).then(p).catch(()=>{})},[f]);const g=N.useMemo(()=>i?r.filter(j=>(j.guest_name||"").toLowerCase().includes(i.toLowerCase())||(j.guest_email||"").toLowerCase().includes(i.toLowerCase())):r,[r,i]),b=j=>{a.mutate({id:j.id,event_id:s,status:"attended",checked_in_at:new Date().toISOString()}),ae.success(`${j.guest_name||"Guest"} checked in`)},v=()=>{o&&(a.mutate({event_id:s,guest_name:o,guest_email:d||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),c(""),u(""),ae.success("Walk-in checked in"))};return n?e.jsx("div",{className:"min-h-screen bg-slate-50",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full mb-3",onClick:()=>t(`/attract/events/${s}`),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Back to event"]}),e.jsxs(fe,{className:"p-5 rounded-2xl bg-gradient-to-br from-slate-900 to-slate-800 text-white border-0",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-white/60",children:"Check-in mode"}),e.jsx("div",{className:"text-xl font-semibold mt-1",children:n.title}),e.jsxs("div",{className:"text-white/70 text-[13px] mt-0.5",children:[n.registration_count," registered · ",n.attendance_count," checked in"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-semibold text-slate-900",children:[e.jsx(ly,{className:"h-4 w-4"})," Registration QR"]}),h?e.jsx("img",{src:h,alt:"QR code",className:"mx-auto mt-3 h-56 w-56"}):e.jsx("div",{className:"text-[12px] text-slate-400 mt-3",children:"Publish this event to generate a QR code."}),f&&e.jsx("div",{className:"text-[11px] font-mono text-center text-slate-500 mt-2 break-all",children:f})]}),e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900 mb-3",children:"Add walk-in"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{placeholder:"Name",value:o,onChange:j=>c(j.target.value)}),e.jsx(ge,{placeholder:"Email (optional)",value:d,onChange:j=>u(j.target.value)}),e.jsxs(B,{className:"w-full rounded-full",onClick:v,children:[e.jsx(Fo,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]})]}),e.jsxs(fe,{className:"mt-4 rounded-2xl border-slate-200 bg-white overflow-hidden",children:[e.jsxs("div",{className:"p-3 border-b border-slate-100 relative",children:[e.jsx(_r,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ge,{placeholder:"Search attendees",value:i,onChange:j=>l(j.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(j=>{const _=j.status==="attended";return e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 truncate",children:j.guest_name||j.guest_email}),e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:j.guest_email})]}),_?e.jsxs(ze,{className:"bg-emerald-500",children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"})," Checked in"]}):e.jsxs(B,{size:"lg",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b(j),children:[e.jsx(Lr,{className:"h-5 w-5 mr-2"})," Check in"]})]},j.id)})})]})]})}):e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"})}const Dhn=["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"],Rhn=["Lead generation","Database marketing","Listing marketing","Social media/video","Open houses","Negotiation","Systems and technology","Team building","Leadership","New construction","Luxury","Business planning"],Het=[{key:"produce",icon:vo,title:"Produce",blurb:"Attract through visible production and excellence.",example:"Publish weekly market updates, share every closing story with the lesson attached."},{key:"influence",icon:un,title:"Influence",blurb:"Teach publicly and earn a following of agents.",example:"Host a monthly masterclass. Post 3 authority pieces a week."},{key:"provide",icon:AA,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:mb,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:tN,title:"Balanced Plan",blurb:"A little of all four. Best for veteran attractors.",example:"Rotate weekly focus between production, teaching, providing, and connecting."}],Ohn=[{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"}],Get=["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 Wet(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 Fhn(){const s=In(),{settings:t,save:n}=JU(),[r,a]=N.useState(0),[i,l]=N.useState([]),[o,c]=N.useState([]),[d,u]=N.useState(null),[h,p]=N.useState({}),[f,g]=N.useState("");N.useEffect(()=>{var S,A;t&&((S=t.audiences)!=null&&S.length&&l(t.audiences),(A=t.teachables)!=null&&A.length&&c(t.teachables),t.attraction_style&&u(t.attraction_style),t.activity_baseline&&p(t.activity_baseline),t.ninety_day_outcome&&g(t.ninety_day_outcome))},[t==null?void 0:t.user_id]);const b=["Welcome","Audience","Teach","Style","Baseline","Outcome","Plan"],v=N.useMemo(()=>r===1?i.length>0:r===2?o.length>0:r===3?!!d:r===5?!!f:!0,[r,i,o,d,f]),j=(S,A,T)=>{T(S.includes(A)?S.filter(D=>D!==A):[...S,A])},_=async()=>{if(!d)return;const S=Wet({style:d,baseline:h,outcome:f});await n.mutateAsync({audiences:i,teachables:o,attraction_style:d,activity_baseline:h,ninety_day_outcome:f,ninety_day_plan:S,primary_pillar:d,onboarding_completed_at:new Date().toISOString()}),ae.success("Your 90-day plan is ready."),s("/attract")};return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("div",{className:"flex items-center gap-2 mb-8",children:b.map((S,A)=>e.jsx("div",{className:Et("h-1.5 flex-1 rounded-full transition-colors",A<=r?"bg-violet-600":"bg-slate-200")},S))}),e.jsx(Pye,{mode:"wait",children:e.jsxs(Zn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.25},children:[r===0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"A strategy session"}),e.jsx("h1",{className:"text-4xl md:text-5xl font-semibold tracking-tight text-slate-900",children:"Build an attraction business people want to be part of."}),e.jsx("p",{className:"text-slate-600 mt-4 text-lg leading-relaxed",children:"Attract isn't a recruiting funnel. It's a way of doing business where the right agents naturally find you — because you produce, teach, provide, and connect at a rhythm no one else in your market keeps."}),e.jsx("div",{className:"mt-8 grid grid-cols-2 md:grid-cols-4 gap-3",children:Het.filter(S=>S.key!=="balanced").map(S=>e.jsxs(fe,{className:"p-4 rounded-2xl border-slate-200",children:[e.jsx(S.icon,{className:"h-5 w-5 text-violet-600 mb-2"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:S.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:S.blurb})]},S.key))})]}),r===1&&e.jsx(e7,{icon:_n,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:Dhn.map(S=>e.jsx(Rke,{label:S,active:i.includes(S),onClick:()=>j(i,S,l)},S))})}),r===2&&e.jsx(e7,{icon:_d,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:Rhn.map(S=>e.jsx(Rke,{label:S,active:o.includes(S),onClick:()=>j(o,S,c)},S))})}),r===3&&e.jsx(e7,{icon:tN,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:Het.map(S=>e.jsx(fe,{onClick:()=>u(S.key),className:Et("p-5 rounded-2xl cursor-pointer transition-all border-2",d===S.key?"border-violet-600 bg-violet-50/70 shadow-md":"border-slate-200 hover:border-violet-300"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-violet-100 text-violet-700 grid place-items-center",children:e.jsx(S.icon,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:S.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:S.blurb}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 italic mt-2",children:["Example: ",S.example]})]}),d===S.key&&e.jsx(Lr,{className:"h-5 w-5 text-violet-600"})]})},S.key))})}),r===4&&e.jsx(e7,{icon:am,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:Ohn.map(S=>e.jsxs("div",{children:[e.jsx(se,{className:"text-[12.5px] text-slate-700",children:S.label}),e.jsx(ge,{type:"number",min:0,value:h[S.key]??"",onChange:A=>p({...h,[S.key]:Number(A.target.value)||0})})]},S.key))})}),r===5&&e.jsx(e7,{icon:wc,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:[Get.map(S=>e.jsx(Rke,{label:S,active:f===S,onClick:()=>g(S),full:!0},S)),e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{className:"text-[12.5px] text-slate-700",children:"Or write your own"}),e.jsx(Ts,{rows:2,placeholder:"A specific outcome you can measure in 90 days...",value:Get.includes(f)?"":f,onChange:S=>g(S.target.value)})]})]})}),r===6&&d&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Your plan"}),e.jsx("h2",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"You're ready. Here's your 90-day plan."}),e.jsx(o4t,{plan:Wet({style:d,baseline:h,outcome:f})})]})]},r)}),e.jsxs("div",{className:"mt-10 flex items-center justify-between",children:[e.jsxs(B,{variant:"ghost",onClick:()=>r===0?s("/attract"):a(r-1),children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"})," ",r===0?"Skip for now":"Back"]}),r<6?e.jsxs(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",disabled:!v,onClick:()=>a(r+1),children:["Continue ",e.jsx(za,{className:"h-4 w-4 ml-1"})]}):e.jsxs(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",onClick:_,disabled:n.isPending,children:[e.jsx(nx,{className:"h-4 w-4 mr-1.5"})," Activate my 90-day plan"]})]})]})}function e7({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 Rke({label:s,active:t,onClick:n,full:r}){return e.jsx("button",{type:"button",onClick:n,className:Et("text-left rounded-xl border px-4 py-3 text-[13.5px] transition-colors",r?"w-full":"",t?"border-violet-600 bg-violet-50 text-violet-900 shadow-sm":"border-slate-200 bg-white hover:border-violet-300 text-slate-800"),children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t&&e.jsx(Lr,{className:"h-4 w-4 text-violet-600"})," ",s]})})}function o4t({plan:s}){return e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs(fe,{className:"p-6 rounded-2xl bg-gradient-to-br from-violet-600 to-indigo-700 text-white border-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] opacity-80",children:"Primary focus"}),e.jsx("div",{className:"text-3xl font-semibold mt-1 capitalize",children:s.primary_pillar}),e.jsx("div",{className:"text-white/85 mt-2",children:s.content_rhythm}),e.jsxs("div",{className:"text-[13px] mt-4 rounded-xl bg-white/10 p-3",children:[e.jsx("span",{className:"opacity-80",children:"90-day outcome:"})," ",s.outcome]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Weekly targets"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(s.weekly_targets).map(([t,n])=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900 tabular-nums",children:n}),e.jsx("div",{className:"text-[11.5px] text-slate-500 capitalize mt-0.5",children:t.replace(/_/g," ")})]},t))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"First 7 days"}),e.jsx(fe,{className:"p-5 rounded-2xl",children:e.jsx("ul",{className:"space-y-2",children:s.first_7_days.map((t,n)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-[13.5px] text-slate-800",children:[e.jsx("div",{className:"h-5 w-5 rounded-full bg-violet-100 text-violet-700 grid place-items-center text-[11px] font-semibold flex-shrink-0 mt-0.5",children:n+1}),t]},n))})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Recommended first tool"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.suggested_tool})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Suggested first offer"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.suggested_offer})]})]})]})}function zhn(){const{settings:s,resetOnboarding:t}=JU(),n=s==null?void 0:s.ninety_day_plan;return e.jsxs("div",{className:"max-w-4xl",children:[e.jsx(Ku,{eyebrow:"90-Day Plan",title:"Your personalized attraction plan.",description:"Generated from your onboarding responses. Adjust any time by rerunning onboarding.",actions:e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>t.mutate(),children:[e.jsx(Fh,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})}),n?e.jsx(o4t,{plan:n}):e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("p",{className:"text-slate-700 mb-4",children:"You haven't set up your 90-day plan yet."}),e.jsx(B,{asChild:!0,className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",children:e.jsx(Ln,{to:"/attract/onboarding",children:"Start onboarding"})})]})]})}async function Ket(s,t,n,r={}){await q.rpc("award_attract_activity",{_user_id:s,_activity_type:t,_title:n,_description:r.description??null,_pillar:r.pillar??null,_agent_id:r.agent_id??null,_metadata:r.metadata??{},_dedupe_minutes:30})}function l4t(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:["attract-transactions",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_transactions").select("*").order("closing_date",{ascending:!1,nullsFirst:!1});if(c)throw c;return o??[]}}),r=gt({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,b)=>g+b,0)/c.length).toFixed(2)):null,u={...o,user_id:s.id,overall_rating:d},{data:h,error:p}=o.id?await q.from("attract_transactions").update(u).eq("id",o.id).select().single():await q.from("attract_transactions").insert(u).select().single();if(p)throw p;const f=h;return o.id||await Ket(s.id,"transaction_logged",`Reviewed ${f.property_address}`,{description:f.cooperating_first_name?`Cooperating agent: ${f.cooperating_first_name} ${f.cooperating_last_name??""}`:null,pillar:"produce",metadata:{transaction_id:f.id,overall_rating:d}}),f},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Transaction saved")},onError:o=>ae.error(o.message)}),a=gt({mutationFn:async({id:o,decision:c,notes:d})=>{const{data:u,error:h}=await q.from("attract_transactions").update({decision:c,decision_notes:d??null}).eq("id",o).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]})}}),i=gt({mutationFn:async o=>{let c=o.attract_agent_id;if(!c){const{data:d}=await q.from("attract_agents").select("id").eq("user_id",s.id).eq("first_name",o.cooperating_first_name??"").eq("last_name",o.cooperating_last_name??"").maybeSingle();if(d!=null&&d.id)c=d.id;else{const{data:u,error:h}=await q.from("attract_agents").insert({user_id:s.id,first_name:o.cooperating_first_name??"Unknown",last_name:o.cooperating_last_name,email:o.cooperating_email,phone:o.cooperating_phone,brokerage:o.cooperating_brokerage,source:"cooperating_transaction",stage:"new_connection",temperature:o.enjoy_business_with==="yes"?"warm":"cold",notes:o.stood_out}).select("id").single();if(h)throw h;c=u.id}}return await q.from("attract_transactions").update({attract_agent_id:c,decision:"add_pipeline"}).eq("id",o.id),await Ket(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=gt({mutationFn:async o=>{const{error:c}=await q.from("attract_transactions").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),ae.success("Transaction removed")}});return{transactions:n.data??[],isLoading:n.isLoading,upsert:r,setDecision:a,addToPipeline:i,remove:l}}function Bhn({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(ua,{className:Et("h-5 w-5",(s??0)>=n?"fill-amber-400 text-amber-400":"text-slate-300")})},n))})}function $hn(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 Uhn={1:"Poor",2:"Fair",3:"OK",4:"Good",5:"Excellent"},Oke={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 qhn(){const{transactions:s,isLoading:t,upsert:n,setDecision:r,addToPipeline:a,remove:i}=l4t(),[l,o]=N.useState(""),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(null),g=N.useMemo(()=>{const v=l.trim().toLowerCase();return v?s.filter(j=>[j.property_address,j.cooperating_first_name,j.cooperating_last_name,j.cooperating_brokerage,j.city].filter(Boolean).some(_=>String(_).toLowerCase().includes(v))):s},[s,l]),b=N.useMemo(()=>{const v=s.length,j=s.filter(A=>A.enjoy_business_with==="yes").length,_=s.filter(A=>A.decision==="add_pipeline").length,S=s.filter(A=>A.follow_up_created).length;return{reviewed:v,highFit:j,inPipeline:_,followUps:S}},[s]);return e.jsxs("div",{children:[e.jsxs(Ln,{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(Wr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Ku,{eyebrow:"Produce → Tool",title:"Transaction-to-Relationship Tracker",description:"Every good cooperating agent is a future relationship. Log the transaction, note what stood out, and turn the best experiences into real professional friendships.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>d(!0),children:[e.jsx(As,{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(rW,{label:"Transactions reviewed",value:b.reviewed}),e.jsx(rW,{label:"High-fit agents",value:b.highFit,tone:"emerald"}),e.jsx(rW,{label:"Added to pipeline",value:b.inPipeline,tone:"violet"}),e.jsx(rW,{label:"Follow-ups created",value:b.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(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ge,{value:l,onChange:v=>o(v.target.value),placeholder:"Search property, agent, brokerage...",className:"pl-9 rounded-full"})]})}),t?e.jsx("div",{className:"space-y-3",children:[0,1,2].map(v=>e.jsx(fe,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},v))}):g.length===0?e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx("div",{className:"h-14 w-14 rounded-2xl bg-violet-100 grid place-items-center mx-auto mb-4",children:e.jsx(un,{className:"h-6 w-6 text-violet-700"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Turn transactions into relationships"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 max-w-md mx-auto mt-2",children:"Add your last 5 closed transactions to spot the agents you'd love to be in business with — then send a thoughtful compliment that opens the door."}),e.jsxs(B,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>d(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Add your first transaction"]})]}):e.jsx("div",{className:"space-y-3",children:g.map(v=>{var j,_;return e.jsx(fe,{className:"p-5 rounded-2xl hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900 truncate",children:v.property_address}),v.closing_date&&e.jsx(ze,{variant:"outline",className:"text-[10.5px]",children:ks(new Date(v.closing_date),"MMM d, yyyy")}),e.jsx(ze,{className:Et("text-[10.5px] border-0",((j=Oke[v.decision])==null?void 0:j.color)??Oke.pending.color),children:((_=Oke[v.decision])==null?void 0:_.label)??"Needs review"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1",children:[v.cooperating_first_name||v.cooperating_last_name?`${v.cooperating_first_name??""} ${v.cooperating_last_name??""}`:"Cooperating agent",v.cooperating_brokerage?` · ${v.cooperating_brokerage}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[12px] text-slate-600",children:[v.overall_rating!=null&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ua,{className:"h-3.5 w-3.5 fill-amber-400 text-amber-400"})," ",v.overall_rating]}),v.enjoy_business_with&&e.jsxs("span",{className:"capitalize",children:["Fit: ",e.jsx("span",{className:Et("font-medium",v.enjoy_business_with==="yes"?"text-emerald-700":v.enjoy_business_with==="maybe"?"text-amber-700":"text-slate-600"),children:v.enjoy_business_with})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>h(v),children:["Review ",e.jsx(ga,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>f(v),children:[e.jsx(mL,{className:"h-3.5 w-3.5 mr-1"})," Message"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600 hover:text-rose-700",onClick:()=>i.mutate(v.id),children:"Remove"})]})]})},v.id)})}),e.jsx("div",{className:"mt-8",children:e.jsx(f6,{})}),e.jsx(Vhn,{open:c,onClose:()=>d(!1),onSaved:v=>{d(!1),h(v)},upsert:n}),e.jsx(Hhn,{tx:u,onClose:()=>h(null),onDecision:v=>u&&r.mutate({id:u.id,decision:v}),onAddToPipeline:()=>u&&a.mutate(u),onMessage:()=>{f(u),h(null)}}),e.jsx(Ghn,{tx:p,onClose:()=>f(null)})]})}function rW({label:s,value:t,tone:n="slate"}){const r={slate:"text-slate-900",emerald:"text-emerald-700",violet:"text-violet-700",amber:"text-amber-700"};return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:Et("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 Vhn({open:s,onClose:t,onSaved:n,upsert:r}){const[a,i]=N.useState({enjoy_business_with:"maybe"}),l=c=>i({...a,...c}),o=async()=>{var d;if(!((d=a.property_address)!=null&&d.trim())){ae.error("Property address is required");return}const c=await r.mutateAsync(a);i({enjoy_business_with:"maybe"}),n(c)};return e.jsx(bs,{open:s,onOpenChange:c=>!c&&t(),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add Transaction"}),e.jsx(Qn,{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(se,{children:"Property address *"}),e.jsx(ge,{value:a.property_address??"",onChange:c=>l({property_address:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"City"}),e.jsx(ge,{value:a.city??"",onChange:c=>l({city:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(ge,{value:a.state??"",onChange:c=>l({state:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Closing date"}),e.jsx(ge,{type:"date",value:a.closing_date??"",onChange:c=>l({closing_date:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"You represented"}),e.jsxs(us,{value:a.represented??"",onValueChange:c=>l({represented:c}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Buyer or seller"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"}),e.jsx(Ze,{value:"both",children:"Both"}),e.jsx(Ze,{value:"other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Cooperating agent"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"First name"}),e.jsx(ge,{value:a.cooperating_first_name??"",onChange:c=>l({cooperating_first_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last name"}),e.jsx(ge,{value:a.cooperating_last_name??"",onChange:c=>l({cooperating_last_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ge,{type:"email",value:a.cooperating_email??"",onChange:c=>l({cooperating_email:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ge,{value:a.cooperating_phone??"",onChange:c=>l({cooperating_phone:c.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(ge,{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(se,{children:d}),e.jsx(Bhn,{value:a[c],onChange:u=>l({[c]:u})}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-1",children:Uhn[a[c]]??"—"})]},c))}),e.jsxs("div",{className:"mt-4",children:[e.jsx(se,{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:Et("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(se,{children:"What stood out?"}),e.jsx(Ts,{rows:2,value:a.stood_out??"",onChange:c=>l({stood_out:c.target.value})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(se,{children:"Private notes"}),e.jsx(Ts,{rows:2,value:a.private_notes??"",onChange:c=>l({private_notes:c.target.value}),placeholder:"Only you can see these."})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:o,disabled:r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save & review"})]})]})})}function Hhn({tx:s,onClose:t,onDecision:n,onAddToPipeline:r,onMessage:a}){return s?e.jsx(bs,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Would you like to build a relationship?"}),e.jsxs(Qn,{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(t7,{icon:Fo,label:"Add to Agent Pipeline",tone:"violet",onClick:r}),e.jsx(t7,{icon:mL,label:"Send a professional compliment",tone:"teal",onClick:()=>{n("send_compliment"),a()}}),e.jsx(t7,{icon:ry,label:"Invite to coffee",tone:"amber",onClick:()=>{n("invite_coffee"),a()}}),e.jsx(t7,{icon:un,label:"Share a relevant resource",tone:"sky",onClick:()=>n("share_resource")}),e.jsx(t7,{icon:Gc,label:"No action right now",tone:"slate",onClick:()=>{n("no_action"),t()}})]})]})}):null}function t7({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:Et("flex items-center gap-3 rounded-xl px-4 py-3 text-left transition-colors",a[n]),children:[e.jsx(s,{className:"h-5 w-5"}),e.jsx("div",{className:"flex-1 text-[13.5px] font-medium",children:t}),e.jsx(ga,{className:"h-4 w-4 opacity-60"})]})}function Ghn({tx:s,onClose:t}){const[n,r]=N.useState("warm");if(!s)return null;const a=$hn(s,n);return e.jsx(bs,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Personalized message"}),e.jsx(Qn,{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:Et("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(Ts,{value:a,readOnly:!0,rows:10,className:"font-mono text-[12.5px]"}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:t,children:"Close"}),e.jsxs(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{navigator.clipboard.writeText(a),ae.success("Copied to clipboard")},children:[e.jsx(ta,{className:"h-4 w-4 mr-1.5"})," Copy"]})]})]})})}function c4t(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:["attract-content",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_content_drafts").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=gt({mutationFn:async o=>{const{data:c,error:d}=await q.functions.invoke("attract-content-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(c.error);return c},onSuccess:o=>{t.invalidateQueries({queryKey:["attract-content"]}),o.demo?ae.info("Demo generation used — configure AI provider for live results"):ae.success("Content generated")},onError:o=>ae.error(o.message)}),a=gt({mutationFn:async o=>{const{data:c,error:d}=await q.from("attract_content_drafts").update(o).eq("id",o.id).select().single();if(d)throw d;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ae.success("Saved")}}),i=gt({mutationFn:async o=>{const{error:c}=await q.from("attract_content_drafts").update({status:"posted",posted_at:new Date().toISOString()}).eq("id",o);if(c)throw c;await q.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"content_posted",_title:"Posted authority content",_description:null,_pillar:"influence",_agent_id:null,_metadata:{draft_id:o},_dedupe_minutes:30})},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Marked as posted")}}),l=gt({mutationFn:async o=>{const{error:c}=await q.from("attract_content_drafts").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ae.success("Draft removed")}});return{drafts:n.data??[],isLoading:n.isLoading,generate:r,save:a,markPosted:i,remove:l}}const cEe=[{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"}]}],Whn=["Direct","Educational","Fun","Contrarian","Encouraging"],Khn=["short","medium","long"],Yhn=["instagram","linkedin","facebook","youtube","email"],h0e={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 Zhn(){const{drafts:s,isLoading:t,generate:n,save:r,markPosted:a,remove:i}=c4t(),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useMemo(()=>({ready:s.filter(h=>h.status==="ready"),draft:s.filter(h=>h.status==="draft"),idea:s.filter(h=>h.status==="idea"),posted:s.filter(h=>h.status==="posted")}),[s]);return e.jsxs("div",{children:[e.jsxs(Ln,{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(Wr,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(Ku,{eyebrow:"Influence → Tool",title:"Authority Content Studio",description:"Turn your real experience into agent-focused content that builds authority — without sounding like a brokerage pitch.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{d(null),o(!0)},children:[e.jsx(Rm,{className:"h-4 w-4 mr-1.5"})," New Content"]})}),e.jsxs("div",{className:"mb-6 rounded-2xl border border-amber-200 bg-amber-50/70 px-5 py-3.5 text-[13px] text-amber-900 flex items-start gap-3",children:[e.jsx(un,{className:"h-4 w-4 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"80/20 rule:"})," Aim for 80% useful industry, business, and personal content — and no more than 20% direct brokerage content."]})]}),e.jsxs($r,{defaultValue:"all",className:"mb-8",children:[e.jsxs(Ur,{children:[e.jsxs(Zt,{value:"all",children:["All (",s.length,")"]}),e.jsxs(Zt,{value:"ready",children:["Ready (",u.ready.length,")"]}),e.jsxs(Zt,{value:"draft",children:["Draft (",u.draft.length,")"]}),e.jsxs(Zt,{value:"posted",children:["Posted (",u.posted.length,")"]})]}),e.jsx(ls,{value:"all",children:e.jsx(aW,{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(ls,{value:"ready",children:e.jsx(aW,{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(ls,{value:"draft",children:e.jsx(aW,{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(ls,{value:"posted",children:e.jsx(aW,{drafts:u.posted,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:()=>{},onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})})]}),e.jsx(f6,{}),e.jsx(Qhn,{open:l,editing:c,onClose:()=>{o(!1),d(null)},generate:n,save:r,markPosted:h=>a.mutate(h)})]})}function aW({drafts:s,isLoading:t,onOpen:n,onPosted:r,onRemove:a,onEmpty:i}){return t?e.jsx("div",{className:"space-y-3 mt-4",children:[0,1,2].map(l=>e.jsx(fe,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},l))}):s.length===0?e.jsxs(fe,{className:"p-10 rounded-2xl text-center mt-4",children:[e.jsx("div",{className:"h-14 w-14 rounded-2xl bg-violet-100 grid place-items-center mx-auto mb-4",children:e.jsx(nb,{className:"h-6 w-6 text-violet-700"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Start your first authority piece"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 max-w-md mx-auto mt-2",children:"Pick a real experience, answer 3 quick questions, and get a script, caption, carousel outline, and email — all in one shot."}),e.jsxs(B,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:i,children:[e.jsx(As,{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=cEe.find(u=>u.key===l.mode))==null?void 0:c.label)??l.mode;return e.jsx(fe,{className:"p-5 rounded-2xl hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(ze,{className:Et("text-[10.5px] border-0",h0e[l.status].color),children:h0e[l.status].label}),e.jsx(ze,{variant:"outline",className:"text-[10.5px]",children:o}),l.tone&&e.jsx(ze,{variant:"outline",className:"text-[10.5px]",children:l.tone}),l.ratio_flag&&e.jsxs(ze,{className:"text-[10.5px] bg-amber-100 text-amber-900 border-0 gap-1",children:[e.jsx(Dl,{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 ${ks(new Date(l.posted_at),"MMM d")}`:`Updated ${ks(new Date(l.updated_at),"MMM d")}`})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>n(l),children:"Open"}),l.status!=="posted"&&e.jsxs(B,{size:"sm",variant:"ghost",className:"text-emerald-700",onClick:()=>r(l.id),children:[e.jsx(Lr,{className:"h-3.5 w-3.5 mr-1"})," Posted"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(l.id),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})},l.id)})})}function Qhn({open:s,editing:t,onClose:n,generate:r,save:a,markPosted:i}){const[l,o]=N.useState((t==null?void 0:t.mode)??"transaction_lesson"),[c,d]=N.useState((t==null?void 0:t.input_json)??{}),[u,h]=N.useState((t==null?void 0:t.topic)??""),[p,f]=N.useState((t==null?void 0:t.tone)??"Educational"),[g,b]=N.useState((t==null?void 0:t.length)??"medium"),[v,j]=N.useState((t==null?void 0:t.platforms)??["instagram"]),[_,S]=N.useState((t==null?void 0:t.include_brokerage_reference)??!1),[A,T]=N.useState(t??null),[D,L]=N.useState(""),[M,F]=N.useState((t==null?void 0:t.status)??"draft"),z=cEe.find(K=>K.key===l),V=async K=>{const Y=await r.mutateAsync({mode:l,topic:u,inputs:c,tone:p,length:g,platforms:v,include_brokerage_reference:_,refinement:K??D,draft_id:A==null?void 0:A.id});Y!=null&&Y.draft&&T(Y.draft),L("")},W=async K=>{if(!A)return;const Y=await a.mutateAsync({id:A.id,...K});T(Y)};return e.jsx(bs,{open:s,onOpenChange:K=>!K&&n(),children:e.jsx(vs,{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(ws,{children:[e.jsx(_s,{className:"text-base",children:"Content Studio"}),e.jsx(Qn,{className:"text-[12px]",children:z.blurb})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Content mode"}),e.jsxs(us,{value:l,onValueChange:K=>{o(K),d({})},children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:cEe.map(K=>e.jsx(Ze,{value:K.key,children:K.label},K.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Topic (optional)"}),e.jsx(ge,{value:u,onChange:K=>h(K.target.value),placeholder:"1-line summary"})]}),z.fields.map(K=>e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:K.label}),e.jsx(Ts,{rows:2,value:c[K.key]??"",onChange:Y=>d({...c,[K.key]:Y.target.value}),placeholder:K.placeholder})]},K.key)),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Tone"}),e.jsxs(us,{value:p,onValueChange:f,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:Whn.map(K=>e.jsx(Ze,{value:K,children:K},K))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Length"}),e.jsxs(us,{value:g,onValueChange:b,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:Khn.map(K=>e.jsx(Ze,{value:K,children:K},K))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Platforms"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:Yhn.map(K=>e.jsx("button",{type:"button",onClick:()=>j(v.includes(K)?v.filter(Y=>Y!==K):[...v,K]),className:Et("rounded-full px-2.5 py-1 text-[11px] capitalize border",v.includes(K)?"bg-violet-600 text-white border-violet-600":"bg-white border-slate-200 text-slate-700"),children:K},K))})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:_,onChange:K=>S(K.target.checked)}),"Include a light brokerage reference"]}),e.jsxs(B,{className:"w-full bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",onClick:()=>V(),disabled:r.isPending,children:[e.jsx(Rm,{className:"h-4 w-4 mr-1.5"})," ",r.isPending?"Generating…":A?"Regenerate":"Generate content"]})]})]}),e.jsx("div",{className:"overflow-y-auto p-6",children:A?e.jsxs("div",{className:"space-y-5",children:[A.ratio_flag&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-[12.5px] text-amber-900 flex items-start gap-2",children:[e.jsx(Dl,{className:"h-4 w-4 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold",children:"Heads up — this leans promotional."}),e.jsx("div",{children:"Not blocking anything, but you can rewrite it to feel more like teaching."})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>V("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(ze,{className:Et("text-[10.5px] border-0",h0e[M].color),children:h0e[M].label}),e.jsxs(us,{value:M,onValueChange:K=>{F(K),W({status:K})},children:[e.jsx(cs,{className:"h-8 w-32 text-[12px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"idea",children:"Idea"}),e.jsx(Ze,{value:"draft",children:"Draft"}),e.jsx(Ze,{value:"ready",children:"Ready"}),e.jsx(Ze,{value:"posted",children:"Posted"})]})]}),e.jsx(ge,{type:"date",className:"h-8 w-40 text-[12px]",value:A.planned_at?A.planned_at.slice(0,10):"",onChange:K=>W({planned_at:K.target.value?new Date(K.target.value).toISOString():null})}),A.status!=="posted"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>i(A.id),children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-1"})," Mark posted"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Ln,{to:`/attract/provide/kits/new?seed=${encodeURIComponent(A.topic||A.mode)}`,children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"})," Turn into a kit"]})})]}),e.jsx(eP,{title:"Hook options",children:e.jsx("div",{className:"space-y-1.5",children:(A.hook_options??[]).map((K,Y)=>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:[Y+1,"."]}),e.jsx("span",{className:"flex-1",children:K}),e.jsx(dEe,{value:K})]},Y))})}),e.jsx(eP,{title:"Teleprompter script",children:e.jsx(Fke,{value:A.script??"",onSave:K=>W({script:K})})}),e.jsx(eP,{title:"Social caption",children:e.jsx(Fke,{value:A.caption??"",onSave:K=>W({caption:K})})}),e.jsx(eP,{title:"Carousel outline",children:e.jsx("div",{className:"space-y-1.5",children:(A.carousel_outline??[]).map((K,Y)=>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 ",K.slide??Y+1]}),e.jsx("div",{className:"text-slate-800 mt-0.5",children:K.text})]},Y))})}),e.jsx(eP,{title:"Email lesson",children:e.jsx(Fke,{value:A.email_lesson??"",onSave:K=>W({email_lesson:K})})}),e.jsx(eP,{title:"CTA options",children:e.jsx("div",{className:"space-y-1.5",children:(A.cta_options??[]).map((K,Y)=>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:K}),e.jsx(dEe,{value:K})]},Y))})}),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(K=>e.jsx(B,{size:"sm",variant:"outline",className:"text-[11.5px]",onClick:()=>V(K),children:K},K))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:D,onChange:K=>L(K.target.value),placeholder:"Custom refinement…"}),e.jsxs(B,{variant:"outline",onClick:()=>V(),disabled:r.isPending,children:[e.jsx(Ai,{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(C9,{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 eP({title:s,children:t}){return e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2 flex items-center gap-1.5",children:[e.jsx(yr,{className:"h-3 w-3 opacity-0"})," ",s]}),t]})}function Fke({value:s,onSave:t}){const[n,r]=N.useState(s);return e.jsxs("div",{children:[e.jsx(Ts,{rows:5,value:n,onChange:a=>r(a.target.value),className:"text-[13.5px]"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>t(n),children:"Save edit"}),e.jsx(dEe,{value:n})]})]})}function dEe({value:s}){return e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(s),ae.success("Copied")},children:e.jsx(ta,{className:"h-3.5 w-3.5"})})}const Xhn={draft:"bg-slate-100 text-slate-700",published:"bg-emerald-100 text-emerald-800",archived:"bg-amber-100 text-amber-800"};function Jhn(){const{kits:s,isLoading:t,create:n,duplicate:r,remove:a}=$R(),i=In(),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(Ku,{eyebrow:"Provide · Resource Kits",title:"Your Resource Kits",description:"Package the value you already share, then track what actually creates conversations.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(Ln,{to:"/attract/provide/kits/templates",children:[e.jsx(Wg,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsxs(B,{onClick:l,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"New kit"]})]})}),t&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading kits…"}),!t&&s.length===0&&e.jsxs(fe,{className:"p-10 text-center rounded-2xl border-dashed border-slate-300 bg-white",children:[e.jsx(un,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"mt-3 text-lg font-semibold",children:"You haven't built a kit yet."}),e.jsx("p",{className:"text-slate-600 max-w-md mx-auto mt-1 text-sm",children:"Start from a starter template or a blank kit. Bundle 3–7 pieces of real value and share with agents you'd love to work alongside."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-5",children:[e.jsx(B,{variant:"outline",asChild:!0,children:e.jsx(Ln,{to:"/attract/provide/kits/templates",children:"Browse starter library"})}),e.jsx(B,{onClick:l,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Start a blank kit"})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:s.map(o=>{var c;return e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white hover:shadow-md transition-shadow flex flex-col",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{className:Xhn[o.status]+" capitalize",children:o.status}),o.pillar&&e.jsx(ze,{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(ze,{variant:"secondary",className:"text-[10.5px]",children:["#",d]},d))}),e.jsxs("div",{className:"mt-auto pt-4 flex items-center gap-2 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(Ln,{to:`/attract/provide/kits/${o.id}/edit`,children:[e.jsx(gL,{className:"h-3.5 w-3.5 mr-1.5"}),"Edit"]})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(Ln,{to:`/attract/provide/kits/${o.id}/analytics`,children:[e.jsx(yo,{className:"h-3.5 w-3.5 mr-1.5"}),"Analytics"]})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:async()=>{const d=await r.mutateAsync(o.id);ae.success("Duplicated"),i(`/attract/provide/kits/${d}/edit`)},children:e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{confirm("Delete this kit? Shares and events will also be removed.")&&a.mutate(o.id,{onSuccess:()=>ae.success("Deleted")})},children:e.jsx(bn,{className:"h-3.5 w-3.5 text-rose-600"})})]})]},o.id)})})]})}const emn={pdf:Nr,video:Al,link:tl,checklist:pu,template:_w,text:Nr,content_studio:un,resource:Nr};function d4t({kit:s,items:t,owner:n,personalNote:r,mode:a="public",onEvent:i}){const l=(o,c,d)=>i==null?void 0:i(o,c,d);return e.jsxs("div",{className:"bg-[#0B0F1E] text-slate-100 rounded-2xl overflow-hidden",children:[s.cover_image_url?e.jsxs("div",{className:"aspect-[16/7] bg-slate-800 relative",children:[e.jsx("img",{src:s.cover_image_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0B0F1E] to-transparent"})]}):e.jsx("div",{className:"h-24 bg-gradient-to-br from-violet-700 via-indigo-700 to-slate-900"}),e.jsxs("div",{className:"p-5 md:p-8",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:"",className:"h-11 w-11 rounded-full object-cover ring-2 ring-white/10"}):e.jsx("div",{className:"h-11 w-11 rounded-full bg-white/10 grid place-items-center text-white/70 font-semibold",children:n.display_name.slice(0,1)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-semibold",children:n.display_name}),n.brokerage&&e.jsx("div",{className:"text-[11px] text-slate-400",children:n.brokerage})]})]}),e.jsx("h1",{className:"mt-5 text-2xl md:text-3xl font-semibold tracking-tight text-white",children:s.title}),s.audience&&e.jsxs("div",{className:"text-[12px] uppercase tracking-widest text-violet-300 mt-1",children:["For ",s.audience]}),s.description&&e.jsx("p",{className:"text-slate-300 mt-3 text-[14.5px] leading-relaxed",children:s.description}),(r||s.intro_text)&&e.jsxs(fe,{className:"mt-6 p-4 bg-white/5 border-white/10 text-slate-200",children:[r&&e.jsx("div",{className:"text-[13px] whitespace-pre-line",children:r}),r&&s.intro_text&&e.jsx("div",{className:"my-2 border-t border-white/10"}),s.intro_text&&e.jsx("div",{className:"text-[13px] whitespace-pre-line text-slate-300",children:s.intro_text})]}),s.intro_video_url&&e.jsx("div",{className:"mt-5 aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("iframe",{src:tmn(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=emn[o.type]??Nr;return e.jsx(fe,{className:"p-4 bg-white/5 border-white/10 text-slate-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-violet-600/20 text-violet-300 grid place-items-center flex-shrink-0",children:e.jsx(c,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:o.title}),o.description&&e.jsx("div",{className:"text-[12.5px] text-slate-300 mt-0.5",children:o.description}),o.type==="checklist"&&((d=o.content)==null?void 0:d.items)&&e.jsx("ul",{className:"mt-2 space-y-1 text-[13px] text-slate-200",children:o.content.items.map((h,p)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-violet-400",children:"•"}),h]},p))}),(o.type==="text"||o.type==="template")&&((u=o.content)==null?void 0:u.body)&&e.jsx("div",{className:"mt-2 text-[13px] text-slate-300 whitespace-pre-line",children:o.content.body}),o.url&&["video","pdf","link","resource"].includes(o.type)&&e.jsxs("div",{className:"mt-3 flex gap-2 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"secondary",asChild:!0,onClick:()=>l("resource_open",o.id),children:e.jsxs("a",{href:o.url,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1.5"}),"Open"]})}),o.allow_download&&o.type!=="link"&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,onClick:()=>l("file_download",o.id),children:e.jsxs("a",{href:o.url,target:"_blank",rel:"noreferrer",download:!0,children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"}),"Download"]})}),o.type==="link"&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,onClick:()=>l("external_link_click",o.id),children:e.jsx("a",{href:o.url,target:"_blank",rel:"noreferrer",children:"Visit"})})]})]})]})},o.id)})}),s.cta_label&&s.cta_url&&e.jsx("div",{className:"mt-8 text-center",children:e.jsx(B,{size:"lg",asChild:!0,className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>l("primary_cta_click"),children:e.jsx("a",{href:s.cta_url,target:"_blank",rel:"noreferrer",children:s.cta_label})})}),e.jsx("div",{className:"mt-10 pt-6 border-t border-white/10 text-[11px] text-slate-500 leading-relaxed",children:"Brokerage and compensation information should always be verified in writing. Nothing shared here constitutes a formal offer, agreement, or guarantee of income."})]})]})}function tmn(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 smn=[{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 Yet(){var K,Y;const{kitId:s}=_i(),[t]=yl(),n=In(),{user:r}=gs(),a=s===void 0,{create:i,update:l}=$R(),{data:o,isLoading:c}=$St(s),{items:d,add:u,update:h,remove:p,reorder:f}=Dun(s),{shares:g,create:b,revoke:v}=USt(s),{agents:j}=d0(),[_,S]=N.useState(null),[A,T]=N.useState("desktop"),[D,L]=N.useState("idle"),M=N.useRef(null);N.useEffect(()=>{a&&!_&&(async()=>{const ee=t.get("seed"),ne=await i.mutateAsync({title:ee?`From: ${ee}`:"Untitled Kit",status:"draft"});n(`/attract/provide/kits/${ne.id}/edit`,{replace:!0})})()},[a]),N.useEffect(()=>{o&&S(o)},[o==null?void 0:o.id]);const F=ee=>{s&&(S(ne=>({...ne,...ee})),L("saving"),clearTimeout(M.current),M.current=setTimeout(async()=>{try{await l.mutateAsync({id:s,patch:ee}),L("saved"),setTimeout(()=>L("idle"),1500)}catch(ne){ae.error(ne.message??"Save failed"),L("idle")}},800))},z=async ee=>{!s||!r||await u.mutateAsync({user_id:r.id,type:ee,title:`New ${ee.replace("_"," ")}`})},V=(ee,ne)=>{const oe=[...d],pe=ee+ne;pe<0||pe>=oe.length||([oe[ee],oe[pe]]=[oe[pe],oe[ee]],f.mutate(oe.map(ce=>ce.id)))},W=g.filter(ee=>ee.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(Ku,{eyebrow:"Provide · Kit builder",title:_.title||"Untitled Kit",description:D==="saving"?"Saving…":D==="saved"?"Saved":`Last edited ${ks(new Date(_.updated_at),"MMM d, h:mm a")}`,actions:e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(Ln,{to:"/attract/provide/kits",children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Kits"]})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsx(Ln,{to:`/attract/provide/kits/${s}/analytics`,children:"Analytics"})}),e.jsxs(us,{value:_.status,onValueChange:ee=>F({status:ee}),children:[e.jsx(cs,{className:"w-[130px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"draft",children:"Draft"}),e.jsx(Ze,{value:"published",children:"Published"}),e.jsx(Ze,{value:"archived",children:"Archived"})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-12 gap-6",children:[e.jsxs("div",{className:"xl:col-span-4 space-y-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit details"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ge,{value:_.title??"",onChange:ee=>F({title:ee.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Short description"}),e.jsx(Ts,{rows:3,value:_.description??"",onChange:ee=>F({description:ee.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cover image URL"}),e.jsx(ge,{placeholder:"https://…",value:_.cover_image_url??"",onChange:ee=>F({cover_image_url:ee.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Audience"}),e.jsx(ge,{placeholder:"e.g. New agents",value:_.audience??"",onChange:ee=>F({audience:ee.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Pillar"}),e.jsxs(us,{value:_.pillar??"",onValueChange:ee=>F({pillar:ee}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Choose"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"produce",children:"Produce"}),e.jsx(Ze,{value:"influence",children:"Influence"}),e.jsx(Ze,{value:"provide",children:"Provide"}),e.jsx(Ze,{value:"connect",children:"Connect"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Tags (comma separated)"}),e.jsx(ge,{value:(_.tags??[]).join(", "),onChange:ee=>F({tags:ee.target.value.split(",").map(ne=>ne.trim()).filter(Boolean)})})]})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Personal welcome"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsx(Ts,{rows:4,placeholder:"Write a short personal note that opens the kit.",value:_.intro_text??"",onChange:ee=>F({intro_text:ee.target.value})}),e.jsxs("div",{children:[e.jsx(se,{children:"Intro video URL (optional)"}),e.jsx(ge,{placeholder:"Loom/YouTube/Vimeo",value:_.intro_video_url??"",onChange:ee=>F({intro_video_url:ee.target.value})})]})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Call to action"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Button label"}),e.jsx(ge,{value:_.cta_label??"",onChange:ee=>F({cta_label:ee.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Button URL"}),e.jsx(ge,{placeholder:"https://…",value:_.cta_url??"",onChange:ee=>F({cta_url:ee.target.value})})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{children:"Expiration (optional)"}),e.jsx(ge,{type:"datetime-local",value:_.expires_at?_.expires_at.slice(0,16):"",onChange:ee=>F({expires_at:ee.target.value?new Date(ee.target.value).toISOString():null})})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Share this kit"}),e.jsx(nmn,{kitId:s,agents:j,shares:W,onCreate:ee=>b.mutate(ee),onRevoke:ee=>v.mutate(ee),status:_.status})]})]}),e.jsx("div",{className:"xl:col-span-5 space-y-4",children:e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit sections"}),e.jsx("div",{className:"text-[13px] text-slate-600",children:"Drag order using arrows. Reorder to change how visitors experience the kit."})]}),e.jsxs(us,{onValueChange:ee=>z(ee),children:[e.jsx(cs,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"+ Add item"})}),e.jsx(ds,{children:smn.map(ee=>e.jsx(Ze,{value:ee.value,children:ee.label},ee.value))})]})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[d.length===0&&e.jsx("div",{className:"text-center text-sm text-slate-500 py-10 border border-dashed rounded-xl",children:"No sections yet. Add your first item above."}),d.map((ee,ne)=>{var oe,pe;return e.jsx(fe,{className:"p-4 border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>V(ne,-1),children:e.jsx(Bu,{className:"h-4 w-4"})}),e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>V(ne,1),children:e.jsx(om,{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(ze,{variant:"outline",className:"capitalize",children:ee.type.replace("_"," ")}),e.jsx(ge,{className:"flex-1",value:ee.title,onChange:ce=>h.mutate({id:ee.id,patch:{title:ce.target.value}})})]}),e.jsx(Ts,{rows:2,placeholder:"Short description",value:ee.description??"",onChange:ce=>h.mutate({id:ee.id,patch:{description:ce.target.value}})}),["video","pdf","link","resource"].includes(ee.type)&&e.jsx(ge,{placeholder:"URL",value:ee.url??"",onChange:ce=>h.mutate({id:ee.id,patch:{url:ce.target.value}})}),["text","template"].includes(ee.type)&&e.jsx(Ts,{rows:4,placeholder:"Body text or script",value:((oe=ee.content)==null?void 0:oe.body)??"",onChange:ce=>h.mutate({id:ee.id,patch:{content:{...ee.content??{},body:ce.target.value}}})}),ee.type==="checklist"&&e.jsx(Ts,{rows:5,placeholder:"One item per line",value:(((pe=ee.content)==null?void 0:pe.items)??[]).join(` `),onChange:ce=>h.mutate({id:ee.id,patch:{content:{items:ce.target.value.split(` `).map(de=>de.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(vn,{checked:ee.allow_download,onCheckedChange:ce=>h.mutate({id:ee.id,patch:{allow_download:ce}})}),"Allow download"]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(vn,{checked:!ee.is_hidden,onCheckedChange:ce=>h.mutate({id:ee.id,patch:{is_hidden:!ce}})}),"Visible"]}),e.jsxs("button",{className:"ml-auto text-rose-600 text-[12px] flex items-center gap-1",onClick:()=>p.mutate(ee.id),children:[e.jsx(bn,{className:"h-3.5 w-3.5"}),"Delete"]})]})]})]})},ee.id)})]})]})}),e.jsx("div",{className:"xl:col-span-3",children:e.jsxs(fe,{className:"p-4 rounded-2xl xl:sticky xl:top-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Live preview"}),e.jsx($r,{value:A,onValueChange:ee=>T(ee),children:e.jsxs(Ur,{className:"h-8",children:[e.jsx(Zt,{value:"desktop",className:"h-6 px-2",children:e.jsx(gb,{className:"h-3.5 w-3.5"})}),e.jsx(Zt,{value:"mobile",className:"h-6 px-2",children:e.jsx(rg,{className:"h-3.5 w-3.5"})})]})})]}),e.jsx("div",{className:A==="mobile"?"max-w-[320px] mx-auto":"",children:e.jsx(d4t,{kit:_,items:d,owner:{display_name:((K=r==null?void 0:r.user_metadata)==null?void 0:K.full_name)||(r==null?void 0:r.email)||"You",avatar_url:((Y=r==null?void 0:r.user_metadata)==null?void 0:Y.avatar_url)??null,brokerage:null},mode:"preview"})})]})})]})]})}function nmn({kitId:s,agents:t,shares:n,onCreate:r,onRevoke:a,status:i}){const[l,o]=N.useState("general"),[c,d]=N.useState("");return i!=="published"?e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-3",children:"Publish this kit to generate share links."}):e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsxs(us,{value:l,onValueChange:u=>o(u),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Choose agent"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"general",children:"General share link"}),t.map(u=>e.jsxs(Ze,{value:u.id,children:[u.first_name," ",u.last_name??""]},u.id))]})]}),e.jsx(Ts,{rows:2,placeholder:"Optional personal note shown on the page",value:c,onChange:u=>d(u.target.value)}),e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{r({kit_id:s,agent_id:l==="general"?null:l,personal_note:c||null}),d("")},children:[e.jsx(Hl,{className:"h-4 w-4 mr-2"}),"Create share link"]})]}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-[12px] text-slate-500",children:"No active links yet."}),n.map(u=>{var f;const h=VSt(u.share_token),p=u.agent_id?((f=t.find(g=>g.id===u.agent_id))==null?void 0:f.first_name)??"Agent":"General";return e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:p}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:u.engagement_level.replace("_"," ")})]}),e.jsx("div",{className:"text-slate-500 truncate mt-1",children:h}),e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(h),ae.success("Link copied")},children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:h,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"}),"Open"]})}),e.jsxs(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(u.id),children:[e.jsx(eL,{className:"h-3.5 w-3.5 mr-1"}),"Revoke"]})]})]},u.id)})]})]})}const rmn={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 amn(){const{kitId:s}=_i(),{data:t}=$St(s),{shares:n}=USt(s),{data:r=[]}=qSt(s),a=N.useMemo(()=>{const l=d=>r.filter(u=>u.event_type===d).length,o=new Set(n.filter(d=>d.agent_id).map(d=>d.agent_id)).size,c=n.filter(d=>d.first_opened_at).length;return{shares:n.length,uniqueAgents:o,viewRate:n.length?Math.round(c/n.length*100):0,engaged:n.filter(d=>["engaged","high_intent"].includes(d.engagement_level)).length,downloads:l("file_download"),ctaClicks:l("primary_cta_click"),questions:l("question_submitted"),meetings:l("meeting_requested")}},[n,r]),i=N.useMemo(()=>{const l=new Map;return r.forEach(o=>{const c=ks(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(Ku,{eyebrow:"Kit analytics",title:(t==null?void 0:t.title)??"Kit",description:"Which value is actually creating conversations.",actions:e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(Ln,{to:`/attract/provide/kits/${s}/edit`,children:[e.jsx(Wr,{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(Dk,{label:"Shares",value:a.shares,icon:Ir,tone:"violet"}),e.jsx(Dk,{label:"Unique agents",value:a.uniqueAgents,icon:Ir,tone:"indigo"}),e.jsx(Dk,{label:"View rate",value:`${a.viewRate}%`,icon:Ir,tone:"teal"}),e.jsx(Dk,{label:"Engaged",value:a.engaged,icon:oc,tone:"emerald"}),e.jsx(Dk,{label:"Downloads",value:a.downloads,icon:Da,tone:"orange"}),e.jsx(Dk,{label:"CTA clicks",value:a.ctaClicks,icon:oc,tone:"rose"}),e.jsx(Dk,{label:"Questions",value:a.questions,icon:Ql,tone:"violet"}),e.jsx(Dk,{label:"Meetings",value:a.meetings,icon:cm,tone:"indigo"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Engagement over time"}),e.jsx("div",{className:"h-64",children:e.jsx(Sw,{width:"100%",height:"100%",children:e.jsxs(fLe,{data:i,children:[e.jsx(mLe,{strokeDasharray:"3 3",stroke:"#eee"}),e.jsx(Bw,{dataKey:"date",fontSize:11}),e.jsx($w,{fontSize:11,allowDecimals:!1}),e.jsx(kp,{}),e.jsx(i6,{type:"monotone",dataKey:"count",stroke:"#7c3aed",strokeWidth:2})]})})})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"By event type"}),e.jsx("div",{className:"space-y-2",children:Object.entries(rmn).map(([l,o])=>{const c=r.filter(d=>d.event_type===l).length;return e.jsxs("div",{className:"flex justify-between text-[13px]",children:[e.jsx("span",{className:"text-slate-600",children:o}),e.jsx("span",{className:"font-semibold tabular-nums",children:c})]},l)})})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl mt-6",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-3",children:"Recipients"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-sm text-slate-500",children:"No one has been shared this kit yet."}),n.map(l=>e.jsxs("div",{className:"flex items-center justify-between border-b py-2 text-[13px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l.agent_id?"Personalized":"General link"}),e.jsxs("div",{className:"text-slate-500 text-[11.5px]",children:["Created ",ks(new Date(l.created_at),"MMM d")," · ",l.open_count," opens",l.last_opened_at&&` · last opened ${ks(new Date(l.last_opened_at),"MMM d")}`]})]}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:l.engagement_level.replace("_"," ")})]},l.id))]})]})]})}function Dk({label:s,value:t,icon:n,tone:r}){const a={violet:"text-violet-700 bg-violet-50",indigo:"text-indigo-700 bg-indigo-50",teal:"text-teal-700 bg-teal-50",emerald:"text-emerald-700 bg-emerald-50",orange:"text-orange-700 bg-orange-50",rose:"text-rose-700 bg-rose-50"};return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${a[r]}`,children:e.jsx(n,{className:"h-4 w-4"})}),e.jsx("div",{className:"mt-2 text-[22px] font-semibold tabular-nums",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function imn(){const{data:s=[],isLoading:t}=Run(),n=Oun(),r=In(),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(Ku,{eyebrow:"Starter library",title:"LevelUp Starter Kits",description:"Ten proven relationship-first kits. Duplicate any of them into your workspace and personalize the parts that matter.",actions:e.jsx(B,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(Ln,{to:"/attract/provide/kits",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Back to my kits"]})})}),t&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading templates…"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:s.map(i=>{var l;return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Starter kit"]}),e.jsx("div",{className:"mt-2 text-[17px] font-semibold text-slate-900",children:i.title}),i.audience&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["For ",i.audience]}),e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:i.description}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1",children:[i.pillar&&e.jsx(ze,{variant:"outline",className:"capitalize",children:i.pillar}),(i.tags??[]).slice(0,4).map(o=>e.jsxs(ze,{variant:"secondary",className:"text-[10.5px]",children:["#",o]},o))]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-3",children:[((l=i.suggested_items)==null?void 0:l.length)??0," suggested sections"]}),e.jsxs(B,{className:"mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>a(i.id),children:[e.jsx(Rm,{className:"h-4 w-4 mr-2"}),"Use this kit"]})]},i.id)})})]})}const Zet={call:{icon:Pr,label:"Call"},text:{icon:Ci,label:"Text"},email:{icon:Hs,label:"Email"},dm:{icon:cr,label:"DM"},resource_share:{icon:Wg,label:"Share a kit"},event_invitation:{icon:Fg,label:"Invite to event"},personal_check_in:{icon:MA,label:"Personal check-in"}},Qet={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 omn(s){var t;return((t=SSt.find(n=>n.key===s))==null?void 0:t.blurb)??""}function u4t(s){var t;return((t=SSt.find(n=>n.key===s))==null?void 0:t.label)??s.replace(/_/g," ")}function uEe({rec:s,agentName:t,agentStage:n,kitTitle:r,eventTitle:a,compact:i,showAgentLink:l=!0,className:o}){const{update:c,dismiss:d,snooze:u,createFollowUp:h,logCompleted:p}=TSt(),[f,g]=N.useState(!1),[b,v]=N.useState(s.draft_message??""),j=c.isPending||d.isPending||u.isPending||h.isPending||p.isPending,_=Zet[s.channel]??Zet.personal_check_in,S=s.suggested_due_at?new Date(s.suggested_due_at):null,A=S?S{c.mutate({id:s.id,patch:{draft_message:b}},{onSuccess:()=>{g(!1),ae.success("Opening message updated")}})},D=async()=>{try{await navigator.clipboard.writeText(s.draft_message??""),ae.success("Opening message copied — send it yourself from your phone or inbox")}catch{ae.error("Could not copy — select the text manually")}};return e.jsx(fe,{className:Et("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(ze,{variant:"outline",className:Et("rounded-full text-[10.5px] uppercase tracking-wider font-semibold ring-1 border-transparent",Qet[s.priority]??Qet.medium),children:s.priority}),e.jsx("span",{className:"text-[11px] text-violet-700 font-medium",children:u4t(s.signal_group)}),s.is_demo&&e.jsx(ze,{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(Ln,{to:`/attract/agents/${s.agent_id}`,className:"font-medium text-slate-700 hover:text-violet-700 inline-flex items-center gap-0.5",children:[t," ",e.jsx(ga,{className:"h-3 w-3"})]}):e.jsx("span",{className:"font-medium text-slate-700",children:t}),n&&e.jsxs("span",{className:"capitalize",children:["· ",n.replace(/_/g," ")]}),e.jsxs("span",{children:["· ",_.label]}),S&&e.jsxs("span",{className:Et("inline-flex items-center gap-1",A?"text-rose-600 font-medium":""),children:["· ",e.jsx(gr,{className:"h-3 w-3"})," ",A?"Due now":`Do by ${S.toLocaleDateString()}`]})]})]}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full","aria-label":"More recommendation actions",children:e.jsx(Lg,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",className:"w-56",children:[e.jsx(I4,{children:"Recommendation"}),e.jsx(Qg,{}),e.jsxs(Xr,{onClick:()=>g(L=>!L),children:[e.jsx(ja,{className:"h-4 w-4 mr-2"})," Edit opening message"]}),e.jsxs(Xr,{onClick:D,children:[e.jsx(ta,{className:"h-4 w-4 mr-2"})," Copy message"]}),e.jsx(Qg,{}),e.jsxs(Xr,{onClick:()=>u.mutate({id:s.id,days:3}),children:[e.jsx(gr,{className:"h-4 w-4 mr-2"})," Snooze 3 days"]}),e.jsxs(Xr,{onClick:()=>u.mutate({id:s.id,days:7}),children:[e.jsx(gr,{className:"h-4 w-4 mr-2"})," Snooze 1 week"]}),e.jsxs(Xr,{className:"text-rose-600",onClick:()=>d.mutate(s.id),children:[e.jsx(Fn,{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(vw,{className:"h-3 w-3"})," Why this, right now"]}),e.jsx("ul",{className:"space-y-1",children:s.reasons.map((L,M)=>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:L})]},M))}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-2",children:omn(s.signal_group)})]}),!i&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-slate-500 mb-1.5",children:"Suggested opening"}),f?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ts,{value:b,onChange:L=>v(L.target.value),rows:4,className:"text-[13.5px]","aria-label":"Opening message"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:T,disabled:j,children:"Save message"}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>{v(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(B,{size:"sm",className:"rounded-full btn-primary text-white",disabled:j,onClick:()=>p.mutate({rec:s}),children:[e.jsx(Lr,{className:"h-3.5 w-3.5 mr-1.5"})," I did this"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:j,onClick:()=>h.mutate(s),children:[e.jsx(Fg,{className:"h-3.5 w-3.5 mr-1.5"})," ",s.follow_up_id?"Follow-up created":"Create follow-up"]}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:D,children:[e.jsx(ta,{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 lmn({label:s="Nothing needs attention right now."}){return e.jsxs(fe,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-emerald-50 text-emerald-600 grid place-items-center mx-auto mb-3",children:e.jsx(Lr,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:s}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Log a conversation, share a resource kit, or invite someone to an event and new opportunities will appear here."})]})}const cmn=q,dmn=["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"],umn={hot:_c,warm:vb,cold:Mv},s7=({label:s})=>e.jsxs("span",{className:"text-slate-400 italic",children:["Not recorded",s?` — add ${s}`:""]}),Rk=s=>[s.first_name,s.last_name].filter(Boolean).join(" "),hmn=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 tP({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 mmn={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 pmn(){const{agentId:s}=_i(),t=In(),{item:n,timeline:r,valueShared:a,nextKit:i,isLoading:l,error:o,refetch:c}=Wdn(s),{data:d=[]}=pDe(),{upsertAgent:u,moveStage:h}=d0(),{followUps:p,complete:f}=eq(),g=Kdn(),{gmailEmail:b}=bh(),[v,j]=N.useState("all"),[_,S]=N.useState(!1),[A,T]=N.useState(!1),[D,L]=N.useState("call"),[M,F]=N.useState(""),[z,V]=N.useState(""),[W,K]=N.useState(!1),[Y,ee]=N.useState(""),[ne,oe]=N.useState(!1),[pe,ce]=N.useState(""),[de,ie]=N.useState(new Date(Date.now()+3*864e5).toISOString().slice(0,10)),[ye,_e]=N.useState(null),[Me,Te]=N.useState(!1),Ce=N.useMemo(()=>d.filter(Ne=>Ne.agent_id===s&&Ne.status==="open").sort((Ne,He)=>He.rank_score-Ne.rank_score),[d,s]),Ee=N.useMemo(()=>p.filter(Ne=>Ne.agent_id===s),[p,s]),De=N.useMemo(()=>{const Ne=Met.find(He=>He.key===v);return!Ne||!Ne.kinds.length?r:r.filter(He=>Ne.kinds.includes(He.kind))},[r,v]);if(l)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-8 w-40"}),e.jsx(Ws,{className:"h-40 w-full rounded-2xl"}),e.jsx(Ws,{className:"h-64 w-full rounded-2xl"})]});if(o)return e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"We couldn't load this relationship."}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:o.message}),e.jsxs(B,{className:"rounded-full mt-4",onClick:()=>c(),children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"})," Try again"]})]});if(!n)return e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Agent not found"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"This relationship may have been removed from your pipeline."}),e.jsx(B,{className:"rounded-full mt-4",onClick:()=>t("/attract/pipeline"),children:"Back to pipeline"})]});const Ie=n.agent,Fe=n.signals,qe=umn[Ie.temperature??""]??vb,ve=()=>{g.mutate({agent_id:Ie.id,activity_type:D,title:M||`${D.replace(/_/g," ")} with ${Rk(Ie)}`,description:z||void 0},{onSuccess:()=>{S(!1),F(""),V("")}})},Je=async()=>{var He;if(!Y.trim())return;const Ne=[(He=Ie.notes)==null?void 0:He.trim(),`[${new Date().toLocaleDateString()}] ${Y.trim()}`].filter(Boolean).join(` `);u.mutate({id:Ie.id,first_name:Ie.first_name,notes:Ne},{onSuccess:()=>{K(!1),ee(""),c()}}),g.mutate({agent_id:Ie.id,activity_type:"note",title:"Note added",description:Y.trim()})},we=async()=>{if(!pe.trim()){ae.error("Give the follow-up a title");return}if(Ee.find(Ye=>!Ye.completed_at&&Ye.title.trim().toLowerCase()===pe.trim().toLowerCase())){ae.error("An open follow-up with that title already exists");return}const{data:He}=await q.auth.getUser(),{error:$e}=await cmn.from("attract_follow_ups").insert({user_id:He.user.id,agent_id:Ie.id,title:pe.trim(),due_at:new Date(`${de}T12:00:00`).toISOString(),touch_type:"call",priority:"medium"});if($e){ae.error($e.message);return}ae.success("Follow-up created"),oe(!1),ce(""),c()},it=()=>{ye&&(window.open(ye.href,"_self"),g.mutate({agent_id:Ie.id,activity_type:ye.kind,title:`${ye.kind==="call"?"Called":ye.kind==="text"?"Texted":"Emailed"} ${Rk(Ie)}`}),_e(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(Ln,{to:"/attract",className:"hover:text-violet-700",children:"Attract"}),e.jsx(ga,{className:"h-3 w-3"}),e.jsx(Ln,{to:"/attract/pipeline",className:"hover:text-violet-700",children:"Pipeline"}),e.jsx(ga,{className:"h-3 w-3"}),e.jsx("span",{className:"text-slate-800 font-medium truncate",children:Rk(Ie)})]}),e.jsxs(fe,{className:"rounded-2xl border-slate-200/70 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-[#0B0F1E] via-[#141a33] to-[#1d1b4b] p-5 sm:p-6 text-white",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"text-slate-300 hover:text-white -ml-2 mb-3 rounded-full",onClick:()=>t(-1),children:[e.jsx(Wr,{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:`${Rk(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:hmn(Ie)}),e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:Rk(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(ze,{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(ze,{className:"rounded-full bg-white/10 text-white border-transparent capitalize",children:Ie.stage.replace(/_/g," ")}),e.jsxs(ze,{className:"rounded-full bg-white/10 text-white border-transparent capitalize inline-flex items-center gap-1",children:[e.jsx(qe,{className:"h-3 w-3"})," ",Ie.temperature??"temperature unset"]}),e.jsx(xDe,{score:n.score,className:"bg-white/10 text-white ring-white/20"}),(Ie.tags??[]).map(Ne=>e.jsx(ze,{variant:"outline",className:"rounded-full bg-transparent text-slate-200 border-white/20",children:Ne},Ne))]})]}),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: ",Fe.lastTouchAt?`${new Date(Fe.lastTouchAt).toLocaleDateString()} (${Fe.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(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>T(!0),children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-1.5"})," Edit contact"]}),e.jsxs(bs,{open:_,onOpenChange:S,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1.5"})," Log touch"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Log a conversation"}),e.jsx(Qn,{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(se,{children:"Type"}),e.jsxs(us,{value:D,onValueChange:L,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:["call","text","email","dm","meeting","note"].map(Ne=>e.jsx(Ze,{value:Ne,className:"capitalize",children:Ne},Ne))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ge,{value:M,onChange:Ne=>F(Ne.target.value),placeholder:`Call with ${Ie.first_name}`})]}),e.jsxs("div",{children:[e.jsx(se,{children:"What happened"}),e.jsx(Ts,{rows:4,value:z,onChange:Ne=>V(Ne.target.value)})]})]}),e.jsx(Xn,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:ve,disabled:g.isPending,children:"Log it"})})]})]}),e.jsxs(bs,{open:W,onOpenChange:K,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(M9,{className:"h-3.5 w-3.5 mr-1.5"})," Add note"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add a relationship note"})}),e.jsx(Ts,{rows:5,value:Y,onChange:Ne=>ee(Ne.target.value),placeholder:"What did you learn about them?"}),e.jsx(Xn,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Je,children:"Save note"})})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ie.phone,onClick:()=>Ie.phone&&_e({kind:"call",href:`tel:${Ie.phone}`}),children:[e.jsx(Pr,{className:"h-3.5 w-3.5 mr-1.5"})," Call"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ie.phone,onClick:()=>Ie.phone&&_e({kind:"text",href:`sms:${Ie.phone}`}),children:[e.jsx(Ci,{className:"h-3.5 w-3.5 mr-1.5"})," Text"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ie.email,onClick:()=>Ie.email&&Te(!0),children:[e.jsx(Hs,{className:"h-3.5 w-3.5 mr-1.5"})," Email"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Ln,{to:"/attract/provide/kits",children:[e.jsx(Wg,{className:"h-3.5 w-3.5 mr-1.5"})," Share kit"]})}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Ln,{to:"/attract/events",children:[e.jsx(Fg,{className:"h-3.5 w-3.5 mr-1.5"})," Invite to event"]})}),e.jsxs(bs,{open:ne,onOpenChange:oe,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(gr,{className:"h-3.5 w-3.5 mr-1.5"})," Create follow-up"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Create a follow-up"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"What will you do?"}),e.jsx(ge,{value:pe,onChange:Ne=>ce(Ne.target.value),placeholder:"Call about their Q3 goals"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due"}),e.jsx(ge,{type:"date",value:de,onChange:Ne=>ie(Ne.target.value)})]})]}),e.jsx(Xn,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:we,children:"Create"})})]})]}),e.jsxs(us,{value:Ie.stage,onValueChange:Ne=>h.mutate({id:Ie.id,to_stage:Ne,from_stage:Ie.stage}),children:[e.jsxs(cs,{className:"w-[210px] h-9 rounded-full text-[13px]","aria-label":"Change stage",children:[e.jsx(pw,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(hs,{})]}),e.jsx(ds,{children:dmn.map(Ne=>e.jsx(Ze,{value:Ne,className:"capitalize",children:Ne.replace(/_/g," ")},Ne))})]})]})]}),e.jsx(bs,{open:!!ye,onOpenChange:Ne=>!Ne&&_e(null),children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:["Open your ",(ye==null?void 0:ye.kind)==="email"?"email app":(ye==null?void 0:ye.kind)==="text"?"messaging app":"phone app","?"]}),e.jsx(Qn,{children:"Attract will open your own device app so you send it personally. Nothing is sent by LevelUp. We'll log this as a touch."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",className:"rounded-full",onClick:()=>_e(null),children:"Cancel"}),e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:it,children:"Continue"})]})]})}),e.jsxs($r,{defaultValue:"overview",children:[e.jsx(Ur,{className:"rounded-full bg-white border border-slate-200 p-1 flex-wrap h-auto",children:["overview","timeline","value","events","followups","notes"].map(Ne=>e.jsx(Zt,{value:Ne,className:"rounded-full text-[13px] capitalize data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:Ne==="value"?"Value shared":Ne==="followups"?"Follow-ups":Ne==="notes"?"Notes & insights":Ne},Ne))}),e.jsxs(ls,{value:"overview",className:"mt-5 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-5",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Next best relationship touch"}),Ce[0]?e.jsx(uEe,{rec:Ce[0],agentName:Rk(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(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-3",children:"What we actually know"}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(tP,{label:"Goals",children:Ie.goals||e.jsx(s7,{label:"their goals"})}),e.jsx(tP,{label:"Challenges",children:Ie.challenges||e.jsx(s7,{label:"their challenges"})}),e.jsx(tP,{label:"Interests",children:Ie.interests||e.jsx(s7,{label:"interests"})}),e.jsx(tP,{label:"Production context",children:Ie.production_context||e.jsx(s7,{label:"production context"})}),e.jsx(tP,{label:"Primary pillar",children:Ie.primary_pillar?e.jsx("span",{className:"capitalize",children:Ie.primary_pillar}):e.jsx(s7,{label:"a pillar"})}),e.jsx(tP,{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:Fe.touches90},{label:"Kits shared",value:Fe.shares.length},{label:"Kit opens",value:Fe.totalKitOpens},{label:"Events attended",value:Fe.attended}].map(Ne=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:Ne.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:Ne.label})]},Ne.label))})]}),e.jsxs(fe,{className:"p-5 rounded-2xl h-fit",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-3",children:"Relationship health"}),e.jsx(ESt,{score:n.score})]})]}),Ce.length>1&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Other open recommendations"}),Ce.slice(1).map(Ne=>e.jsx(uEe,{rec:Ne,agentName:Rk(Ie),showAgentLink:!1,compact:!0},Ne.id))]})]}),e.jsx(ls,{value:"timeline",className:"mt-5",children:e.jsxs(fe,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap mb-4",children:[e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Met.map(Ne=>e.jsx("button",{onClick:()=>j(Ne.key),className:Et("rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors",v===Ne.key?"bg-violet-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"),children:Ne.label},Ne.key))}),e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>S(!0),children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1.5"})," Log something"]})]}),De.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"}),De.map(Ne=>e.jsxs("li",{className:"relative pb-5",children:[e.jsx("span",{"aria-hidden":!0,className:Et("absolute -left-[15px] sm:-left-[18px] top-1.5 h-2.5 w-2.5 rounded-full ring-2 ring-white",mmn[Ne.kind]??"bg-slate-300")}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:Ne.title}),Ne.detail&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5 whitespace-pre-wrap",children:Ne.detail}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-1",children:[new Date(Ne.at).toLocaleString()," · ",e.jsx("span",{className:"capitalize",children:Ne.kind.replace(/_/g," ")})]})]},Ne.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(ls,{value:"value",className:"mt-5 space-y-4",children:[i&&e.jsxs(fe,{className:"p-4 rounded-2xl bg-gradient-to-r from-teal-50 to-emerald-50 border-teal-100",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-teal-700",children:"Suggested next kit"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mt-1",children:i.kit.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:i.why}),e.jsx(B,{size:"sm",className:"rounded-full mt-3 btn-primary text-white",asChild:!0,children:e.jsx(Ln,{to:"/attract/provide/kits",children:"Open Resource Kits"})})]}),a.length?a.map(Ne=>e.jsxs(fe,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:Ne.kitTitle}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["Sent ",new Date(Ne.share.created_at).toLocaleDateString()," ·",Ne.firstViewedAt?` first viewed ${new Date(Ne.firstViewedAt).toLocaleDateString()}`:" never viewed",Ne.lastViewedAt?` · last viewed ${new Date(Ne.lastViewedAt).toLocaleDateString()}`:""]})]}),e.jsx(ze,{variant:"outline",className:Et("rounded-full border-transparent ring-1",Ne.classification==="High Intent"?"bg-rose-50 text-rose-700 ring-rose-200":Ne.classification==="Engaged"?"bg-teal-50 text-teal-700 ring-teal-200":Ne.classification==="Viewed"?"bg-amber-50 text-amber-700 ring-amber-200":"bg-slate-50 text-slate-600 ring-slate-200"),children:Ne.classification})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3 mt-4",children:[["Visits",Ne.visits],["Downloads",Ne.downloads],["Link clicks",Ne.ctaClicks],["Questions",Ne.questions],["Meeting asks",Ne.meetingRequests]].map(([He,$e])=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-2.5",children:[e.jsx("div",{className:"text-[17px] font-semibold tabular-nums text-slate-900",children:$e}),e.jsx("div",{className:"text-[10.5px] text-slate-500",children:He})]},He))}),e.jsxs("div",{className:"mt-3 text-[12.5px] text-slate-600 space-y-1",children:[e.jsxs("div",{children:["Link status: ",e.jsx("span",{className:"capitalize font-medium",children:Ne.share.status})]}),e.jsxs("div",{children:["Follow-up after sharing: ",Ne.followUp?`${Ne.followUp.title}${Ne.followUp.completed_at?" (completed)":" (open)"}`:"none created"]}),e.jsxs("div",{children:["Stage movement after sharing: ",Ne.stageAdvancedAfter?`moved to ${Ne.stageAdvancedAfter.to_stage.replace(/_/g," ")} on ${new Date(Ne.stageAdvancedAfter.created_at).toLocaleDateString()}`:"no stage movement yet"]})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full mt-3",asChild:!0,children:e.jsxs("a",{href:Ne.shareUrl,target:"_blank",rel:"noreferrer",children:["Open share link ",e.jsx(tr,{className:"h-3.5 w-3.5 ml-1.5"})]})})]},Ne.share.id)):e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Nothing shared yet"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Value first is how this whole system works. Share a Resource Kit to begin."})]})]}),e.jsx(ls,{value:"events",className:"mt-5 space-y-3",children:Fe.attendees.length?Fe.attendees.map(Ne=>e.jsx(fe,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(Ln,{to:`/attract/events/${Ne.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:[Ne.invited_at&&`Invited ${new Date(Ne.invited_at).toLocaleDateString()} · `,Ne.registered_at?`Registered ${new Date(Ne.registered_at).toLocaleDateString()}`:"Not registered",Ne.checked_in_at&&` · Attended ${new Date(Ne.checked_in_at).toLocaleDateString()}`,Ne.no_show_at&&" · No-show"]})]}),e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:Ne.followup_status?`follow-up ${Ne.followup_status}`:Ne.status??"invited"})]})},Ne.id)):e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(W0,{className:"h-6 w-6 mx-auto text-slate-400 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Never invited to an event"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Events are the fastest way to deepen a relationship."}),e.jsx(B,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",asChild:!0,children:e.jsx(Ln,{to:"/attract/events",children:"See your events"})})]})}),e.jsx(ls,{value:"followups",className:"mt-5 space-y-3",children:Ee.length?Ee.map(Ne=>{const He=!Ne.completed_at&&Ne.due_at&&new Date(Ne.due_at)f.mutate(Ne.id),children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1.5"})," Complete"]})]},Ne.id)}):e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No follow-ups yet"}),e.jsx(B,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",onClick:()=>oe(!0),children:"Create one"})]})}),e.jsxs(ls,{value:"notes",className:"mt-5 space-y-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Your notes"}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>K(!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(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:"What the data says"}),e.jsx("ul",{className:"text-[13px] text-slate-700 space-y-1.5 list-disc pl-4",children:[...n.score.positives.map(Ne=>`Strength: ${Ne}`),...n.score.negatives.map(Ne=>`Risk: ${Ne}`),...n.score.improvements.map(Ne=>`Next: ${Ne}`)].map((Ne,He)=>e.jsx("li",{children:Ne},He))})]})]})]}),e.jsx(zSt,{agent:Ie,open:A,onOpenChange:T,onDeleted:()=>t("/attract/pipeline")}),Ie.email&&e.jsx(Ty,{open:Me,onOpenChange:Te,contact:{id:Ie.id,first_name:Ie.preferred_name||Ie.first_name,last_name:Ie.last_name||"",email:Ie.email},gmailEmail:b,sendSource:"attract",logTouchpoint:!1,onSendComplete:()=>{g.mutate({agent_id:Ie.id,activity_type:"email",title:`Emailed ${Rk(Ie)}`})}})]})}const fmn=[{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 xmn(){const{intel:s,byId:t,isLoading:n,error:r,refetch:a}=p6(),{data:i=[],isLoading:l}=pDe(),o=fDe();ASt();const[c,d]=N.useState(""),[u,h]=N.useState("all"),[p,f]=N.useState("open"),g=j=>{var S;const _=(S=t.get(j))==null?void 0:S.agent;return _?[_.first_name,_.last_name].filter(Boolean).join(" "):"Unknown agent"},b=N.useMemo(()=>{const j=Date.now();return i.filter(_=>p==="open"?_.status==="open"||_.status==="snoozed"&&_.snoozed_until&&+new Date(_.snoozed_until)<=j:p==="snoozed"?_.status==="snoozed":p==="done"?_.status==="completed":p==="dismissed"?_.status==="dismissed":!0).filter(_=>u==="all"||_.signal_group===u).filter(_=>{if(!c.trim())return!0;const S=c.toLowerCase();return g(_.agent_id).toLowerCase().includes(S)||_.title.toLowerCase().includes(S)||(_.reasons??[]).join(" ").toLowerCase().includes(S)}).sort((_,S)=>S.rank_score-_.rank_score)},[i,p,u,c,t]),v=N.useMemo(()=>{const j=i.filter(_=>_.status==="open");return{open:j.length,urgent:j.filter(_=>_.priority==="urgent").length,highIntent:j.filter(_=>_.signal_group==="high_intent").length,overdue:j.filter(_=>_.suggested_due_at&&+new Date(_.suggested_due_at)e.jsx(Ws,{className:"h-28 w-full rounded-2xl"},j))}):r?e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"We couldn't load your opportunities."}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:r.message}),e.jsxs(B,{className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"})," Try again"]})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Relationship Intelligence"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900 mt-0.5",children:"Who needs attention"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-2xl",children:"Ranked by real signals only — value they engaged with, events they attended, commitments you made, and silence past your cadence. Nothing here is invented."})]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>o.mutate(s),disabled:o.isPending,children:[e.jsx(Ai,{className:Et("h-3.5 w-3.5 mr-1.5",o.isPending&&"animate-spin")})," Recalculate"]})]}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Open recommendations",value:v.open},{label:"Urgent",value:v.urgent},{label:"High intent signals",value:v.highIntent},{label:"Past suggested date",value:v.overdue}].map(j=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:j.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:j.label})]},j.label))}),e.jsxs(fe,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(_r,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(ge,{value:c,onChange:j=>d(j.target.value),placeholder:"Search agents or reasons",className:"pl-9 rounded-full h-9","aria-label":"Search recommendations"})]}),e.jsxs(us,{value:u,onValueChange:h,children:[e.jsxs(cs,{className:"w-[190px] h-9 rounded-full text-[13px]",children:[e.jsx(Fv,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(hs,{})]}),e.jsx(ds,{children:fmn.map(j=>e.jsx(Ze,{value:j.key,children:j.label},j.key))})]}),e.jsxs(us,{value:p,onValueChange:f,children:[e.jsx(cs,{className:"w-[150px] h-9 rounded-full text-[13px]",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"open",children:"Needs action"}),e.jsx(Ze,{value:"snoozed",children:"Snoozed"}),e.jsx(Ze,{value:"done",children:"Completed"}),e.jsx(Ze,{value:"dismissed",children:"Dismissed"}),e.jsx(Ze,{value:"all",children:"All"})]})]})]}),b.length?e.jsx("div",{className:"space-y-3",children:b.map(j=>{var _;return e.jsx(uEe,{rec:j,agentName:g(j.agent_id),agentStage:(_=t.get(j.agent_id))==null?void 0:_.agent.stage},j.id)})}):i.length?e.jsx(lmn,{label:"Nothing matches this view. Try switching the filter."}):e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx(un,{className:"h-6 w-6 mx-auto text-violet-500 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No recommendations yet"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Attract only recommends what it can prove. Add agents to your pipeline, share a Resource Kit, or invite someone to an event — real signals will show up here."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-4",children:[e.jsx(B,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(Ln,{to:"/attract/pipeline",children:"Open pipeline"})}),e.jsx(B,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(Ln,{to:"/attract/provide/kits",children:"Share a kit"})})]})]}),!!b.length&&e.jsxs("div",{className:"text-[11.5px] text-slate-400",children:["Showing ",b.length," of ",i.length," tracked recommendations · grouped signals: ",[...new Set(b.map(j=>u4t(j.signal_group)))].join(", ")]})]})}const zke=s=>[s.first_name,s.last_name].filter(Boolean).join(" ");function gmn(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 h4t(s,t,n=new Date){const r=gmn(n),a=new Date(r.getTime()+6*864e5),i=new Date(n.getTime()-7*864e5),c=s.filter(M=>M.primary).slice().sort((M,F)=>F.primary.rank_score-M.primary.rank_score||M.score.score-F.score.score).slice(0,5).map((M,F)=>({agent_id:M.agent.id,agent_name:zke(M.agent),rank:F+1,reason:M.primary.reasons.join(" · "),channel:M.primary.channel,draft_message:M.primary.draft_message,score:M.score.score,stage:M.agent.stage})),d=M=>s.map(F=>{const z=M(F);return z?{agent_id:F.agent.id,agent_name:zke(F.agent),detail:z}:null}).filter(Boolean).slice(0,8),u=d(M=>M.signals.meetingRequests>0||M.signals.questions>0||M.signals.highIntentShares.some(F=>F.engagement_level==="high_intent")?`${M.signals.meetingRequests} meeting request(s), ${M.signals.questions} question(s), ${M.signals.totalKitOpens} kit open(s)`:null),h=d(M=>M.recommendations.some(F=>F.rec_key==="renewed_interest")?"Came back to a kit you shared after going quiet":null),p=d(M=>M.signals.overdueFollowUps.length?`${M.signals.overdueFollowUps.length} overdue follow-up(s) — oldest: ${M.signals.overdueFollowUps[0].title}`:null),f=d(M=>M.signals.daysSinceTouch!==null&&M.signals.daysSinceTouch>60?`${M.signals.daysSinceTouch} days since a real conversation`:null),g=t.shares.filter(M=>new Date(M.created_at)>=i),b={shares:g.length,opened:t.shares.filter(M=>M.first_opened_at&&new Date(M.first_opened_at)>=i).length,engaged:t.shares.filter(M=>M.engagement_level==="engaged").length,high_intent:t.shares.filter(M=>M.engagement_level==="high_intent").length,downloads:t.kitEvents.filter(M=>M.event_type==="file_download"&&new Date(M.created_at)>=i).length,questions:t.kitEvents.filter(M=>M.event_type==="question_submitted"&&new Date(M.created_at)>=i).length},v={invited:t.attendees.filter(M=>M.invited_at&&new Date(M.invited_at)>=i).length,registered:t.attendees.filter(M=>M.registered_at&&new Date(M.registered_at)>=i).length,attended:t.attendees.filter(M=>M.checked_in_at&&new Date(M.checked_in_at)>=i).length,no_shows:t.attendees.filter(M=>M.no_show_at&&new Date(M.no_show_at)>=i).length,follow_ups_pending:t.attendees.filter(M=>M.checked_in_at&&M.followup_status!=="done").length,upcoming:t.events.filter(M=>M.starts_at&&new Date(M.starts_at)>n&&M.status==="published").sort((M,F)=>+new Date(M.starts_at)-+new Date(F.starts_at)).slice(0,3).map(M=>({title:M.title,starts_at:M.starts_at??null}))},j=[...s.filter(M=>M.agent.next_follow_up_at&&new Date(M.agent.next_follow_up_at)>n&&Mm(n,M.agent.next_follow_up_at)<=7).slice(0,5).map(M=>({label:zke(M.agent),detail:`Follow-up scheduled ${new Date(M.agent.next_follow_up_at).toLocaleDateString()}`})),...v.upcoming.map(M=>({label:M.title,detail:M.starts_at?`Event on ${new Date(M.starts_at).toLocaleDateString()}`:"Event scheduled"}))].slice(0,6),_=t.activities.filter(M=>new Date(M.created_at)>=i),S={produce:0,influence:0,provide:0,connect:0};for(const M of _)M.pillar&&S[M.pillar]!==void 0&&S[M.pillar]++;const A=Object.entries(S).map(([M,F])=>({pillar:M,count:F})),T=A.slice().sort((M,F)=>M.count-F.count)[0],D=t.primaryPillar?`Your 90-day primary pillar is ${t.primaryPillar}. This week your lightest pillar was ${T.pillar} (${T.count} activities) — give it one deliberate rep.`:`Your lightest pillar this week was ${T.pillar} (${T.count} activities). Pick one action there.`,L={advanced:t.stageChanges.filter(M=>new Date(M.created_at)>=i).length,follow_ups_completed:t.followUps.filter(M=>M.completed_at&&new Date(M.completed_at)>=i).length,conversations_logged:_.filter(M=>["touch_logged","call","text","email","dm","meeting"].includes(M.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:p,stale:f,kit_summary:b,event_summary:v,upcoming_opportunities:j,pillar_balance:A,recommended_focus:D,wins:L}}function Xet(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 V2=q;function ymn(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:["attract-digest-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await V2.from("attract_digest_settings").select("*").eq("user_id",s.id).maybeSingle();if(i)throw i;return a??null}}),r=gt({mutationFn:async a=>{const{error:i}=await V2.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 vmn(){const{user:s}=gs();return lt({queryKey:["attract-digests",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V2.from("attract_digests").select("*").order("week_start",{ascending:!1}).limit(26);if(n)throw n;return t??[]}})}function bmn(s){const t=Gt(),n=lt({queryKey:["attract-digest-items",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await V2.from("attract_digest_items").select("*").eq("digest_id",s).order("rank");if(i)throw i;return a??[]}}),r=gt({mutationFn:async a=>{const{error:i}=await V2.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 _mn(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{const{data:r,error:a}=await V2.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 V2.from("attract_digest_items").delete().eq("digest_id",i).is("completed_at",null);const{data:l}=await V2.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 V2.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 wmn(){const s=Gt();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("attract-send-digest",{body:t});if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-digests"]}),t!=null&&t.ok?ae.success("Digest email sent"):ae.error((t==null?void 0:t.reason)||"Email delivery is not configured yet")},onError:t=>ae.error(t.message??"Send failed")})}const jmn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function sP({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 iW({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(Ln,{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 Nmn(){var D;const{user:s}=gs(),{intel:t,dataset:n,isLoading:r}=p6(),{settings:a,save:i}=ymn(),{data:l=[]}=vmn(),o=_mn(),c=wmn(),[d,u]=N.useState(),h=d??((D=l[0])==null?void 0:D.id),{items:p,markComplete:f}=bmn(h),[g,b]=N.useState(""),v=N.useMemo(()=>n?h4t(t,n):null,[t,n]),j=l.find(L=>L.id===h),_=(j==null?void 0:j.payload)??v,S=g||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",A=()=>{v&&o.mutate(v,{onSuccess:L=>{u(L),ae.success("This week's digest is ready")}})},T=L=>{if(!_)return;if(!S){ae.error("Add an email address first");return}const M=F=>c.mutate({digestId:F,to:S,subject:`Your Weekly Attraction Digest — ${_.week_start}`,html:Xet(_,window.location.origin),test:L});j?M(j.id):v&&o.mutate(v,{onSuccess:F=>{u(F),M(F)}})};return r||!_?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-10 w-56"}),e.jsx(Ws,{className:"h-72 w-full rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Relationship Intelligence"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900 mt-0.5",children:"Weekly Attraction Digest"}),e.jsxs("p",{className:"text-[13.5px] text-slate-500 mt-1",children:["Week of ",new Date(`${_.week_start}T12:00:00`).toLocaleDateString()," – ",new Date(`${_.week_end}T12:00:00`).toLocaleDateString(),j&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:j.delivery_status.replace(/_/g," ")}),j.sent_at?` ${new Date(j.sent_at).toLocaleString()}`:""]})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:A,disabled:o.isPending,children:[e.jsx(Ai,{className:Et("h-3.5 w-3.5 mr-1.5",o.isPending&&"animate-spin")})," Regenerate"]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(Xet(_,window.location.origin)),ae.success("Digest HTML copied")},children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-1.5"})," Copy HTML"]}),e.jsxs(B,{className:"rounded-full btn-primary text-white",onClick:()=>T(!0),disabled:c.isPending,children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-1.5"})," Email it to me"]})]})]}),e.jsxs($r,{defaultValue:"digest",children:[e.jsx(Ur,{className:"rounded-full bg-white border border-slate-200 p-1",children:[["digest","This week"],["history","History"],["settings","Delivery settings"]].map(([L,M])=>e.jsx(Zt,{value:L,className:"rounded-full text-[13px] data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:M},L))}),e.jsxs(ls,{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(([L,M])=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:M}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:L})]},L))}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Your five conversations this week"}),_.conversations.length?e.jsx("div",{className:"space-y-3",children:_.conversations.map(L=>{const M=p.find(z=>z.agent_id===L.agent_id),F=!!(M!=null&&M.completed_at);return e.jsxs("div",{className:Et("rounded-xl border border-slate-200 p-4",F&&"bg-emerald-50/60 border-emerald-200"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14.5px] font-semibold text-slate-900",children:[L.rank,". ",e.jsx(Ln,{to:`/attract/agents/${L.agent_id}`,className:"hover:text-violet-700",children:L.agent_name})]}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:L.reason})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:L.channel}),e.jsxs(ze,{variant:"outline",className:"rounded-full",children:["Health ",L.score]})]})]}),L.draft_message&&e.jsx("div",{className:"mt-3 rounded-lg bg-slate-50 p-3 text-[13px] text-slate-700 whitespace-pre-wrap",children:L.draft_message}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(L.draft_message||""),ae.success("Copied")},children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]}),M&&!F&&e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>f.mutate(M.id),children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark done"]}),F&&e.jsx("span",{className:"text-[12.5px] text-emerald-700 font-medium self-center",children:"Completed"}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(Ln,{to:`/attract/agents/${L.agent_id}`,children:"Open relationship"})})]})]},L.agent_id)})}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No conversations to recommend yet — Attract needs real signals first."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(sP,{title:"High intent",children:e.jsx(iW,{rows:_.high_intent,empty:"No high-intent signals this week."})}),e.jsx(sP,{title:"Renewed interest",children:e.jsx(iW,{rows:_.renewed,empty:"Nobody re-engaged after going quiet."})})]}),e.jsxs(fe,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(sP,{title:"Overdue commitments",children:e.jsx(iW,{rows:_.overdue,empty:"Nothing overdue. Well kept."})}),e.jsx(sP,{title:"Going cold",children:e.jsx(iW,{rows:_.stale,empty:"No relationships past 60 days of silence."})})]}),e.jsx(fe,{className:"p-5 rounded-2xl",children:e.jsx(sP,{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(fe,{className:"p-5 rounded-2xl",children:e.jsx(sP,{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(L=>e.jsxs("div",{className:"text-slate-600 flex items-center gap-1.5",children:[e.jsx(Tl,{className:"h-3.5 w-3.5"})," ",L.title,L.starts_at?` — ${new Date(L.starts_at).toLocaleDateString()}`:""]},L.title))]})})})]}),e.jsxs(fe,{className:"p-5 rounded-2xl bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-700",children:"Recommended focus"}),e.jsx("p",{className:"text-[14px] text-slate-800 mt-1.5",children:_.recommended_focus}),e.jsx("div",{className:"flex gap-2 mt-3 flex-wrap",children:_.pillar_balance.map(L=>e.jsxs(ze,{variant:"outline",className:"rounded-full capitalize bg-white/70",children:[L.pillar,": ",L.count]},L.pillar))})]})]}),e.jsx(ls,{value:"history",className:"mt-5 space-y-3",children:l.length?l.map(L=>e.jsxs(fe,{className:Et("p-4 rounded-2xl flex items-center justify-between gap-3 flex-wrap",L.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(`${L.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:L.delivery_status.replace(/_/g," ")}),L.sent_at&&` · sent ${new Date(L.sent_at).toLocaleString()}`,L.delivery_note&&` · ${L.delivery_note}`]})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u(L.id),children:"View"})]},L.id)):e.jsx(fe,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"No digests generated yet."})}),e.jsx(ls,{value:"settings",className:"mt-5",children:e.jsxs(fe,{className:"p-5 rounded-2xl max-w-xl space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[14px] font-medium text-slate-900",children:"Weekly email"}),e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Send the digest automatically each week."})]}),e.jsx(vn,{checked:!!(a!=null&&a.enabled),onCheckedChange:L=>i.mutate({enabled:L})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Day"}),e.jsxs(us,{value:String((a==null?void 0:a.weekday)??1),onValueChange:L=>i.mutate({weekday:Number(L)}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:jmn.map((L,M)=>e.jsx(Ze,{value:String(M),children:L},L))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Hour (local)"}),e.jsxs(us,{value:String((a==null?void 0:a.send_hour)??7),onValueChange:L=>i.mutate({send_hour:Number(L)}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:Array.from({length:24},(L,M)=>e.jsxs(Ze,{value:String(M),children:[M,":00"]},M))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Send to"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:g||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",onChange:L=>b(L.target.value),placeholder:"you@example.com"}),e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>i.mutate({email:S}),children:"Save"})]})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-3 text-[12.5px] text-amber-900 flex gap-2",children:[e.jsx(Hs,{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 _3=q,kmn=[{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 Smn(){const{user:s}=gs(),t=Gt(),{intel:n,dataset:r,isLoading:a,refetch:i}=p6(),l=fDe(),o=CSt(),[c,d]=N.useState(""),[u,h]=N.useState(!1),p=N.useMemo(()=>r?h4t(n,r):null,[n,r]),f=N.useMemo(()=>{const v=c.toLowerCase().trim();return n.filter(j=>!v||`${j.agent.first_name} ${j.agent.last_name??""}`.toLowerCase().includes(v))},[n,c]),g=async()=>{if(!s)return;h(!0);const{data:v}=await _3.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0);if((v??[]).length){ae.info("Demo agents already exist"),h(!1);return}const{data:j,error:_}=await _3.from("attract_agents").insert(kmn.map(A=>({...A,user_id:s.id,is_demo:!0,source:"demo_seed"}))).select("id, first_name");if(_){ae.error(_.message),h(!1);return}const S=Date.now();await _3.from("attract_activities").insert((j??[]).map((A,T)=>({user_id:s.id,agent_id:A.id,activity_type:"touch_logged",pillar:"connect",title:`Demo conversation with ${A.first_name}`,created_at:new Date(S-(T+1)*14*864e5).toISOString()}))),await _3.from("attract_follow_ups").insert({user_id:s.id,agent_id:j[0].id,title:"Demo overdue commitment",touch_type:"call",priority:"high",due_at:new Date(S-6*864e5).toISOString()}),ae.success("Demo relationships seeded"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()},b=async()=>{if(!s)return;h(!0);const{data:v}=await _3.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0),j=(v??[]).map(_=>_.id);if(!j.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 _3.from(_).delete().in("agent_id",j);await _3.from("attract_agents").delete().in("id",j),ae.success("Demo data removed"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()};return a?e.jsx(Ws,{className:"h-72 w-full rounded-2xl"}):e.jsxs("div",{className:"p-4 sm:p-6 max-w-6xl mx-auto space-y-5",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(Ln,{to:"/admin",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1.5"})," Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Attract Intelligence Debug"}),e.jsx("p",{className:"text-[13.5px] text-muted-foreground mt-1",children:"Full transparency into scores, signals and recommendations for your own Attract data. Demo records are flagged and removable."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>{o.mutate({items:n}),l.mutate(n)},disabled:l.isPending||o.isPending,children:[e.jsx(Ai,{className:"h-3.5 w-3.5 mr-1.5"})," Recompute & persist"]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:g,disabled:u,children:[e.jsx(K7,{className:"h-3.5 w-3.5 mr-1.5"})," Seed demo relationships"]}),e.jsxs(B,{variant:"outline",className:"rounded-full text-destructive",onClick:b,disabled:u,children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-1.5"})," Clear demo data"]})]}),e.jsxs($r,{defaultValue:"agents",children:[e.jsxs(Ur,{className:"rounded-full",children:[e.jsx(Zt,{value:"agents",className:"rounded-full",children:"Scores & signals"}),e.jsx(Zt,{value:"digest",className:"rounded-full",children:"Digest payload"})]}),e.jsxs(ls,{value:"agents",className:"mt-4 space-y-3",children:[e.jsx(ge,{value:c,onChange:v=>d(v.target.value),placeholder:"Filter by name",className:"max-w-sm rounded-full"}),!f.length&&e.jsx(fe,{className:"p-6 rounded-2xl text-[13.5px] text-muted-foreground",children:"No agents in your Attract pipeline."}),f.map(v=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(Ln,{to:`/attract/agents/${v.agent.id}`,className:"text-[15px] font-semibold hover:text-violet-700",children:[v.agent.first_name,v.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("div",{className:"text-[12px] text-muted-foreground mt-0.5 capitalize",children:[v.agent.stage.replace(/_/g," ")," · ",v.agent.temperature??"no temperature"," · ",v.signals.daysSinceTouch??"—"," days since touch"]})]}),v.agent.is_demo&&e.jsx(ze,{variant:"outline",className:"rounded-full",children:"Demo"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4 mt-4",children:[e.jsx(ESt,{score:v.score}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground mb-1.5",children:["Recommendations (",v.recommendations.length,")"]}),v.recommendations.length?e.jsx("ul",{className:"space-y-2",children:v.recommendations.map(j=>e.jsxs("li",{className:"text-[12.5px]",children:[e.jsx("span",{className:"font-medium",children:j.title}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",j.signal_group," · rank ",j.rank_score," · ",j.priority]}),e.jsx("div",{className:"text-muted-foreground",children:j.reasons.join(" · ")})]},j.rec_key))}):e.jsx("div",{className:"text-[13px] text-muted-foreground",children:"None generated."})]})]}),e.jsxs("details",{className:"mt-3",children:[e.jsx("summary",{className:"text-[12px] cursor-pointer text-muted-foreground",children:"Raw signals"}),e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto mt-2 max-h-72",children:JSON.stringify({touches90:v.signals.touches90,kitShares:v.signals.shares.length,kitOpens:v.signals.totalKitOpens,questions:v.signals.questions,meetingRequests:v.signals.meetingRequests,overdueFollowUps:v.signals.overdueFollowUps.length,attended:v.signals.attended},null,2)})]})]},v.agent.id))]}),e.jsx(ls,{value:"digest",className:"mt-4",children:e.jsx(fe,{className:"p-4 rounded-2xl",children:e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto max-h-[600px]",children:JSON.stringify(p,null,2)})})})]})]})}function Cmn(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),a=N.useMemo(()=>nEe.filter(l=>{const o=s.toLowerCase().trim();return n!=="all"&&l.status!==n?!1:!o||`${l.title} ${l.pillar} ${l.route??""}`.toLowerCase().includes(o)}),[s,n]),i=N.useMemo(()=>{const l={live:0,partial:0,placeholder:0,integration_required:0};return nEe.forEach(o=>{l[o.status]++}),l},[]);return e.jsxs("div",{className:"p-4 sm:p-6 max-w-6xl mx-auto space-y-5",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(Ln,{to:"/admin",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1.5"})," Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Attract Pillar Tools QA"}),e.jsx("p",{className:"text-[13.5px] text-muted-foreground mt-1",children:"Private status map of every Attract tool — route, database dependencies, and what still needs work."})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Object.keys(i).map(l=>e.jsxs(fe,{className:"p-4 rounded-2xl cursor-pointer",onClick:()=>r(n===l?"all":l),children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums",children:i[l]}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:rEe[l]})]},l))}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(ge,{value:s,onChange:l=>t(l.target.value),placeholder:"Filter tools",className:"max-w-sm rounded-full"}),n!=="all"&&e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>r("all"),children:"Clear status filter"})]}),e.jsx("div",{className:"space-y-2",children:a.map(l=>e.jsx(fe,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold",children:l.title}),e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:l.pillar}),e.jsx(ze,{variant:"outline",className:`rounded-full ${BSt[l.status]}`,children:rEe[l.status]})]}),e.jsx("div",{className:"text-[12.5px] text-muted-foreground mt-1",children:l.notes||"—"}),e.jsxs("div",{className:"text-[11.5px] text-muted-foreground mt-1",children:["Tables: ",l.tables.length?l.tables.join(", "):"none"]})]}),l.route&&!l.route.includes(":")?e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs(Ln,{to:l.route,children:[l.route," ",e.jsx(tr,{className:"h-3 w-3 ml-1.5"})]})}):e.jsx("span",{className:"text-[12px] text-muted-foreground",children:l.route??"No route"})]})},`${l.pillar}-${l.key}`))})]})}const w3=q,Jet=["idea","researching","pitching","applied","tentative","confirmed","completed","declined","archived"],ett=["panel","keynote","mls_talk","podcast","webinar","mastermind","training","conference","other"],ttt=["attract-speaking"];function m4t(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:[...ttt,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await w3.from("attract_speaking_opportunities").select("*").order("starts_at",{ascending:!0,nullsFirst:!1});if(h)throw h;return u??[]}}),r=()=>{t.invalidateQueries({queryKey:ttt}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-activities"]})},a=gt({mutationFn:async u=>{const{data:h,error:p}=await w3.from("attract_speaking_opportunities").insert({...u,user_id:s.id}).select("*").single();if(p)throw p;return h},onSuccess:()=>{r(),ae.success("Speaking opportunity saved")},onError:u=>ae.error(u.message)}),i=gt({mutationFn:async({id:u,...h})=>{const{error:p}=await w3.from("attract_speaking_opportunities").update(h).eq("id",u);if(p)throw p},onSuccess:()=>{r(),ae.success("Updated")},onError:u=>ae.error(u.message)}),l=gt({mutationFn:async u=>{const{id:h,created_at:p,updated_at:f,user_id:g,...b}=u,{data:v,error:j}=await w3.from("attract_speaking_opportunities").insert({...b,title:`${u.title} (copy)`,status:"idea",user_id:s.id}).select("id").single();if(j)throw j;return v},onSuccess:()=>{r(),ae.success("Duplicated")},onError:u=>ae.error(u.message)}),o=gt({mutationFn:async u=>{const{error:h}=await w3.from("attract_speaking_opportunities").delete().eq("id",u);if(h)throw h},onSuccess:()=>{r(),ae.success("Deleted")},onError:u=>ae.error(u.message)}),c=gt({mutationFn:async({title:u,dueAt:h,notes:p,touchType:f="speaking"})=>{const{error:g}=await w3.from("attract_follow_ups").insert({user_id:s.id,title:u,due_at:h??null,notes:p??null,touch_type:f,priority:"medium"});if(g)throw g},onSuccess:()=>{r(),ae.success("Added to Follow-Up Center")},onError:u=>ae.error(u.message)}),d=gt({mutationFn:async({title:u,pillar:h="influence",activityType:p="speaking_outreach",agentId:f})=>{const{error:g}=await w3.from("attract_activities").insert({user_id:s.id,title:u,pillar:h,activity_type:p,agent_id:f??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 hEe={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"},Bke={title:"",organization:"",event_type:"panel",status:"idea",timezone:"America/New_York",pillar:"influence",linked_agent_ids:[]};function Tmn(){const{items:s,isLoading:t,create:n,update:r,duplicate:a,remove:i,addTask:l,logActivity:o}=m4t(),{agents:c=[]}=d0(),{kits:d=[]}=$R(),u=xbe(),h=(u==null?void 0:u.events)??(u==null?void 0:u.data)??[],[p,f]=N.useState("month"),[g,b]=N.useState(new Date),[v,j]=N.useState("all"),[_,S]=N.useState("all"),[A,T]=N.useState("all"),[D,L]=N.useState(!1),[M,F]=N.useState(null),[z,V]=N.useState(null),W=N.useMemo(()=>s.filter(ie=>!(!D&&(ie.is_archived||ie.status==="archived")||v!=="all"&&ie.status!==v||_!=="all"&&ie.event_type!==_||A!=="all"&&!(ie.linked_agent_ids??[]).includes(A))),[s,v,_,A,D]),K=W.filter(ie=>ie.starts_at),Y=W.filter(ie=>!ie.starts_at),ee=new Date,ne=N.useMemo(()=>{const ie=K.filter(Ce=>Uv(Lu(Ce.starts_at),ee)&&["confirmed","tentative"].includes(Ce.status)),ye=W.filter(Ce=>Ce.submission_deadline&&Uv(Lu(Ce.submission_deadline),ee)),_e=W.filter(Ce=>["pitching","applied","researching"].includes(Ce.status)),Me=W.filter(Ce=>Ce.status==="confirmed"),Te=W.filter(Ce=>Ce.follow_up_date&&Ce.status==="completed");return{upcoming:ie,deadlines:ye,pitches:_e,confirmed:Me,followUps:Te}},[W,K]),oe=N.useMemo(()=>B4e(p==="week"?{start:Km(g),end:k8(g)}:{start:Km(Bd(g)),end:k8(H0(g))}),[g,p]),pe=ie=>K.filter(ye=>Rl(Lu(ye.starts_at),ie)),ce=async()=>{var ye;if(!((ye=M==null?void 0:M.title)!=null&&ye.trim())){ae.error("Give the talk a title");return}const ie={...M};delete ie.created_at,delete ie.updated_at,delete ie.user_id,(ie.fee===""||ie.fee==null)&&(ie.fee=null),["starts_at","ends_at","submission_deadline","follow_up_date","linked_event_id","linked_kit_id"].forEach(_e=>{ie[_e]===""&&(ie[_e]=null)}),M.id?await r.mutateAsync(ie):await n.mutateAsync(ie),F(null)},de=ie=>{if(!ie.starts_at){ae.error("Add a date first");return}const ye=Ee=>new Date(Ee).toISOString().replace(/[-:]|\.\d{3}/g,""),_e=ie.ends_at??new Date(new Date(ie.starts_at).getTime()+60*6e4).toISOString(),Me=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp Attract//Speaking//EN","BEGIN:VEVENT",`UID:${ie.id}@levelup-attract`,`DTSTAMP:${ye(new Date().toISOString())}`,`DTSTART:${ye(ie.starts_at)}`,`DTEND:${ye(_e)}`,`SUMMARY:${(ie.title||"").replace(/\n/g," ")}`,`LOCATION:${(ie.location||ie.virtual_link||"").replace(/\n/g," ")}`,`DESCRIPTION:${[ie.organization,ie.topic].filter(Boolean).join(" — ").replace(/\n/g," ")}`,"END:VEVENT","END:VCALENDAR"].join(`\r `),Te=URL.createObjectURL(new Blob([Me],{type:"text/calendar"})),Ce=document.createElement("a");Ce.href=Te,Ce.download=`${ie.title.replace(/\W+/g,"-").toLowerCase()}.ics`,Ce.click(),URL.revokeObjectURL(Te)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-32 rounded-2xl"}),e.jsx(Ws,{className:"h-96 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ku,{eyebrow:"Pillar 02 · Influence",title:"Speaking Calendar",description:"Every stage, panel, podcast, and MLS talk — from first idea to post-event follow-up.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>F({...Bke}),children:[e.jsx(As,{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(n7,{label:"Upcoming talks",value:ne.upcoming.length,icon:Bv}),e.jsx(n7,{label:"Deadlines ahead",value:ne.deadlines.length,icon:gr}),e.jsx(n7,{label:"Pitches in flight",value:ne.pitches.length,icon:cr}),e.jsx(n7,{label:"Confirmed",value:ne.confirmed.length,icon:xr}),e.jsx(n7,{label:"Post-event follow-ups",value:ne.followUps.length,icon:pu})]}),e.jsxs(fe,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"flex rounded-full bg-slate-100 p-1",children:["month","week","agenda"].map(ie=>e.jsx("button",{onClick:()=>f(ie),className:`px-3 py-1.5 rounded-full text-[12.5px] font-medium capitalize ${p===ie?"bg-white shadow-sm text-slate-900":"text-slate-500"}`,children:ie},ie))}),p!=="agenda"&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>b(p==="week"?F2(g,-1):kf(g,-1)),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-semibold min-w-[130px] text-center",children:ks(g,p==="week"?"'Week of' MMM d":"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>b(p==="week"?F2(g,1):kf(g,1)),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>b(new Date),children:"Today"})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(us,{value:v,onValueChange:j,children:[e.jsx(cs,{className:"w-[140px] rounded-full h-9",children:e.jsx(hs,{placeholder:"Status"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All statuses"}),Jet.map(ie=>e.jsx(Ze,{value:ie,className:"capitalize",children:ie.replace(/_/g," ")},ie))]})]}),e.jsxs(us,{value:_,onValueChange:S,children:[e.jsx(cs,{className:"w-[140px] rounded-full h-9",children:e.jsx(hs,{placeholder:"Type"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All types"}),ett.map(ie=>e.jsx(Ze,{value:ie,className:"capitalize",children:ie.replace(/_/g," ")},ie))]})]}),e.jsxs(us,{value:A,onValueChange:T,children:[e.jsx(cs,{className:"w-[160px] rounded-full h-9",children:e.jsx(hs,{placeholder:"Relationship"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All relationships"}),c.map(ie=>e.jsx(Ze,{value:ie.id,children:[ie.first_name,ie.last_name].filter(Boolean).join(" ")},ie.id))]})]}),e.jsxs(B,{variant:D?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>L(ie=>!ie),children:[e.jsx(im,{className:"h-3.5 w-3.5 mr-1.5"}),"Archived"]})]}),s.length===0?e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx(Bv,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"text-[16px] font-semibold mt-3",children:"No speaking opportunities yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-md mx-auto",children:"Start with the rooms you already have access to — your office meeting, a local MLS class, a peer's podcast. Track the pitch, the deadline, and the follow-up in one place."}),e.jsxs(B,{className:"mt-4 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>F({...Bke}),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"Add your first opportunity"]})]}):p==="agenda"?e.jsxs("div",{className:"space-y-3",children:[[...K,...Y].length===0&&e.jsx(fe,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"Nothing matches these filters."}),[...K,...Y].map(ie=>e.jsx(Emn,{o:ie,onEdit:()=>F(ie),onComplete:()=>V(ie),onDuplicate:()=>a.mutate(ie),onDelete:()=>i.mutate(ie.id),onArchive:()=>r.mutate({id:ie.id,is_archived:!ie.is_archived,status:ie.is_archived?"idea":"archived"}),onIcs:()=>de(ie),onPitchTask:()=>l.mutate({title:`Pitch: ${ie.title}${ie.organization?` (${ie.organization})`:""}`,dueAt:ie.submission_deadline?new Date(ie.submission_deadline).toISOString():null,notes:ie.notes??void 0}),onLogOutreach:()=>o.mutate({title:`Outreach for ${ie.title}`}),onConfirm:()=>r.mutate({id:ie.id,status:"confirmed"})},ie.id))]}):e.jsxs(fe,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 border-b bg-slate-50",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(ie=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider font-semibold text-slate-500 text-center",children:ie},ie))}),e.jsx("div",{className:"grid grid-cols-7",children:oe.map(ie=>{const ye=pe(ie);return e.jsxs("div",{className:`min-h-[92px] sm:min-h-[112px] border-b border-r p-1.5 ${aU(ie,g)||p==="week"?"bg-white":"bg-slate-50/60"}`,children:[e.jsx("button",{onClick:()=>F({...Bke,starts_at:new Date(ie.setHours(10,0,0,0)).toISOString()}),className:`text-[11.5px] font-semibold h-6 w-6 rounded-full grid place-items-center ${Rl(ie,ee)?"bg-violet-600 text-white":"text-slate-500 hover:bg-slate-100"}`,children:ks(ie,"d")}),e.jsxs("div",{className:"mt-1 space-y-1",children:[ye.slice(0,3).map(_e=>e.jsx("button",{onClick:()=>F(_e),className:`w-full text-left text-[11px] px-1.5 py-1 rounded-md border truncate ${hEe[_e.status]??""}`,children:_e.title},_e.id)),ye.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-400 pl-1",children:["+",ye.length-3," more"]})]})]},ie.toISOString())})}),Y.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 (",Y.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Y.map(ie=>e.jsx("button",{onClick:()=>F(ie),className:`text-[12px] px-2.5 py-1 rounded-full border ${hEe[ie.status]??""}`,children:ie.title},ie.id))})]})]}),e.jsx(f6,{}),e.jsx(bs,{open:!!M,onOpenChange:ie=>!ie&&F(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:M!=null&&M.id?"Edit speaking opportunity":"New speaking opportunity"})}),M&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(xd,{label:"Title",className:"sm:col-span-2",children:e.jsx(ge,{value:M.title??"",onChange:ie=>F({...M,title:ie.target.value}),placeholder:"Panel: Winning listings in a shifting market"})}),e.jsx(xd,{label:"Event / organization",children:e.jsx(ge,{value:M.organization??"",onChange:ie=>F({...M,organization:ie.target.value})})}),e.jsx(xd,{label:"Event type",children:e.jsxs(us,{value:M.event_type??"panel",onValueChange:ie=>F({...M,event_type:ie}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:ett.map(ie=>e.jsx(Ze,{value:ie,className:"capitalize",children:ie.replace(/_/g," ")},ie))})]})}),e.jsx(xd,{label:"Contact name",children:e.jsx(ge,{value:M.contact_name??"",onChange:ie=>F({...M,contact_name:ie.target.value})})}),e.jsx(xd,{label:"Contact email",children:e.jsx(ge,{type:"email",value:M.contact_email??"",onChange:ie=>F({...M,contact_email:ie.target.value})})}),e.jsx(xd,{label:"Contact phone",children:e.jsx(ge,{value:M.contact_phone??"",onChange:ie=>F({...M,contact_phone:ie.target.value})})}),e.jsx(xd,{label:"Audience",children:e.jsx(ge,{value:M.audience??"",onChange:ie=>F({...M,audience:ie.target.value}),placeholder:"120 local agents"})}),e.jsx(xd,{label:"Location",children:e.jsx(ge,{value:M.location??"",onChange:ie=>F({...M,location:ie.target.value})})}),e.jsx(xd,{label:"Virtual link",children:e.jsx(ge,{value:M.virtual_link??"",onChange:ie=>F({...M,virtual_link:ie.target.value})})}),e.jsx(xd,{label:"Starts",children:e.jsx(ge,{type:"datetime-local",value:stt(M.starts_at),onChange:ie=>F({...M,starts_at:ie.target.value?new Date(ie.target.value).toISOString():null})})}),e.jsx(xd,{label:"Ends",children:e.jsx(ge,{type:"datetime-local",value:stt(M.ends_at),onChange:ie=>F({...M,ends_at:ie.target.value?new Date(ie.target.value).toISOString():null})})}),e.jsx(xd,{label:"Status",children:e.jsxs(us,{value:M.status??"idea",onValueChange:ie=>F({...M,status:ie}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:Jet.map(ie=>e.jsx(Ze,{value:ie,className:"capitalize",children:ie},ie))})]})}),e.jsx(xd,{label:"Fee / honorarium",children:e.jsx(ge,{type:"number",value:M.fee??"",onChange:ie=>F({...M,fee:ie.target.value===""?null:Number(ie.target.value)})})}),e.jsx(xd,{label:"Submission deadline",children:e.jsx(ge,{type:"date",value:M.submission_deadline??"",onChange:ie=>F({...M,submission_deadline:ie.target.value||null})})}),e.jsx(xd,{label:"Follow-up date",children:e.jsx(ge,{type:"date",value:M.follow_up_date??"",onChange:ie=>F({...M,follow_up_date:ie.target.value||null})})}),e.jsx(xd,{label:"Application URL",className:"sm:col-span-2",children:e.jsx(ge,{value:M.application_url??"",onChange:ie=>F({...M,application_url:ie.target.value})})}),e.jsx(xd,{label:"Topic",className:"sm:col-span-2",children:e.jsx(ge,{value:M.topic??"",onChange:ie=>F({...M,topic:ie.target.value})})}),e.jsx(xd,{label:"Linked Connect event",children:e.jsxs(us,{value:M.linked_event_id??"none",onValueChange:ie=>F({...M,linked_event_id:ie==="none"?null:ie}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"None"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"None"}),h.map(ie=>e.jsx(Ze,{value:ie.id,children:ie.title},ie.id))]})]})}),e.jsx(xd,{label:"Linked Resource Kit",children:e.jsxs(us,{value:M.linked_kit_id??"none",onValueChange:ie=>F({...M,linked_kit_id:ie==="none"?null:ie}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"None"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"None"}),d.map(ie=>e.jsx(Ze,{value:ie.id,children:ie.title},ie.id))]})]})}),e.jsx(xd,{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(ie=>{const ye=(M.linked_agent_ids??[]).includes(ie.id);return e.jsx("button",{type:"button",onClick:()=>F({...M,linked_agent_ids:ye?(M.linked_agent_ids??[]).filter(_e=>_e!==ie.id):[...M.linked_agent_ids??[],ie.id]}),className:`text-[12px] px-2.5 py-1 rounded-full border ${ye?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-600"}`,children:[ie.first_name,ie.last_name].filter(Boolean).join(" ")},ie.id)})]})}),e.jsx(xd,{label:"Travel notes",className:"sm:col-span-2",children:e.jsx(Ts,{rows:2,value:M.travel_notes??"",onChange:ie=>F({...M,travel_notes:ie.target.value})})}),e.jsx(xd,{label:"Notes",className:"sm:col-span-2",children:e.jsx(Ts,{rows:3,value:M.notes??"",onChange:ie=>F({...M,notes:ie.target.value})})})]}),e.jsxs(Xn,{className:"gap-2",children:[e.jsx(B,{variant:"ghost",onClick:()=>F(null),children:"Cancel"}),e.jsx(B,{onClick:ce,disabled:n.isPending||r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save"})]})]})}),e.jsx(Amn,{item:z,onClose:()=>V(null),onSave:async(ie,ye)=>{await r.mutateAsync({id:z.id,status:"completed",outcome:ie}),ye&&await l.mutateAsync({title:`Post-event follow-up: ${z.title}`,dueAt:new Date(Date.now()+2*864e5).toISOString(),notes:ie.next_actions}),await o.mutateAsync({title:`Spoke at ${z.title}`,activityType:"speaking_completed"}),V(null)}})]})}function stt(s){if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)}function xd({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(se,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function n7({label:s,value:t,icon:n}){return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx(n,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"mt-1 text-[22px] font-semibold tabular-nums text-slate-900",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function Emn({o:s,onEdit:t,onComplete:n,onDuplicate:r,onDelete:a,onArchive:i,onIcs:l,onPitchTask:o,onLogOutreach:c,onConfirm:d}){var p;const u=s,h=u.submission_deadline?Wx(Lu(u.submission_deadline),new Date):null;return e.jsx(fe,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("button",{onClick:t,className:"text-[15px] font-semibold text-slate-900 hover:text-violet-700 text-left",children:u.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:[u.organization,(p=u.event_type)==null?void 0:p.replace(/_/g," "),u.audience].filter(Boolean).join(" · ")||"No details yet"}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1 flex items-center gap-3 flex-wrap",children:[u.starts_at&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Tl,{className:"h-3.5 w-3.5"}),ks(Lu(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(gr,{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(_n,{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(ze,{variant:"outline",className:`capitalize rounded-full ${hEe[u.status]??""}`,children:u.status}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",children:e.jsx(Xf,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[e.jsx(Xr,{onClick:t,children:"Edit"}),e.jsxs(Xr,{onClick:o,children:[e.jsx(pu,{className:"h-3.5 w-3.5 mr-2"}),"Add pitch task"]}),e.jsxs(Xr,{onClick:c,children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-2"}),"Log outreach"]}),e.jsxs(Xr,{onClick:d,children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-2"}),"Mark confirmed"]}),e.jsxs(Xr,{onClick:n,children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-2"}),"Mark completed"]}),e.jsxs(Xr,{onClick:l,children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-2"}),"Download .ics"]}),e.jsxs(Xr,{onClick:r,children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(Xr,{onClick:i,children:[e.jsx(im,{className:"h-3.5 w-3.5 mr-2"}),u.is_archived?"Unarchive":"Archive"]}),e.jsxs(Xr,{className:"text-destructive",onClick:a,children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]})]})})}function Amn({item:s,onClose:t,onSave:n}){const[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState("");return e.jsx(bs,{open:!!s,onOpenChange:h=>!h&&t(),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Capture the outcome"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(xd,{label:"Attendance",children:e.jsx(ge,{value:r,onChange:h=>a(h.target.value),placeholder:"How many were in the room?"})}),e.jsx(xd,{label:"Leads / relationships created",children:e.jsx(Ts,{rows:2,value:i,onChange:h=>l(h.target.value)})}),e.jsx(xd,{label:"Content captured",children:e.jsx(Ts,{rows:2,value:o,onChange:h=>c(h.target.value),placeholder:"Photos, clips, quotes"})}),e.jsx(xd,{label:"Next actions",children:e.jsx(Ts,{rows:2,value:d,onChange:h=>u(h.target.value)})})]}),e.jsxs(Xn,{className:"gap-2",children:[e.jsx(B,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(B,{variant:"outline",onClick:()=>n({attendance:r,leads:i,content:o,next_actions:d},!1),children:"Save only"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>n({attendance:r,leads:i,content:o,next_actions:d},!0),children:"Save + create follow-up"})]})]})})}const HP=q,mEe=["attract-masterclasses"];function Mmn(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:[...mEe,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await HP.from("attract_masterclasses").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=()=>t.invalidateQueries({queryKey:mEe}),a=gt({mutationFn:async o=>{const{data:c,error:d}=await HP.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=gt({mutationFn:async o=>{const{id:c,created_at:d,updated_at:u,user_id:h,...p}=o,{data:f,error:g}=await HP.from("attract_masterclasses").insert({...p,title:`${o.title} (copy)`,status:"draft",user_id:s.id}).select("id").single();if(g)throw g;return f},onSuccess:()=>{r(),ae.success("Duplicated")},onError:o=>ae.error(o.message)}),l=gt({mutationFn:async o=>{const{error:c}=await HP.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 Imn(s){const t=Gt(),n=lt({queryKey:["attract-masterclass",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await HP.from("attract_masterclasses").select("*").eq("id",s).maybeSingle();if(i)throw i;return a}}),r=gt({mutationFn:async a=>{const{error:i}=await HP.from("attract_masterclasses").update(a).eq("id",s);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-masterclass",s]}),t.invalidateQueries({queryKey:mEe})},onError:a=>ae.error(a.message)});return{masterclass:n.data??null,isLoading:n.isLoading,save:r}}const ru=(s,t)=>({id:crypto.randomUUID(),title:s,lessons:t.map(([n,r,a])=>({id:crypto.randomUUID(),title:n,minutes:r,talking_points:a}))}),ntt=[{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:[ru("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"]]),ru("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"]]),ru("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:[ru("Audit",[["Sorting your list into A/B/C",10,"Criteria that actually predict referrals"],["Fixing missing data",8,"Birthdays, anniversaries, spouse names"]]),ru("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"]]),ru("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:[ru("Before",[["Neighborhood invites",8,"Door knocking and digital invites"],["Setting the stage",7,"Materials that create conversations"]]),ru("During",[["The three questions",10,"How to qualify without interrogating"],["Capturing real contact info",8,"Sign-in that people actually complete"]]),ru("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:[ru("Positioning",[["Pick your lane",10,"Neighborhood, niche, or narrative"],["What to never post",6,"The credibility killers"]]),ru("Content system",[["The four content types",14,"Teach, prove, connect, invite"],["Batch filming",10,"One hour, ten pieces"]]),ru("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:[ru("Foundations",[["What AI is good and bad at",10,"Drafting vs deciding"],["Prompting basics",10,"Context, role, constraints"]]),ru("Workflows",[["Listing descriptions and marketing",12,"Brand voice inputs"],["Follow-up and email drafts",12,"Never auto-send"]]),ru("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:[ru("The builder landscape",[["How builder comp works",12,"Registration rules that protect you"],["Local builders worth knowing",8,"Relationship map"]]),ru("Representing the buyer",[["Contract differences",14,"What is negotiable"],["Inspections and walkthroughs",10,"Timeline checkpoints"]]),ru("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:[ru("Standards",[["What luxury clients notice",12,"Response time, discretion, detail"],["Your materials",10,"Photography, print, web"]]),ru("The listing experience",[["Pre-market strategy",12,"Whisper listings and staging"],["Private showings",8,"Choreography"]]),ru("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:[ru("Mindset",[["Why value beats pitching",10,"Relationship-first framing"],["Choosing your 20",8,"Fit criteria"]]),ru("The value plan",[["Resource kits that help",14,"What agents actually want"],["Events and masterminds",10,"Small rooms win"]]),ru("The conversation",[["When to talk business",10,"Earned invitation"],['Handling "I am happy where I am"',8,"Stay in relationship"]])]}];function Pmn(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 Lmn(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 Dmn(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("",`${oW(n)} SECTION: ${r.title}`),r.lessons.forEach(a=>{t.push(`${oW(n)} ${a.title}${a.minutes?` (${a.minutes}m)`:""}${a.talking_points?` — ${a.talking_points}`:""}`),n+=a.minutes??5})}),t.push("",`${oW(n)} Q&A`,`${oW(n+7)} Close: next step + resource kit`),t.join(` `)}function oW(s){const t=Math.floor(s/60),n=s%60;return`${t}:${String(n).padStart(2,"0")}`}function Rmn(){const{items:s,isLoading:t,create:n,duplicate:r,remove:a}=Mmn(),i=In(),[l,o]=N.useState(!1),c=s.filter(p=>!p.is_archived),d=s.filter(p=>p.is_archived),u=async()=>{const p=await n.mutateAsync({title:"Untitled masterclass"});i(`/attract/provide/masterclasses/${p.id}`)},h=async p=>{const f=ntt.find(b=>b.key===p),g=await n.mutateAsync(Pmn(f));i(`/attract/provide/masterclasses/${g.id}`)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-28 rounded-2xl"}),e.jsx(Ws,{className:"h-64 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ku,{eyebrow:"Pillar 03 · Provide",title:"Masterclass Builder",description:"Turn what you already know into a 45-minute teaching moment agents actually attend — curriculum, assets, promotion, run-of-show, and follow-up.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>o(p=>!p),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Starter templates"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:u,disabled:n.isPending,children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),"New masterclass"]})]})}),(l||s.length===0)&&e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-3",children:"Starter templates"}),e.jsx("div",{className:"grid sm:grid-cols-2 xl:grid-cols-4 gap-3",children:ntt.map(p=>e.jsxs("button",{onClick:()=>h(p.key),className:"text-left p-4 rounded-xl border hover:border-violet-300 hover:shadow-sm transition",children:[e.jsx(ze,{variant:"secondary",className:"capitalize mb-2",children:p.pillar}),e.jsx("div",{className:"font-semibold text-[14px] text-slate-900",children:p.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1 line-clamp-3",children:p.promise}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-2",children:[p.duration_minutes," min · ",p.curriculum.length," sections"]})]},p.key))})]}),c.length===0?e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx(_d,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"text-[16px] font-semibold mt-3",children:"No masterclasses yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-md mx-auto",children:"Pick a starter template above or build one from scratch. Nothing sends automatically — every piece of copy stays an editable draft."})]}):e.jsx("div",{className:"grid sm:grid-cols-2 xl:grid-cols-3 gap-3",children:c.map(p=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(ze,{variant:"outline",className:"capitalize rounded-full",children:p.status}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full h-7 w-7",children:e.jsx(Xf,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[e.jsx(Xr,{onClick:()=>i(`/attract/provide/masterclasses/${p.id}`),children:"Open builder"}),e.jsxs(Xr,{onClick:()=>r.mutate(p),children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(Xr,{className:"text-destructive",onClick:()=>a.mutate(p.id),children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]}),e.jsxs(Ln,{to:`/attract/provide/masterclasses/${p.id}`,className:"block mt-2",children:[e.jsx("div",{className:"font-semibold text-slate-900 line-clamp-2",children:p.title}),p.promise&&e.jsx("div",{className:"text-[12.5px] text-slate-500 line-clamp-2 mt-1",children:p.promise})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-3",children:[(p.curriculum??[]).length," sections · ",p.duration_minutes??45," min",p.delivery_date&&` · ${ks(new Date(p.delivery_date),"MMM d")}`]})]},p.id))}),d.length>0&&e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2 flex items-center gap-1.5",children:[e.jsx(im,{className:"h-3.5 w-3.5"}),"Archived"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(p=>e.jsx(Ln,{to:`/attract/provide/masterclasses/${p.id}`,className:"text-[12.5px] px-2.5 py-1 rounded-full border text-slate-600",children:p.title},p.id))})]}),e.jsx(f6,{})]})}const rtt=q,Omn=["Strategy","Curriculum","Assets","Promotion","Delivery","Follow-up"];function Fmn(){var K,Y,ee,ne,oe,pe,ce,de,ie,ye,_e,Me,Te;const{masterclassId:s}=_i(),t=In(),{user:n}=gs(),{masterclass:r,isLoading:a,save:i}=Imn(s),l=LSt(),{create:o}=$R(),[c,d]=N.useState(null),[u,h]=N.useState(0),[p,f]=N.useState(!1),[g,b]=N.useState("idle"),v=N.useRef(null),j=N.useRef(!1);N.useEffect(()=>{r&&!c&&d(r)},[r,c]);const _=Ce=>{d(Ee=>Ee&&{...Ee,...Ce}),j.current=!0,b("saving"),clearTimeout(v.current),v.current=setTimeout(()=>S({...c??{},...Ce}),900)},S=async Ce=>{const{id:Ee,user_id:De,created_at:Ie,updated_at:Fe,...qe}=Ce;await i.mutateAsync(qe),j.current=!1,b("saved"),setTimeout(()=>b(ve=>ve==="saved"?"idle":ve),1800)},A=(c==null?void 0:c.curriculum)??[],T=Ce=>_({curriculum:Ce}),D=N.useMemo(()=>A.reduce((Ce,Ee)=>Ce+Ee.lessons.reduce((De,Ie)=>De+(Ie.minutes??0),0),0),[A]);if(a||!c)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-24 rounded-2xl"}),e.jsx(Ws,{className:"h-96 rounded-2xl"})]});const L=()=>{_({promotion:{...c.promotion,...Lmn(c)}}),ae.success("Draft copy generated — edit before you send anything")},M=()=>{_({delivery:{...c.delivery,run_of_show:Dmn(c)}}),ae.success("Run of show generated")},F=async()=>{const Ce=await l.mutateAsync({title:c.title,description:c.promise??void 0,event_type:"masterclass",intended_audience:c.target_audience??void 0,related_pillar:c.pillar??"provide",starts_at:c.delivery_date??new Date(Date.now()+12096e5).toISOString(),format:c.format==="in_person"?"in_person":"virtual",agenda:A.flatMap(Ee=>Ee.lessons.map(De=>({item:`${Ee.title}: ${De.title}`}))),learning_outcomes:c.desired_outcome?[c.desired_outcome]:[]});await i.mutateAsync({linked_event_id:Ce.id,status:"scheduled"}),d(Ee=>Ee&&{...Ee,linked_event_id:Ce.id,status:"scheduled"}),ae.success("Connect event created as a draft"),t(`/attract/events/${Ce.id}/edit`)},z=async()=>{var De,Ie,Fe,qe,ve;const Ce=await o.mutateAsync({title:`${c.title} — Resource Kit`,description:c.promise??void 0,audience:c.target_audience??void 0,pillar:c.pillar??"provide",intro_text:((De=c.assets)==null?void 0:De.workbook)??void 0,cta_label:((Ie=c.assets)==null?void 0:Ie.cta_label)??void 0,cta_url:((Fe=c.assets)==null?void 0:Fe.cta_url)??void 0}),Ee=[...(((qe=c.assets)==null?void 0:qe.downloads)??[]).map((Je,we)=>({type:"link",title:Je.title,url:Je.url,sort_order:we})),...(((ve=c.assets)==null?void 0:ve.videos)??[]).map((Je,we)=>({type:"video",title:Je.title,url:Je.url,sort_order:100+we}))];Ee.length&&await rtt.from("attract_resource_kit_items").insert(Ee.map(Je=>({...Je,kit_id:Ce.id,user_id:n.id}))),await i.mutateAsync({linked_kit_id:Ce.id}),d(Je=>Je&&{...Je,linked_kit_id:Ce.id}),ae.success("Resource Kit created from your assets"),t(`/attract/provide/kits/${Ce.id}/edit`)},V=async()=>{const Ce=Date.now(),Ee=[{title:`Send recap + resources: ${c.title}`,due_at:new Date(Ce+1*864e5).toISOString()},{title:`Personal check-in with attendees: ${c.title}`,due_at:new Date(Ce+3*864e5).toISOString()},{title:`Invite engaged attendees to a 1:1: ${c.title}`,due_at:new Date(Ce+7*864e5).toISOString()}],{error:De}=await rtt.from("attract_follow_ups").insert(Ee.map(Ie=>({...Ie,user_id:n.id,touch_type:"masterclass",priority:"medium"})));if(De){ae.error(De.message);return}ae.success("3 follow-ups added to your Follow-Up Center")};return e.jsxs("div",{className:"space-y-5",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(Ln,{to:"/attract/provide/masterclasses",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1.5"}),"All masterclasses"]})}),e.jsx(Ku,{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(ss,{className:"h-3.5 w-3.5 animate-spin"}),"Saving…"]}):g==="saved"?e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"h-3.5 w-3.5 text-emerald-600"}),"Saved"]}):"All changes saved"}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>f(Ce=>!Ce),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),p?"Edit":"Preview"]})]})}),e.jsx(fe,{className:"p-2 rounded-2xl flex gap-1 overflow-x-auto",children:Omn.map((Ce,Ee)=>e.jsxs("button",{onClick:()=>{f(!1),h(Ee)},className:`px-3.5 py-2 rounded-xl text-[13px] font-medium whitespace-nowrap ${u===Ee&&!p?"bg-violet-600 text-white":"text-slate-600 hover:bg-slate-100"}`,children:[Ee+1,". ",Ce]},Ce))}),p?e.jsx(Bmn,{m:c}):e.jsxs(fe,{className:"p-5 rounded-2xl space-y-4",children:[u===0&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(th,{label:"Title",className:"sm:col-span-2",children:e.jsx(ge,{value:c.title,onChange:Ce=>_({title:Ce.target.value})})}),e.jsx(th,{label:"The promise",className:"sm:col-span-2",children:e.jsx(Ts,{rows:2,value:c.promise??"",onChange:Ce=>_({promise:Ce.target.value}),placeholder:"Walk out with…"})}),e.jsx(th,{label:"Target audience",children:e.jsx(ge,{value:c.target_audience??"",onChange:Ce=>_({target_audience:Ce.target.value})})}),e.jsx(th,{label:"Problem solved",children:e.jsx(ge,{value:c.problem_solved??"",onChange:Ce=>_({problem_solved:Ce.target.value})})}),e.jsx(th,{label:"Desired outcome",className:"sm:col-span-2",children:e.jsx(ge,{value:c.desired_outcome??"",onChange:Ce=>_({desired_outcome:Ce.target.value})})}),e.jsx(th,{label:"Pillar",children:e.jsxs(us,{value:c.pillar??"provide",onValueChange:Ce=>_({pillar:Ce}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:["produce","influence","provide","connect"].map(Ce=>e.jsx(Ze,{value:Ce,className:"capitalize",children:Ce},Ce))})]})}),e.jsx(th,{label:"Format",children:e.jsxs(us,{value:c.format??"virtual",onValueChange:Ce=>_({format:Ce}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:["virtual","in_person","hybrid"].map(Ce=>e.jsx(Ze,{value:Ce,className:"capitalize",children:Ce.replace("_"," ")},Ce))})]})}),e.jsx(th,{label:"Duration (minutes)",children:e.jsx(ge,{type:"number",value:c.duration_minutes??45,onChange:Ce=>_({duration_minutes:Number(Ce.target.value)})})}),e.jsx(th,{label:"Delivery date",children:e.jsx(ge,{type:"datetime-local",value:zmn(c.delivery_date),onChange:Ce=>_({delivery_date:Ce.target.value?new Date(Ce.target.value).toISOString():null})})}),e.jsx(th,{label:"Status",children:e.jsxs(us,{value:c.status,onValueChange:Ce=>_({status:Ce}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:["draft","ready","scheduled","delivered","archived"].map(Ce=>e.jsx(Ze,{value:Ce,className:"capitalize",children:Ce},Ce))})]})})]}),u===1&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[A.length," sections · ",D," minutes planned"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>T([...A,{id:crypto.randomUUID(),title:"New section",lessons:[]}]),children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1.5"}),"Add section"]})]}),A.length===0&&e.jsx("div",{className:"text-[13.5px] text-slate-500 border border-dashed rounded-xl p-8 text-center",children:"No sections yet. Add your first one."}),A.map((Ce,Ee)=>e.jsxs(fe,{className:"p-4 rounded-xl bg-slate-50/60",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{value:Ce.title,onChange:De=>T(A.map(Ie=>Ie.id===Ce.id?{...Ie,title:De.target.value}:Ie)),className:"font-semibold"}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Ee===0,onClick:()=>T(lW(A,Ee,Ee-1)),children:e.jsx(sx,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Ee===A.length-1,onClick:()=>T(lW(A,Ee,Ee+1)),children:e.jsx(io,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>T(A.filter(De=>De.id!==Ce.id)),children:e.jsx(bn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[Ce.lessons.map((De,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(ge,{value:De.title,placeholder:"Lesson title",onChange:Fe=>W(Ce.id,De.id,{title:Fe.target.value})}),e.jsx(ge,{type:"number",className:"w-20",value:De.minutes??"",placeholder:"min",onChange:Fe=>W(Ce.id,De.id,{minutes:Number(Fe.target.value)})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Ie===0,onClick:()=>T(A.map(Fe=>Fe.id===Ce.id?{...Fe,lessons:lW(Fe.lessons,Ie,Ie-1)}:Fe)),children:e.jsx(sx,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Ie===Ce.lessons.length-1,onClick:()=>T(A.map(Fe=>Fe.id===Ce.id?{...Fe,lessons:lW(Fe.lessons,Ie,Ie+1)}:Fe)),children:e.jsx(io,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>T(A.map(Fe=>Fe.id===Ce.id?{...Fe,lessons:Fe.lessons.filter(qe=>qe.id!==De.id)}:Fe)),children:e.jsx(bn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-2",children:[e.jsx(Ts,{rows:2,placeholder:"Talking points",value:De.talking_points??"",onChange:Fe=>W(Ce.id,De.id,{talking_points:Fe.target.value})}),e.jsx(Ts,{rows:2,placeholder:"Exercise",value:De.exercise??"",onChange:Fe=>W(Ce.id,De.id,{exercise:Fe.target.value})}),e.jsx(Ts,{rows:2,placeholder:"Example / story",value:De.example??"",onChange:Fe=>W(Ce.id,De.id,{example:Fe.target.value})}),e.jsx(Ts,{rows:2,placeholder:"Speaker notes",value:De.speaker_notes??"",onChange:Fe=>W(Ce.id,De.id,{speaker_notes:Fe.target.value})})]})]},De.id)),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>T(A.map(De=>De.id===Ce.id?{...De,lessons:[...De.lessons,{id:crypto.randomUUID(),title:""}]}:De)),children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1.5"}),"Add lesson"]})]})]},Ce.id))]}),u===2&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(th,{label:"Slide outline",children:e.jsx(Ts,{rows:5,value:((K=c.assets)==null?void 0:K.slide_outline)??"",onChange:Ce=>_({assets:{...c.assets,slide_outline:Ce.target.value}})})}),e.jsx(th,{label:"Workbook / checklist outline",children:e.jsx(Ts,{rows:5,value:((Y=c.assets)==null?void 0:Y.workbook)??"",onChange:Ce=>_({assets:{...c.assets,workbook:Ce.target.value}})})}),e.jsx(att,{label:"Downloads",items:((ee=c.assets)==null?void 0:ee.downloads)??[],onChange:Ce=>_({assets:{...c.assets,downloads:Ce}})}),e.jsx(att,{label:"Videos",items:((ne=c.assets)==null?void 0:ne.videos)??[],onChange:Ce=>_({assets:{...c.assets,videos:Ce}})}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(th,{label:"CTA label",children:e.jsx(ge,{value:((oe=c.assets)==null?void 0:oe.cta_label)??"",onChange:Ce=>_({assets:{...c.assets,cta_label:Ce.target.value}})})}),e.jsx(th,{label:"CTA URL",children:e.jsx(ge,{value:((pe=c.assets)==null?void 0:pe.cta_url)??"",onChange:Ce=>_({assets:{...c.assets,cta_url:Ce.target.value}})})})]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:z,disabled:o.isPending,children:[e.jsx(y9,{className:"h-4 w-4 mr-2"}),"Create Resource Kit from these assets"]}),c.linked_kit_id&&e.jsx(ze,{variant:"outline",className:"ml-2",children:"Kit linked"})]}),u===3&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Every piece stays an editable draft. Nothing sends automatically."}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:L,children:[e.jsx(Rm,{className:"h-4 w-4 mr-2"}),"Generate draft copy"]})]}),[["registration_copy","Registration page copy"],["email_invite","Email invite"],["social_post","Social post"],["dm_invite","DM / text invite"],["reminder","Reminder message"],["follow_up","Follow-up message"]].map(([Ce,Ee])=>{var De;return e.jsx(th,{label:Ee,children:e.jsx(Ts,{rows:5,value:((De=c.promotion)==null?void 0:De[Ce])??"",onChange:Ie=>_({promotion:{...c.promotion,[Ce]:Ie.target.value}})})},Ce)})]}),u===4&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:M,children:[e.jsx(Rm,{className:"h-4 w-4 mr-2"}),"Build run of show"]})}),e.jsx(th,{label:"Run of show",children:e.jsx(Ts,{rows:12,className:"font-mono text-[12.5px]",value:((ce=c.delivery)==null?void 0:ce.run_of_show)??"",onChange:Ce=>_({delivery:{...c.delivery,run_of_show:Ce.target.value}})})}),e.jsx(th,{label:"Check-in link",children:e.jsx(ge,{value:((de=c.delivery)==null?void 0:de.checkin_link)??"",onChange:Ce=>_({delivery:{...c.delivery,checkin_link:Ce.target.value}}),placeholder:"Paste the Connect event check-in URL"})}),e.jsx(th,{label:"Event notes",children:e.jsx(Ts,{rows:4,value:((ie=c.delivery)==null?void 0:ie.event_notes)??"",onChange:Ce=>_({delivery:{...c.delivery,event_notes:Ce.target.value}})})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:F,disabled:l.isPending,children:[e.jsx(Fg,{className:"h-4 w-4 mr-2"}),"Convert to a Connect event"]}),c.linked_event_id&&e.jsx(B,{variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(Ln,{to:`/attract/events/${c.linked_event_id}`,children:"Open linked event"})})]})]}),u===5&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(th,{label:"Attendee segmentation",children:e.jsx(Ts,{rows:3,value:((ye=c.follow_up)==null?void 0:ye.segments)??"",onChange:Ce=>_({follow_up:{...c.follow_up,segments:Ce.target.value}}),placeholder:"Attended + asked a question / attended / registered no-show"})}),e.jsx(th,{label:"Resource kit sharing note",children:e.jsx(Ts,{rows:3,value:((_e=c.follow_up)==null?void 0:_e.kit_note)??"",onChange:Ce=>_({follow_up:{...c.follow_up,kit_note:Ce.target.value}})})}),e.jsx(th,{label:"Suggested personal follow-ups",children:e.jsx(Ts,{rows:3,value:((Me=c.follow_up)==null?void 0:Me.personal_touches)??"",onChange:Ce=>_({follow_up:{...c.follow_up,personal_touches:Ce.target.value}})})}),e.jsx(th,{label:"Conversion / relationship outcomes",children:e.jsx(Ts,{rows:3,value:((Te=c.follow_up)==null?void 0:Te.outcomes)??"",onChange:Ce=>_({follow_up:{...c.follow_up,outcomes:Ce.target.value}})})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:V,children:[e.jsx(pu,{className:"h-4 w-4 mr-2"}),"Add 3 follow-ups to Follow-Up Center"]})]})]})]});function W(Ce,Ee,De){T(A.map(Ie=>Ie.id===Ce?{...Ie,lessons:Ie.lessons.map(Fe=>Fe.id===Ee?{...Fe,...De}:Fe)}:Ie))}}function lW(s,t,n){const r=[...s],[a]=r.splice(t,1);return r.splice(n,0,a),r}function zmn(s){if(!s)return"";const t=new Date(s);return new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function th({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(se,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function att({label:s,items:t,onChange:n}){return e.jsxs("div",{children:[e.jsx(se,{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(ge,{value:r.title,placeholder:"Title",onChange:i=>n(t.map((l,o)=>o===a?{...l,title:i.target.value}:l))}),e.jsx(ge,{value:r.url,placeholder:"https://",onChange:i=>n(t.map((l,o)=>o===a?{...l,url:i.target.value}:l))}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>n(t.filter((i,l)=>l!==a)),children:e.jsx(bn,{className:"h-4 w-4"})})]},a)),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>n([...t,{title:"",url:""}]),children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1.5"}),"Add ",s.toLowerCase().slice(0,-1)]})]})]})}function Bmn({m:s}){var t,n,r;return e.jsxs("div",{className:"grid lg:grid-cols-2 gap-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Curriculum"}),(s.curriculum??[]).length===0?e.jsx("div",{className:"text-[13px] text-slate-500",children:"Nothing yet."}):(s.curriculum??[]).map(a=>e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:"font-semibold text-[14px]",children:a.title}),e.jsx("ul",{className:"mt-1 space-y-1",children:a.lessons.map(i=>e.jsxs("li",{className:"text-[13px] text-slate-600",children:["• ",i.title,i.minutes?` (${i.minutes}m)`:""]},i.id))})]},a.id))]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Workbook outline"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap text-slate-700",children:((t=s.assets)==null?void 0:t.workbook)||"Nothing yet."})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Registration copy"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap text-slate-700",children:((n=s.promotion)==null?void 0:n.registration_copy)||"Nothing yet."})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Presenter run of show"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap font-mono text-slate-700",children:((r=s.delivery)==null?void 0:r.run_of_show)||"Nothing yet."})]})]})}const cS=q;function nq(s,t={}){const{orderBy:n="created_at",ascending:r=!1,titleField:a="title",duplicateOverrides:i={},label:l="Record"}=t,{user:o}=gs(),c=Gt(),d=[s,o==null?void 0:o.id],u=lt({queryKey:d,enabled:!!o,queryFn:async()=>{const{data:j,error:_}=await cS.from(s).select("*").order(n,{ascending:r,nullsFirst:!1});if(_)throw _;return j??[]}}),h=()=>{c.invalidateQueries({queryKey:[s]}),c.invalidateQueries({queryKey:["attract-followups"]}),c.invalidateQueries({queryKey:["attract-activities"]})},p=gt({mutationFn:async j=>{const{data:_,error:S}=await cS.from(s).insert({...j,user_id:o.id}).select("*").single();if(S)throw S;return _},onSuccess:()=>{h(),ae.success(`${l} saved`)},onError:j=>ae.error(j.message)}),f=gt({mutationFn:async({id:j,..._})=>{const{error:S}=await cS.from(s).update(_).eq("id",j);if(S)throw S},onSuccess:()=>{h(),ae.success("Updated")},onError:j=>ae.error(j.message)}),g=gt({mutationFn:async j=>{const{id:_,created_at:S,updated_at:A,user_id:T,...D}=j,L={...D,...i,user_id:o.id};a&&L[a]&&(L[a]=`${L[a]} (copy)`);const{data:M,error:F}=await cS.from(s).insert(L).select("id").single();if(F)throw F;return M},onSuccess:()=>{h(),ae.success("Duplicated")},onError:j=>ae.error(j.message)}),b=gt({mutationFn:async({id:j,archived:_})=>{const{error:S}=await cS.from(s).update({is_archived:_}).eq("id",j);if(S)throw S},onSuccess:(j,_)=>{h(),ae.success(_.archived?"Archived":"Restored")},onError:j=>ae.error(j.message)}),v=gt({mutationFn:async j=>{const{error:_}=await cS.from(s).delete().eq("id",j);if(_)throw _},onSuccess:()=>{h(),ae.success("Deleted")},onError:j=>ae.error(j.message)});return{items:u.data??[],isLoading:u.isLoading,error:u.error,refetch:u.refetch,create:p,update:f,duplicate:g,archive:b,remove:v,userId:o==null?void 0:o.id}}function wbe(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async({title:n,dueAt:r,notes:a,touchType:i="task",agentId:l})=>{const{error:o}=await cS.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 rq(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async({title:n,description:r,pillar:a="produce",activityType:i="tool_action",agentId:l,metadata:o})=>{const{error:c}=await cS.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 $mn=["annual","quarterly","monthly"],nP=[{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 rP(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 Umn(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 qmn(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 Vmn(){const s=nq("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}=l4t(),n=wbe(),r=rq(),a=N.useMemo(()=>{const i={};return s.items.forEach(l=>{i[l.id]={closings:t.filter(o=>qmn(o.closing_date,l)).length}}),i},[s.items,t]);return{...s,goals:s.items,autoProgress:a,quickTask:n,logActivity:r}}function Hmn(s){const t=Number(s??0);return t?{monthly:t/12,weekly:t/52}:null}const Gmn=Array.from({length:12},(s,t)=>({value:t+1,label:new Date(2e3,t,1).toLocaleString("en-US",{month:"long"})}));function f2(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 Wmn({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 itt={period_type:"annual",year:new Date().getFullYear(),quarter:1,month:new Date().getMonth()+1,use_auto_progress:!0};function Kmn(){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}=Vmn(),[p,f]=N.useState(!1),[g,b]=N.useState(null),[v,j]=N.useState(null),[_,S]=N.useState(null),A=N.useMemo(()=>s.filter(M=>p?M.is_archived:!M.is_archived),[s,p]),T=(M,F)=>{var V;const z=Number(M[F.actual]??0);return M.use_auto_progress&&F.key==="closings"?Math.max(z,((V=d[M.id])==null?void 0:V.closings)??0):z},D=async()=>{var F;if(!g)return;const M={label:((F=g.label)==null?void 0:F.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,...M}):await a.mutateAsync(M),b(null)},L=async()=>{if(!v)return;const M={};nP.forEach(F=>{M[F.actual]=Number(v[F.actual]??0)}),await i.mutateAsync({id:v.id,...M}),await h.mutateAsync({title:`Updated production progress — ${rP(v)}`,pillar:"produce",activityType:"goal_progress"}),j(null)};return e.jsxs("div",{children:[e.jsxs(Ln,{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(Wr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Ku,{eyebrow:"Produce → Tool",title:"Production Goals",description:"Set the annual, quarterly, and monthly numbers you're playing for — then track pace, not just totals. Progress can be updated manually or pulled from the transactions you log.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>f(M=>!M),children:p?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({...itt}),children:[e.jsx(As,{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(M=>e.jsx(Ws,{className:"h-56 rounded-2xl"},M))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Gi,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load your goals"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Fh,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&A.length===0&&e.jsxs(fe,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(wc,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:p?"No archived goals":"No production goals yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Start with one annual goal. Attract will break it into monthly and weekly activity targets and show whether you're ahead or behind pace."}),!p&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({...itt}),children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Create your first goal"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:A.map(M=>{const F=Umn(M),z=nP.find(oe=>M[oe.target])??nP[0],V=Number(M[z.target]??0),W=T(M,z),K=V?W/V:0,Y=V*F,ee=W>=Y,ne=Hmn(V);return e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[16px] font-semibold text-slate-900",children:M.label||`${rP(M)} Goals`}),e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:M.period_type}),e.jsx(ze,{variant:"outline",className:"rounded-full",children:rP(M)})]}),M.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:M.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>b(M),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(M),children:e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:M.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:M.id,archived:!M.is_archived}),children:e.jsx(im,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>S(M),children:e.jsx(bn,{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(Wmn,{pct:K}),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(K*100),"%"]})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:z.label}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:[f2(W,z.format)," ",e.jsxs("span",{className:"text-slate-400 text-[15px]",children:["/ ",f2(V,z.format)]})]}),e.jsxs("div",{className:`text-[12.5px] mt-0.5 font-medium ${ee?"text-emerald-600":"text-amber-600"}`,children:[ee?"Ahead of pace":"Behind pace"," · pace target ",f2(Y,z.format)," (",Math.round(F*100),"% of period elapsed)"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 mt-4",children:nP.filter(oe=>M[oe.target]).map(oe=>{const pe=Number(M[oe.target]),ce=T(M,oe);return e.jsxs("div",{className:"rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:oe.label}),e.jsxs("div",{className:"text-[13.5px] font-semibold tabular-nums text-slate-900",children:[f2(ce,oe.format)," / ",f2(pe,oe.format)]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-200 mt-1.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-violet-600",style:{width:`${Math.min(100,pe?ce/pe*100:0)}%`}})})]},oe.key)})}),M.period_type==="annual"&&ne&&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:f2(ne.monthly,z.format)})," per month ·"," ",e.jsx("strong",{children:f2(ne.weekly,z.format)})," per week of ",z.label.toLowerCase(),"."]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>j({...M}),children:"Update progress"}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u.mutate({title:`Goal push: ${z.label} — ${f2(ne?ne.weekly:V,z.format)} this week`,dueAt:new Date().toISOString(),notes:`From ${rP(M)} production goal`,touchType:"goal"}),children:[e.jsx(pu,{className:"h-3.5 w-3.5 mr-1.5"})," Add to Today's Plan"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>h.mutate({title:`Win logged toward ${rP(M)} goals`,pillar:"produce",activityType:"goal_win"}),children:[e.jsx(vo,{className:"h-3.5 w-3.5 mr-1.5"})," Log a win"]})]})]},M.id)})}),e.jsx(bs,{open:!!g,onOpenChange:M=>!M&&b(null),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:g!=null&&g.id?"Edit goal":"New production goal"}),e.jsx(Qn,{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(se,{children:"Label (optional)"}),e.jsx(ge,{value:g.label??"",onChange:M=>b({...g,label:M.target.value}),placeholder:"e.g. 2026 Big Rock"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Period"}),e.jsxs(us,{value:g.period_type,onValueChange:M=>b({...g,period_type:M}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:$mn.map(M=>e.jsx(Ze,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Year"}),e.jsx(ge,{type:"number",value:g.year??"",onChange:M=>b({...g,year:Number(M.target.value)})})]}),g.period_type==="quarterly"&&e.jsxs("div",{children:[e.jsx(se,{children:"Quarter"}),e.jsxs(us,{value:String(g.quarter??1),onValueChange:M=>b({...g,quarter:Number(M)}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:[1,2,3,4].map(M=>e.jsxs(Ze,{value:String(M),children:["Q",M]},M))})]})]}),g.period_type==="monthly"&&e.jsxs("div",{children:[e.jsx(se,{children:"Month"}),e.jsxs(us,{value:String(g.month??1),onValueChange:M=>b({...g,month:Number(M)}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:Gmn.map(M=>e.jsx(Ze,{value:String(M.value),children:M.label},M.value))})]})]})]}),e.jsx("div",{className:"grid sm:grid-cols-3 gap-3",children:nP.map(M=>e.jsxs("div",{children:[e.jsxs(se,{children:[M.label," target"]}),e.jsx(ge,{type:"number",value:g[M.target]??"",onChange:F=>b({...g,[M.target]:F.target.value===""?null:Number(F.target.value)})})]},M.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(vn,{checked:g.use_auto_progress??!0,onCheckedChange:M=>b({...g,use_auto_progress:M})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ts,{value:g.notes??"",onChange:M=>b({...g,notes:M.target.value}),rows:3})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>b(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:D,disabled:a.isPending||i.isPending,children:"Save goal"})]})]})}),e.jsx(bs,{open:!!v,onOpenChange:M=>!M&&j(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Update progress"}),e.jsxs(Qn,{children:[v?rP(v):""," — enter your actuals to date."]})]}),v&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:nP.filter(M=>v[M.target]).map(M=>e.jsxs("div",{children:[e.jsx(se,{children:M.label}),e.jsx(ge,{type:"number",value:v[M.actual]??0,onChange:F=>j({...v,[M.actual]:Number(F.target.value)})})]},M.key))}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>j(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:L,children:"Save progress"})]})]})}),e.jsx(bs,{open:!!_,onOpenChange:M=>!M&&S(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete this goal?"}),e.jsx(Qn,{children:"This can't be undone. Archive it instead if you want to keep the history."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(_.id),S(null)},children:"Delete"})]})]})})]})}const $ke=[{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 Ymn(){const s=nq("attract_awards",{orderBy:"awarded_on",ascending:!1,label:"Award",duplicateOverrides:{is_archived:!1}}),t=rq();return{...s,awards:s.items,logActivity:t}}const ott={category:"award",status:"active",is_public:!0};function ltt(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 Zmn(){const{awards:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,logActivity:d}=Ymn(),[u,h]=N.useState(!1),[p,f]=N.useState("all"),[g,b]=N.useState(""),[v,j]=N.useState(null),[_,S]=N.useState(null),A=N.useMemo(()=>s.filter(L=>{if(u!==!!L.is_archived||p!=="all"&&L.category!==p)return!1;const M=g.toLowerCase().trim();return!M||`${L.title} ${L.issuer??""} ${L.description??""}`.toLowerCase().includes(M)}),[s,u,p,g]),T=async()=>{var M;if(!((M=v==null?void 0:v.title)!=null&&M.trim())){ae.error("Add a title");return}const L={title:v.title.trim(),issuer:v.issuer||null,awarded_on:v.awarded_on||null,category:v.category??"award",description:v.description||null,proof_url:v.proof_url||null,production_period:v.production_period||null,is_public:v.is_public??!0};v.id?await i.mutateAsync({id:v.id,...L}):(await a.mutateAsync(L),await d.mutateAsync({title:`Added recognition: ${L.title}`,pillar:"produce",activityType:"award_added"})),j(null)},D=L=>{var F;const M=[L.title,L.issuer&&`— ${L.issuer}`,L.awarded_on&&`(${ltt(L.awarded_on)})`].filter(Boolean).join(" ");(F=navigator.clipboard)==null||F.writeText(M),ae.success("Proof point copied — paste it into Content Studio")};return e.jsxs("div",{children:[e.jsxs(Ln,{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(Wr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Ku,{eyebrow:"Produce → Tool",title:"Awards & Recognition",description:"Your credibility file. Keep every award, ranking, and certification in one place so proof points are ready when you write content or pitch a speaking slot.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>h(L=>!L),children:u?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>j({...ott}),children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Add Recognition"]})]})}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(ge,{value:g,onChange:L=>b(L.target.value),placeholder:"Search recognitions",className:"max-w-xs rounded-full"}),e.jsxs(us,{value:p,onValueChange:f,children:[e.jsx(cs,{className:"w-[190px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All categories"}),$ke.map(L=>e.jsx(Ze,{value:L.value,children:L.label},L.value))]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(L=>e.jsx(Ws,{className:"h-36 rounded-2xl"},L))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Gi,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load recognitions"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Fh,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&A.length===0&&e.jsxs(fe,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(vc,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:u?"Nothing archived":"No recognitions logged yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add awards, production rankings, and designations. Copy any one of them as a proof point when writing authority content."}),!u&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>j({...ott}),children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Add your first"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:A.map(L=>{var M;return e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15.5px] font-semibold text-slate-900",children:L.title}),e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:((M=$ke.find(F=>F.value===L.category))==null?void 0:M.label)??L.category})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[L.issuer,ltt(L.awarded_on),L.production_period].filter(Boolean).join(" · ")}),L.description&&e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:L.description})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>j(L),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(L),children:e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:L.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:L.id,archived:!L.is_archived}),children:e.jsx(im,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>S(L),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>D(L),children:[e.jsx(El,{className:"h-3.5 w-3.5 mr-1.5"})," Copy proof point"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Ln,{to:"/attract/influence/content-studio",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Write about it"]})}),L.proof_url&&e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:L.proof_url,target:"_blank",rel:"noreferrer",children:["Proof ",e.jsx(tr,{className:"h-3 w-3 ml-1.5"})]})})]})]},L.id)})}),e.jsx(bs,{open:!!v,onOpenChange:L=>!L&&j(null),children:e.jsxs(vs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:v!=null&&v.id?"Edit recognition":"Add recognition"}),e.jsx(Qn,{children:"Keep it factual — this feeds the proof points you use publicly."})]}),v&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(ge,{value:v.title??"",onChange:L=>j({...v,title:L.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(se,{children:"Issued by"}),e.jsx(ge,{value:v.issuer??"",onChange:L=>j({...v,issuer:L.target.value}),placeholder:"Board, brokerage, publication"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(us,{value:v.category??"award",onValueChange:L=>j({...v,category:L}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:$ke.map(L=>e.jsx(Ze,{value:L.value,children:L.label},L.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date awarded"}),e.jsx(ge,{type:"date",value:v.awarded_on??"",onChange:L=>j({...v,awarded_on:L.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Production period"}),e.jsx(ge,{value:v.production_period??"",onChange:L=>j({...v,production_period:L.target.value}),placeholder:"e.g. 2025"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Proof link"}),e.jsx(ge,{value:v.proof_url??"",onChange:L=>j({...v,proof_url:L.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{rows:3,value:v.description??"",onChange:L=>j({...v,description:L.target.value})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>j(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:T,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(bs,{open:!!_,onOpenChange:L=>!L&&S(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete this recognition?"}),e.jsx(Qn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(_.id),S(null)},children:"Delete"})]})]})})]})}const Qmn=q,ctt=[{value:"pending",label:"Permission pending"},{value:"granted",label:"Permission granted"},{value:"anonymous_only",label:"Anonymous use only"},{value:"declined",label:"Permission declined"}],Xmn=["buyer","seller","both","investor","referral_partner","agent","other"];function cW(s){return s.status==="approved"&&(s.permission_status==="granted"||s.permission_status==="anonymous_only")}function Jmn(){const s=nq("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=rq(),n=Gt(),r=gt({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 Qmn.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 dtt={permission_status:"pending",status:"draft",rating:5,tags:[]};function epn(){const{testimonials:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,recordUse:d,logActivity:u}=Jmn(),[h,p]=N.useState(!1),[f,g]=N.useState("all"),[b,v]=N.useState(""),[j,_]=N.useState(null),[S,A]=N.useState(null),T=N.useMemo(()=>s.filter(F=>{if(h!==!!F.is_archived||f==="usable"&&!cW(F)||f==="pending"&&F.permission_status!=="pending")return!1;const z=b.toLowerCase().trim();return!z||`${F.client_name} ${F.quote} ${(F.tags??[]).join(" ")}`.toLowerCase().includes(z)}),[s,h,f,b]),D=s.filter(F=>!F.is_archived&&cW(F)).length,L=async()=>{var z,V;if(!((z=j==null?void 0:j.client_name)!=null&&z.trim())||!((V=j==null?void 0:j.quote)!=null&&V.trim())){ae.error("Client name and quote are required");return}const F={client_name:j.client_name.trim(),quote:j.quote.trim(),relationship_type:j.relationship_type||null,transaction_type:j.transaction_type||null,rating:j.rating??null,received_on:j.received_on||null,source_url:j.source_url||null,permission_status:j.permission_status??"pending",market:j.market||null,status:j.status??"draft",tags:j.tags??[]};j.id?await i.mutateAsync({id:j.id,...F}):(await a.mutateAsync(F),await u.mutateAsync({title:`Captured a testimonial from ${F.client_name}`,pillar:"produce",activityType:"testimonial_added"})),_(null)},M=(F,z)=>{var V;if(!cW(F)){ae.error("Mark it approved with permission before using it publicly");return}(V=navigator.clipboard)==null||V.writeText(`"${F.quote}" — ${F.permission_status==="anonymous_only"?"Client":F.client_name}`),d.mutate({item:F,kind:z})};return e.jsxs("div",{children:[e.jsxs(Ln,{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(Wr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Ku,{eyebrow:"Produce → Tool",title:"Client Testimonials",description:"Your social proof library. Capture the exact words clients use, track who gave permission, and see which quotes you've already used so nothing gets overexposed.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>p(F=>!F),children:h?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({...dtt}),children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Add Testimonial"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(F=>!F.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"In library"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:D}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Cleared for use"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:s.filter(F=>!F.is_archived&&F.permission_status==="pending").length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Permission pending"})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(ge,{value:b,onChange:F=>v(F.target.value),placeholder:"Search quotes, clients, tags",className:"max-w-xs rounded-full"}),e.jsxs(us,{value:f,onValueChange:F=>g(F),children:[e.jsx(cs,{className:"w-[200px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All testimonials"}),e.jsx(Ze,{value:"usable",children:"Cleared for use"}),e.jsx(Ze,{value:"pending",children:"Permission pending"})]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(F=>e.jsx(Ws,{className:"h-40 rounded-2xl"},F))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Gi,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load testimonials"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Fh,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&T.length===0&&e.jsxs(fe,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(yb,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No testimonials match"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Paste in the reviews and thank-you notes you already have. Mark permission so you always know what's safe to publish."}),!h&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({...dtt}),children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Add one"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:T.map(F=>{var z;return e.jsxs(fe,{className:"p-5 rounded-2xl flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:F.client_name}),F.relationship_type&&e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:F.relationship_type.replace("_"," ")}),e.jsx(ze,{variant:"outline",className:`rounded-full ${cW(F)?"bg-emerald-50 text-emerald-700 border-emerald-200":"bg-amber-50 text-amber-700 border-amber-200"}`,children:((z=ctt.find(V=>V.value===F.permission_status))==null?void 0:z.label)??F.permission_status})]}),!!F.rating&&e.jsx("div",{className:"flex gap-0.5 mt-1.5",children:Array.from({length:5}).map((V,W)=>e.jsx(ua,{className:`h-3.5 w-3.5 ${W<(F.rating??0)?"text-amber-500 fill-amber-500":"text-slate-200"}`},W))})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>_(F),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(F),children:e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:F.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:F.id,archived:!F.is_archived}),children:e.jsx(im,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>A(F),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("blockquote",{className:"mt-3 text-[13.5px] text-slate-700 border-l-2 border-violet-200 pl-3 italic",children:['"',F.quote,'"']}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-3",children:["Used ",F.use_count??0," ",F.use_count===1?"time":"times",F.last_used_at?` · last ${new Date(F.last_used_at).toLocaleDateString("en-US")}`:"",F.status==="approved"?"":" · draft"]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>M(F,"copied"),children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-1.5"})," Copy & log use"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Ln,{to:"/attract/influence/content-studio",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Draft social proof"]})}),F.status!=="approved"&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-emerald-700",onClick:()=>i.mutate({id:F.id,status:"approved"}),children:[e.jsx(ng,{className:"h-3.5 w-3.5 mr-1.5"})," Mark approved"]})]})]},F.id)})}),e.jsx(bs,{open:!!j,onOpenChange:F=>!F&&_(null),children:e.jsxs(vs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:j!=null&&j.id?"Edit testimonial":"Add testimonial"}),e.jsx(Qn,{children:"Use the client's own words. Only publish quotes where permission is granted."})]}),j&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Client name *"}),e.jsx(ge,{value:j.client_name??"",onChange:F=>_({...j,client_name:F.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Relationship"}),e.jsxs(us,{value:j.relationship_type??"",onValueChange:F=>_({...j,relationship_type:F}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(ds,{children:Xmn.map(F=>e.jsx(Ze,{value:F,className:"capitalize",children:F.replace("_"," ")},F))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Quote *"}),e.jsx(Ts,{rows:4,value:j.quote??"",onChange:F=>_({...j,quote:F.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Rating"}),e.jsxs(us,{value:String(j.rating??5),onValueChange:F=>_({...j,rating:Number(F)}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:[5,4,3,2,1].map(F=>e.jsxs(Ze,{value:String(F),children:[F," star",F>1?"s":""]},F))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Received on"}),e.jsx(ge,{type:"date",value:j.received_on??"",onChange:F=>_({...j,received_on:F.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Permission"}),e.jsxs(us,{value:j.permission_status??"pending",onValueChange:F=>_({...j,permission_status:F}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:ctt.map(F=>e.jsx(Ze,{value:F.value,children:F.label},F.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(us,{value:j.status??"draft",onValueChange:F=>_({...j,status:F}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"draft",children:"Draft"}),e.jsx(Ze,{value:"approved",children:"Approved"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Market / area"}),e.jsx(ge,{value:j.market??"",onChange:F=>_({...j,market:F.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Source link"}),e.jsx(ge,{value:j.source_url??"",onChange:F=>_({...j,source_url:F.target.value}),placeholder:"https://"})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>_(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:L,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(bs,{open:!!S,onOpenChange:F=>!F&&A(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete this testimonial?"}),e.jsx(Qn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>A(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(S.id),A(null)},children:"Delete"})]})]})})]})}const utt=[{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"}],htt=["idea","planned","drafted","scheduled","published","skipped"],tpn=["weekly","biweekly","monthly","quarterly","one_off"];function p4t(){const s=nq("attract_market_presence",{orderBy:"planned_for",ascending:!0,label:"Commitment",duplicateOverrides:{status:"idea",published_url:null,results_notes:null,is_archived:!1}}),t=wbe(),n=rq();return{...s,commitments:s.items,quickTask:t,logActivity:n}}const mtt={content_type:"market_update",cadence:"monthly",status:"planned"};function spn(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 npn={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 rpn(){const{commitments:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,quickTask:d,logActivity:u}=p4t(),[h,p]=N.useState(!1),[f,g]=N.useState("all"),[b,v]=N.useState(null),[j,_]=N.useState(null),S=N.useMemo(()=>s.filter(M=>h!==!!M.is_archived?!1:f==="all"||M.status===f),[s,h,f]),A=s.filter(M=>{if(M.status!=="published"||!M.planned_for)return!1;const[F,z,V]=M.planned_for.split(/[-/T]/).map(Number);return(Date.now()-new Date(F,z-1,V).getTime())/864e5<=30}).length,T=s.filter(M=>{if(M.is_archived||!M.planned_for||["published","skipped"].includes(M.status))return!1;const[F,z,V]=M.planned_for.split(/[-/T]/).map(Number);return new Date(F,z-1,V){var F;if(!((F=b==null?void 0:b.title)!=null&&F.trim())){ae.error("Add a title");return}const M={title:b.title.trim(),content_type:b.content_type??"market_update",cadence:b.cadence??"monthly",planned_for:b.planned_for||null,status:b.status??"planned",channel:b.channel||null,audience:b.audience||null,campaign:b.campaign||null,notes:b.notes||null,published_url:b.published_url||null,results_notes:b.results_notes||null};b.id?await i.mutateAsync({id:b.id,...M}):await a.mutateAsync(M),v(null)},L=async M=>{await i.mutateAsync({id:M.id,status:"published"}),await u.mutateAsync({title:`Published market presence: ${M.title}`,pillar:"produce",activityType:"market_presence_published"})};return e.jsxs("div",{children:[e.jsxs(Ln,{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(Wr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Ku,{eyebrow:"Produce → Tool",title:"Market Presence",description:"Consistency beats intensity. Commit to a cadence of market updates and local content, then track whether you actually shipped it.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>p(M=>!M),children:h?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v({...mtt}),children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," New Commitment"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(M=>!M.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Active commitments"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:A}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Published last 30 days"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:T.length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Past due"})]})]}),e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(us,{value:f,onValueChange:g,children:[e.jsx(cs,{className:"w-[190px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All statuses"}),htt.map(M=>e.jsx(Ze,{value:M,className:"capitalize",children:M},M))]})]})}),t&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(M=>e.jsx(Ws,{className:"h-24 rounded-2xl"},M))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Gi,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load commitments"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Fh,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&S.length===0&&e.jsxs(fe,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(wf,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No commitments yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Start with one: a monthly market update. Set the date, ship it, mark it published — that rhythm is what agents notice."}),!h&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v({...mtt}),children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Add a commitment"]})]}),e.jsx("div",{className:"space-y-2",children:S.map(M=>{var F;return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:M.title}),e.jsx(ze,{variant:"outline",className:"rounded-full",children:((F=utt.find(z=>z.value===M.content_type))==null?void 0:F.label)??M.content_type}),e.jsx(ze,{variant:"outline",className:`rounded-full capitalize ${npn[M.status]??""}`,children:M.status}),e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:M.cadence.replace("_"," ")})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[spn(M.planned_for),M.channel,M.audience].filter(Boolean).join(" · ")}),M.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:M.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>v(M),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(M),children:e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:M.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:M.id,archived:!M.is_archived}),children:e.jsx(im,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>_(M),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[M.status!=="published"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>L(M),children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark published"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>d.mutate({title:`Create: ${M.title}`,dueAt:M.planned_for?`${M.planned_for}T09:00:00`:new Date().toISOString(),notes:M.notes,touchType:"content"}),children:[e.jsx(pu,{className:"h-3.5 w-3.5 mr-1.5"})," Add task"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs(Ln,{to:"/attract/influence/content-studio",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Draft it"]})})]})]},M.id)})}),e.jsx(bs,{open:!!b,onOpenChange:M=>!M&&v(null),children:e.jsxs(vs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:b!=null&&b.id?"Edit commitment":"New commitment"}),e.jsx(Qn,{children:"Pick something you can genuinely sustain."})]}),b&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(ge,{value:b.title??"",onChange:M=>v({...b,title:M.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(se,{children:"Type"}),e.jsxs(us,{value:b.content_type??"market_update",onValueChange:M=>v({...b,content_type:M}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:utt.map(M=>e.jsx(Ze,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cadence"}),e.jsxs(us,{value:b.cadence??"monthly",onValueChange:M=>v({...b,cadence:M}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:tpn.map(M=>e.jsx(Ze,{value:M,className:"capitalize",children:M.replace("_"," ")},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Planned for"}),e.jsx(ge,{type:"date",value:b.planned_for??"",onChange:M=>v({...b,planned_for:M.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(us,{value:b.status??"planned",onValueChange:M=>v({...b,status:M}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:htt.map(M=>e.jsx(Ze,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Channel"}),e.jsx(ge,{value:b.channel??"",onChange:M=>v({...b,channel:M.target.value}),placeholder:"Instagram, email, YouTube"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Audience"}),e.jsx(ge,{value:b.audience??"",onChange:M=>v({...b,audience:M.target.value}),placeholder:"Agents, sphere, neighborhood"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ts,{rows:3,value:b.notes??"",onChange:M=>v({...b,notes:M.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Published URL"}),e.jsx(ge,{value:b.published_url??"",onChange:M=>v({...b,published_url:M.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Results"}),e.jsx(ge,{value:b.results_notes??"",onChange:M=>v({...b,results_notes:M.target.value}),placeholder:"Reach, replies, leads"})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>v(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:D,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(bs,{open:!!j,onOpenChange:M=>!M&&_(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete this commitment?"}),e.jsx(Qn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>_(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(j.id),_(null)},children:"Delete"})]})]})})]})}function ptt(s){if(!s)return null;const[t]=s.split("T");return t||null}const dW={draft:{label:"Content",icon:un,cls:"bg-violet-50 text-violet-700 border-violet-200"},presence:{label:"Market presence",icon:wf,cls:"bg-blue-50 text-blue-700 border-blue-200"},speaking:{label:"Speaking",icon:Bv,cls:"bg-amber-50 text-amber-700 border-amber-200"}};function apn(){const{drafts:s,isLoading:t,save:n}=c4t(),{commitments:r,isLoading:a}=p4t(),i=m4t(),l=wbe(),[o,c]=N.useState(()=>{const T=new Date;return new Date(T.getFullYear(),T.getMonth(),1)}),[d,u]=N.useState("all"),[h,p]=N.useState(null),f=N.useMemo(()=>(i.items??[]).filter(T=>!T.is_archived).map(T=>({id:T.id,kind:"speaking",title:T.title,date:ptt(T.starts_at),status:T.status,href:"/attract/influence/speaking"})),[i.items]),g=N.useMemo(()=>{const T=s.map(L=>({id:L.id,kind:"draft",title:L.topic||L.mode.replace(/_/g," "),date:ptt(L.planned_at??L.posted_at??null),status:L.status,href:"/attract/influence/content-studio"})),D=r.filter(L=>!L.is_archived).map(L=>({id:L.id,kind:"presence",title:L.title,date:L.planned_for,status:L.status,href:"/attract/produce/market-presence"}));return[...T,...D,...f].filter(L=>d==="all"||L.kind===d)},[s,r,f,d]),b=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`,v=g.filter(T=>{var D;return(D=T.date)==null?void 0:D.startsWith(b)}),j=g.filter(T=>!T.date),_=N.useMemo(()=>{const T=new Date(o.getFullYear(),o.getMonth(),1),D=new Date(T);return D.setDate(T.getDate()-T.getDay()),Array.from({length:42},(L,M)=>{const F=new Date(D);F.setDate(D.getDate()+M);const z=`${F.getFullYear()}-${String(F.getMonth()+1).padStart(2,"0")}-${String(F.getDate()).padStart(2,"0")}`;return{date:F,key:z,inMonth:F.getMonth()===o.getMonth(),items:g.filter(V=>V.date===z)}})},[o,g]),S=(()=>{const T=new Date;return`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`})(),A=t||a;return e.jsxs("div",{children:[e.jsxs(Ln,{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(Wr,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(Ku,{eyebrow:"Produce + Influence → Tool",title:"Content Calendar",description:"One month view of everything you've committed to publish — Content Studio drafts, market presence commitments, and speaking dates.",actions:e.jsx(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",asChild:!0,children:e.jsxs(Ln,{to:"/attract/influence/content-studio",children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," New Draft"]})})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{size:"icon",variant:"outline",className:"rounded-full h-9 w-9",onClick:()=>c(new Date(o.getFullYear(),o.getMonth()-1,1)),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 min-w-[170px] text-center",children:o.toLocaleString("en-US",{month:"long",year:"numeric"})}),e.jsx(B,{size:"icon",variant:"outline",className:"rounded-full h-9 w-9",onClick:()=>c(new Date(o.getFullYear(),o.getMonth()+1,1)),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",className:"rounded-full",onClick:()=>{const T=new Date;c(new Date(T.getFullYear(),T.getMonth(),1))},children:"Today"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ze,{variant:"outline",className:"rounded-full",children:[v.length," scheduled this month"]}),e.jsxs(us,{value:d,onValueChange:T=>u(T),children:[e.jsx(cs,{className:"w-[180px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"all",children:"All types"}),e.jsx(Ze,{value:"draft",children:"Content drafts"}),e.jsx(Ze,{value:"presence",children:"Market presence"}),e.jsx(Ze,{value:"speaking",children:"Speaking"})]})]})]})]}),A?e.jsx(Ws,{className:"h-[560px] rounded-2xl"}):e.jsxs(fe,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 bg-slate-50 border-b",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(T=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider text-slate-500 font-semibold text-center",children:T},T))}),e.jsx("div",{className:"grid grid-cols-7",children:_.map(T=>e.jsxs("div",{className:`min-h-[96px] border-b border-r p-1.5 ${T.inMonth?"":"bg-slate-50/60"}`,children:[e.jsx("div",{className:`text-[11.5px] font-medium mb-1 ${T.key===S?"text-violet-700":T.inMonth?"text-slate-700":"text-slate-400"}`,children:T.date.getDate()}),e.jsxs("div",{className:"space-y-1",children:[T.items.slice(0,3).map(D=>{const L=dW[D.kind];return e.jsx(Ln,{to:D.href,className:`block truncate rounded-md border px-1.5 py-0.5 text-[11px] ${L.cls}`,title:D.title,children:D.title},`${D.kind}-${D.id}`)}),T.items.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-500 px-1",children:["+",T.items.length-3," more"]})]})]},T.key))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 mt-5",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:["Unscheduled (",j.length,")"]}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Give these a date so they show on the calendar."}),j.length===0&&e.jsx("div",{className:"text-[13px] text-slate-500",children:"Everything has a date. Nice."}),e.jsx("div",{className:"space-y-2",children:j.slice(0,8).map(T=>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:T.title}),e.jsxs("div",{className:"text-[11.5px] text-slate-500",children:[dW[T.kind].label," · ",T.status]})]}),T.kind==="draft"?e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full flex-shrink-0",onClick:()=>p({id:T.id,title:T.title,date:S}),children:"Schedule"}):e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full flex-shrink-0",asChild:!0,children:e.jsx(Ln,{to:T.href,children:"Open"})})]},`${T.kind}-${T.id}`))})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:"This month at a glance"}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Keep a steady rhythm across all three surfaces."}),e.jsx("div",{className:"space-y-2",children:Object.keys(dW).map(T=>{const D=dW[T],L=D.icon,M=v.filter(F=>F.kind===T).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 ${D.cls}`,children:e.jsx(L,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 flex-1",children:D.label}),e.jsx("div",{className:"text-[16px] font-semibold tabular-nums text-slate-900",children:M})]},T)})}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4 w-full",onClick:()=>l.mutate({title:`Plan content for ${o.toLocaleString("en-US",{month:"long"})}`,dueAt:new Date().toISOString(),touchType:"content"}),children:[e.jsx(pu,{className:"h-3.5 w-3.5 mr-1.5"})," Add planning block to Today's Plan"]}),e.jsx(B,{variant:"ghost",className:"rounded-full mt-2 w-full",asChild:!0,children:e.jsxs(Ln,{to:"/attract/produce/market-presence",children:[e.jsx(Tl,{className:"h-3.5 w-3.5 mr-1.5"})," Manage market presence cadence"]})})]})]}),e.jsx(bs,{open:!!h,onOpenChange:T=>!T&&p(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Schedule draft"}),e.jsx(Qn,{className:"capitalize",children:h==null?void 0:h.title})]}),h&&e.jsxs("div",{children:[e.jsx(se,{children:"Planned date"}),e.jsx(ge,{type:"date",value:h.date,onChange:T=>p({...h,date:T.target.value})})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>p(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:async()=>{h&&(await n.mutateAsync({id:h.id,planned_at:`${h.date}T09:00:00`}),p(null))},children:"Save"})]})]})})]})}const ftt=[{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 ipn(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return{y:t,m:n,d:r}}function pEe(s,t=new Date){const{y:n,m:r,d:a}=ipn(s.milestone_on);if(!s.recurs_annually)return new Date(n,r-1,a);const i=new Date(t.getFullYear(),r-1,a),l=new Date(t.getFullYear(),t.getMonth(),t.getDate());return i{const l=[];return r.forEach(o=>{const c=[o.preferred_name||o.first_name,o.last_name].filter(Boolean).join(" ");[["birthday",o.birthday_on,`${c} — Birthday`],["work_anniversary",o.work_anniversary_on,`${c} — Work Anniversary`],["license_anniversary",o.license_anniversary_on,`${c} — License Anniversary`]].forEach(([d,u,h])=>{u&&l.push({id:`agent:${o.id}:${d}`,user_id:o.user_id,title:h,milestone_type:d,milestone_on:String(u).slice(0,10),recurs_annually:!0,linked_agent_ids:[o.id],notes:null,last_celebrated_at:null,is_archived:!1,created_at:o.created_at,updated_at:o.updated_at})})}),l},[r]),i=N.useMemo(()=>{const l=new Set(s.items.filter(c=>!c.is_archived).map(c=>{var d;return`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${((d=c.linked_agent_ids)==null?void 0:d[0])??""}`}));return[...s.items.filter(c=>!c.is_archived),...a.filter(c=>!l.has(`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${c.linked_agent_ids[0]}`))].map(c=>({item:c,next:pEe(c)})).map(c=>({...c,days:f4t(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 xtt={milestone_type:"birthday",recurs_annually:!0,linked_agent_ids:[]};function lpn(s){return s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function cpn(){var z;const{milestones:s,upcoming:t,isLoading:n,error:r,refetch:a,create:i,update:l,duplicate:o,archive:c,remove:d,quickTask:u,logActivity:h}=opn(),p=d0(),f=(p==null?void 0:p.agents)??(p==null?void 0:p.items)??[],[g,b]=N.useState(!1),[v,j]=N.useState("90"),[_,S]=N.useState(null),[A,T]=N.useState(null),D=N.useMemo(()=>{if(g)return s.filter(W=>W.is_archived).map(W=>({item:W,next:pEe(W),days:f4t(pEe(W))}));const V=v==="all"?1/0:Number(v);return t.filter(W=>W.days<=V)},[s,t,g,v]),L=V=>{const W=f.find(K=>K.id===V);return W?[W.preferred_name||W.first_name,W.last_name].filter(Boolean).join(" "):"Agent"},M=async()=>{var W;if(!((W=_==null?void 0:_.title)!=null&&W.trim())||!(_!=null&&_.milestone_on)){ae.error("Title and date are required");return}const V={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,...V}):await i.mutateAsync(V),S(null)},F=async V=>{var W;await l.mutateAsync({id:V.id,last_celebrated_at:new Date().toISOString()}),await h.mutateAsync({title:`Celebrated: ${V.title}`,pillar:"connect",activityType:"milestone_celebrated",agentId:((W=V.linked_agent_ids)==null?void 0:W[0])??null})};return e.jsxs("div",{children:[e.jsxs(Ln,{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(Wr,{className:"h-3.5 w-3.5"})," Back to Connect"]}),e.jsx(Ku,{eyebrow:"Connect → Tool",title:"Milestones & Celebrations",description:"Remember the dates that matter to the agents in your pipeline. Recurring milestones roll forward every year so you never miss the reason to reach out.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>b(V=>!V),children:g?"Show upcoming":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>S({...xtt}),children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Add Milestone"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:t.filter(V=>V.days<=7).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 7 days"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-violet-600",children:t.filter(V=>V.days<=30).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 30 days"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(V=>!V.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(us,{value:v,onValueChange:V=>j(V),children:[e.jsx(cs,{className:"w-[190px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"30",children:"Next 30 days"}),e.jsx(Ze,{value:"90",children:"Next 90 days"}),e.jsx(Ze,{value:"all",children:"All upcoming"})]})]})}),n&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(V=>e.jsx(Ws,{className:"h-20 rounded-2xl"},V))}),!n&&r&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Gi,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load milestones"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:r.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(Fh,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!n&&!r&&D.length===0&&e.jsxs(fe,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(hu,{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(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>S({...xtt}),children:[e.jsx(As,{className:"h-4 w-4 mr-1.5"})," Add a milestone"]})]}),e.jsx("div",{className:"space-y-2",children:D.map(({item:V,next:W,days:K})=>{var ee,ne;const Y=String(V.id).startsWith("agent:");return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 text-violet-700 grid place-items-center flex-shrink-0",children:e.jsxs("div",{className:"text-center leading-none",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider",children:W.toLocaleString("en-US",{month:"short"})}),e.jsx("div",{className:"text-[15px] font-semibold",children:W.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:V.title}),e.jsx(ze,{variant:"outline",className:"rounded-full",children:((ee=ftt.find(oe=>oe.value===V.milestone_type))==null?void 0:ee.label)??V.milestone_type}),Y&&e.jsx(ze,{variant:"outline",className:"rounded-full bg-violet-50 text-violet-700 border-violet-200",children:"From contact record"}),!g&&e.jsx(ze,{variant:"outline",className:`rounded-full ${K<=7?"bg-amber-50 text-amber-700 border-amber-200":""}`,children:K===0?"Today":K===1?"Tomorrow":`in ${K} days`}),V.recurs_annually&&e.jsx(ze,{variant:"outline",className:"rounded-full",children:"Annual"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[lpn(W),(ne=V.linked_agent_ids)!=null&&ne.length?` · ${V.linked_agent_ids.map(L).join(", ")}`:"",V.last_celebrated_at?` · last celebrated ${new Date(V.last_celebrated_at).toLocaleDateString("en-US")}`:""]}),V.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:V.notes})]})]}),e.jsx("div",{className:"flex gap-1",children:Y?e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full text-[12px]",asChild:!0,children:e.jsx(Ln,{to:`/attract/agents/${V.linked_agent_ids[0]}`,children:"Open contact"})}):e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>S(V),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>o.mutate(V),children:e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:V.is_archived?"Restore":"Archive",onClick:()=>c.mutate({id:V.id,archived:!V.is_archived}),children:e.jsx(im,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>T(V),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{var oe;return u.mutate({title:`Reach out: ${V.title}`,dueAt:W.toISOString(),notes:V.notes,touchType:"celebration",agentId:((oe=V.linked_agent_ids)==null?void 0:oe[0])??null})},children:[e.jsx(pu,{className:"h-3.5 w-3.5 mr-1.5"})," Add reach-out task"]}),!Y&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>F(V),children:[e.jsx(uh,{className:"h-3.5 w-3.5 mr-1.5"})," Mark celebrated"]})]})]},V.id)})}),e.jsx(bs,{open:!!_,onOpenChange:V=>!V&&S(null),children:e.jsxs(vs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:_!=null&&_.id?"Edit milestone":"Add milestone"}),e.jsx(Qn,{children:"Annual milestones roll forward automatically each year."})]}),_&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(ge,{value:_.title??"",onChange:V=>S({..._,title:V.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(se,{children:"Type"}),e.jsxs(us,{value:_.milestone_type??"birthday",onValueChange:V=>S({..._,milestone_type:V}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:ftt.map(V=>e.jsx(Ze,{value:V.value,children:V.label},V.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date *"}),e.jsx(ge,{type:"date",value:_.milestone_on??"",onChange:V=>S({..._,milestone_on:V.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(vn,{checked:_.recurs_annually??!0,onCheckedChange:V=>S({..._,recurs_annually:V})})]}),f.length>0&&e.jsxs("div",{children:[e.jsx(se,{children:"Link to agent"}),e.jsxs(us,{value:((z=_.linked_agent_ids)==null?void 0:z[0])??"none",onValueChange:V=>S({..._,linked_agent_ids:V==="none"?[]:[V]}),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Optional"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"No agent"}),f.map(V=>e.jsx(Ze,{value:V.id,children:L(V.id)},V.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ts,{rows:3,value:_.notes??"",onChange:V=>S({..._,notes:V.target.value}),placeholder:"Gift ideas, personal details, how you'll reach out"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:M,disabled:i.isPending||l.isPending,children:"Save"})]})]})}),e.jsx(bs,{open:!!A,onOpenChange:V=>!V&&T(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete this milestone?"}),e.jsx(Qn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>T(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{d.mutate(A.id),T(null)},children:"Delete"})]})]})})]})}function dpn(){var c;const{shareToken:s}=_i(),[t,n]=N.useState("loading"),[r,a]=N.useState(null),[i,l]=N.useState(!1);N.useEffect(()=>{(async()=>{if(!s){n("not_found");return}const{data:d,error:u}=await q.rpc("public_get_attract_kit",{_token:s});if(u){n("error");return}if(!d||d.status!=="ok"){n((d==null?void 0:d.status)??"not_found");return}a(d),n("ok"),q.rpc("public_log_attract_kit_event",{_token:s,_event_type:"page_view",_item_id:null,_metadata:{}})})()},[s]);const o=(d,u,h)=>{s&&q.rpc("public_log_attract_kit_event",{_token:s,_event_type:d,_item_id:u??null,_metadata:h??{}})};return t==="loading"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center text-slate-300",children:"Loading…"}):t!=="ok"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center px-6",children:e.jsxs(fe,{className:"max-w-md w-full p-8 bg-white/5 border-white/10 text-slate-100 rounded-2xl text-center",children:[e.jsx(Gi,{className:"h-8 w-8 text-amber-400 mx-auto"}),e.jsx("div",{className:"mt-3 text-xl font-semibold",children:t==="expired"?"This kit has expired":t==="revoked"?"This kit is no longer available":t==="not_found"?"This kit could not be found":"Something went wrong"}),e.jsx("p",{className:"text-slate-400 mt-2 text-sm",children:"Please reach out to the person who shared it with you for an updated link."})]})}):e.jsx("div",{className:"min-h-screen bg-[#05070f]",children:e.jsxs("div",{className:"max-w-3xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-400 font-semibold justify-center py-3",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," A LevelUp Attract kit"]}),e.jsx(d4t,{kit:r.kit,items:r.items,owner:r.owner,personalNote:(c=r.share)==null?void 0:c.personal_note,mode:"public",onEvent:o}),e.jsx(fe,{className:"mt-6 p-6 bg-white/5 border-white/10 text-slate-100 rounded-2xl",children:i?e.jsx(upn,{token:s,onSent:()=>l(!1),onEvent:o}):e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold",children:"Have a question about this?"}),e.jsxs("p",{className:"text-slate-400 text-[13px] mt-1",children:["Send a private note — ",r.owner.display_name," will get it right away."]}),e.jsx(B,{className:"mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>l(!0),children:"Ask a question"})]})}),e.jsx("div",{className:"text-center text-[11px] text-slate-600 mt-6 pb-10",children:"Powered by LevelUp Attract"})]})})}function upn({token:s,onSent:t,onEvent:n}){const[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(!1),h=async()=>{if(o.trim().length<2)return ae.error("Please add a short message");u(!0);const{data:p,error:f}=await q.rpc("public_submit_attract_kit_question",{_token:s,_name:r,_email:i,_message:o});if(u(!1),f||!(p!=null&&p.ok))return ae.error("Could not send — please try again");ae.success("Sent — thank you!"),t()};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[14px] font-semibold",children:"Send a private message"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsx(ge,{placeholder:"Your name (optional)",value:r,onChange:p=>a(p.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"}),e.jsx(ge,{placeholder:"Your email (optional)",value:i,onChange:p=>l(p.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"})]}),e.jsx(Ts,{rows:4,placeholder:"What's your question?",value:o,onChange:p=>c(p.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>{n("meeting_requested"),ae.success("Request sent")},children:"Request a conversation"}),e.jsx(B,{onClick:h,disabled:d,className:"bg-gradient-to-r from-violet-600 to-indigo-600 ml-auto",children:d?"Sending…":"Send question"})]})]})}function hpn(){const{slug:s}=_i(),[t]=yl(),n=t.get("inv")||null,[r,a]=N.useState("loading"),[i,l]=N.useState(null),[o,c]=N.useState({name:"",email:"",phone:"",answers:{}}),[d,u]=N.useState(!1),[h,p]=N.useState(null);N.useEffect(()=>{s&&(async()=>{const{data:b,error:v}=await q.rpc("public_get_attract_event",{_slug:s});if(v||!b||b.error){a((b==null?void 0:b.error)||"not_found");return}l(b),a("ok"),n&&q.rpc("public_track_attract_invitation_view",{_token:n})})()},[s,n]);const f=async()=>{u(!0);const{data:b,error:v}=await q.rpc("public_register_attract_event",{_slug:s,_name:o.name,_email:o.email,_phone:o.phone||null,_answers:o.answers||{},_invitation_token:n});if(u(!1),v){alert("Something went wrong. Please try again.");return}const j=b;if(j!=null&&j.error){alert(j.error==="invalid_email"?"That email looks off.":j.error==="full"?"This event is full.":"Could not register.");return}p(j)},g=()=>{if(!i)return;const b=new Blob([OSt(i)],{type:"text/calendar"}),v=document.createElement("a");v.href=URL.createObjectURL(b),v.download=`${s}.ics`,v.click()};if(r==="loading")return e.jsx("div",{className:"min-h-screen grid place-items-center text-slate-400",children:"Loading…"});if(r!=="ok"||!i){const b=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:b}),e.jsx("div",{className:"text-slate-500 mt-2",children:"The link may have expired."})]})})}return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-violet-50",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-10 md:py-16",children:[i.cover_image_url&&e.jsx("div",{className:"rounded-3xl overflow-hidden mb-8 aspect-[16/7] bg-slate-100",children:e.jsx("img",{src:i.cover_image_url,alt:"",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] text-violet-600 font-semibold mb-3",children:"You are invited"}),e.jsx("h1",{className:"text-3xl md:text-5xl font-semibold tracking-tight text-slate-900",children:i.title}),i.host&&e.jsxs("div",{className:"text-slate-600 mt-3 text-[15px]",children:["Hosted by ",e.jsx("span",{className:"font-semibold",children:i.host.name}),i.host.brokerage_name?` · ${i.host.brokerage_name}`:""]})]}),e.jsxs(fe,{className:"p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-[14px]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(yr,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"When"}),e.jsx("div",{className:"font-semibold text-slate-900",children:ks(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(vr,{className:"h-5 w-5 text-violet-600 mt-0.5"}):e.jsx(Ca,{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(_n,{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((b,v)=>e.jsxs("li",{className:"flex gap-2 text-[14px] text-slate-800",children:[e.jsx(Lr,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",b]},v))})]}),(i.agenda||[]).length>0&&e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Agenda"}),e.jsx("ul",{className:"space-y-1",children:i.agenda.map((b,v)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:b.time}),e.jsx("span",{className:"text-slate-800",children:b.item})]},v))})]})]}),h?e.jsxs(fe,{className:"mt-6 p-8 rounded-3xl border-emerald-200 bg-emerald-50 text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-emerald-500 text-white grid place-items-center",children:e.jsx(Lr,{className:"h-7 w-7"})}),e.jsx("div",{className:"text-2xl font-semibold text-slate-900 mt-4",children:h.status==="waitlisted"?"You are on the waitlist":"You are in."}),i.confirmation_message&&e.jsx("div",{className:"text-[15px] text-slate-700 mt-2 max-w-lg mx-auto",children:i.confirmation_message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-5",onClick:g,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"})," Add to calendar"]})]}):e.jsxs(fe,{className:"mt-6 p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"text-lg font-semibold text-slate-900 mb-1 flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-violet-600"})," Save your seat"]}),e.jsx("div",{className:"text-[13px] text-slate-500 mb-4",children:"The room is small on purpose."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Full name"}),e.jsx(ge,{value:o.name,onChange:b=>c({...o,name:b.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ge,{type:"email",value:o.email,onChange:b=>c({...o,email:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone (optional)"}),e.jsx(ge,{value:o.phone,onChange:b=>c({...o,phone:b.target.value})})]})]}),(i.registration_questions||[]).map(b=>e.jsxs("div",{children:[e.jsx(se,{children:b.label}),b.type==="long"?e.jsx(Ts,{rows:3,value:o.answers[b.key]||"",onChange:v=>c({...o,answers:{...o.answers,[b.key]:v.target.value}})}):e.jsx(ge,{value:o.answers[b.key]||"",onChange:v=>c({...o,answers:{...o.answers,[b.key]:v.target.value}})})]},b.key))]}),e.jsx(B,{disabled:d,className:"w-full mt-5 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 h-11",onClick:f,children:d?"Saving…":i.seats_left===0?"Join the waitlist":"Save my seat"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center mt-3",children:"Build relationships first. We will only email you about this event."})]})]})})}function mpn(){const{token:s}=_i(),[t]=yl(),n=t.get("a"),[r,a]=N.useState("loading"),[i,l]=N.useState("");return N.useEffect(()=>{if(!s||!n){a("error");return}(async()=>{const{data:o}=await q.rpc("public_check_in_attendee",{_check_in_token:s,_attendee_token:n}),c=o;c!=null&&c.ok?(l(c.name||""),a(c.already?"already":"ok")):a("error")})()},[s,n]),e.jsx("div",{className:"min-h-screen grid place-items-center bg-slate-50 px-4",children:e.jsxs(fe,{className:"p-8 rounded-3xl border-slate-200 bg-white max-w-md w-full text-center",children:[r==="loading"&&e.jsx("div",{className:"text-slate-500",children:"Checking you in…"}),(r==="ok"||r==="already")&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-emerald-500 text-white grid place-items-center",children:e.jsx(Lr,{className:"h-7 w-7"})}),e.jsx("div",{className:"text-2xl font-semibold mt-4 text-slate-900",children:r==="already"?"Already checked in":"You are in!"}),i&&e.jsxs("div",{className:"text-slate-600 mt-1",children:["Welcome, ",i,"."]}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-4",children:"Find your seat and enjoy the room."})]}),r==="error"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-semibold text-slate-900",children:"We could not check you in."}),e.jsx("div",{className:"text-slate-500 mt-2",children:"Please see the host at the door."})]})]})})}const uW=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function ppn(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 x4t({cfg:s,onSubmitLead:t,onTrack:n,preview:r}){var L,M,F;const a=s.primary_color||"#0f1b3d",i=s.accent_color||"#c9a84c",l=s.sections||{},[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(!1),[f,g]=N.useState({first_name:"",last_name:"",email:"",phone:"",brokerage:"",message:""}),[b,v]=N.useState({first_name:"",email:""}),j=s.calculator||{},[_,S]=N.useState(15e4),A=N.useMemo(()=>{const z=Number(j.cap??16e3),V=Number(j.split??80)/100,W=Number(j.transaction_fee??250),K=Number(j.current_split??70)/100,Y=Number(j.current_monthly_fees??150),ee=Math.min(_*(1-V),z),ne=_-ee-W*12,oe=_*K-Y*12;return{here:Math.max(ne,0),current:Math.max(oe,0),diff:Math.max(ne-oe,0),capped:ee>=z}},[_,j]),T=async(z,V,W)=>{if(r||!t){u(z);return}p(!0);try{await t({first_name:V.first_name||"",last_name:V.last_name||"",email:V.email||"",phone:V.phone||"",brokerage:V.brokerage||"",message:V.message||"",source:z,metadata:W}),u(z)}catch(K){Dr({title:"We couldn't send that",description:(K==null?void 0:K.message)||"Please try again in a moment.",variant:"destructive"})}finally{p(!1)}},D=z=>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:[z||s.cta_label||"Book a confidential 15-min call",e.jsx(za,{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:[D(),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(yr,{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((z,V)=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold md:text-3xl",style:{color:i},children:z.value}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-wider text-white/50",children:z.label})]},V))})}),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:ppn(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(Pu,{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((z,V)=>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(Lr,{className:"h-4 w-4"})}),e.jsx("h3",{className:"mb-2 text-lg font-semibold",children:z.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:z.body}),z.proof&&e.jsx("p",{className:"mt-3 text-xs uppercase tracking-wider text-white/40",children:z.proof})]},V))})]})}),l.calculator!==!1&&j.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:j.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(se,{className:"text-white/70",children:"Your annual GCI"}),e.jsx("span",{className:"text-2xl font-bold",style:{color:i},children:uW(_)})]}),e.jsx("input",{type:"range",min:25e3,max:1e6,step:5e3,value:_,onChange:z=>S(Number(z.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:uW(A.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:uW(A.here)}),A.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:["+",uW(A.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:D("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((z,V)=>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:V+1}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1.5 font-semibold",children:z.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:z.body})]})]},V))})]})}),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((z,V)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(yb,{className:"mb-4 h-6 w-6",style:{color:i}}),e.jsxs("p",{className:"text-sm leading-relaxed text-white/75",children:['"',z.quote,'"']}),e.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[z.photo_url?e.jsx("img",{src:z.photo_url,alt:z.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(ua,{className:"h-4 w-4 text-white/50"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:z.name}),z.role&&e.jsx("div",{className:"text-xs text-white/45",children:z.role})]})]})]},V))})]})}),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(jIe,{type:"single",collapsible:!0,className:"w-full",children:(s.faqs||[]).map((z,V)=>e.jsxs(pve,{value:`faq-${V}`,className:"border-white/10",children:[e.jsx(fve,{className:"text-left text-base font-medium text-white hover:no-underline",children:z.q}),e.jsx(xve,{className:"text-sm leading-relaxed text-white/65",children:z.a})]},V))})]})}),l.lead_magnet!==!1&&((L=s.lead_magnet)==null?void 0:L.enabled)!==!1&&((M=s.lead_magnet)==null?void 0:M.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(Da,{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:z=>{z.preventDefault(),T("lead_magnet",{first_name:b.first_name,email:b.email,message:`Requested: ${s.lead_magnet.title}`})},children:[e.jsx(ge,{required:!0,placeholder:"First name",value:b.first_name,onChange:z=>v(V=>({...V,first_name:z.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(ge,{required:!0,type:"email",placeholder:"Email",value:b.email,onChange:z=>v(V=>({...V,email:z.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(B,{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&&((F=s.event_block)==null?void 0:F.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(Lr,{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(yr,{className:"h-4 w-4"})," Pick a time"]})]}):e.jsxs("form",{onSubmit:z=>{z.preventDefault(),T("attraction_page",f,{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(se,{className:"text-sm text-white/70",children:"First name *"}),e.jsx(ge,{required:!0,value:f.first_name,onChange:z=>g(V=>({...V,first_name:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Last name"}),e.jsx(ge,{value:f.last_name,onChange:z=>g(V=>({...V,last_name:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Email *"}),e.jsx(ge,{required:!0,type:"email",value:f.email,onChange:z=>g(V=>({...V,email:z.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(se,{className:"text-sm text-white/70",children:"Phone"}),e.jsx(ge,{value:f.phone,onChange:z=>g(V=>({...V,phone:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Current brokerage"}),e.jsx(ge,{value:f.brokerage,onChange:z=>g(V=>({...V,brokerage:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"What would you want to know?"}),e.jsx(Ts,{rows:3,value:f.message,onChange:z=>g(V=>({...V,message:z.target.value})),className:"resize-none border-white/15 bg-white/5 text-white"})]}),e.jsx(B,{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(hh,{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(Pr,{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(za,{className:"h-4 w-4"})]})})]})}const hW=q;function fpn(){const{slug:s}=_i(),[t,n]=N.useState(null),[r,a]=N.useState("loading");N.useEffect(()=>{if(!s)return;let o=!1;return(async()=>{const{data:c,error:d}=await hW.rpc("public_get_attract_landing_page",{_slug:s});if(!o){if(d||!c||c.error){a("missing");return}n(c),a("ready"),hW.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&&hW.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 hW.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(Yo,{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(x4t,{cfg:t,onSubmitLead:l,onTrack:i})]})}const g4t={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},gtt={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"},xpn=[{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."}],gpn=[{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."}],ypn=[{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."}],vpn="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.",bpn={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:""},_pn={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 wpn(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:xpn,sponsor_cards:ypn,faqs:gpn,lead_magnet:bpn,calculator:_pn,sections:g4t,disclaimer:vpn,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 y4t(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}const r7=q;function jpn(){const{user:s}=gs(),t=Gt(),n=["attract-landing-page",s==null?void 0:s.id],{data:r,isLoading:a}=lt({queryKey:n,enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await r7.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}=lt({queryKey:["attract-landing-analytics",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:c,error:d}=await r7.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,p=u.filter(g=>g.event_type==="cta_click").length,f=u.filter(g=>g.event_type==="calculator_run").length;return{views:h,ctas:p,calcs:f,conversion:h?Math.round(p/h*100):0}}}),l=gt({mutationFn:async c=>{const d=y4t(c||"my-attraction-page")||"attraction-page";let u=d;for(let g=0;g<5;g++){const{data:b}=await r7.from("attract_landing_pages").select("id").eq("slug",u).maybeSingle();if(!b)break;u=`${d}-${Math.random().toString(36).slice(2,6)}`}const h=wpn(c||"Your Name"),{data:p,error:f}=await r7.from("attract_landing_pages").insert({...h,user_id:s.id,slug:u}).select("*").single();if(f)throw f;return p},onSuccess:()=>{t.invalidateQueries({queryKey:n}),ae.success("Attraction page created")},onError:c=>ae.error(c.message||"Could not create the page")}),o=gt({mutationFn:async c=>{const{error:d}=await r7.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 Npn(){var v,j,_,S,A,T,D,L,M,F,z,V;const{user:s}=gs(),{page:t,isLoading:n,analytics:r,createPage:a,savePage:i}=jpn(),[l,o]=N.useState(null),[c,d]=N.useState(!1);N.useEffect(()=>{t&&o({...t})},[t]);const u=N.useMemo(()=>l!=null&&l.slug?`${window.location.origin}/join/${l.slug}`:"",[l==null?void 0:l.slug]),h=W=>o(K=>({...K,...W})),p=(W,K)=>h({[W]:K}),f=(W,K,Y)=>p(W,l[W].map((ee,ne)=>ne===K?{...ee,...Y}:ee)),g=()=>{const{id:W,user_id:K,created_at:Y,updated_at:ee,...ne}=l;i.mutate({...ne,slug:y4t(ne.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(un,{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(B,{size:"lg",onClick:()=>{var W;return a.mutate(((W=s==null?void 0:s.user_metadata)==null?void 0:W.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(B,{variant:"outline",size:"sm",onClick:()=>d(!1),children:"Back to editor"})]}),e.jsx(x4t,{cfg:l,preview:!0})]});const b={...g4t,...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(B,{variant:"outline",size:"sm",onClick:()=>d(!0),children:[e.jsx(Ir,{className:"mr-2 h-4 w-4"})," Preview"]}),l.is_published&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:u,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs(B,{size:"sm",onClick:g,disabled:i.isPending,children:[e.jsx(Ho,{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(W=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:W.label}),e.jsx("div",{className:"mt-1 text-2xl font-bold",children:W.value})]})},W.label))}),e.jsxs($r,{defaultValue:"content",children:[e.jsxs(Ur,{className:"mb-6 flex-wrap",children:[e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"proof",children:"Proof & FAQ"}),e.jsx(Zt,{value:"calculator",children:"Calculator"}),e.jsx(Zt,{value:"sections",children:"Sections"}),e.jsx(Zt,{value:"publish",children:"Publish"})]}),e.jsxs(ls,{value:"content",className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Hero"})}),e.jsxs(Ae,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(pd,{label:"Your name",value:l.agent_name,onChange:W=>h({agent_name:W})}),e.jsx(pd,{label:"Title / brokerage",value:l.agent_title,onChange:W=>h({agent_title:W})}),e.jsx(pd,{label:"Eyebrow line",value:l.eyebrow,onChange:W=>h({eyebrow:W}),className:"md:col-span-2"}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(se,{children:"Headline"}),e.jsx(Ts,{rows:2,value:l.headline||"",onChange:W=>h({headline:W.target.value})})]}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(se,{children:"Subheadline"}),e.jsx(Ts,{rows:3,value:l.subheadline||"",onChange:W=>h({subheadline:W.target.value})})]}),e.jsx(pd,{label:"Button text",value:l.cta_label,onChange:W=>h({cta_label:W})}),e.jsx(pd,{label:"Scheduling link (Calendly etc.)",value:l.calendar_url,onChange:W=>h({calendar_url:W})}),e.jsx(pd,{label:"Headshot URL",value:l.headshot_url,onChange:W=>h({headshot_url:W})}),e.jsx(pd,{label:"Hero background image URL",value:l.hero_image_url,onChange:W=>h({hero_image_url:W})}),e.jsx(pd,{label:"Logo URL",value:l.logo_url,onChange:W=>h({logo_url:W})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(pd,{label:"Primary color",type:"color",value:l.primary_color,onChange:W=>h({primary_color:W})}),e.jsx(pd,{label:"Accent color",type:"color",value:l.accent_color,onChange:W=>h({accent_color:W})})]}),e.jsx(pd,{label:"Phone",value:l.phone,onChange:W=>h({phone:W})}),e.jsx(pd,{label:"Email",value:l.email,onChange:W=>h({email:W})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Credibility strip"})}),e.jsxs(Ae,{className:"space-y-3",children:[(l.credibility||[]).map((W,K)=>e.jsxs(a7,{onRemove:()=>p("credibility",l.credibility.filter((Y,ee)=>ee!==K)),children:[e.jsx(ge,{placeholder:"Value (e.g. $42M)",value:W.value||"",onChange:Y=>f("credibility",K,{value:Y.target.value})}),e.jsx(ge,{placeholder:"Label (e.g. Closed volume)",value:W.label||"",onChange:Y=>f("credibility",K,{label:Y.target.value})})]},K)),e.jsx(i7,{onClick:()=>p("credibility",[...l.credibility||[],{value:"",label:""}]),label:"Add stat"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Your story"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsx(pd,{label:"Section title",value:l.story_title,onChange:W=>h({story_title:W})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Story"}),e.jsx(Ts,{rows:6,value:l.story_body||"",onChange:W=>h({story_body:W.target.value})})]}),e.jsx(pd,{label:"Story video URL (YouTube, Vimeo, Loom, MP4)",value:l.story_video_url,onChange:W=>h({story_video_url:W})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Value stack"})}),e.jsxs(Ae,{className:"space-y-4",children:[(l.value_cards||[]).map((W,K)=>e.jsxs(a7,{vertical:!0,onRemove:()=>p("value_cards",l.value_cards.filter((Y,ee)=>ee!==K)),children:[e.jsx(ge,{placeholder:"Title",value:W.title||"",onChange:Y=>f("value_cards",K,{title:Y.target.value})}),e.jsx(Ts,{rows:2,placeholder:"Description",value:W.body||"",onChange:Y=>f("value_cards",K,{body:Y.target.value})}),e.jsx(ge,{placeholder:"Proof point (optional)",value:W.proof||"",onChange:Y=>f("value_cards",K,{proof:Y.target.value})})]},K)),e.jsx(i7,{onClick:()=>p("value_cards",[...l.value_cards||[],{title:"",body:""}]),label:"Add value card"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"What you get from me"})}),e.jsxs(Ae,{className:"space-y-4",children:[(l.sponsor_cards||[]).map((W,K)=>e.jsxs(a7,{vertical:!0,onRemove:()=>p("sponsor_cards",l.sponsor_cards.filter((Y,ee)=>ee!==K)),children:[e.jsx(ge,{placeholder:"Title",value:W.title||"",onChange:Y=>f("sponsor_cards",K,{title:Y.target.value})}),e.jsx(Ts,{rows:2,placeholder:"Description",value:W.body||"",onChange:Y=>f("sponsor_cards",K,{body:Y.target.value})})]},K)),e.jsx(i7,{onClick:()=>p("sponsor_cards",[...l.sponsor_cards||[],{title:"",body:""}]),label:"Add commitment"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Free download & upcoming event"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsx(pd,{label:"Download title",value:(v=l.lead_magnet)==null?void 0:v.title,onChange:W=>h({lead_magnet:{...l.lead_magnet,title:W}})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Download description"}),e.jsx(Ts,{rows:2,value:((j=l.lead_magnet)==null?void 0:j.body)||"",onChange:W=>h({lead_magnet:{...l.lead_magnet,body:W.target.value}})})]}),e.jsx(pd,{label:"File URL",value:(_=l.lead_magnet)==null?void 0:_.file_url,onChange:W=>h({lead_magnet:{...l.lead_magnet,file_url:W}})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(pd,{label:"Event title",value:(S=l.event_block)==null?void 0:S.title,onChange:W=>h({event_block:{...l.event_block,title:W}})}),e.jsx(pd,{label:"When",value:(A=l.event_block)==null?void 0:A.when,onChange:W=>h({event_block:{...l.event_block,when:W}})}),e.jsx(pd,{label:"Registration link",value:(T=l.event_block)==null?void 0:T.url,onChange:W=>h({event_block:{...l.event_block,url:W}})})]})]})]})]}),e.jsxs(ls,{value:"proof",className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Testimonials"})}),e.jsxs(Ae,{className:"space-y-4",children:[(l.testimonials||[]).map((W,K)=>e.jsxs(a7,{vertical:!0,onRemove:()=>p("testimonials",l.testimonials.filter((Y,ee)=>ee!==K)),children:[e.jsx(Ts,{rows:3,placeholder:"Quote",value:W.quote||"",onChange:Y=>f("testimonials",K,{quote:Y.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(ge,{placeholder:"Name",value:W.name||"",onChange:Y=>f("testimonials",K,{name:Y.target.value})}),e.jsx(ge,{placeholder:"Role / market",value:W.role||"",onChange:Y=>f("testimonials",K,{role:Y.target.value})}),e.jsx(ge,{placeholder:"Photo URL",value:W.photo_url||"",onChange:Y=>f("testimonials",K,{photo_url:Y.target.value})})]})]},K)),e.jsx(i7,{onClick:()=>p("testimonials",[...l.testimonials||[],{quote:"",name:""}]),label:"Add testimonial"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Objection-handling FAQ"})}),e.jsxs(Ae,{className:"space-y-4",children:[(l.faqs||[]).map((W,K)=>e.jsxs(a7,{vertical:!0,onRemove:()=>p("faqs",l.faqs.filter((Y,ee)=>ee!==K)),children:[e.jsx(ge,{placeholder:"Question",value:W.q||"",onChange:Y=>f("faqs",K,{q:Y.target.value})}),e.jsx(Ts,{rows:3,placeholder:"Answer",value:W.a||"",onChange:Y=>f("faqs",K,{a:Y.target.value})})]},K)),e.jsx(i7,{onClick:()=>p("faqs",[...l.faqs||[],{q:"",a:""}]),label:"Add question"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Income disclaimer"})}),e.jsx(Ae,{children:e.jsx(Ts,{rows:4,value:l.disclaimer||"",onChange:W=>h({disclaimer:W.target.value})})})]})]}),e.jsx(ls,{value:"calculator",children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Earnings calculator"})}),e.jsxs(Ae,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(pd,{label:"Section title",value:(D=l.calculator)==null?void 0:D.title,onChange:W=>h({calculator:{...l.calculator,title:W}}),className:"md:col-span-2"}),e.jsx(pd,{label:"Cap ($)",type:"number",value:(L=l.calculator)==null?void 0:L.cap,onChange:W=>h({calculator:{...l.calculator,cap:Number(W)}})}),e.jsx(pd,{label:"Your split (%)",type:"number",value:(M=l.calculator)==null?void 0:M.split,onChange:W=>h({calculator:{...l.calculator,split:Number(W)}})}),e.jsx(pd,{label:"Per-transaction fee ($)",type:"number",value:(F=l.calculator)==null?void 0:F.transaction_fee,onChange:W=>h({calculator:{...l.calculator,transaction_fee:Number(W)}})}),e.jsx(pd,{label:"Typical competitor split (%)",type:"number",value:(z=l.calculator)==null?void 0:z.current_split,onChange:W=>h({calculator:{...l.calculator,current_split:Number(W)}})}),e.jsx(pd,{label:"Typical competitor monthly fees ($)",type:"number",value:(V=l.calculator)==null?void 0:V.current_monthly_fees,onChange:W=>h({calculator:{...l.calculator,current_monthly_fees:Number(W)}})}),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(ls,{value:"sections",children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Show or hide sections"})}),e.jsx(Ae,{className:"divide-y",children:Object.keys(gtt).map(W=>e.jsxs("div",{className:"flex items-center justify-between py-3",children:[e.jsx("span",{className:"text-sm",children:gtt[W]}),e.jsx(vn,{checked:b[W]!==!1,onCheckedChange:K=>h({sections:{...b,[W]:K}})})]},W))})]})}),e.jsxs(ls,{value:"publish",className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Publishing"})}),e.jsxs(Ae,{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(vn,{checked:!!l.is_published,onCheckedChange:W=>h({is_published:W})})]}),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(vn,{checked:!!l.noindex,onCheckedChange:W=>h({noindex:W})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Web address"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:l.slug||"",onChange:W=>h({slug:W.target.value})}),e.jsx(B,{variant:"outline",onClick:()=>{navigator.clipboard.writeText(u),ae.success("Link copied")},children:e.jsx(ta,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u})]}),e.jsx(pd,{label:"Search title",value:l.seo_title,onChange:W=>h({seo_title:W})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Search description"}),e.jsx(Ts,{rows:2,value:l.seo_description||"",onChange:W=>h({seo_description:W.target.value})})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"flex items-center gap-2 text-base",children:[e.jsx(yo,{className:"h-4 w-4"})," Where leads go"]})}),e.jsx(Ae,{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(B,{onClick:g,disabled:i.isPending,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})})]})}function pd({label:s,value:t,onChange:n,type:r="text",className:a}){return e.jsxs("div",{className:`space-y-1.5 ${a||""}`,children:[e.jsx(se,{children:s}),e.jsx(ge,{type:r,value:t??"",onChange:i=>n(i.target.value)})]})}function a7({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(B,{variant:"ghost",size:"icon",onClick:t,className:"text-muted-foreground hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})]})}function i7({onClick:s,label:t}){return e.jsxs(B,{variant:"outline",size:"sm",onClick:s,children:[e.jsx(As,{className:"mr-2 h-4 w-4"})," ",t]})}function kpn(s){const{user:t}=gs(),n=Gt(),r=lt({queryKey:["admin-attract-list",s,t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{let o=q.from("profiles").select("id, email, full_name").order("full_name",{ascending:!0}).limit(100);if(s.trim()){const p=`%${s.trim()}%`;o=o.or(`email.ilike.${p},full_name.ilike.${p}`)}const{data:c,error:d}=await o;if(d)throw d;const u=(c??[]).map(p=>p.id);let h={};if(u.length){const{data:p,error:f}=await q.from("feature_entitlements").select("user_id, enabled, tier, enabled_at, expires_at, notes, enabled_by").eq("feature_key","levelup_attract").in("user_id",u);if(f)throw f;(p??[]).forEach(g=>{h[g.user_id]=g})}return(c??[]).map(p=>{var f,g,b,v,j,_;return{user_id:p.id,email:p.email,full_name:p.full_name,enabled:!!((f=h[p.id])!=null&&f.enabled),tier:((g=h[p.id])==null?void 0:g.tier)??null,enabled_at:((b=h[p.id])==null?void 0:b.enabled_at)??null,expires_at:((v=h[p.id])==null?void 0:v.expires_at)??null,notes:((j=h[p.id])==null?void 0:j.notes)??null,enabled_by:((_=h[p.id])==null?void 0:_.enabled_by)??null}})}}),a=lt({queryKey:["admin-attract-audit",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:o,error:c}=await q.from("feature_entitlement_audit").select("*").eq("feature_key","levelup_attract").order("created_at",{ascending:!1}).limit(50);if(c)throw c;return o??[]}}),i=gt({mutationFn:async({target_user_id:o,tier:c,expires_at:d,notes:u})=>{const h={user_id:o,feature_key:"levelup_attract",enabled:!0,tier:c??"beta",enabled_by:t.id,enabled_at:new Date().toISOString(),expires_at:d??null,notes:u??null},{error:p}=await q.from("feature_entitlements").upsert(h,{onConflict:"user_id,feature_key"});if(p)throw p;await q.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"grant",tier:h.tier,expires_at:h.expires_at,notes:h.notes,performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),ae.success("Access granted")},onError:o=>ae.error(o.message)}),l=gt({mutationFn:async o=>{const{error:c}=await q.from("feature_entitlements").update({enabled:!1}).eq("user_id",o).eq("feature_key","levelup_attract");if(c)throw c;await q.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"revoke",performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),ae.success("Access revoked")},onError:o=>ae.error(o.message)});return{list:r,audit:a,grant:i,revoke:l}}function Spn(){const[s,t]=N.useState(""),{list:n,audit:r,grant:a,revoke:i}=kpn(s),[l,o]=N.useState(null),[c,d]=N.useState(null),[u,h]=N.useState("beta"),[p,f]=N.useState(""),[g,b]=N.useState(""),v=_=>{d(_),h(_.tier??"beta"),f(_.expires_at?_.expires_at.slice(0,10):""),b(_.notes??"")},j=async()=>{c&&(await a.mutateAsync({target_user_id:c.user_id,tier:u,expires_at:p?new Date(p).toISOString():null,notes:g||void 0}),d(null))};return e.jsxs("div",{className:"p-6",children:[e.jsx(Vd,{title:"LevelUp Attract — Access Management",description:"Grant or revoke access to LevelUp Attract for individual members. Every change is audited."}),e.jsx(fe,{className:"p-4 rounded-2xl mb-4",children:e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(_r,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ge,{value:s,onChange:_=>t(_.target.value),placeholder:"Search by name or email...",className:"pl-9"})]})}),e.jsxs(fe,{className:"rounded-2xl overflow-hidden mb-8",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 text-[11px] uppercase tracking-widest text-slate-500 font-semibold border-b",children:[e.jsx("div",{children:"Member"}),e.jsx("div",{children:"Access"}),e.jsx("div",{children:"Enabled"}),e.jsx("div",{children:"Actions"})]}),n.isLoading&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"Loading members…"}),!n.isLoading&&(n.data??[]).length===0&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"No members match."}),(n.data??[]).map(_=>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(ze,{className:"bg-emerald-100 text-emerald-800 border-0 gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," ",_.tier??"enabled"]}):e.jsx(ze,{variant:"outline",className:"text-slate-500",children:"Not enabled"})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:_.enabled_at?ks(new Date(_.enabled_at),"MMM d, yyyy"):"—"}),e.jsx("div",{className:"flex gap-1.5",children:_.enabled?e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>v(_),children:"Edit"}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>o({user:_,action:"revoke"}),children:"Revoke"})]}):e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v(_),children:[e.jsx(ng,{className:"h-3.5 w-3.5 mr-1"})," Enable"]})})]},_.user_id))]}),e.jsxs(fe,{className:"rounded-2xl p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-[12px] uppercase tracking-widest text-slate-500 font-semibold",children:[e.jsx(IA,{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(ze,{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:ks(new Date(_.created_at),"MMM d h:mm a")})]},_.id))})]}),e.jsx(bs,{open:!!c,onOpenChange:_=>!_&&d(null),children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[c!=null&&c.enabled?"Update":"Enable"," Attract access"]}),e.jsx(Qn,{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(se,{children:"Tier"}),e.jsxs(us,{value:u,onValueChange:h,children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"beta",children:"Beta"}),e.jsx(Ze,{value:"standard",children:"Standard"}),e.jsx(Ze,{value:"pro",children:"Pro"}),e.jsx(Ze,{value:"founder",children:"Founder"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Expires (optional)"}),e.jsx(ge,{type:"date",value:p,onChange:_=>f(_.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Internal notes (optional)"}),e.jsx(Ts,{rows:2,value:g,onChange:_=>b(_.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>d(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:j,disabled:a.isPending,children:c!=null&&c.enabled?"Save changes":"Enable access"})]})]})}),e.jsx(Oo,{open:!!l,onOpenChange:_=>!_&&o(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Revoke Attract access?"}),e.jsxs(Mo,{children:[(l==null?void 0:l.user.full_name)||(l==null?void 0:l.user.email)," will lose access to LevelUp Attract immediately. Their data is preserved and access can be re-enabled."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsxs(jo,{className:"bg-rose-600 hover:bg-rose-700",onClick:async()=>{l&&await i.mutateAsync(l.user.user_id),o(null)},children:[e.jsx(Gc,{className:"h-4 w-4 mr-1.5"})," Revoke access"]})]})]})})]})}const Cpn=({team:s,onSelect:t})=>{const{data:n}=lt({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:r}=await q.from("team_members").select("user_id, role").eq("team_id",s.id),a=(r==null?void 0:r.length)||0,i=r==null?void 0:r.find(o=>o.role==="team_leader");let l=null;if(i){const{data:o}=await q.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(fe,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Pt,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(Hn,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(ze,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(_n,{className:"h-3 w-3 mr-1"}),(n==null?void 0:n.count)??"…"]})]})}),e.jsxs(Ae,{className:"space-y-3",children:[(n==null?void 0:n.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(aa,{className:"h-6 w-6",children:[e.jsx(ri,{src:n.leaderProfile.avatar_url||""}),e.jsx(ia,{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(xf,{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(hh,{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(ze,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(ze,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(ze,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},Tpn=()=>{const{user:s,isAdmin:t,isBrokerageManager:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i}=gs(),l=i||(a.length>0?a[0].id:r),o=t?void 0:l||void 0,{teams:c,isLoading:d,createTeam:u,updateTeam:h,deleteTeam:p,addMember:f,removeMember:g,updateMemberRole:b}=s6(o),[v,j]=N.useState(!1),[_,S]=N.useState(null),{data:A}=lt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:L,error:M}=await q.from("brokerages").select("id, name").order("name");if(M)throw M;return L||[]},enabled:t}),{data:T}=lt({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:L,error:M}=await q.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if(M)throw M;return L||[]},enabled:!!l}),D=async L=>{const M=L.brokerage_id||l||null,F=await u.mutateAsync({name:L.name,brokerage_id:M,description:L.description});if(L.leaderId&&L.leaderId!=="none"&&await f.mutateAsync({team_id:F.id,user_id:L.leaderId,role:"team_leader"}),L.memberIds)for(const z of L.memberIds)await f.mutateAsync({team_id:F.id,user_id:z,role:"team_member"});j(!1)};return!n&&!t?e.jsx(Cs,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(_n,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Access Denied"}),e.jsx("p",{className:"text-muted-foreground",children:"You need brokerage manager access to manage teams."})]})}):e.jsx(Cs,{title:"Teams",description:"Create and manage teams within your brokerage",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Teams"}),e.jsx("p",{className:"text-muted-foreground",children:"Organize your agents into teams with leaders and shared resources."})]}),e.jsxs(B,{onClick:()=>j(!0),children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(myt,{open:v,onOpenChange:j,onCreateTeam:D,isCreating:u.isPending,brokerageAgents:T||[],isAdmin:t,allBrokerages:A,activeBrokerageId:l}),d&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(L=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-6",children:[e.jsx(Ws,{className:"h-5 w-32 mb-3"}),e.jsx(Ws,{className:"h-4 w-48 mb-4"}),e.jsx(Ws,{className:"h-8 w-full"})]})},L))}),!d&&c.length===0&&!_&&e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(_n,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create your first team to organize agents and share resources."}),e.jsxs(B,{onClick:()=>j(!0),children:[e.jsx(As,{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(L=>e.jsx(Cpn,{team:L,onSelect:()=>S(L)},L.id))}),_&&e.jsx(hyt,{team:_,brokerageAgents:T||[],onBack:()=>S(null),onUpdate:L=>h.mutateAsync({id:_.id,...L}).then(M=>S(M)),onAddMember:(L,M)=>f.mutateAsync({team_id:_.id,user_id:L,role:M}),onRemoveMember:L=>g.mutateAsync({team_id:_.id,member_id:L}),onUpdateRole:(L,M)=>b.mutateAsync({team_id:_.id,member_id:L,role:M}),onDeleteTeam:()=>p.mutate(_.id),isUpdating:h.isPending,isAddingMember:f.isPending})]})})},Epn=()=>{const{data:s,isLoading:t}=Xv(),{useTeamMembers:n}=s6(),{data:r=[],isLoading:a}=n((s==null?void 0:s.teamId)||"");if(t)return e.jsx(Cs,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-8 w-48"}),e.jsx(Ws,{className:"h-40 w-full"})]})});if(!s)return e.jsx(Cs,{title:"My Team",description:"Your team",children:e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(_n,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Team Yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't been assigned to a team. Ask your brokerage manager to add you."})]})})});const i=s.team;return e.jsx(Cs,{title:"My Team",description:i.name,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:i.name}),e.jsx(ze,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(xf,{className:"mr-1 h-3 w-3"})," Leader"]}):"Member"})]}),i.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:i.description})]}),e.jsxs($r,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Ur,{className:"flex-wrap",children:[e.jsx(Zt,{value:"members",children:"Members"}),i.contact_visibility!=="private"&&e.jsxs(Zt,{value:"contacts",children:[e.jsx(CA,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),i.lead_pond_enabled&&e.jsxs(Zt,{value:"lead-pond",children:[e.jsx(pb,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),i.shared_assets_enabled&&e.jsxs(Zt,{value:"shared-assets",children:[e.jsx(yf,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]})]}),e.jsx(ls,{value:"members",className:"space-y-2",children:a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(l=>e.jsx(Ws,{className:"h-16 w-full"},l))}):r.map(l=>{var o,c,d,u;return e.jsx(fe,{children:e.jsxs(Ae,{className:"flex items-center gap-3 p-4",children:[e.jsxs(aa,{className:"h-10 w-10",children:[e.jsx(ri,{src:((o=l.profile)==null?void 0:o.avatar_url)||""}),e.jsx(ia,{children:(((c=l.profile)==null?void 0:c.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:((d=l.profile)==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(u=l.profile)==null?void 0:u.email})]}),l.role==="team_leader"?e.jsxs(ze,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(xf,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(ze,{variant:"secondary",className:"ml-auto",children:"Member"})]})},l.id)})}),i.contact_visibility!=="private"&&e.jsx(ls,{value:"contacts",className:"space-y-4",children:e.jsx(JIe,{})}),i.lead_pond_enabled&&e.jsx(ls,{value:"lead-pond",className:"space-y-4",children:e.jsx(ePe,{teamId:s.teamId})}),i.shared_assets_enabled&&e.jsx(ls,{value:"shared-assets",className:"space-y-4",children:e.jsx(uyt,{teamId:s.teamId})})]})]})})};function Apn(){const{user:s}=gs(),t=Gt(),n=lt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(j)throw j;return v},enabled:!!s}),r=lt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(j)throw j;return v},enabled:!!s}),a=lt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(j)throw j;return v},enabled:!!s}),i=lt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(j)throw j;return v},enabled:!!s}),l=lt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(j)throw j;return v},enabled:!!s}),o=gt({mutationFn:async()=>{const{data:v,error:j}=await q.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(j)throw j;const _=[{name:"Listing Consultation",description:"Get a comprehensive market analysis and listing strategy for your home",duration_minutes:60,color:"#10B981",icon:"Home",sort_order:0},{name:"Buyer Consultation",description:"Discuss your home search criteria, budget, and buying process",duration_minutes:45,color:"#3B82F6",icon:"Search",sort_order:1},{name:"Home Valuation",description:"Find out what your home is worth in today's market",duration_minutes:30,color:"#F59E0B",icon:"DollarSign",sort_order:2},{name:"General Meeting",description:"Coffee chat, check-in, or quick real estate question",duration_minutes:30,color:"#8B5CF6",icon:"Coffee",sort_order:3}],{error:S}=await q.from("agent_booking_types").insert(_.map(D=>({...D,user_id:s.id})));if(S)throw S;const A=[1,2,3,4,5].map(D=>({user_id:s.id,day_of_week:D,start_time:"09:00",end_time:"17:00"})),{error:T}=await q.from("agent_availability_slots").insert(A);if(T)throw T;return v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),ae.success("Scheduler set up successfully!")},onError:v=>ae.error(v.message)}),c=gt({mutationFn:async v=>{const{error:j}=await q.from("agent_booking_settings").update(v).eq("user_id",s.id);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),ae.success("Settings updated")},onError:v=>ae.error(v.message)}),d=gt({mutationFn:async v=>{const j={...v,user_id:s.id};if(v.id){const{error:_}=await q.from("agent_booking_types").update(j).eq("id",v.id);if(_)throw _}else{const{error:_}=await q.from("agent_booking_types").insert(j);if(_)throw _}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ae.success("Booking type saved")},onError:v=>ae.error(v.message)}),u=gt({mutationFn:async v=>{const{error:j}=await q.from("agent_booking_types").delete().eq("id",v);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ae.success("Booking type deleted")},onError:v=>ae.error(v.message)}),h=gt({mutationFn:async v=>{const j={...v,user_id:s.id};if(v.id){const{error:_}=await q.from("agent_availability_slots").update(j).eq("id",v.id);if(_)throw _}else{const{error:_}=await q.from("agent_availability_slots").insert(j);if(_)throw _}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>ae.error(v.message)}),p=gt({mutationFn:async v=>{const{error:j}=await q.from("agent_availability_slots").delete().eq("id",v);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>ae.error(v.message)}),f=gt({mutationFn:async v=>{const{error:j}=await q.from("agent_blocked_dates").insert({...v,user_id:s.id});if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]}),ae.success("Date blocked")},onError:v=>ae.error(v.message)}),g=gt({mutationFn:async v=>{const{error:j}=await q.from("agent_blocked_dates").delete().eq("id",v);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:v=>ae.error(v.message)}),b=gt({mutationFn:async({id:v,reason:j})=>{const{error:_}=await q.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:j}).eq("id",v);if(_)throw _},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),ae.success("Booking cancelled")},onError:v=>ae.error(v.message)});return{settings:n.data,bookingTypes:r.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:n.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:u,upsertAvailability:h,deleteAvailability:p,addBlockedDate:f,removeBlockedDate:g,cancelBooking:b}}const ytt={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function Mpn({types:s,onSave:t,onDelete:n}){const[r,a]=N.useState(null),[i,l]=N.useState(!1),o=()=>{a({name:"",description:"",duration_minutes:30,color:"#3B82F6",icon:"Calendar",is_active:!0,qualification_enabled:!1}),l(!0)},c=u=>{a({...u}),l(!0)},d=()=>{r!=null&&r.name&&(t(r),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pt,{children:"Booking Types"}),e.jsx(Hn,{children:"The meeting types prospects can book with you"})]}),e.jsxs(B,{onClick:o,size:"sm",children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(Ae,{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:ytt[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(ze,{variant:"secondary",className:"text-xs",children:"Inactive"}),u.qualification_enabled&&e.jsxs(ze,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(x9,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(gr,{className:"h-3 w-3"}),u.duration_minutes," min",u.description&&e.jsxs("span",{children:["· ",u.description.slice(0,60),u.description.length>60?"...":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(u),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>n(u.id),className:"text-destructive hover:text-destructive",children:e.jsx(bn,{className:"h-4 w-4"})})]})]},u.id))})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(ws,{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(se,{children:"Name"}),e.jsx(ge,{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(se,{children:"Description"}),e.jsx(Ts,{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(se,{children:"Duration (minutes)"}),e.jsx(ge,{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(se,{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(ge,{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(se,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(ytt).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(se,{children:"Meeting Link Override (optional)"}),e.jsx(ge,{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(se,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(vn,{checked:r.qualification_enabled||!1,onCheckedChange:u=>a({...r,qualification_enabled:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Active"}),e.jsx(vn,{checked:r.is_active??!0,onCheckedChange:u=>a({...r,is_active:u})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:d,children:"Save"})]})]})})]})}const vtt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Ipn({slots:s,onSave:t,onDelete:n}){const[r,a]=N.useState(null),[i,l]=N.useState("09:00"),[o,c]=N.useState("17:00"),d=vtt.map((h,p)=>s.filter(f=>f.day_of_week===p)),u=()=>{r!==null&&(t({day_of_week:r,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Hn,{children:"Set your available hours for each day"})]}),e.jsx(Ae,{className:"space-y-2",children:vtt.map((h,p)=>{const f=d[p];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:h})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):f.map(g=>{var b,v;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(b=g.start_time)==null?void 0:b.slice(0,5),onBlur:j=>t({id:g.id,start_time:j.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(ge,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(v=g.end_time)==null?void 0:v.slice(0,5),onBlur:j=>t({id:g.id,end_time:j.target.value})}),e.jsx(vn,{checked:g.is_active,onCheckedChange:j=>t({id:g.id,is_active:j})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(g.id),children:e.jsx(bn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},g.id)}),r===p?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{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(ge,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:g=>c(g.target.value)}),e.jsx(B,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(p),children:[e.jsx(As,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}const Ppn={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 Lpn({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(Xi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(ze,{className:`text-xs ${Ppn[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(Tl,{className:"h-3.5 w-3.5"}),ks(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{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(Hs,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pr,{className:"h-3 w-3"}),i.guest_phone]})]}),i.booking_type&&e.jsx(ze,{variant:"outline",className:"text-xs mt-1",children:i.booking_type.name}),i.guest_message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 italic",children:['"',i.guest_message,'"']})]}),l&&i.status==="confirmed"&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(Gc,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Upcoming Bookings"}),e.jsxs(Hn,{children:[n.length," upcoming appointment",n.length!==1?"s":""]})]}),e.jsx(Ae,{children:n.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No upcoming bookings"}):e.jsx("div",{className:"space-y-3",children:n.map(i=>a(i,!0))})})]}),r.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Past & Cancelled"})}),e.jsx(Ae,{children:e.jsx("div",{className:"space-y-3",children:r.slice(0,20).map(i=>a(i))})})]})]})}function Dpn({blockedDates:s,onAdd:t,onRemove:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(""),d=()=>{i&&(t({blocked_date:i,reason:o||void 0}),a(!1),l(""),c(""))};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(Q7,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Hn,{children:"Block specific dates (vacations, holidays, etc.)"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-1"})," Block Date"]})]}),e.jsxs(Ae,{children:[r&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx(ge,{type:"date",value:i,onChange:u=>l(u.target.value),className:"w-40"}),e.jsx(ge,{placeholder:"Reason (optional)",value:o,onChange:u=>c(u.target.value),className:"flex-1"}),e.jsx(B,{size:"sm",onClick:d,children:"Add"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>a(!1),children:"Cancel"})]}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No blocked dates"}):e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map(u=>e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-full border bg-muted/50 text-sm",children:[e.jsx("span",{children:ks(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(Fn,{className:"h-3.5 w-3.5"})})]},u.id))})]})]})}function Rpn(){const{settings:s,bookingTypes:t,availability:n,blockedDates:r,bookings:a,isLoading:i,initializeSettings:l,updateSettings:o,upsertBookingType:c,deleteBookingType:d,upsertAvailability:u,deleteAvailability:h,addBlockedDate:p,removeBlockedDate:f,cancelBooking:g}=Apn(),[b,v]=N.useState("");N.useState(15),b||s!=null&&s.meeting_link;const j=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(Cs,{children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):s?e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Tl,{className:"h-6 w-6 text-primary"}),"LevelUp Scheduler"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage your booking types, availability, and appointments"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[j&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(j),ae.success("Booking link copied!")},children:[e.jsx(ta,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(vn,{id:"scheduler-active",checked:s.is_active,onCheckedChange:_=>o.mutate({is_active:_})})]})]})]}),e.jsxs($r,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"types",children:"Booking Types"}),e.jsx(Zt,{value:"availability",children:"Availability"}),e.jsx(Zt,{value:"settings",children:"Settings"}),e.jsxs(Zt,{value:"bookings",children:["Bookings",a.filter(_=>_.status==="confirmed").length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(_=>_.status==="confirmed").length})]})]}),e.jsx(ls,{value:"types",children:e.jsx(Mpn,{types:t,onSave:_=>c.mutate(_),onDelete:_=>d.mutate(_)})}),e.jsx(ls,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ipn,{slots:n,onSave:_=>u.mutate(_),onDelete:_=>h.mutate(_)}),e.jsx(Dpn,{blockedDates:r,onAdd:_=>p.mutate(_),onRemove:_=>f.mutate(_)})]})}),e.jsx(ls,{value:"settings",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(E9,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(Hn,{children:"Configure your booking page defaults"})]}),e.jsxs(Ae,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{j&&(navigator.clipboard.writeText(j),ae.success("Copied!"))},children:e.jsx(ta,{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(se,{htmlFor:"meeting-link",children:[e.jsx(El,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(ge,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:_=>o.mutate({meeting_link:_.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(se,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:_=>o.mutate({buffer_minutes:parseInt(_.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:_=>o.mutate({min_notice_hours:parseInt(_.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:_=>o.mutate({max_advance_days:parseInt(_.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]})]})]})}),e.jsx(ls,{value:"bookings",children:e.jsx(Lpn,{bookings:a,onCancel:_=>g.mutate({id:_})})})]})]})}):e.jsx(Cs,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-8 space-y-8",children:[e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center",children:e.jsx(Tl,{className:"h-8 w-8 text-primary"})}),e.jsx("h1",{className:"text-3xl font-bold",children:"LevelUp Scheduler"}),e.jsx("p",{className:"text-muted-foreground text-lg max-w-md mx-auto",children:"Your own booking page — built for real estate. Prospects book with you, get auto-added to your CRM, and you never miss a lead."})]}),e.jsx(fe,{children:e.jsxs(Ae,{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(_=>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:_.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:_.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_.desc})]})]},_.title))}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"✅ Auto-creates CRM contacts from every booking"}),e.jsx("p",{children:"✅ Optional pre-qualification questions per booking type"}),e.jsx("p",{children:"✅ Embeds on your Smart Card — replaces TidyCal"}),e.jsx("p",{children:"✅ Standalone shareable booking page"})]}),e.jsxs(B,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}const btt=[{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 Opn(){const{user:s}=gs(),t=fa(),{toast:n}=Ua(),r=In(),a=Gt(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState({title:"",description:"",page_type:"lead_capture"}),{data:f=[],isLoading:g}=lt({queryKey:["landing-pages",t],queryFn:async()=>{const{data:_,error:S}=await q.from("landing_pages").select("*").eq("user_id",t).is("deleted_at",null).order("created_at",{ascending:!1});if(S)throw S;return _},enabled:!!t}),b=gt({mutationFn:async()=>{const _=h.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:S}=await q.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),A=h.page_type==="just_listed"||h.page_type==="just_sold",{data:T,error:D}=await q.from("landing_pages").insert({user_id:t,title:h.title,description:h.description||null,page_type:h.page_type,slug:_,hero_headline:A?h.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":h.page_type==="lead_magnet"?"📥 Free Download":h.title,agent_name:(S==null?void 0:S.name)||null,agent_phone:(S==null?void 0:S.phone)||null,agent_email:(S==null?void 0:S.email)||s.email||null,agent_photo_url:(S==null?void 0:S.avatar_url)||null,property_status:A?h.page_type.replace("just_",""):null}).select().single();if(D)throw D;const L=Fpn(h.page_type);if(L.length>0){const{error:M}=await q.from("landing_page_fields").insert(L.map((F,z)=>({...F,page_id:T.id,sort_order:z})));if(M)throw M}return T},onSuccess:_=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),p({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"})}),v=gt({mutationFn:async _=>{const{error:S}=await q.from("landing_pages").update({deleted_at:new Date().toISOString(),is_published:!1}).eq("id",_);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),n({title:"Landing page deleted"})}}),j=_=>`https://pages.relevelup.com/${_}`;return e.jsxs(Cs,{title:"Landing Pages",children:[e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Pages"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Create branded lead capture pages for events, consultations, and more"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>r("/mission-control/landing-pages/defaults"),children:[e.jsx(Vo,{className:"h-4 w-4 mr-2"})," Defaults"]}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(As,{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"})}):f.length===0?e.jsx(fe,{children:e.jsxs(Ae,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Nr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No landing pages yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1 mb-4",children:"Create your first page to start capturing leads"}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(As,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:f.map(_=>{var S;return e.jsx(fe,{className:"hover:shadow-md transition-shadow",children:e.jsx(Ae,{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(ze,{variant:_.is_published?"default":"secondary",className:"text-[10px]",children:_.is_published?"Published":"Draft"}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:((S=btt.find(A=>A.id===_.page_type))==null?void 0:S.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(Ir,{className:"h-3 w-3"})," ",_.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nr,{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(B,{size:"sm",variant:"outline",onClick:()=>u(j(_.slug)),children:e.jsx(ly,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(j(_.slug)),n({title:"Link copied!"})},children:e.jsx(ta,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:j(_.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsx(B,{size:"sm",variant:"ghost",children:e.jsx(Lg,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[e.jsxs(Xr,{onClick:()=>r(`/mission-control/landing-pages/${_.id}`),children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(Xr,{onClick:()=>c(_.id),className:"text-destructive",children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},_.id)})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Page Title"}),e.jsx(ge,{value:h.title,onChange:_=>p(S=>({...S,title:_.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description (optional)"}),e.jsx(Ts,{value:h.description,onChange:_=>p(S=>({...S,description:_.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Page Template"}),e.jsxs(us,{value:h.page_type,onValueChange:_=>p(S=>({...S,page_type:_})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:btt.map(_=>e.jsx(Ze,{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(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>b.mutate(),disabled:!h.title.trim()||b.isPending,children:b.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(Oo,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Landing Page?"}),e.jsx(Mo,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>o&&v.mutate(o),children:"Delete"})]})]})}),e.jsx(bs,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsx(ws,{children:e.jsx(_s,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(QU,{value:d,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:d}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{d&&(navigator.clipboard.writeText(d),n({title:"URL copied!"}))},children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function Fpn(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 zpn(s,t){return t?`${(s/t*100).toFixed(1)}%`:"0%"}function Bpn({pageId:s}){const{data:t=[],isLoading:n}=lt({queryKey:["landing-page-events",s],queryFn:async()=>{const l=new Date(Date.now()-2592e6).toISOString(),{data:o,error:c}=await q.from("landing_page_events").select("event_type, session_id, utm_source, utm_medium, utm_campaign, referrer, device, created_at").eq("page_id",s).gte("created_at",l).order("created_at",{ascending:!1}).limit(1e3);if(c)throw c;return o||[]}}),{data:r=[]}=lt({queryKey:["landing-page-submissions-analytics",s],queryFn:async()=>{const{data:l}=await q.from("landing_page_submissions").select("id, created_at").eq("page_id",s);return l||[]}}),a=N.useMemo(()=>{const l=t.filter(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 b=g.utm_source||"Direct / unknown";if(d.set(b,(d.get(b)||0)+1),g.referrer)try{const j=new URL(g.referrer).hostname.replace(/^www\./,"");u.set(j,(u.get(j)||0)+1)}catch{}const v=g.device||"unknown";h.set(v,(h.get(v)||0)+1)}const p=[];for(let g=13;g>=0;g--){const b=new Date;b.setHours(0,0,0,0),b.setDate(b.getDate()-g);const v=new Date(b);v.setDate(b.getDate()+1);const j=b.toLocaleDateString("en-US",{month:"numeric",day:"numeric"}),_=l.filter(A=>{const T=new Date(A.created_at);return T>=b&&T{const T=new Date(A.created_at);return T>=b&&Tg.views));return{views:l.length,sessions:c.size,clicks:o.length,submissions:r.length,conversion:zpn(r.length,c.size||l.length),sourceCounts:[...d.entries()].sort((g,b)=>b[1]-g[1]).slice(0,6),referrerCounts:[...u.entries()].sort((g,b)=>b[1]-g[1]).slice(0,6),deviceCounts:[...h.entries()].sort((g,b)=>b[1]-g[1]),days:p,maxBar:f}},[t,r]);if(n)return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((l,o)=>e.jsx(Ws,{className:"h-24"},o))});const i=[{label:"Views (30d)",value:a.views,icon:Ir},{label:"Unique visitors",value:a.sessions,icon:_n},{label:"Submissions",value:a.submissions,icon:cr},{label:"Conversion rate",value:a.conversion,icon:mo}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:i.map(l=>e.jsx(fe,{children:e.jsxs(Ae,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(l.icon,{className:"h-3.5 w-3.5"})," ",l.label]}),e.jsx("div",{className:"text-2xl font-semibold mt-1",children:l.value})]})},l.label))}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Last 14 days"})}),e.jsxs(Ae,{children:[a.views===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No traffic yet. Share your page link or QR code to start collecting visits."}):e.jsx("div",{className:"flex items-end gap-1.5 h-32",children:a.days.map((l,o)=>e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"w-full flex flex-col justify-end h-24",children:[e.jsx("div",{title:`${l.views} views · ${l.submits} submits`,className:"w-full rounded-t bg-primary/70",style:{height:`${l.views/a.maxBar*100}%`,minHeight:l.views?2:0}}),l.submits>0&&e.jsx("div",{className:"w-full bg-emerald-500",style:{height:`${Math.max(2,l.submits/a.maxBar*100)}%`}})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:l.label})]},o))}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-primary/70"})," Views"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-emerald-500"})," Submissions"]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(oc,{className:"h-4 w-4"})," Top sources"]})}),e.jsx(Ae,{children:a.sourceCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No UTM data yet."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.sourceCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"truncate",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Top referrers"})}),e.jsx(Ae,{children:a.referrerCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No external referrers tracked."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.referrerCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"truncate",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Devices"})}),e.jsx(Ae,{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 $pn=[{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 Upn=0;const _tt=()=>`f_${Date.now()}_${++Upn}`;function qpn({field:s,index:t,updateField:n,removeField:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=Fve({id:s.clientId}),u={transform:F4.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(fe,{ref:l,style:u,children:e.jsx(Ae,{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(Uu,{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(se,{className:"text-xs",children:"Field Type"}),e.jsxs(us,{value:s.field_type,onValueChange:h=>n(t,{field_type:h}),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsx(ds,{children:$pn.map(h=>e.jsx(Ze,{value:h.value,children:h.label},h.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Label"}),e.jsx(ge,{value:s.label,onChange:h=>n(t,{label:h.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Placeholder"}),e.jsx(ge,{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(se,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(ge,{value:s.options?(typeof s.options=="string"?JSON.parse(s.options):s.options).join(", "):"",onChange:h=>n(t,{options:JSON.stringify(h.target.value.split(",").map(p=>p.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{checked:s.is_required,onCheckedChange:h=>n(t,{is_required:h})}),e.jsx(se,{className:"text-xs",children:"Required"})]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>r(t),children:e.jsx(bn,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function Vpn(){const{pageId:s}=_i(),t=In(),{user:n}=gs(),r=fa(),{toast:a}=Ua(),i=Gt(),[l,o]=N.useState(null),[c,d]=N.useState(!1),{data:u,isLoading:h}=lt({queryKey:["landing-page",s],queryFn:async()=>{const{data:de,error:ie}=await q.from("landing_pages").select("*").eq("id",s).single();if(ie)throw ie;return de},enabled:!!s}),{data:p=[],isLoading:f}=lt({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:de,error:ie}=await q.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(ie)throw ie;return de},enabled:!!s}),{data:g=[]}=lt({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:de,error:ie}=await q.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(ie)throw ie;return de},enabled:!!s}),{data:b=[]}=lt({queryKey:["my-listings-for-pages",r],queryFn:async()=>{const{data:de,error:ie}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",r).order("created_at",{ascending:!1});if(ie)throw ie;return de},enabled:!!n&&((u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold")}),{data:v=[]}=lt({queryKey:["drips-for-landing",r],queryFn:async()=>{const{data:de}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",r).eq("is_active",!0).order("name");return de||[]},enabled:!!r}),{data:j}=lt({queryKey:["agent-landing-defaults",r],queryFn:async()=>{const{data:de}=await q.from("agent_landing_page_defaults").select("*").eq("user_id",r).maybeSingle();return de},enabled:!!r}),[_,S]=N.useState({title:"",hero_headline:"",hero_subtext:"",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",agent_name:"",agent_phone:"",agent_email:"",agent_photo_url:null,success_message:"Thank you! We'll be in touch soon.",is_published:!1,description:"",lead_magnet_file_url:null,lead_magnet_file_name:null,lead_magnet_external_url:null,listing_id:null,property_address:"",property_price:"",property_beds:"",property_baths:"",property_sqft:"",property_description:"",property_photos:[],property_status:"just_listed",theme_style:"premium",eyebrow:"",headline_accent:"",heading_font:"playfair",trust_pills:["No obligation","100% free","60 seconds or less"],settings_redirect_url:"",settings_auto_responder_subject:"",settings_auto_responder_body:"",settings_drip_campaign_id:null,settings_disable_auto_responder:!1,settings_disable_drip:!1,settings_event_starts_at:"",settings_event_location_name:"",settings_event_address:""}),[A,T]=N.useState([]);N.useEffect(()=>{var de,ie,ye,_e,Me,Te,Ce,Ee,De;u&&S({title:u.title,hero_headline:u.hero_headline,hero_subtext:u.hero_subtext||"",hero_image_url:u.hero_image_url,logo_url:u.logo_url,primary_color:u.primary_color,accent_color:u.accent_color,agent_name:u.agent_name||"",agent_phone:u.agent_phone||"",agent_email:u.agent_email||"",agent_photo_url:u.agent_photo_url,success_message:u.success_message||"Thank you! We'll be in touch soon.",is_published:u.is_published,description:u.description||"",lead_magnet_file_url:u.lead_magnet_file_url||null,lead_magnet_file_name:u.lead_magnet_file_name||null,lead_magnet_external_url:u.lead_magnet_external_url||null,listing_id:u.listing_id||null,property_address:u.property_address||"",property_price:u.property_price||"",property_beds:u.property_beds||"",property_baths:u.property_baths||"",property_sqft:u.property_sqft||"",property_description:u.property_description||"",property_photos:Array.isArray(u.property_photos)?u.property_photos:[],property_status:u.property_status||"just_listed",theme_style:u.theme_style||"premium",eyebrow:u.eyebrow||"",headline_accent:u.headline_accent||"",heading_font:u.heading_font||"playfair",trust_pills:Array.isArray(u.trust_pills)?u.trust_pills:["No obligation","100% free","60 seconds or less"],settings_redirect_url:((de=u.settings)==null?void 0:de.redirect_url)||"",settings_auto_responder_subject:((ie=u.settings)==null?void 0:ie.auto_responder_subject)||"",settings_auto_responder_body:((ye=u.settings)==null?void 0:ye.auto_responder_body)||"",settings_drip_campaign_id:((_e=u.settings)==null?void 0:_e.drip_campaign_id)||null,settings_disable_auto_responder:!!((Me=u.settings)!=null&&Me.disable_auto_responder),settings_disable_drip:!!((Te=u.settings)!=null&&Te.disable_drip),settings_event_starts_at:((Ce=u.settings)==null?void 0:Ce.event_starts_at)||"",settings_event_location_name:((Ee=u.settings)==null?void 0:Ee.event_location_name)||"",settings_event_address:((De=u.settings)==null?void 0:De.event_address)||""})},[u]),N.useEffect(()=>{p.length>0&&T(p.map(de=>({id:de.id,clientId:de.id||_tt(),field_type:de.field_type,label:de.label,placeholder:de.placeholder,is_required:de.is_required,options:typeof de.options=="string"?de.options:de.options?JSON.stringify(de.options):null,sort_order:de.sort_order})))},[p]);const D=gt({mutationFn:async()=>{const{error:de}=await q.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,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(de)throw de;if(await q.from("landing_page_fields").delete().eq("page_id",s),A.length>0){const{error:ie}=await q.from("landing_page_fields").insert(A.map((ye,_e)=>({page_id:s,field_type:ye.field_type,label:ye.label,placeholder:ye.placeholder||null,is_required:ye.is_required,options:ye.options?JSON.parse(ye.options):null,sort_order:_e})));if(ie)throw ie}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:de=>a({title:"Error",description:de.message,variant:"destructive"})}),L=async(de,ie)=>{const ye=de.name.split(".").pop(),_e=`landing-pages/${n.id}/${ie}-${Date.now()}.${ye}`,{error:Me}=await q.storage.from("recruit-landing").upload(_e,de);if(Me)throw Me;const{data:{publicUrl:Te}}=q.storage.from("recruit-landing").getPublicUrl(_e);return Te},M=async(de,ie)=>{var _e;const ye=(_e=de.target.files)==null?void 0:_e[0];if(ye){o(ie);try{const Me=await L(ye,ie);S(Te=>({...Te,[ie]:Me})),a({title:"Image uploaded!"})}catch(Me){a({title:"Upload failed",description:Me.message,variant:"destructive"})}finally{o(null)}}},F=async de=>{var ye;const ie=(ye=de.target.files)==null?void 0:ye[0];if(ie){o("lead_magnet");try{const _e=await L(ie,"lead-magnet");S(Me=>({...Me,lead_magnet_file_url:_e,lead_magnet_file_name:ie.name})),a({title:"File uploaded!"})}catch(_e){a({title:"Upload failed",description:_e.message,variant:"destructive"})}finally{o(null)}}},z=async de=>{const ie=de.target.files;if(!(!ie||ie.length===0)){o("property_photos");try{const ye=[];for(const _e of Array.from(ie)){const Me=await L(_e,"property-photo");ye.push(Me)}S(_e=>({..._e,property_photos:[..._e.property_photos,...ye]})),a({title:`${ye.length} photo(s) uploaded!`})}catch(ye){a({title:"Upload failed",description:ye.message,variant:"destructive"})}finally{o(null)}}},V=async de=>{const ie=b.find(_e=>_e.id===de);if(!ie)return;const{data:ye}=await q.from("listing_photos").select("photo_url").eq("listing_id",de).order("sort_order");S(_e=>({..._e,listing_id:de,property_address:ie.property_address||`${ie.city}, ${ie.state}`,property_price:ie.price?`$${ie.price.toLocaleString()}`:"",property_beds:ie.bedrooms?String(ie.bedrooms):"",property_baths:ie.bathrooms?String(ie.bathrooms):"",property_sqft:ie.square_footage?ie.square_footage.toLocaleString():"",property_description:ie.description||"",property_photos:(ye==null?void 0:ye.map(Me=>Me.photo_url))||_e.property_photos})),a({title:"Listing data imported!"})},W=()=>{T(de=>[...de,{clientId:_tt(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:de.length}])},K=(de,ie)=>{T(ye=>ye.map((_e,Me)=>Me===de?{..._e,...ie}:_e))},Y=de=>{T(ie=>ie.filter((ye,_e)=>_e!==de))},ee=Eve(z8(oR,{activationConstraint:{distance:6}}),z8(Ive,{coordinateGetter:Ryt})),ne=de=>{const{active:ie,over:ye}=de;!ye||ie.id===ye.id||T(_e=>{const Me=_e.findIndex(Ce=>Ce.clientId===ie.id),Te=_e.findIndex(Ce=>Ce.clientId===ye.id);return Me<0||Te<0?_e:Rve(_e,Me,Te).map((Ce,Ee)=>({...Ce,sort_order:Ee}))})},oe=u?`https://pages.relevelup.com/${u.slug}`:"",pe=(u==null?void 0:u.page_type)==="lead_magnet",ce=(u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold";return h||f?e.jsx(Cs,{title:"Loading...",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):u?e.jsxs(Cs,{title:_.title||"Edit Page",children:[e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(Wr,{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(ze,{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(Ir,{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(_n,{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(B,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(ly,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(oe),a({title:"Link copied!"})},children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-1"})," Copy Link"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:oe,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(B,{onClick:()=>D.mutate(),disabled:D.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),D.isPending?"Saving...":"Save"]})]})]}),e.jsxs($r,{defaultValue:"design",children:[e.jsxs(Ur,{children:[e.jsx(Zt,{value:"design",children:"Design"}),pe&&e.jsx(Zt,{value:"lead_magnet",children:"Lead Magnet"}),ce&&e.jsx(Zt,{value:"property",children:"Property Details"}),e.jsxs(Zt,{value:"fields",children:["Form Fields (",A.length,")"]}),e.jsxs(Zt,{value:"submissions",children:["Submissions (",g.length,")"]}),e.jsx(Zt,{value:"automation",children:"Automation"}),e.jsx(Zt,{value:"analytics",children:"Analytics"}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(ls,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Page Details"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Page Title (internal)"}),e.jsx(ge,{value:_.title,onChange:de=>S(ie=>({...ie,title:de.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description (internal)"}),e.jsx(ge,{value:_.description,onChange:de=>S(ie=>({...ie,description:de.target.value}))})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(Ae,{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(se,{children:"Theme Style"}),e.jsxs(us,{value:_.theme_style,onValueChange:de=>S(ie=>({...ie,theme_style:de})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(Ze,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline Font"}),e.jsxs(us,{value:_.heading_font,onValueChange:de=>S(ie=>({...ie,heading_font:de})),children:[e.jsx(cs,{children:e.jsx(hs,{})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(Ze,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(Ze,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(Ze,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(ge,{value:_.trust_pills.join(", "),onChange:de=>S(ie=>({...ie,trust_pills:de.target.value.split(",").map(ye=>ye.trim()).filter(Boolean)})),placeholder:"No obligation, 100% free, 60 seconds or less"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Premium theme uses a cinematic full-screen hero, italic accent word, glass-effect form, and trust pills — magazine-style."})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Ae,{className:"space-y-4",children:[_.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(se,{children:"Eyebrow (small label above headline)"}),e.jsx(ge,{value:_.eyebrow,onChange:de=>S(ie=>({...ie,eyebrow:de.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(ge,{value:_.hero_headline,onChange:de=>S(ie=>({...ie,hero_headline:de.target.value})),placeholder:"What Is Your Home"})]}),_.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(se,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(ge,{value:_.headline_accent,onChange:de=>S(ie=>({...ie,headline_accent:de.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Subtext"}),e.jsx(Ts,{value:_.hero_subtext,onChange:de=>S(ie=>({...ie,hero_subtext:de.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(se,{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(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),l==="hero_image_url"?"Uploading...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:de=>M(de,"hero_image_url")})]}),_.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>S(de=>({...de,hero_image_url:null})),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Branding"})}),e.jsxs(Ae,{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(se,{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(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:de=>M(de,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{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(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:de=>M(de,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:_.primary_color,onChange:de=>S(ie=>({...ie,primary_color:de.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ge,{value:_.primary_color,onChange:de=>S(ie=>({...ie,primary_color:de.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:_.accent_color,onChange:de=>S(ie=>({...ie,accent_color:de.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ge,{value:_.accent_color,onChange:de=>S(ie=>({...ie,accent_color:de.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(Ae,{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(se,{children:"Name"}),e.jsx(ge,{value:_.agent_name,onChange:de=>S(ie=>({...ie,agent_name:de.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ge,{value:_.agent_phone,onChange:de=>S(ie=>({...ie,agent_phone:de.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ge,{value:_.agent_email,onChange:de=>S(ie=>({...ie,agent_email:de.target.value}))})]})]})})]})]}),pe&&e.jsx(ls,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(Ae,{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(se,{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(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Da,{className:"h-3 w-3"})," ",_.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:F})]}),_.lead_magnet_file_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>S(de=>({...de,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(bn,{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(se,{className:"flex items-center gap-1",children:[e.jsx(El,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(ge,{value:_.lead_magnet_external_url||"",onChange:de=>S(ie=>({...ie,lead_magnet_external_url:de.target.value||null})),placeholder:"https://drive.google.com/... or https://dropbox.com/...",className:"mt-1"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Link to a file on Google Drive, Dropbox, or any URL"})]})]})]})}),ce&&e.jsxs(ls,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Pt,{className:"text-base flex items-center gap-2",children:[e.jsx(zr,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pull property details and photos directly from one of your listings, or enter them manually below."}),e.jsxs(us,{value:_.listing_id||"",onValueChange:de=>V(de),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Select a listing to import..."})}),e.jsx(ds,{children:b.map(de=>{var ie;return e.jsxs(Ze,{value:de.id,children:[de.property_address||`${de.city}, ${de.state}`," — $",(ie=de.price)==null?void 0:ie.toLocaleString()]},de.id)})})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Property Information"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Property Address"}),e.jsx(ge,{value:_.property_address,onChange:de=>S(ie=>({...ie,property_address:de.target.value})),placeholder:"123 Main St, City, State"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Price"}),e.jsx(ge,{value:_.property_price,onChange:de=>S(ie=>({...ie,property_price:de.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Beds"}),e.jsx(ge,{value:_.property_beds,onChange:de=>S(ie=>({...ie,property_beds:de.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Baths"}),e.jsx(ge,{value:_.property_baths,onChange:de=>S(ie=>({...ie,property_baths:de.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Sq Ft"}),e.jsx(ge,{value:_.property_sqft,onChange:de=>S(ie=>({...ie,property_sqft:de.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ts,{value:_.property_description,onChange:de=>S(ie=>({...ie,property_description:de.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Property Photos"})}),e.jsxs(Ae,{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((de,ie)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:de,alt:`Property ${ie+1}`,className:"h-24 w-full object-cover rounded"}),e.jsx(B,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>S(ye=>({...ye,property_photos:ye.property_photos.filter((_e,Me)=>Me!==ie)})),children:e.jsx(bn,{className:"h-3 w-3"})})]},ie))}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="property_photos",children:e.jsxs("span",{children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),l==="property_photos"?"Uploading...":"Add Photos"]})}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:z})]})]})]})]}),e.jsxs(ls,{value:"fields",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the form fields visitors will fill out"}),e.jsxs(B,{size:"sm",onClick:W,children:[e.jsx(As,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),A.length===0?e.jsx(fe,{children:e.jsx(Ae,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(Dve,{sensors:ee,collisionDetection:Ave,onDragEnd:ne,children:e.jsx(Ove,{items:A.map(de=>de.clientId),strategy:Xws,children:e.jsx("div",{className:"space-y-3",children:A.map((de,ie)=>e.jsx(qpn,{field:de,index:ie,updateField:K,removeField:Y},de.clientId))})})})]}),e.jsx(ls,{value:"submissions",className:"mt-4",children:g.length===0?e.jsx(fe,{children:e.jsx(Ae,{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(de=>e.jsx(fe,{children:e.jsx(Ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:de.contact_name||"Anonymous"}),de.synced_to_crm&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[de.contact_email&&e.jsx("span",{className:"mr-3",children:de.contact_email}),de.contact_phone&&e.jsx("span",{children:de.contact_phone})]}),de.answers&&typeof de.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(de.answers).map(([ie,ye])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[ie,":"]})," ",e.jsx("span",{children:String(ye)})]},ie))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(de.created_at).toLocaleDateString()})]})})},de.id))})}),e.jsxs(ls,{value:"automation",className:"space-y-4 mt-4",children:[(u==null?void 0:u.page_type)==="event_registration"&&e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{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(Ae,{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 md:col-span-2",children:[e.jsx(se,{children:"Starts at"}),e.jsx(ge,{type:"datetime-local",value:_.settings_event_starts_at,onChange:de=>S(ie=>({...ie,settings_event_starts_at:de.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Venue / location name"}),e.jsx(ge,{placeholder:"e.g. The Grand Hotel",value:_.settings_event_location_name,onChange:de=>S(ie=>({...ie,settings_event_location_name:de.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Address (for map link)"}),e.jsx(ge,{placeholder:"123 Main St, City, ST",value:_.settings_event_address,onChange:de=>S(ie=>({...ie,settings_event_address:de.target.value}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{className:"text-base",children:"Instant auto-reply to lead"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent the moment someone submits this page. Leave blank to use your",j!=null&&j.default_auto_responder_body?" account default":" built-in template",". Merge fields: ",e.jsx("code",{children:"{{client_first_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{page_title}}"}),", ",e.jsx("code",{children:"{{calendar_link}}"}),"."]})]}),e.jsxs(Ae,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Send auto-reply for this page"}),e.jsx(vn,{checked:!_.settings_disable_auto_responder,onCheckedChange:de=>S(ie=>({...ie,settings_disable_auto_responder:!de}))})]}),!_.settings_disable_auto_responder&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{children:"Subject (override)"}),e.jsx(ge,{value:_.settings_auto_responder_subject,onChange:de=>S(ie=>({...ie,settings_auto_responder_subject:de.target.value})),placeholder:(j==null?void 0:j.default_auto_responder_subject)||"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Body (override)"}),e.jsx(Ts,{rows:8,value:_.settings_auto_responder_body,onChange:de=>S(ie=>({...ie,settings_auto_responder_body:de.target.value})),placeholder:(j==null?void 0:j.default_auto_responder_body)||`Hi {{client_first_name}}, Thanks for reaching out…`})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{className:"text-base",children:"Smart Drip enrollment"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatically enroll every new lead into a drip campaign.",(j==null?void 0:j.default_drip_campaign_id)&&" Account default applies if no override is selected."]})]}),e.jsxs(Ae,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Enroll new leads in a drip"}),e.jsx(vn,{checked:!_.settings_disable_drip,onCheckedChange:de=>S(ie=>({...ie,settings_disable_drip:!de}))})]}),!_.settings_disable_drip&&e.jsxs("div",{children:[e.jsx(se,{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:de=>S(ie=>({...ie,settings_drip_campaign_id:de.target.value||null})),children:[e.jsx("option",{value:"",children:"— Use account default —"}),v.map(de=>e.jsx("option",{value:de.id,children:de.name},de.id))]})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Redirect after submit"})}),e.jsxs(Ae,{children:[e.jsx(ge,{value:_.settings_redirect_url,onChange:de=>S(ie=>({...ie,settings_redirect_url:de.target.value})),placeholder:(j==null?void 0:j.default_redirect_url)||"https://your-site.com/thank-you (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Leave blank to keep the inline Thank-You message."})]})]})]}),e.jsx(ls,{value:"analytics",className:"space-y-4 mt-4",children:e.jsx(Bpn,{pageId:s})}),e.jsxs(ls,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Publishing"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(vn,{checked:_.is_published,onCheckedChange:de=>S(ie=>({...ie,is_published:de}))})]}),_.is_published&&e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Public URL:"}),e.jsx("code",{className:"text-xs ml-2 break-all",children:oe})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{className:"text-base",children:"Thank You Message"})}),e.jsx(Ae,{children:e.jsx(Ts,{value:_.success_message,onChange:de=>S(ie=>({...ie,success_message:de.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsx(ws,{children:e.jsx(_s,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(QU,{value:oe,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:oe})]})]})})]}):e.jsx(Cs,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}const Hpn={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},Gpn=`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 Wpn(){const s=fa(),{toast:t}=Ua(),n=In(),r=Gt(),[a,i]=N.useState(Hpn),{data:l}=lt({queryKey:["landing-page-defaults",s],queryFn:async()=>{const{data:d}=await q.from("agent_landing_page_defaults").select("*").eq("user_id",s).maybeSingle();return d||null},enabled:!!s}),{data:o=[]}=lt({queryKey:["drip-campaigns-mine",s],queryFn:async()=>{const{data:d}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",s).eq("is_active",!0).order("name");return d||[]},enabled:!!s});N.useEffect(()=>{l&&i({default_auto_responder_subject:l.default_auto_responder_subject??"",default_auto_responder_body:l.default_auto_responder_body??"",default_drip_campaign_id:l.default_drip_campaign_id??null,default_redirect_url:l.default_redirect_url??"",default_calendar_link:l.default_calendar_link??"",text_agent_on_lead:!!l.text_agent_on_lead,agent_sms_phone:l.agent_sms_phone??"",use_brand_kit:l.use_brand_kit??!0})},[l]);const c=gt({mutationFn:async()=>{const{error:d}=await q.from("agent_landing_page_defaults").upsert({user_id:s,...a},{onConflict:"user_id"});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["landing-page-defaults"]}),t({title:"Defaults saved"})},onError:d=>t({title:"Save failed",description:d.message,variant:"destructive"})});return e.jsx(Cs,{title:"Landing Page Defaults",children:e.jsxs("div",{className:"space-y-6 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/mission-control/landing-pages"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"})," Back to pages"]}),e.jsxs(B,{onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"})," ",c.isPending?"Saving…":"Save Defaults"]})]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Page Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"These run on every landing page automatically. Any page can override them in its own settings."})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Instant auto-reply to the lead"}),e.jsxs(Hn,{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(Ae,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Subject"}),e.jsx(ge,{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(se,{children:"Message body"}),e.jsx(Ts,{rows:10,value:a.default_auto_responder_body||"",onChange:d=>i(u=>({...u,default_auto_responder_body:d.target.value})),placeholder:Gpn}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the polished built-in template that adapts to each page type."})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Default Smart Drip"}),e.jsx(Hn,{children:"Every new lead drops into this drip unless a page overrides it."})]}),e.jsx(Ae,{children:e.jsxs(us,{value:a.default_drip_campaign_id||"none",onValueChange:d=>i(u=>({...u,default_drip_campaign_id:d==="none"?null:d})),children:[e.jsx(cs,{children:e.jsx(hs,{placeholder:"Pick a drip…"})}),e.jsxs(ds,{children:[e.jsx(Ze,{value:"none",children:"— No default drip —"}),o.map(d=>e.jsx(Ze,{value:d.id,children:d.name},d.id))]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Pt,{children:"Defaults for every page"})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Default booking / calendar link"}),e.jsx(ge,{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(se,{children:"Default redirect after submit (optional)"}),e.jsx(ge,{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(se,{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(vn,{checked:a.use_brand_kit,onCheckedChange:d=>i(u=>({...u,use_brand_kit:d}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(Pt,{children:"Text me when a lead submits"}),e.jsx(Hn,{children:"Get an SMS the second a lead hits your inbox. Coming soon — requires SMS sender setup."})]}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(se,{className:"text-base",children:"SMS me new leads"}),e.jsx(vn,{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(se,{children:"Phone number for alerts"}),e.jsx(ge,{type:"tel",value:a.agent_sms_phone||"",onChange:d=>i(u=>({...u,agent_sms_phone:d.target.value})),placeholder:"(555) 123-4567"})]})]})]})]})})}function Kpn(){return lt({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await q.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function jbe(){const{user:s}=gs();return lt({queryKey:["agent-website-app-installs",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(n)throw n;return t||[]},enabled:!!(s!=null&&s.id)})}function Nbe(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async({app_slug:n,enabled:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await q.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:n,enabled:r},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),ae.success(r.enabled?"App installed":"App turned off")},onError:n=>ae.error(n.message||"Failed to update app")})}const Ypn={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"}},Zpn={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 Qpn(){const s=In(),{data:t=[],isLoading:n}=Kpn(),{data:r=[]}=jbe(),{hasLeadSite:a,siteUrl:i,isLoading:l}=Pp(),o=Nbe(),[c,d]=N.useState(!1),u=p=>{var f;return((f=r.find(g=>g.app_slug===p))==null?void 0:f.enabled)??!1},h=p=>r.some(f=>f.app_slug===p);return e.jsxs(Cs,{title:"Website Apps",description:"Conversion-boosting widgets for your website",children:[e.jsxs("div",{className:"max-w-6xl mx-auto p-6 lg:p-8 space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl bg-gradient-to-br from-indigo-600 via-fuchsia-600 to-rose-500 p-8 lg:p-10 shadow-xl",children:[e.jsx("div",{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-white/10 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-16 w-80 h-80 rounded-full bg-fuchsia-300/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/15 backdrop-blur-sm text-white text-xs font-semibold uppercase tracking-wider mb-4",children:[e.jsx(ph,{className:"w-3.5 h-3.5"})," Boost conversions on autopilot"]}),e.jsxs("h1",{className:"text-3xl lg:text-4xl font-extrabold tracking-tight text-white flex items-center gap-3",children:[e.jsx(un,{className:"w-8 h-8 text-yellow-300 drop-shadow"}),"Website Apps"]}),e.jsx("p",{className:"text-white/90 mt-2 max-w-2xl text-base lg:text-lg",children:"Drop-in widgets that turn website visitors into leads. Add them to your Lead Site or embed on your own website with one line of code."}),e.jsxs(B,{onClick:()=>d(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx(Pu,{className:"w-5 h-5"}),"Watch: How to use Website Apps"]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(fe,{className:`p-5 border-2 ${a?"border-emerald-200 bg-emerald-50/50":"border-dashed border-muted"}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0 ${a?"bg-emerald-500 text-white":"bg-muted text-muted-foreground"}`,children:e.jsx(lc,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 1 — The Local Move Websites"}),a&&e.jsxs(ze,{className:"bg-emerald-100 text-emerald-700 hover:bg-emerald-100 text-[10px] gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"})," Auto-installed"]})]}),a&&i?e.jsxs("a",{href:i,target:"_blank",rel:"noreferrer",className:"text-xs text-emerald-700 hover:underline inline-flex items-center gap-1 mt-1",children:[i.replace(/^https?:\/\//,"")," ",e.jsx(tr,{className:"w-3 h-3"})]}):e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Don't have a Local Move website yet? Visit"," ",e.jsxs("a",{href:"https://www.thelocalmove.com",target:"_blank",rel:"noreferrer",className:"text-primary font-medium hover:underline inline-flex items-center gap-0.5",children:["www.thelocalmove.com ",e.jsx(tr,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(fe,{className:"p-5 border-2 border-indigo-200 bg-indigo-50/40",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gradient-to-br from-indigo-500 to-fuchsia-600 text-white flex items-center justify-center flex-shrink-0",children:e.jsx(T2,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 2 — Your existing website"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Already have a site (Wix, Squarespace, WordPress, custom)? Paste a one-line snippet and the widget appears anywhere."}),e.jsx("p",{className:"text-[11px] text-indigo-700 mt-2 font-medium",children:'Open any app below → "Install on my website" tab to copy your code.'})]})]})})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading apps..."}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(p=>{const f=M0e[p.icon||"Sparkles"]||un,g=u(p.slug),b=h(p.slug),v=p.status==="coming_soon",j=Ypn[p.slug]||Zpn;return e.jsxs(fe,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${j.ring} hover:ring-2 transition-all hover:shadow-xl ${v?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${j.gradient}`}),e.jsxs("div",{className:"p-5 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:`w-14 h-14 rounded-2xl ${j.iconBg} ${j.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(f,{className:"w-7 h-7"})}),v?e.jsx(ze,{variant:"secondary",children:"Coming soon"}):g?e.jsxs(ze,{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"]}):b?e.jsx(ze,{variant:"outline",children:"Paused"}):e.jsx(ze,{className:j.chip+" hover:"+j.chip,children:"New"})]}),e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("h3",{className:"font-bold text-lg",children:p.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:p.description})]}),!v&&e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{checked:g,onCheckedChange:_=>o.mutate({app_slug:p.slug,enabled:_})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:g?"On":"Off"})]}),e.jsxs(B,{size:"sm",className:`bg-gradient-to-r ${j.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${p.slug}`),children:[e.jsx(Vo,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(za,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},p.id)})})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(ws,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx(_s,{children:"How to use Website Apps"})}),c&&e.jsx("video",{src:"/website-apps-tutorial.mp4",controls:!0,autoPlay:!0,playsInline:!0,className:"w-full h-auto bg-black"})]})})]})}const Uke={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 Xpn(){const{user:s}=gs();return lt({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return Uke;const{data:t,error:n}=await q.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t?{...Uke,...t}:Uke},enabled:!!(s!=null&&s.id)})}function Jpn(){const{user:s}=gs(),t=Gt();return gt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:r}=await q.from("video_greeter_configs").upsert({user_id:s.id,...n},{onConflict:"user_id"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),ae.success("Saved")},onError:n=>ae.error(n.message||"Failed to save")})}function efn({label:s,value:t,onChange:n,thumbnailUrl:r,placeholder:a="https://...",hint:i}){const l=N.useRef(null),[o,c]=N.useState(!1),d=async u=>{var p;const h=(p=u.target.files)==null?void 0:p[0];if(h){if(!h.type.startsWith("video/")){ae.error("Please select a video file");return}if(h.size>50*1024*1024){ae.error("Video must be under 50MB");return}c(!0);try{const f=h.name.split(".").pop()||"mp4",g=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${f}`,{error:b}=await q.storage.from("agent-uploads").upload(g,h,{upsert:!0});if(b)throw b;const{data:{publicUrl:v}}=q.storage.from("agent-uploads").getPublicUrl(g);n(v),ae.success("Video uploaded!")}catch(f){ae.error(f.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(se,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{value:t,onChange:u=>n(u.target.value),placeholder:a,className:"flex-1"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5 h-9",onClick:()=>{var u;return(u=l.current)==null?void 0:u.click()},disabled:o,children:[o?e.jsx(ss,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Sa,{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}):VP(t)?e.jsx(tEe,{sourceUrl:t,thumbnailUrl:r,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-contain"}):e.jsx("video",{src:t,className:"w-full h-full object-contain",controls:!0,muted:!0,preload:"metadata"})}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>n(""),children:e.jsx(Fn,{className:"h-3 w-3"})})]})})()]})}const tfn=[{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 sfn({onVideoReady:s}){const[t,n]=N.useState(!1),[r,a]=N.useState("script"),[i,l]=N.useState(""),[o,c]=N.useState(!0),[d,u]=N.useState(!1),[h,p]=N.useState(0),[f,g]=N.useState(0),b=PN(),v=()=>{a("script"),l(""),p(0),g(0),c(!0)},j=S=>{!S&&(r==="uploading"||r==="processing")||(n(S),S||v())},_=N.useCallback(async(S,A)=>{a("uploading");try{const T="Video Greeter",{videoId:D,libraryId:L}=await l6(T),{uploadUrl:M,apiKey:F}=await c6(D),z=new XMLHttpRequest;z.upload.onprogress=ce=>{ce.lengthComputable&&p(ce.loaded/ce.total*100)},await new Promise((ce,de)=>{z.onload=()=>z.status>=200&&z.status<300?ce():de(new Error("Upload failed")),z.onerror=()=>de(new Error("Upload failed")),z.open("PUT",M),z.setRequestHeader("AccessKey",F),z.send(S)}),a("processing");let V=0;const W=Date.now(),K=9e4,Y=`https://iframe.mediadelivery.net/embed/${L}/${D}`,ee=`https://iframe.mediadelivery.net/play/${L}/${D}`;for(;V<4;){if(await new Promise(de=>setTimeout(de,3e3)),Date.now()-W>K){const de=S.size/1048576,ie=await b.mutateAsync({bunny_video_id:D,playback_url:ee,file_size_mb:de,title:T,status:"processing",touch_type:"video"});s({videoId:(ie==null?void 0:ie.id)||D,playbackUrl:Y,thumbnailUrl:null}),ae.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{n(!1),v()},1500);return}const ce=await Uw(D);if(V=ce.status,g(ce.encodeProgress||0),V===5||V===6)throw new Error("Video processing failed")}const ne=await Uw(D),oe=(ne.storageSize||S.size)/(1024*1024),pe=await b.mutateAsync({bunny_video_id:D,playback_url:ne.directPlayUrl||Y,thumbnail_url:ne.thumbnailUrl,preview_url:ne.previewUrl||null,duration_seconds:ne.length||A,file_size_mb:oe,title:T,status:"ready",touch_type:"video"});s({videoId:(pe==null?void 0:pe.id)||D,playbackUrl:ne.directPlayUrl||Y,thumbnailUrl:ne.thumbnailUrl||null}),ae.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{n(!1),v()},1500)}catch(T){console.error(T),ae.error("Failed to process video. Please try again."),a("record")}},[b,s]);return e.jsxs(bs,{open:t,onOpenChange:j,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(B,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(vr,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(vs,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Record your Video Greeter"]})}),r==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"1. Pick a script (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Edit it to sound like you, or skip and freestyle."}),e.jsx(mi,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:tfn.map(S=>e.jsxs(fe,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(S.text),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:"font-medium text-sm",children:S.title}),e.jsx(ze,{variant:"outline",className:"text-[10px] shrink-0",children:S.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:S.description})]},S.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(Ts,{rows:5,value:i,onChange:S=>l(S.target.value),placeholder:"Pick a script above or type your own. Leave blank to freestyle."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t",children:[e.jsx(B,{variant:"ghost",onClick:()=>{l(""),a("record")},children:"Skip — freestyle"}),e.jsxs(B,{onClick:()=>a("record"),children:[e.jsx(Nr,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),r==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(m6,{maxDurationSeconds:60,onRecordingComplete:_,onRecordingStateChange:u,onError:S=>ae.error(S),teleprompterContent:o&&i?e.jsx(N8e,{text:i,isVisible:o,onToggleVisibility:()=>c(!1),isRecording:d,startCountdown:!1}):void 0}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>a("script"),children:"← Back to script"}),i&&!o&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(Nr,{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(ss,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(xi,{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(ss,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(xi,{value:f,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(f),"%"]})]}),r==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(zi,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function nfn(){var A;const s=In(),{user:t}=gs(),{leadSite:n}=Pp(),{data:r}=Xpn(),a=Jpn(),{data:i=[]}=jbe(),l=Nbe(),[o,c]=N.useState(null),[d,u]=N.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(N.useEffect(()=>{r&&!o&&c(r)},[r,o]),N.useEffect(()=>{t!=null&&t.id&&q.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:T})=>{const D=T||[];u({impressions:D.filter(L=>L.event_type==="impression").length,expands:D.filter(L=>L.event_type==="expand").length,ctaClicks:D.filter(L=>L.event_type==="cta_click").length,leads:D.filter(L=>L.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(Cs,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const h=((A=i.find(T=>T.app_slug==="video_greeter"))==null?void 0:A.enabled)??!1,p=T=>c({...o,...T}),f=T=>p({ctas:T}),g=()=>f([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),b=T=>f((o.ctas||[]).filter(D=>D.id!==T)),v=(T,D)=>f((o.ctas||[]).map(L=>L.id===T?{...L,...D}:L)),j=()=>a.mutate(o),_=(n==null?void 0:n.subdomain_slug)||(t==null?void 0:t.id)||"",S=`